document360-writer 0.5.12 → 0.5.14

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 +47 -47
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var Il=Object.defineProperty;var Io=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Nl=(e,t)=>{for(var n in t)Il(e,n,{get:t[n],enumerable:!0})};import We from"picocolors";var M,_l,Ol,Ul,Ss,Ft,m,$,U,E,O,oe,Pe,W=Io(()=>{"use strict";M="#7f56d9",[_l,Ol,Ul]=[127,86,217],Ss=e=>We.isColorSupported?`\x1B[38;2;${_l};${Ol};${Ul}m${e}\x1B[39m`:e,Ft=e=>We.bold(Ss(e)),m=e=>We.dim(e),$=e=>We.red(e),U=e=>We.yellow(e),E=e=>We.green(e),O=Ss,oe=e=>We.gray(e),Pe=e=>We.bold(e)});import{existsSync as Dn,writeFileSync as Bt,readFileSync as xc,readdirSync as $c}from"node:fs";import{join as vc}from"node:path";import{devHintsGuidePath as jn,hintsDir as Vs,architectureDir as Xs,messagesDir as Mo,creatorNotesPath as zs,devhintsStatePath as Js,ensureDir as Sn,writeMessage as Cc,listOpenForDev as Pc}from"document360-engine";function Qs(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var Il=Object.defineProperty;var Io=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Nl=(e,t)=>{for(var n in t)Il(e,n,{get:t[n],enumerable:!0})};import We from"picocolors";var L,_l,Ol,Ul,Ss,Ft,m,$,U,E,O,oe,Te,W=Io(()=>{"use strict";L="#7f56d9",[_l,Ol,Ul]=[127,86,217],Ss=e=>We.isColorSupported?`\x1B[38;2;${_l};${Ol};${Ul}m${e}\x1B[39m`:e,Ft=e=>We.bold(Ss(e)),m=e=>We.dim(e),$=e=>We.red(e),U=e=>We.yellow(e),E=e=>We.green(e),O=Ss,oe=e=>We.gray(e),Te=e=>We.bold(e)});import{existsSync as Dn,writeFileSync as Bt,readFileSync as xc,readdirSync as $c}from"node:fs";import{join as vc}from"node:path";import{devHintsGuidePath as jn,hintsDir as Ys,architectureDir as Xs,messagesDir as Lo,creatorNotesPath as zs,devhintsStatePath as Js,ensureDir as Sn,writeMessage as Cc,listOpenForDev as Pc}from"document360-engine";function Qs(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
3
3
 
4
4
  <!-- devhints script v${ne} \xB7 maintained by document360-writer (/devhints). -->
5
5
 
@@ -173,60 +173,60 @@ Anything only a human knows that would help document this product. For example:
173
173
  - Gotchas or non-obvious behavior.
174
174
 
175
175
  (Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
176
- `}function Ct(e){Sn(Vs(e)),Sn(Xs(e)),Sn(Mo(e));for(let n of[Vs(e),Mo(e)]){let o=vc(n,".gitkeep");Dn(o)||Bt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
176
+ `}function Ct(e){Sn(Ys(e)),Sn(Xs(e)),Sn(Lo(e));for(let n of[Ys(e),Lo(e)]){let o=vc(n,".gitkeep");Dn(o)||Bt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
177
177
  `)}Dn(zs(e))||Bt(zs(e),Tc()),Bt(jn(e),Qs());let t=Ee(e);return ei(e,new Date().toISOString()),t}async function Zs(e,t){for(let n of Pt(Ct(t.cwd)))console.log(n);return{kind:"continue"}}function nt(){return[`This is document360-writer's dev hand-off setup (v${ne}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20134). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current; AND each session, check"," `.d360-writer/messages/` for open questions from the docs agent and answer them \u2014 all per"," `.d360-writer/DEV-HINTS-GUIDE.md`. If that section is already there, leave it (refine in place only if"," wrong) \u2014 do NOT add a duplicate. Then commit `.d360-writer/` and the memory-file change ONLY if"," something actually changed.","4. Two-way messages (Part 3): check `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each \u2014 fold durable facts into the architecture brief and/or drop"," a reply (`from: dev`, `kind: answer`, `re: <id>`) \u2014 then set the question's frontmatter `status: done`."," If there are none, continue.","5. Then STOP and ask me for tribal knowledge \u2014 present it as a clearly-marked, standalone prompt on its"," own line (NOT buried in prose) and WAIT for my reply before doing anything else. Use this shape:",' "\u23F8 YOUR INPUT NEEDED \u2014 Any tribal knowledge that would help document this product? (folder map,',` terminology, what to prioritize or skip, gotchas.) Type it below, or reply 'none' / 'carry on' to skip."`," If I give you anything, phrase it clearly and append it to `.d360-writer/architecture/CREATOR-NOTES.md`"," (keep the existing header comment and every note already there; only add). If I say 'none'/'carry on', continue.",`6. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${ne},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","7. When everything is done, print the completion line, THEN the next command as its own copy-paste"," block so it is unmistakable. Pick the matching first line:",' \u2022 first-time setup: "\u2705 Setup complete. Now switch to the document360-writer terminal and paste this:"',' \u2022 a refresh (brief/notes already existed): "\u2705 Hand-off refreshed. Back in the document360-writer terminal, paste this:"'," Then, on its OWN line, fenced as a code block so it copies cleanly:"," ```"," write the docs for this repo"," ```"].join(`
178
178
  `)}function Wo(e){try{let t=xc(Js(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function ei(e,t){let o={...Wo(e)??{},emittedVersion:ne,emittedAt:t};Bt(Js(e),`${JSON.stringify(o,null,2)}
179
- `)}function Gt(e){try{return $c(Xs(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ee(e){let n=Wo(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ne?"stale":"current",completedVersion:n}}function An(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ne};try{if(!Dn(jn(e)))return n;let o=Wo(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;ne>r&&(Sn(Mo(e)),Bt(jn(e),Qs()),ei(e,t),n.guideRefreshed=!0),ne>s&&(Pc(e).some(p=>p.kind==="request"&&p.subject.startsWith(Ks))||(Cc(e,{id:`onb${ne}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Ks}${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:","",nt()].join(`
179
+ `)}function Gt(e){try{return $c(Xs(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ee(e){let n=Wo(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ne?"stale":"current",completedVersion:n}}function An(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ne};try{if(!Dn(jn(e)))return n;let o=Wo(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;ne>r&&(Sn(Lo(e)),Bt(jn(e),Qs()),ei(e,t),n.guideRefreshed=!0),ne>s&&(Pc(e).some(p=>p.kind==="request"&&p.subject.startsWith(Ks))||(Cc(e,{id:`onb${ne}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Ks}${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:","",nt()].join(`
180
180
  `)}),n.notifiedBuilder=!0))}catch{}return n}function En(e){if(!Dn(jn(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}`,vt,nt(),vt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Fo(){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 In(){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):",vt,Fo(),vt]}function Pt(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):",vt,nt(),vt,"","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 vt,ne,Ks,ot=Io(()=>{"use strict";vt="-".repeat(64),ne=5;Ks="Re-run dev\u2194docs onboarding (protocol v"});var ra={};Nl(ra,{doctorCommand:()=>Zt,renderDoctorChecks:()=>oa,runDoctorChecks:()=>na});import{existsSync as Zi}from"node:fs";import{d360GetAll as nd,getAccessToken as od,isExpired as Sr,loadProfileMap as rd,loadTokens as sd,packageSkillsDir as ea,projectConfigPath as id,readProjectConfig as ad,DEFAULT_DOCS_DIR as ld,resolveActiveProfile as cd,classifyClaudeAuth as ud,CLAUDE_CODE_SETUP_HINT as ta,resolveModelSetting as dd,probeModel as pd,devHintsGuidePath as fd}from"document360-engine";async function na(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=ud();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. ${ta}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ta});let r=dd(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let w=await pd(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=ad(e);if(!s)return t.push({level:"fail",label:`No ${id(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??ld).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=cd(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 b=sd(f.name);b?Sr(b)&&!b.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Sr(b)?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(b.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=rd(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(Zi(ea())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ea()}`,fix:"Reinstall document360-writer (broken install)"});let A=Ee(e);if((Zi(fd(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)"})),b&&(!Sr(b)||b.refreshToken)){let w={profile:f.name,connection:f.connection};try{await od(w);let P=await nd(w,"/v3/projects");t.push({level:"ok",label:`API reachable (${f.connection.apiUrl}) \u2014 ${P.length} project(s) visible`})}catch(P){t.push({level:"fail",label:`API call failed: ${P.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}}return t}function oa(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?U("\u26A0"):$("\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"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Zt(e,t){console.log(m("Running checks\u2026"));for(let n of oa(await na(t.cwd)))console.log(n);return{kind:"continue"}}var qn=Io(()=>{"use strict";ot();W()});import{Command as If}from"commander";import{createRequire as Nf}from"node:module";import{AUTH_MODES as _f}from"document360-engine";import{input as Jl}from"@inquirer/prompts";import{loginPkce as Ql,refreshTokens as Zl,toStoredTokens as _s,clearTokens as ec,decodeJwtClaims as Ns,isExpired as tc,loadTokens as nc,saveTokens as Os,resolveActiveProfile as $n,setProfileProject as oc,readProjectConfig as rc}from"document360-engine";W();import{select as Ll}from"@inquirer/prompts";import{resolveActiveProfile as Ml,setProfileProject as Wl,resolveProjectId as Fl,listWorkspaces as Hl}from"document360-engine";async function Ht(e,t){let n=Ml(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Fl(o);return{workspaces:await Hl(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Ds=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function No(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 xn(e,t,n,o,r){Wl(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function js(e,t,n){let o;try{o=await Ht(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=No(o.workspaces,t);return r?(xn(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($(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function $t(e,t){let n;try{n=await Ht(e,t)}catch(b){console.log($(`Could not list workspaces: ${b.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 b of o)console.log(` ${b.id===c?O("\u25CF"):" "} ${Ds(b)} ${m(b.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let p=await Ll({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${Ds(b)}${b.id===c?" (current)":""}`,value:b.id}))}),f=o.find(b=>b.id===p);xn(e,s,r,p,f?.name),console.log(E(`\u2713 Workspace set to "${f?.name??p}" for profile "${s}".`))}W();import{select as ql}from"@inquirer/prompts";import{resolveActiveProfile as Bl,setProfileProject as Gl,listProjects as Yl}from"document360-engine";async function tt(e,t){let n=Bl(e,t),o={profile:n.name,connection:n.connection};return{projects:await Yl(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var As=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Es(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 _o(e,t,n,o){Gl(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Is(e,t){let n;try{n=await tt(e,t)}catch(f){console.log($(`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"):" "} ${As(f)} ${m(f.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let c=await ql({message:"Select the Document360 project for this repo:",choices:o.map(f=>({name:`${As(f)}${f.id===s?" (current)":""}`,value:f.id}))}),p=o.find(f=>f.id===c);_o(e,r,c,p?.name),console.log(E(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import Vl from"picocolors";function zl(e=process.env){return e.FORCE_HYPERLINK==="0"||!Vl.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 Kl(e,t=e,n){return zl(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Xl=/https?:\/\/[^\s\x1b]+/g;function qt(e,t){return e.replace(Xl,n=>Kl(n,n,t))}function Us(e){return{...Ns(e.idToken)??{},...Ns(e.accessToken)??{}}}function vn(e){let t=Us(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 Cn(e){let t=$n(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 Ql(n,{manual:e.manual,promptForRedirect:s=>Jl({message:s})},s=>console.log(qt(s))),r=_s(t.name,o);if(Os(r),await Oo(r,t.name,s=>console.log(m(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${vn(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{rc(process.cwd())?.profiles?.[t.name]&&(console.log(""),await $t(process.cwd(),t.name))}catch{}}async function Oo(e,t,n){let r=Us(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if($n(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await tt(process.cwd(),t);c=p.find(f=>f.id===r)?.name}catch{}oc(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Ls(e){let t=$n(process.cwd(),e.profile),n=t.connection,o=nc(t.name);if(!o){console.log($(`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":""}: ${vn(o)}`),tc(o))if(o.refreshToken)try{let r=_s(t.name,await Zl(n,o.refreshToken));Os(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 Ms(e){let t=$n(process.cwd(),e.profile);ec(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 Ws,writeProjectConfig as sc,resolveActiveProfile as ic,loadTokens as ac,isExpired as lc}from"document360-engine";function Pn(e){let t=Ws(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("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=ac(n),f=p?lc(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 Tn(e,t){let n=Ws(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log($(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,sc(n,e);let o=n.profiles[t].production?U(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function Rn(e,t){try{let n=ic(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($(n.message)),process.exitCode=1}}W();import{existsSync as cc,readdirSync as uc,statSync as Fs}from"node:fs";import{join as Hs}from"node:path";import{apiLogDir as dc}from"document360-engine";function qs(){let e=dc();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!cc(e)){console.log(m(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=uc(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=(Fs(Hs(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=(Fs(Hs(e,r)).size/1024).toFixed(1);console.log(` ${$(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 pc,resolveAuth as fc,findByName as mc,slugify as hc,touchSession as gc,upsertSession as wc,resolveActiveProfile as yc}from"document360-engine";async function Bs(e,t,n,o,r,s){let c=fc(n);c.kind==="none"&&(console.error(""),console.error($("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=yc(e,r)}catch(w){console.error($(`Document360 profile error: ${w.message}`)),process.exit(2)}p.production&&(console.error(U(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error($("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=mc(e,o);w||(console.error($(`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 b=pc({cwd:e,resume:f,profileName:r,allowProdWrites:s===!0}),k=f??null,A=1;for await(let w of b.send(t))switch(w.type){case"session":if(!k){k=w.sessionId;let P=new Date().toISOString();wc({uuid:k,name:hc(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}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($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${w.message}`)),process.exit(1)}k&&gc(k),process.stdout.write(`
182
- `),process.exit(A)}import{createInterface as np}from"node:readline/promises";import{createSession as Br,resolveAuth as op,getSession as rp,setTitle as sp,slugify as ip,touchSession as Da,upsertSession as ap,generateTitle as lp,resolveActiveProfile as ja,resolveModelSetting as cp,readProjectConfig as up,decodeJwtClaims as Ra,isExpired as dp,loadTokens as pp}from"document360-engine";var Te=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase and generates end-user documentation for 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:"dim",s:"Agentic and Assistant aren't a setting you switch \u2014 just two ways to drive the same tool."},{t:"gap"},{t:"text",s:"D360-Writer works autonomously, like a technical writer dedicated to your project. Your coding agent leaves notes as it ships; you just run the loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, update the docs, and publish."},{t:"dim",s:" (or run /catch-up for drafts, then /publish when you are ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/audit",s:"Preview what changed and what's missing \u2014 writes nothing."},{t:"cmd",name:"/sync",s:"Pull edits made in the Document360 portal; reconcile drift."},{t:"cmd",name:"/inbox",s:"Act on messages from 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 kc(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 Gs(){let e=["document360-writer \u2014 help",""];for(let t of Te){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push(kc(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function Uo(){console.log("");for(let e of Gs())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 bc}from"document360-engine";async function Ys(e,t){let n=t.currentUuid(),o=n?bc(n):void 0;return console.log(o?m(`
181
+ `)}function In(){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):",vt,Fo(),vt]}function Pt(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):",vt,nt(),vt,"","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 vt,ne,Ks,ot=Io(()=>{"use strict";vt="-".repeat(64),ne=5;Ks="Re-run dev\u2194docs onboarding (protocol v"});var ra={};Nl(ra,{doctorCommand:()=>Zt,renderDoctorChecks:()=>oa,runDoctorChecks:()=>na});import{existsSync as Zi}from"node:fs";import{d360GetAll as nd,getAccessToken as od,isExpired as Sr,loadProfileMap as rd,loadTokens as sd,packageSkillsDir as ea,projectConfigPath as id,readProjectConfig as ad,DEFAULT_DOCS_DIR as ld,resolveActiveProfile as cd,classifyClaudeAuth as ud,CLAUDE_CODE_SETUP_HINT as ta,resolveModelSetting as dd,probeModel as pd,devHintsGuidePath as fd}from"document360-engine";async function na(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=ud();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. ${ta}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ta});let r=dd(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let w=await pd(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=ad(e);if(!s)return t.push({level:"fail",label:`No ${id(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??ld).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=cd(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 b=sd(f.name);b?Sr(b)&&!b.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Sr(b)?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(b.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=rd(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(Zi(ea())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ea()}`,fix:"Reinstall document360-writer (broken install)"});let A=Ee(e);if((Zi(fd(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)"})),b&&(!Sr(b)||b.refreshToken)){let w={profile:f.name,connection:f.connection};try{await od(w);let P=await nd(w,"/v3/projects");t.push({level:"ok",label:`API reachable (${f.connection.apiUrl}) \u2014 ${P.length} project(s) visible`})}catch(P){t.push({level:"fail",label:`API call failed: ${P.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}}return t}function oa(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?U("\u26A0"):$("\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"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Zt(e,t){console.log(m("Running checks\u2026"));for(let n of oa(await na(t.cwd)))console.log(n);return{kind:"continue"}}var qn=Io(()=>{"use strict";ot();W()});import{Command as If}from"commander";import{createRequire as Nf}from"node:module";import{AUTH_MODES as _f}from"document360-engine";import{input as Jl}from"@inquirer/prompts";import{loginPkce as Ql,refreshTokens as Zl,toStoredTokens as _s,clearTokens as ec,decodeJwtClaims as Ns,isExpired as tc,loadTokens as nc,saveTokens as Os,resolveActiveProfile as $n,setProfileProject as oc,readProjectConfig as rc}from"document360-engine";W();import{select as Ml}from"@inquirer/prompts";import{resolveActiveProfile as Ll,setProfileProject as Wl,resolveProjectId as Fl,listWorkspaces as Hl}from"document360-engine";async function Ht(e,t){let n=Ll(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Fl(o);return{workspaces:await Hl(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Ds=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function No(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 xn(e,t,n,o,r){Wl(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function js(e,t,n){let o;try{o=await Ht(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=No(o.workspaces,t);return r?(xn(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($(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function $t(e,t){let n;try{n=await Ht(e,t)}catch(b){console.log($(`Could not list workspaces: ${b.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 b of o)console.log(` ${b.id===c?O("\u25CF"):" "} ${Ds(b)} ${m(b.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let p=await Ml({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${Ds(b)}${b.id===c?" (current)":""}`,value:b.id}))}),f=o.find(b=>b.id===p);xn(e,s,r,p,f?.name),console.log(E(`\u2713 Workspace set to "${f?.name??p}" for profile "${s}".`))}W();import{select as ql}from"@inquirer/prompts";import{resolveActiveProfile as Bl,setProfileProject as Gl,listProjects as Vl}from"document360-engine";async function tt(e,t){let n=Bl(e,t),o={profile:n.name,connection:n.connection};return{projects:await Vl(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var As=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Es(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 _o(e,t,n,o){Gl(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Is(e,t){let n;try{n=await tt(e,t)}catch(f){console.log($(`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"):" "} ${As(f)} ${m(f.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let c=await ql({message:"Select the Document360 project for this repo:",choices:o.map(f=>({name:`${As(f)}${f.id===s?" (current)":""}`,value:f.id}))}),p=o.find(f=>f.id===c);_o(e,r,c,p?.name),console.log(E(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import Yl from"picocolors";function zl(e=process.env){return e.FORCE_HYPERLINK==="0"||!Yl.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 Kl(e,t=e,n){return zl(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Xl=/https?:\/\/[^\s\x1b]+/g;function qt(e,t){return e.replace(Xl,n=>Kl(n,n,t))}function Us(e){return{...Ns(e.idToken)??{},...Ns(e.accessToken)??{}}}function vn(e){let t=Us(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 Cn(e){let t=$n(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 Ql(n,{manual:e.manual,promptForRedirect:s=>Jl({message:s})},s=>console.log(qt(s))),r=_s(t.name,o);if(Os(r),await Oo(r,t.name,s=>console.log(m(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${vn(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{rc(process.cwd())?.profiles?.[t.name]&&(console.log(""),await $t(process.cwd(),t.name))}catch{}}async function Oo(e,t,n){let r=Us(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if($n(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await tt(process.cwd(),t);c=p.find(f=>f.id===r)?.name}catch{}oc(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Ms(e){let t=$n(process.cwd(),e.profile),n=t.connection,o=nc(t.name);if(!o){console.log($(`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":""}: ${vn(o)}`),tc(o))if(o.refreshToken)try{let r=_s(t.name,await Zl(n,o.refreshToken));Os(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 Ls(e){let t=$n(process.cwd(),e.profile);ec(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 Ws,writeProjectConfig as sc,resolveActiveProfile as ic,loadTokens as ac,isExpired as lc}from"document360-engine";function Pn(e){let t=Ws(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("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=ac(n),f=p?lc(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 Tn(e,t){let n=Ws(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log($(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,sc(n,e);let o=n.profiles[t].production?U(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function Rn(e,t){try{let n=ic(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($(n.message)),process.exitCode=1}}W();import{existsSync as cc,readdirSync as uc,statSync as Fs}from"node:fs";import{join as Hs}from"node:path";import{apiLogDir as dc}from"document360-engine";function qs(){let e=dc();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!cc(e)){console.log(m(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=uc(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=(Fs(Hs(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=(Fs(Hs(e,r)).size/1024).toFixed(1);console.log(` ${$(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 pc,resolveAuth as fc,findByName as mc,slugify as hc,touchSession as gc,upsertSession as wc,resolveActiveProfile as yc}from"document360-engine";async function Bs(e,t,n,o,r,s){let c=fc(n);c.kind==="none"&&(console.error(""),console.error($("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=yc(e,r)}catch(w){console.error($(`Document360 profile error: ${w.message}`)),process.exit(2)}p.production&&(console.error(U(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error($("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=mc(e,o);w||(console.error($(`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 b=pc({cwd:e,resume:f,profileName:r,allowProdWrites:s===!0}),k=f??null,A=1;for await(let w of b.send(t))switch(w.type){case"session":if(!k){k=w.sessionId;let P=new Date().toISOString();wc({uuid:k,name:hc(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}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($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${w.message}`)),process.exit(1)}k&&gc(k),process.stdout.write(`
182
+ `),process.exit(A)}import{createInterface as np}from"node:readline/promises";import{createSession as Br,resolveAuth as op,getSession as rp,setTitle as sp,slugify as ip,touchSession as Da,upsertSession as ap,generateTitle as lp,resolveActiveProfile as ja,resolveModelSetting as cp,readProjectConfig as up,decodeJwtClaims as Ra,isExpired as dp,loadTokens as pp}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 kc(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 Gs(){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(kc(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function Uo(){console.log("");for(let e of Gs())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 bc}from"document360-engine";async function Vs(e,t){let n=t.currentUuid(),o=n?bc(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 Lo(){return{kind:"exit"}}W();ot();import{input as Yt,confirm as Rc}from"@inquirer/prompts";import{basename as ti,join as Nn}from"node:path";import{existsSync as Tt,readFileSync as Sc,readdirSync as Dc,writeFileSync as jc}from"node:fs";import{writeProjectConfig as ni,readProjectConfig as Ac,projectConfigPath as oi,writerDir as Ec,DEFAULT_DOCS_DIR as ri,DEFAULT_CAPTURE_DIR as si,DEFAULT_OUTPUT_DIR as ii}from"document360-engine";function ai(e,t="berlin"){let n=oi(e);if(Tt(n))return{created:!1,path:n,profileName:""};let o={projectId:ui(e)??ti(e),docsDir:ri,captureDir:si,outputDir:ii,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:di(e)};return ni(o,e),li(e),{created:!0,path:n,profileName:t}}function li(e){let t=Nn(Ec(e),".gitignore");Tt(t)||jc(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
187
- `),"utf8")}async function ci(){let e=process.cwd(),t=oi(e);if(Tt(t)&&!await Rc({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(m("init cancelled.")),{kind:"continue"};let n=ui(e)??ti(e),o=await Yt({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Yt({message:"Capture directory (where document360-capture .spec.ts files live):",default:si}),s=await Yt({message:"Screenshot output directory:",default:ii}),c=await Yt({message:"Default connection profile name:",default:"berlin"}),p=await Yt({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),f={projectId:o,docsDir:ri,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:di(e)},b=Ac(e);b?.terminologyGlossary&&(f.terminologyGlossary=b.terminologyGlossary),ni(f,e),li(e);let k=Ct(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 Pt(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 ui(e){let t=Nn(e,"package.json");if(!Tt(t))return null;try{return JSON.parse(Sc(t,"utf8")).name??null}catch{return null}}function di(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Tt(Nn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Nn(e,n);Tt(o)&&!Ic(o)&&t.push(n)}return t}function Ic(e){try{return Dc(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}W();import{readMcpConfig as Ho,writeMcpConfig as pi}from"document360-engine";async function _n(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Nc(),{kind:"continue"}):t==="add"?(_c(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Oc(e.slice(1)),{kind:"continue"}):(console.log($(`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 Nc(){let e=Ho(),t=Object.keys(e.servers);if(t.length===0){console.log(m(`
186
+ `)),{kind:"clear"}}async function Mo(){return{kind:"exit"}}W();ot();import{input as Vt,confirm as Rc}from"@inquirer/prompts";import{basename as ti,join as Nn}from"node:path";import{existsSync as Tt,readFileSync as Sc,readdirSync as Dc,writeFileSync as jc}from"node:fs";import{writeProjectConfig as ni,readProjectConfig as Ac,projectConfigPath as oi,writerDir as Ec,DEFAULT_DOCS_DIR as ri,DEFAULT_CAPTURE_DIR as si,DEFAULT_OUTPUT_DIR as ii}from"document360-engine";function ai(e,t="berlin"){let n=oi(e);if(Tt(n))return{created:!1,path:n,profileName:""};let o={projectId:ui(e)??ti(e),docsDir:ri,captureDir:si,outputDir:ii,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:di(e)};return ni(o,e),li(e),{created:!0,path:n,profileName:t}}function li(e){let t=Nn(Ec(e),".gitignore");Tt(t)||jc(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
187
+ `),"utf8")}async function ci(){let e=process.cwd(),t=oi(e);if(Tt(t)&&!await Rc({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(m("init cancelled.")),{kind:"continue"};let n=ui(e)??ti(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:si}),s=await Vt({message:"Screenshot output directory:",default:ii}),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:ri,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:di(e)},b=Ac(e);b?.terminologyGlossary&&(f.terminologyGlossary=b.terminologyGlossary),ni(f,e),li(e);let k=Ct(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 Pt(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 ui(e){let t=Nn(e,"package.json");if(!Tt(t))return null;try{return JSON.parse(Sc(t,"utf8")).name??null}catch{return null}}function di(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Tt(Nn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Nn(e,n);Tt(o)&&!Ic(o)&&t.push(n)}return t}function Ic(e){try{return Dc(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}W();import{readMcpConfig as Ho,writeMcpConfig as pi}from"document360-engine";async function _n(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Nc(),{kind:"continue"}):t==="add"?(_c(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Oc(e.slice(1)),{kind:"continue"}):(console.log($(`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 Nc(){let e=Ho(),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
- `));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 _c(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log($("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log($(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Ho(),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],b=f?.match(/^([^:=]+)[:=](.+)$/);if(!b){console.log($(`-H expects key:value (no spaces). Got: ${f??"(nothing)"}`));return}c[b[1].trim()]=b[2].trim()}else{console.log($(`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,pi(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 Oc(e){let t=e[0];if(!t){console.log($("Usage: /mcp remove <name>"));return}let n=Ho();if(!n.servers[t]){console.log($(`No server named "${t}".`));return}delete n.servers[t],pi(n),console.log(E(`\u2713 Removed "${t}".`)),console.log(m(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as Jc}from"node:fs";import{join as Qc}from"node:path";import{select as Zc}from"@inquirer/prompts";import{computeSyncStatus as Jo,planPartitions as eu,relatedArticlePaths as tu,resolveModelForOperation as nu,runPartitioned as ou,loadProfileMap as ru,resolveActiveProfile as su,resolveCrossLinks as iu}from"document360-engine";import V from"picocolors";import yi from"wrap-ansi";import zo from"string-width";W();import Fe from"picocolors";import qo from"wrap-ansi";import Bo from"string-width";var fi=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),mi=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),hi=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Uc(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(fi(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&mi(t[o+1])){let p=hi(r);o+=2;let f=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)f.push(hi(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])&&!fi(t[o])&&!(t[o].includes("|")&&o+1<t.length&&mi(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function Go(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 Lc=(e,t)=>e+" ".repeat(Math.max(0,t-Bo(e)));function Mc(e,t,n){let o=e.length,r=e.map((C,R)=>Math.max(Bo(C),...t.map(I=>Bo(I[R]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],f=()=>p.reduce((C,R)=>C+R,0)+c,b=0;for(;f()>s&&b++<1e4;){let C=-1,R=6;for(let I=0;I<o;I++)p[I]>R&&(R=p[I],C=I);if(C===-1)break;p[C]-=1}let k=(C,R,I)=>Fe.gray(C+p.map(H=>"\u2500".repeat(H+2)).join(R)+I),A=Fe.gray("\u2502"),w=(C,R)=>{let I=p.map(($e,ae)=>{let ve=C[ae]??"",le=R?Fe.bold(ve):Go(ve);return qo(le,$e,{hard:!0}).split(`
191
- `)}),H=Math.max(...I.map($e=>$e.length)),se=[];for(let $e=0;$e<H;$e++)se.push(p.map((ae,ve)=>`${A} ${Lc(I[ve][$e]??"",ae)} `).join("")+A);return se.join(`
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 _c(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log($("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log($(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Ho(),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],b=f?.match(/^([^:=]+)[:=](.+)$/);if(!b){console.log($(`-H expects key:value (no spaces). Got: ${f??"(nothing)"}`));return}c[b[1].trim()]=b[2].trim()}else{console.log($(`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,pi(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 Oc(e){let t=e[0];if(!t){console.log($("Usage: /mcp remove <name>"));return}let n=Ho();if(!n.servers[t]){console.log($(`No server named "${t}".`));return}delete n.servers[t],pi(n),console.log(E(`\u2713 Removed "${t}".`)),console.log(m(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as Jc}from"node:fs";import{join as Qc}from"node:path";import{select as Zc}from"@inquirer/prompts";import{computeSyncStatus as Jo,planPartitions as eu,relatedArticlePaths as tu,resolveModelForOperation as nu,runPartitioned as ou,loadProfileMap as ru,resolveActiveProfile as su,resolveCrossLinks as iu}from"document360-engine";import Y from"picocolors";import yi from"wrap-ansi";import zo from"string-width";W();import Fe from"picocolors";import qo from"wrap-ansi";import Bo from"string-width";var fi=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),mi=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),hi=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Uc(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(fi(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&mi(t[o+1])){let p=hi(r);o+=2;let f=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)f.push(hi(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])&&!fi(t[o])&&!(t[o].includes("|")&&o+1<t.length&&mi(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function Go(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 Mc=(e,t)=>e+" ".repeat(Math.max(0,t-Bo(e)));function Lc(e,t,n){let o=e.length,r=e.map((C,R)=>Math.max(Bo(C),...t.map(I=>Bo(I[R]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],f=()=>p.reduce((C,R)=>C+R,0)+c,b=0;for(;f()>s&&b++<1e4;){let C=-1,R=6;for(let I=0;I<o;I++)p[I]>R&&(R=p[I],C=I);if(C===-1)break;p[C]-=1}let k=(C,R,I)=>Fe.gray(C+p.map(H=>"\u2500".repeat(H+2)).join(R)+I),A=Fe.gray("\u2502"),w=(C,R)=>{let I=p.map((ve,ae)=>{let Ce=C[ae]??"",le=R?Fe.bold(Ce):Go(Ce);return qo(le,ve,{hard:!0}).split(`
191
+ `)}),H=Math.max(...I.map(ve=>ve.length)),se=[];for(let ve=0;ve<H;ve++)se.push(p.map((ae,Ce)=>`${A} ${Mc(I[Ce][ve]??"",ae)} `).join("")+A);return se.join(`
192
192
  `)},P=[k("\u250C","\u252C","\u2510"),w(e,!0)];return P.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((C,R)=>{P.push(w(C,!1)),P.push(R===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),P.join(`
193
193
  `)}function Wc(e,t){switch(e.kind){case"heading":return Fe.bold(e.text);case"hr":return Fe.gray("\u2500".repeat(t));case"para":return qo(Go(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=qo(Go(n),Math.max(10,t-4)).split(`
194
194
  `);return" \u2022 "+o+r.map(s=>`
195
195
  `+s).join("")}).join(`
196
196
  `);case"code":return e.lines.map(n=>Fe.gray(" "+n)).join(`
197
- `);case"table":return Mc(e.header,e.rows,t)}}function Yo(e,t){let n=Math.max(20,t);return Uc(e).map(o=>Wc(o,n)).join(`
197
+ `);case"table":return Lc(e.header,e.rows,t)}}function Vo(e,t){let n=Math.max(20,t);return Uc(e).map(o=>Wc(o,n)).join(`
198
198
 
199
- `)}W();import Fc from"picocolors";var Hc=[127,86,217],qc=[22,38,43],gi={T:Hc,E:qc},Vt=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Vo=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Bc=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function wi(){if(!Fc.isColorSupported)return[];let e=Vt[0].length,t=[];for(let n=0;n<Vt.length;n+=2){let o="";for(let r=0;r<e;r++){let s=gi[Vt[n][r]],c=n+1<Vt.length?gi[Vt[n+1][r]]:void 0;s&&c?o+=`${Vo(s)}${Bc(c)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Vo(s)}\u2580\x1B[39m`:c?o+=`${Vo(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function zt(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function de(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function He(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Rt=(e,t)=>` ${e.padEnd(13)}${t}`;function Gc(e,t){let n=[Ft("\u270E document360-writer")+V.gray(` v${e.version}`),V.gray(" Reads your code, writes your docs."),"",Rt("Claude:",`${e.claude}${V.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Rt("Document360:",e.configured?e.loggedOut?V.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?V.gray(` (${e.sessionHint})`):""}`:V.yellow("not set up \u2014 run /init")),Rt("Profile:",e.configured?`${e.profile}${V.gray(` (${e.apiUrl})`)}${e.prod?V.bold(V.yellow(" \u26A0 PRODUCTION")):""}`:V.gray("\u2014 (run /init)")),Rt("Project:",e.project),Rt("Mode:",V.gray(e.mode)),Rt("cwd:",V.gray(e.cwd))],o=wi();if(o.length===0)return n.join(`
199
+ `)}W();import Fc from"picocolors";var Hc=[127,86,217],qc=[22,38,43],gi={T:Hc,E:qc},Yt=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Yo=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Bc=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function wi(){if(!Fc.isColorSupported)return[];let e=Yt[0].length,t=[];for(let n=0;n<Yt.length;n+=2){let o="";for(let r=0;r<e;r++){let s=gi[Yt[n][r]],c=n+1<Yt.length?gi[Yt[n+1][r]]:void 0;s&&c?o+=`${Yo(s)}${Bc(c)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Yo(s)}\u2580\x1B[39m`:c?o+=`${Yo(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function zt(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function de(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function He(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Rt=(e,t)=>` ${e.padEnd(13)}${t}`;function Gc(e,t){let n=[Ft("\u270E document360-writer")+Y.gray(` v${e.version}`),Y.gray(" Reads your code, writes your docs."),"",Rt("Claude:",`${e.claude}${Y.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Rt("Document360:",e.configured?e.loggedOut?Y.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?Y.gray(` (${e.sessionHint})`):""}`:Y.yellow("not set up \u2014 run /init")),Rt("Profile:",e.configured?`${e.profile}${Y.gray(` (${e.apiUrl})`)}${e.prod?Y.bold(Y.yellow(" \u26A0 PRODUCTION")):""}`:Y.gray("\u2014 (run /init)")),Rt("Project:",e.project),Rt("Mode:",Y.gray(e.mode)),Rt("cwd:",Y.gray(e.cwd))],o=wi();if(o.length===0)return n.join(`
200
200
  `);let r=2,s=3,c=zo(o[0]);if(!(t>=r+c+s+Math.max(...n.map(k=>zo(k)))))return[...o.map(k=>" "+k),...n].join(`
201
201
  `);let f=Math.max(0,Math.floor((n.length-o.length)/2)),b=[];for(let k=0;k<Math.max(o.length+f,n.length);k++){let A=o[k-f]??" ".repeat(c);b.push((" ".repeat(r)+A+" ".repeat(s)+(n[k]??"")).trimEnd())}return b.join(`
202
- `)}var Yc={error:V.red,warn:V.yellow,ok:V.green,info:V.gray};function Ko(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Gc(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),c=50,p=e.text.split(`
202
+ `)}var Vc={error:Y.red,warn:Y.yellow,ok:Y.green,info:Y.gray};function Ko(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Gc(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),c=50,p=e.text.split(`
203
203
  `).flatMap(b=>yi(b,s,{hard:!0}).split(`
204
- `)),f=Math.max(0,p.length-c);return f>0&&(p=[...p.slice(0,c),V.dim(`\u2026 +${f} more lines`)]),`
204
+ `)),f=Math.max(0,p.length-c);return f>0&&(p=[...p.slice(0,c),Y.dim(`\u2026 +${f} more lines`)]),`
205
205
  `+p.map((b,k)=>o+(k===0?O(" \u276F "):" ")+b+" ".repeat(Math.max(0,s-zo(b))+1)+r).join(`
206
206
  `)}case"assistant":return`
207
- `+Yo(e.text,n);case"tool":{let o=e.arg!==null?V.gray(`${e.sep}(${e.arg})`):"";return`
208
- `+yi(V.green("\u25CF ")+V.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?V.red:V.gray,r=e.lines.map((s,c)=>o((c===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(V.dim(` \u2026 +${e.hidden} lines`)),r.join(`
209
- `)}case"diff":{let o=c=>c===1?"":"s",s=[V.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(V.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
207
+ `+Vo(e.text,n);case"tool":{let o=e.arg!==null?Y.gray(`${e.sep}(${e.arg})`):"";return`
208
+ `+yi(Y.green("\u25CF ")+Y.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?Y.red:Y.gray,r=e.lines.map((s,c)=>o((c===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(Y.dim(` \u2026 +${e.hidden} lines`)),r.join(`
209
+ `)}case"diff":{let o=c=>c===1?"":"s",s=[Y.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(Y.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
210
210
  `)}case"link":return e.lines.map(o=>O(qt(` \u2B95 ${o}`))).join(`
211
211
  `);case"preview":return`
212
212
  `+Ft(`\u25A3 Preview \u2014 ${e.name}`)+`
213
213
 
214
- `+Yo(e.text,n);case"note":return`
215
- `+Yc[e.tone](qt(e.text));case"done":return`
216
- `+(e.ok?V.magenta("\u2736 "):V.red("\u2736 "))+V.gray(`Cooked for ${zt(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${de(e.costUsd)}`:""))}}function ki(e,t){return e.map(n=>Ko(n,t)).join(`
217
- `)}import{resolveActiveProfile as Vc,loadTokens as zc,isExpired as Kc,decodeJwtClaims as bi}from"document360-engine";function Xc(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ie(e,t){try{let n=Vc(e,t),o=zc(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Kc(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={...bi(o.idToken)??{},...bi(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 ${Xc(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var Kt=3;function Qo(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(`
214
+ `+Vo(e.text,n);case"note":return`
215
+ `+Vc[e.tone](qt(e.text));case"done":return`
216
+ `+(e.ok?Y.magenta("\u2736 "):Y.red("\u2736 "))+Y.gray(`Cooked for ${zt(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${de(e.costUsd)}`:""))}}function ki(e,t){return e.map(n=>Ko(n,t)).join(`
217
+ `)}import{resolveActiveProfile as Yc,loadTokens as zc,isExpired as Kc,decodeJwtClaims as bi}from"document360-engine";function Xc(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ie(e,t){try{let n=Yc(e,t),o=zc(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Kc(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={...bi(o.idToken)??{},...bi(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 ${Xc(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var Kt=3;function Qo(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 xi={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Xt(e){return e.filter(t=>t.path!==null&&t.status in xi&&!t.link).map(t=>({path:t.path,label:xi[t.status]}))}function On(e){return e.filter(t=>t.link).length}function Zo(e,t){try{let n=ru(e,su(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=iu(Jc(Qc(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 au(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 $i(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:`${au(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 Un(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 er(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,P)=>w+o(P),0),p=r.reduce((w,P)=>w+o(P),0),f=n==="api"?`${de(e.reduce((w,P)=>w+P.costUsd,0))} total`:He(e.reduce((w,P)=>w+P.outputTokens,0)),b=`${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)} (${b}) successfully \xB7 ${f}.`),A.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{A.push(`Published ${p}/${k(c)} (${b}) \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 Xo(e,t){let n=eu(t),{model:o}=nu(e.cwd,"standard");console.log(m(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${Kt} 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 ou({cwd:e.cwd,partitions:n,promptFor:s=>Un(s.paths),concurrency:Kt,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($(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let s=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of er(r.results,n,s))console.log(r.ok?E(p):U(p));let c=Zo(e.cwd,e.profileName);c&&console.log(m(c))}}catch(r){console.log($(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Ln(e,t,n){let o=tu(e,n);if(o.length===0)return[];let r=new Set(Xt((await Jo({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function vi(e,t){let n=Ie(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Ln(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 Xo(t,r)}if(o==="--all"){console.log(m("Checking what needs publishing\u2026"));try{let r=await Jo({cwd:t?.cwd??process.cwd()}),s=Xt(r.entries),c=On(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 Xo(t,s.map(p=>p.path)):{kind:"forward-to-agent",prompt:Un(s.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log($(`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 Jo({cwd:t?.cwd??process.cwd()});r=Xt(s.entries);let c=On(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($(`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(()=>Zc({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 Xo(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Qo(o),display:`/publish ${o}`}}async function Jt(){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 lu}from"@inquirer/prompts";import{inventoryRepo as cu,readProjectConfig as Ci,writeProjectConfig as uu}from"document360-engine";function tr(e,t){let n=Ci(e);n&&(n.authoritativeSourceFiles=t,uu(n,e))}function Mn(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 Pi(e,t){let n=t?.cwd??process.cwd();if(!Ci(n))return console.log($("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=cu(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(Mn(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>lu({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Mn(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"};tr(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 hu}from"@inquirer/prompts";import{applyPull as ji,computeSyncStatus as Ai,planPull as gu,establishBaselines as wu,D360AuthError as yu}from"document360-engine";W();var Ti=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/sync pull <path> or /publish <path>):",paint:$,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:$,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:$,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 du(e){return e.path?e.path:`${e.title??"(untitled)"} ${oe(`[${e.articleId}]`)}`}function Wn(e){let t=[],n=e.entries.filter(f=>f.link);if(n.length>0){t.push(""),t.push(Pe("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 Ti){let b=e.entries.filter(k=>k.status===f.status&&!(f.status==="untracked-local"&&k.link));if(b.length!==0){t.push(""),t.push(Pe(f.header));for(let k of b)t.push(` ${f.paint(f.mark)} ${f.paint(du(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,...Ti.map(f=>{let b=(e.counts[f.status]??0)-(f.status==="untracked-local"?c:0);return b>0?`${b} ${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 pu}from"diff";import Ri from"picocolors";var Si=80,fu="\x1B[48;2;74;28;28m",mu="\x1B[48;2;24;66;24m",Di="\x1B[49m",nr=e=>String(e).padStart(5);function rt(e,t,n){let o=w=>{let P=w.replace(/\r\n/g,`
219
+ `)}function er(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,P)=>w+o(P),0),p=r.reduce((w,P)=>w+o(P),0),f=n==="api"?`${de(e.reduce((w,P)=>w+P.costUsd,0))} total`:He(e.reduce((w,P)=>w+P.outputTokens,0)),b=`${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)} (${b}) successfully \xB7 ${f}.`),A.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{A.push(`Published ${p}/${k(c)} (${b}) \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 Xo(e,t){let n=eu(t),{model:o}=nu(e.cwd,"standard");console.log(m(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${Kt} 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 ou({cwd:e.cwd,partitions:n,promptFor:s=>Un(s.paths),concurrency:Kt,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($(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let s=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of er(r.results,n,s))console.log(r.ok?E(p):U(p));let c=Zo(e.cwd,e.profileName);c&&console.log(m(c))}}catch(r){console.log($(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Mn(e,t,n){let o=tu(e,n);if(o.length===0)return[];let r=new Set(Xt((await Jo({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function vi(e,t){let n=Ie(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Mn(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 Xo(t,r)}if(o==="--all"){console.log(m("Checking what needs publishing\u2026"));try{let r=await Jo({cwd:t?.cwd??process.cwd()}),s=Xt(r.entries),c=On(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 Xo(t,s.map(p=>p.path)):{kind:"forward-to-agent",prompt:Un(s.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log($(`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 Jo({cwd:t?.cwd??process.cwd()});r=Xt(s.entries);let c=On(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($(`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(()=>Zc({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 Xo(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Qo(o),display:`/publish ${o}`}}async function Jt(){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 lu}from"@inquirer/prompts";import{inventoryRepo as cu,readProjectConfig as Ci,writeProjectConfig as uu}from"document360-engine";function tr(e,t){let n=Ci(e);n&&(n.authoritativeSourceFiles=t,uu(n,e))}function Ln(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 Pi(e,t){let n=t?.cwd??process.cwd();if(!Ci(n))return console.log($("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=cu(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(Ln(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>lu({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Ln(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"};tr(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 hu}from"@inquirer/prompts";import{applyPull as ji,computeSyncStatus as Ai,planPull as gu,establishBaselines as wu,D360AuthError as yu}from"document360-engine";W();var Ti=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/sync pull <path> or /publish <path>):",paint:$,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:$,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:$,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 du(e){return e.path?e.path:`${e.title??"(untitled)"} ${oe(`[${e.articleId}]`)}`}function Wn(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 Ti){let b=e.entries.filter(k=>k.status===f.status&&!(f.status==="untracked-local"&&k.link));if(b.length!==0){t.push(""),t.push(Te(f.header));for(let k of b)t.push(` ${f.paint(f.mark)} ${f.paint(du(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,...Ti.map(f=>{let b=(e.counts[f.status]??0)-(f.status==="untracked-local"?c:0);return b>0?`${b} ${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 pu}from"diff";import Ri from"picocolors";var Si=80,fu="\x1B[48;2;74;28;28m",mu="\x1B[48;2;24;66;24m",Di="\x1B[49m",nr=e=>String(e).padStart(5);function rt(e,t,n){let o=w=>{let P=w.replace(/\r\n/g,`
221
221
  `);return P.endsWith(`
222
222
  `)||P===""?P:P+`
223
- `},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=pu("a","b",r,s,"","",{context:3}),f=0,b=0,k=[];p.hunks.forEach((w,P)=>{P>0&&k.push(Ri.gray(" \u2026"));let C=w.oldStart,R=w.newStart;for(let I of w.lines){let H=I[0],se=I.slice(1).slice(0,c);H==="-"?(b++,k.push(`${fu}${nr(C++)} - ${se}${Di}`)):H==="+"?(f++,k.push(`${mu}${nr(R++)} + ${se}${Di}`)):(k.push(Ri.gray(nr(R))+" "+se),C++,R++)}});let A=k.slice(0,Si);return{added:f,removed:b,lines:A,hidden:Math.max(0,k.length-Si)}}async function Ei(e,t){let n=Ie(t.cwd,t.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=(e[0]??"status").toLowerCase();try{if(o==="status")return await ku(t.cwd),{kind:"continue"};if(o==="pull")return await xu(t,e.slice(1)),{kind:"continue"};if(o==="baseline")return await bu(t,e.slice(1)),{kind:"continue"};console.log($(`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 yu?console.log($(r.message)):console.log($(`Sync failed: ${r.message}`))}return{kind:"continue"}}async function ku(e){console.log(m("Checking Document360 for drift\u2026"));let t=await Ai({cwd:e});for(let n of Wn(t))console.log(n);console.log("")}async function bu(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 wu({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 xu(e,t){let n=t[0];if(!n){console.log($("Usage: /sync pull <article-path> | --all"));return}let o;if(n==="--all"){if(console.log(m("Checking Document360 for drift\u2026")),o=(await Ai({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(`${Pe(String(o.length))} article(s) are remote-ahead.`)}else o=[n.replace(/\\/g,"/")];for(let r of o){let s=await gu({cwd:e.cwd,relPath:r});console.log(""),console.log(`${O("\u25CF")} ${Pe(s.title)} ${oe(`(${s.path})`)}`);for(let b of s.notes)console.log(U(` \u26A0 ${b}`));s.overwritesLocalChanges&&console.log(U(" \u26A0 This OVERWRITES local edits made since the last sync."));let c=rt(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.")),ji({cwd:e.cwd},s);continue}let p=b=>b===1?"":"s";console.log(oe(` \u23BF Added ${c.added} line${p(c.added)}, removed ${c.removed} line${p(c.removed)}`));for(let b of c.lines)console.log(b);if(c.hidden>0&&console.log(m(` \u2026 +${c.hidden} more diff lines`)),!await e.withPausedInput(()=>hu({message:`Write ${s.path}?`,default:!s.overwritesLocalChanges}))){console.log(m(" Skipped."));continue}ji({cwd:e.cwd},s),console.log(E(` \u2713 Pulled ${s.path} (sync base advanced).`))}console.log("")}W();import{statSync as $u}from"node:fs";import{resolve as vu}from"node:path";import{estimateBulkCost as Cu,planPartitions as Pu,readProjectConfig as Tu,resolveModelForOperation as Ru,runPartitioned as Su,trackedArticlePaths as Du}from"document360-engine";var or=3;function rr(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 sr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function ir(e,t){return t.map(n=>{let o=0;try{o=$u(vu(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ar(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=pu("a","b",r,s,"","",{context:3}),f=0,b=0,k=[];p.hunks.forEach((w,P)=>{P>0&&k.push(Ri.gray(" \u2026"));let C=w.oldStart,R=w.newStart;for(let I of w.lines){let H=I[0],se=I.slice(1).slice(0,c);H==="-"?(b++,k.push(`${fu}${nr(C++)} - ${se}${Di}`)):H==="+"?(f++,k.push(`${mu}${nr(R++)} + ${se}${Di}`)):(k.push(Ri.gray(nr(R))+" "+se),C++,R++)}});let A=k.slice(0,Si);return{added:f,removed:b,lines:A,hidden:Math.max(0,k.length-Si)}}async function Ei(e,t){let n=Ie(t.cwd,t.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=(e[0]??"status").toLowerCase();try{if(o==="status")return await ku(t.cwd),{kind:"continue"};if(o==="pull")return await xu(t,e.slice(1)),{kind:"continue"};if(o==="baseline")return await bu(t,e.slice(1)),{kind:"continue"};console.log($(`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 yu?console.log($(r.message)):console.log($(`Sync failed: ${r.message}`))}return{kind:"continue"}}async function ku(e){console.log(m("Checking Document360 for drift\u2026"));let t=await Ai({cwd:e});for(let n of Wn(t))console.log(n);console.log("")}async function bu(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 wu({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 xu(e,t){let n=t[0];if(!n){console.log($("Usage: /sync pull <article-path> | --all"));return}let o;if(n==="--all"){if(console.log(m("Checking Document360 for drift\u2026")),o=(await Ai({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 gu({cwd:e.cwd,relPath:r});console.log(""),console.log(`${O("\u25CF")} ${Te(s.title)} ${oe(`(${s.path})`)}`);for(let b of s.notes)console.log(U(` \u26A0 ${b}`));s.overwritesLocalChanges&&console.log(U(" \u26A0 This OVERWRITES local edits made since the last sync."));let c=rt(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.")),ji({cwd:e.cwd},s);continue}let p=b=>b===1?"":"s";console.log(oe(` \u23BF Added ${c.added} line${p(c.added)}, removed ${c.removed} line${p(c.removed)}`));for(let b of c.lines)console.log(b);if(c.hidden>0&&console.log(m(` \u2026 +${c.hidden} more diff lines`)),!await e.withPausedInput(()=>hu({message:`Write ${s.path}?`,default:!s.overwritesLocalChanges}))){console.log(m(" Skipped."));continue}ji({cwd:e.cwd},s),console.log(E(` \u2713 Pulled ${s.path} (sync base advanced).`))}console.log("")}W();import{statSync as $u}from"node:fs";import{resolve as vu}from"node:path";import{estimateBulkCost as Cu,planPartitions as Pu,readProjectConfig as Tu,resolveModelForOperation as Ru,runPartitioned as Su,trackedArticlePaths as Du}from"document360-engine";var or=3;function rr(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 sr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function ir(e,t){return t.map(n=>{let o=0;try{o=$u(vu(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ar(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 lr(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: ${de(r)}\u2013${de(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function cr(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),b=e.reduce((C,R)=>C+R.outputTokens,0),k=n==="api"?`${de(f)} total`:He(b),A=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,w=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Converted ${w(c)} (${A}) successfully \xB7 ${k}.`);else{P.push(`Converted ${p}/${w(c)} (${A}) \xB7 ${k}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}async function Ii(e,t){if(!Tu(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=rr(e),r=Du(t.cwd,t.profileName);if(r.length===0)return console.log($("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=sr(r,n);if(s.length===0)return console.log($(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=Pu(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:f,forced:b}=Ru(t.cwd,"light");if(!o){let k=Cu({files:ir(t.cwd,s),op:"convert",model:f});n&&console.log(m(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let A of lr(c,k,or))console.log(A);return console.log(m(`Model: ${f}${b?" (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${or} 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 Su({cwd:t.cwd,partitions:c,promptFor:ar,concurrency:or,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($(` \u2717 ${k.label}`));else if(k.type==="run_done"){console.log("");let A=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let w of cr(k.results,c,A))console.log(k.ok?E(w):U(w))}}catch(k){console.log($(`Convert run failed: ${k.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as Ni}from"node:fs";import{resolve as _i}from"node:path";import{estimateBulkCost as ju,planPartitions as Au,readDocsPlan as Eu,readProjectConfig as Oi,DEFAULT_DOCS_DIR as Iu,resolveModelForOperation as Nu,runPartitioned as _u}from"document360-engine";var Ou=3,Uu=8;function ur(e){return e===void 0||!Number.isFinite(e)?Ou:Math.max(1,Math.min(Math.floor(e),Uu))}function dr(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 Lu(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Mu(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function pr(e,t,n){return n.filter(o=>{try{return Ni(_i(e,t,o)).size===0}catch{return!0}})}function fr(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+=Ni(_i(e,c)).size}catch{}return{path:r,bytes:s}})}function mr(e,t){return`Run the write-article skill to author EACH documentation article listed below. For each path:
229
+ `)}function lr(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: ${de(r)}\u2013${de(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function cr(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),b=e.reduce((C,R)=>C+R.outputTokens,0),k=n==="api"?`${de(f)} total`:He(b),A=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,w=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Converted ${w(c)} (${A}) successfully \xB7 ${k}.`);else{P.push(`Converted ${p}/${w(c)} (${A}) \xB7 ${k}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}async function Ii(e,t){if(!Tu(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=rr(e),r=Du(t.cwd,t.profileName);if(r.length===0)return console.log($("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=sr(r,n);if(s.length===0)return console.log($(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=Pu(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:f,forced:b}=Ru(t.cwd,"light");if(!o){let k=Cu({files:ir(t.cwd,s),op:"convert",model:f});n&&console.log(m(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let A of lr(c,k,or))console.log(A);return console.log(m(`Model: ${f}${b?" (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${or} 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 Su({cwd:t.cwd,partitions:c,promptFor:ar,concurrency:or,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($(` \u2717 ${k.label}`));else if(k.type==="run_done"){console.log("");let A=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let w of cr(k.results,c,A))console.log(k.ok?E(w):U(w))}}catch(k){console.log($(`Convert run failed: ${k.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as Ni}from"node:fs";import{resolve as _i}from"node:path";import{estimateBulkCost as ju,planPartitions as Au,readDocsPlan as Eu,readProjectConfig as Oi,DEFAULT_DOCS_DIR as Iu,resolveModelForOperation as Nu,runPartitioned as _u}from"document360-engine";var Ou=3,Uu=8;function ur(e){return e===void 0||!Number.isFinite(e)?Ou:Math.max(1,Math.min(Math.floor(e),Uu))}function dr(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 Mu(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Lu(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function pr(e,t,n){return n.filter(o=>{try{return Ni(_i(e,t,o)).size===0}catch{return!0}})}function fr(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+=Ni(_i(e,c)).size}catch{}return{path:r,bytes:s}})}function mr(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,26 +234,26 @@ 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 hr(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: ${de(r)}\u2013${de(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function gr(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),b=e.reduce((C,R)=>C+R.outputTokens,0),k=n==="api"?`${de(f)} total`:He(b),A=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,w=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Wrote ${w(c)} (${A}) successfully \xB7 ${k}.`),P.push("Next \u2014 push them to Document360:"),P.push("/publish --all"),P.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{P.push(`Wrote ${p}/${w(c)} (${A}) \xB7 ${k}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}function wr(e,t,n){let o=(Oi(e)?.docsDir??Iu).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Lu(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=Mu(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=pr(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 Ui(e,t){if(!Oi(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=Eu(t.cwd);if(n.length===0)return console.log($("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:c}=dr(e),{docsDir:p,targets:f,reason:b}=wr(t.cwd,n,{scope:o,path:r});if(f.length===0)return console.log(b?U(b):U("Nothing to write.")),{kind:"continue"};let k=Au(f),A=ur(c),{model:w,forced:P}=Nu(t.cwd,"standard");if(s&&!!!r){let R=ju({files:fr(t.cwd,n,f),op:"write",model:w});o&&console.log(m(`Scope: ${o} (${f.length} pending).`));for(let I of hr(k,R,A))console.log(I);return console.log(m(`Model: ${w}${P?" (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 R of _u({cwd:t.cwd,partitions:k,promptFor:I=>mr(I,p),concurrency:A,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:w}))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($(` \u2717 ${R.label}`));else if(R.type==="run_done"){console.log("");let I=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let H of gr(R.results,k,I))console.log(R.ok?E(H):U(H))}}catch(R){console.log($(`Write run failed: ${R.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as Wu,readdirSync as Li,statSync as Mi}from"node:fs";import{join as Wi}from"node:path";import{inputDir as Fu,readProjectConfig as Hu}from"document360-engine";var Fi=/\.(md|markdown|pdf|txt)$/i;function yr(e){let t=Fu(e);if(!Wu(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Li(t)){let s=Wi(t,r),c=!1;try{c=Mi(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=qu(s);p>0&&n.push({name:r,docCount:p})}else Fi.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function qu(e){let t=0;for(let n of Li(e))try{Mi(Wi(e,n)).isFile()&&Fi.test(n)&&t++}catch{}return t}function kr(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 Fn(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 hr(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: ${de(r)}\u2013${de(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function gr(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),b=e.reduce((C,R)=>C+R.outputTokens,0),k=n==="api"?`${de(f)} total`:He(b),A=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,w=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Wrote ${w(c)} (${A}) successfully \xB7 ${k}.`),P.push("Next \u2014 push them to Document360:"),P.push("/publish --all"),P.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{P.push(`Wrote ${p}/${w(c)} (${A}) \xB7 ${k}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}function wr(e,t,n){let o=(Oi(e)?.docsDir??Iu).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Mu(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=Lu(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=pr(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 Ui(e,t){if(!Oi(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=Eu(t.cwd);if(n.length===0)return console.log($("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:c}=dr(e),{docsDir:p,targets:f,reason:b}=wr(t.cwd,n,{scope:o,path:r});if(f.length===0)return console.log(b?U(b):U("Nothing to write.")),{kind:"continue"};let k=Au(f),A=ur(c),{model:w,forced:P}=Nu(t.cwd,"standard");if(s&&!!!r){let R=ju({files:fr(t.cwd,n,f),op:"write",model:w});o&&console.log(m(`Scope: ${o} (${f.length} pending).`));for(let I of hr(k,R,A))console.log(I);return console.log(m(`Model: ${w}${P?" (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 R of _u({cwd:t.cwd,partitions:k,promptFor:I=>mr(I,p),concurrency:A,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:w}))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($(` \u2717 ${R.label}`));else if(R.type==="run_done"){console.log("");let I=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let H of gr(R.results,k,I))console.log(R.ok?E(H):U(H))}}catch(R){console.log($(`Write run failed: ${R.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as Wu,readdirSync as Mi,statSync as Li}from"node:fs";import{join as Wi}from"node:path";import{inputDir as Fu,readProjectConfig as Hu}from"document360-engine";var Fi=/\.(md|markdown|pdf|txt)$/i;function yr(e){let t=Fu(e);if(!Wu(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Mi(t)){let s=Wi(t,r),c=!1;try{c=Li(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=qu(s);p>0&&n.push({name:r,docCount:p})}else Fi.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function qu(e){let t=0;for(let n of Mi(e))try{Li(Wi(e,n)).isFile()&&Fi.test(n)&&t++}catch{}return t}function kr(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 Fn(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 br="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Hi(e,t){let n=t?.cwd??process.cwd();if(!Hu(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=yr(n);if(o.length===0&&r===0)return console.log(m(br)),{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:Fn(p),display:p?`/draft ${p}`:"/draft"}}let c=kr(o,s);return{kind:"forward-to-agent",prompt:Fn(c??"",c?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as Bu,readProjectConfig as Gu}from"document360-engine";function xr(e){try{return Bu(e).filter(t=>t.kind==="request").length}catch{return 0}}function $r(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function vr(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 Cr="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 qi(e,t){let n=t?.cwd??process.cwd();if(!Gu(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=$r(e);if(!r&&xr(n)===0)return console.log(m(Cr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:vr(r,o),display:s}}W();import{search as Yu}from"@inquirer/prompts";import{findByName as Vu,getSession as zu,listSessions as Ku,relativeTime as Gi}from"document360-engine";async function Yi(e,t){let n=Ku(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=Vu(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),Bi(n),{kind:"continue"})}if(!process.stdin.isTTY)return Bi(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Yu({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} ${Gi(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=zu(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Bi(e){console.log("");for(let t of e.slice(0,15))console.log(` ${O(t.name)} ${m(Gi(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Xu}from"document360-engine";function Pr(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 Vi(e,t){let n=Pr(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Xu(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(console.log($("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as zi,readProjectConfig as Ju,writeProjectConfig as Qu}from"document360-engine";W();function Tr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Ju(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 zi().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Qu(o,e),null):`Unknown environment "${r}". Known: ${zi().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function Ki(e,t){let n=e[0];if(!n)return Pn(t.cwd),{kind:"continue"};if(n==="add"){let o=Tr(t.cwd,e[1],e[2]);return o?(console.log($(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 Tn(t.cwd,n),Rn(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Zu}from"@inquirer/prompts";import{readProjectConfig as ed,readUserConfig as Xi,resolveModelSetting as Rr,writeUserConfig as Ji}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 Hn(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 td(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 Qt(e,t){let n=()=>{let s=Rr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Xi();return s.defaultModel?(delete s.defaultModel,Ji(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Rr(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}}Ji({...Xi(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=ed(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 Qi(e,t){let n=e[0]?.trim();if(!n){let c=Rr(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${O(c.model??"Claude Code default")}`),console.log(m(` source: ${td(c)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Hn(c),f;try{f=await t.withPausedInput(()=>Zu({message:`Select model (current: ${c.model??"Claude Code default"})`,default:Re[p].value,choices:Re.map((w,P)=>({name:`${w.label}${P===p?" \u2714":""}`,value:w.value,description:w.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:b,changed:k,effective:A}=Qt(t.cwd,f??"default");for(let w of b)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}=Qt(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"}}qn();async function sa(e,t){return await t.withPausedInput(()=>$t(t.cwd)),{kind:"clear"}}async function ia(e,t){return await t.withPausedInput(()=>Is(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as md}from"document360-engine";async function aa(e,t){let n=!1;try{n=md(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 la=async(e,t)=>{try{await t.withPausedInput(()=>Cn({}))}catch(n){console.log($(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as hd,clearTokens as gd,clearProfileProject as wd}from"document360-engine";async function ca(e,t){let n;try{n=hd(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let o=gd(n);return wd(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 ua}from"node:fs";import{isAbsolute as yd,join as kd,resolve as bd}from"node:path";import{readProjectConfig as xd,screenshotPlaceholderIds as $d,DEFAULT_CAPTURE_DIR as vd,DEFAULT_OUTPUT_DIR as Cd}from"document360-engine";var da=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Dr(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?da(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:da(o),setup:t}:{mode:"single",id:o}}function jr(e,t){let n=xd(e),o=n?.captureDir??vd,r=n?.outputDir??Cd,s=(c,p)=>yd(c)?kd(c,p):bd(e,c,p);return $d(e,{scope:t}).map(({id:c,file:p})=>{let f=ua(s(r,`${c}.png`))?"captured":ua(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:f}})}var Pd={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Td={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Ar(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(` ${Pd[c.state]} ${c.id.padEnd(34)} ${Td[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function pa(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 Cr="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 qi(e,t){let n=t?.cwd??process.cwd();if(!Gu(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=$r(e);if(!r&&xr(n)===0)return console.log(m(Cr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:vr(r,o),display:s}}W();import{search as Vu}from"@inquirer/prompts";import{findByName as Yu,getSession as zu,listSessions as Ku,relativeTime as Gi}from"document360-engine";async function Vi(e,t){let n=Ku(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=Yu(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),Bi(n),{kind:"continue"})}if(!process.stdin.isTTY)return Bi(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Vu({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} ${Gi(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=zu(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Bi(e){console.log("");for(let t of e.slice(0,15))console.log(` ${O(t.name)} ${m(Gi(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Xu}from"document360-engine";function Pr(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 Yi(e,t){let n=Pr(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Xu(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(console.log($("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as zi,readProjectConfig as Ju,writeProjectConfig as Qu}from"document360-engine";W();function Tr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Ju(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 zi().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Qu(o,e),null):`Unknown environment "${r}". Known: ${zi().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function Ki(e,t){let n=e[0];if(!n)return Pn(t.cwd),{kind:"continue"};if(n==="add"){let o=Tr(t.cwd,e[1],e[2]);return o?(console.log($(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 Tn(t.cwd,n),Rn(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Zu}from"@inquirer/prompts";import{readProjectConfig as ed,readUserConfig as Xi,resolveModelSetting as Rr,writeUserConfig as Ji}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 Hn(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 td(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 Qt(e,t){let n=()=>{let s=Rr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Xi();return s.defaultModel?(delete s.defaultModel,Ji(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Rr(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}}Ji({...Xi(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=ed(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 Qi(e,t){let n=e[0]?.trim();if(!n){let c=Rr(t.cwd);if(!process.stdin.isTTY)return console.log(`${Te("Model:")} ${O(c.model??"Claude Code default")}`),console.log(m(` source: ${td(c)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Hn(c),f;try{f=await t.withPausedInput(()=>Zu({message:`Select model (current: ${c.model??"Claude Code default"})`,default:Re[p].value,choices:Re.map((w,P)=>({name:`${w.label}${P===p?" \u2714":""}`,value:w.value,description:w.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:b,changed:k,effective:A}=Qt(t.cwd,f??"default");for(let w of b)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}=Qt(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"}}qn();async function sa(e,t){return await t.withPausedInput(()=>$t(t.cwd)),{kind:"clear"}}async function ia(e,t){return await t.withPausedInput(()=>Is(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as md}from"document360-engine";async function aa(e,t){let n=!1;try{n=md(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 la=async(e,t)=>{try{await t.withPausedInput(()=>Cn({}))}catch(n){console.log($(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as hd,clearTokens as gd,clearProfileProject as wd}from"document360-engine";async function ca(e,t){let n;try{n=hd(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let o=gd(n);return wd(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 ua}from"node:fs";import{isAbsolute as yd,join as kd,resolve as bd}from"node:path";import{readProjectConfig as xd,screenshotPlaceholderIds as $d,DEFAULT_CAPTURE_DIR as vd,DEFAULT_OUTPUT_DIR as Cd}from"document360-engine";var da=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Dr(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?da(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:da(o),setup:t}:{mode:"single",id:o}}function jr(e,t){let n=xd(e),o=n?.captureDir??vd,r=n?.outputDir??Cd,s=(c,p)=>yd(c)?kd(c,p):bd(e,c,p);return $d(e,{scope:t}).map(({id:c,file:p})=>{let f=ua(s(r,`${c}.png`))?"captured":ua(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:f}})}var Pd={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Td={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Ar(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(` ${Pd[c.state]} ${c.id.padEnd(34)} ${Td[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function pa(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 Bn(e,t){let n=Dr(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of Ar(jr(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(`
243
243
  `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as Rd,readFileSync as Sd}from"node:fs";import{isAbsolute as Dd,join as jd,resolve as Ad}from"node:path";import{readProjectConfig as Ed,DEFAULT_CAPTURE_DIR as Id}from"document360-engine";async function en(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-SETUP.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
244
244
  `),display:"/capture-setup"}}var fa="-".repeat(64);function Er(e){let t=Id;try{let k=Ed(e);k?.captureDir&&(t=k.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Dd(t)?jd(t,"CAPTURE-TESTID-REQUESTS.json"):Ad(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Rd(n))return null;let o;try{let k=JSON.parse(Sd(n,"utf8").replace(/^/,""));o=Array.isArray(k?.requests)?k.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(k=>k.file).filter(Boolean)).size,s=o.length,c=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,f=`${t}/CAPTURE-TESTID-REQUESTS.md`,b=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${c} requested across ${p}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",fa,`Read ${f} and ${b}. They list ${c} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",fa]}ot();W();import{listOpenForDocs as Nd,readProjectConfig as _d}from"document360-engine";function Ir(e){try{return Nd(e).length}catch{return 0}}function Nr(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape."," \u2022 answer (a reply to a question you asked; `re` = your question id) \u2192 fold the fact into the affected"," article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only \u2014 do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
245
- `)}async function ma(e,t){let n=t?.cwd??process.cwd();return _d(n)?Ir(n)===0?(console.log(m("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:Nr(),display:"/inbox"}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as Od,listOpenForDocs as Ud,readProjectConfig as Ld}from"document360-engine";function St(e){let t=0,n=0,o=0;try{t=Od(e).length}catch{}try{let r=Ud(e);n=r.filter(s=>s.kind==="request").length,o=r.filter(s=>s.kind==="answer").length}catch{}return{hints:t,requests:n,answers:o}}function Dt(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),t.length?t.join(", "):null}function _r(e){return{publish:e.includes("--publish")}}function Or({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. Trust the inventory first \u2014 call d360_sync_status. If anything is in conflict or remote-ahead, STOP and tell me what to resolve (never write over a copy you can't trust).","2. Gather the pending work: d360_pending_hints (the builder's per-change hints) AND d360_inbox (open requests + answers).","3. Decide the right doc actions across all of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), and fold any answers into the affected article(s) + the architecture brief.","4. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","5. Write/update the articles as drafts, grounded in the cited sources.","6. Close the loop: stamp consumed hints, and mark handled messages status: done with resulting_articles.","7. Push the drafts to Document360.","8. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs \u2014 only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)"];return t.push(e?"9. Then publish the new/updated articles live (publish-to-d360 skill), respecting the production write-guard.":"Leave everything as DRAFTS for review \u2014 do not publish live (run /publish when you want them live)."),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (plus the d360_ask_builder question you left for it)."),t.join(`
246
- `)}async function ha(e,t){let n=t?.cwd??process.cwd();if(!Ld(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ie(n,t?.profileName);if(!o.ok)return console.log($(o.reason)),{kind:"continue"};let{publish:r}=_r(e),s=Dt(St(n));return console.log(m(s?`Catching up on ${s} (+ checking Document360 for drift)\u2026`:"No local queue \u2014 checking for code changes and drift\u2026")),{kind:"forward-to-agent",prompt:Or({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as Md}from"node:child_process";var st="document360-writer",Gn=`npm i -g ${st}@latest`;async function Yn(){let e=process.platform==="win32";return new Promise(t=>{try{let n=Md(`npm i -g ${st}@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 ga(){return console.log(m(`Updating ${st}\u2026`)),(await Yn()).ok?console.log(E("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log($(`Update failed \u2014 run manually: ${Gn}`)),{kind:"continue"}}W();ot();import{existsSync as Ur,rmSync as Wd}from"node:fs";import{basename as wa,resolve as Lr}from"node:path";import{execFileSync as Fd}from"node:child_process";import{input as Hd}from"@inquirer/prompts";import{readProjectConfig as qd,devHintsGuidePath as Bd}from"document360-engine";var Gd=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Yd=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Vn=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),ya=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function ka(e){let t=Vn(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:ya(t)?!0:Yd.has(t)}function Mr(e){let t=null;try{t=qd(e)}catch{t=null}let n=new Set(Gd);for(let o of[Vn(t?.docsDir),Vn(t?.captureDir),Vn(t?.outputDir)])o&&ya(o)&&n.add(o);return[...n].filter(o=>ka(o)&&Ur(Lr(e,o)))}function Wr(e,t){let n=[],o=[];for(let r of t){if(!ka(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Wd(Lr(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function ba(e,t){try{return Fd("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
247
- `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Vd(e){return ba(e,".d360-writer/hints")}function zd(e){return ba(e,".d360-writer/messages")}function Fr(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Vd(e),o=zd(e),r=Ur(Lr(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: ${wa(e)}`]}async function xa(e,t){let n=Mr(t.cwd);for(let f of Fr(t.cwd,n))console.log(n.length===0?m(f):f);if(n.length===0)return{kind:"continue"};let o=wa(t.cwd);if((await t.withPausedInput(()=>Hd({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(U("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Ur(Bd(t.cwd)),{removed:c,failed:p}=Wr(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($(` \u2717 ${f.path}: ${f.error}`));if(s){for(let f of In())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 $a={help:Uo,"?":Uo,clear:Ys,exit:Lo,quit:Lo,init:ci,mcp:_n,publish:vi,audit:Jt,scope:Pi,sync:Ei,convert:Ii,write:Ui,draft:Hi,document:qi,resume:Yi,rename:Vi,profile:Ki,model:Qi,doctor:Zt,workspace:sa,project:ia,"allow-prod":aa,login:la,logout:ca,screenshot:Bn,"capture-setup":en,devhints:Zs,inbox:ma,"catch-up":ha,update:ga,reset:xa};function va(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}ot();W();var Kd={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"},Pa=160,qr=200,Ta=40;function he(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Ca(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),Ta)}`);return t.length>4&&n.push("\u2026"),he(n.join(", "),Pa)}var qe=e=>typeof e=="string"&&e?e:null,Hr=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Xd(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 Jd(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=Xd(t.local_path);return n("Create article",`"${he(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=qe(t.title),r=Hr(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)",Hr(t.article_id)?`id ${Hr(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 zn(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),c=s.join("__");if(r==="document360"){let b=Jd(c,t);if(b)return b}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Ca(t)}}let n=Kd[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:he(o,Pa)}:{title:e,sep:"",arg:Ca(t)}}function Qd(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 Zd(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Qd).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>he(r,qr))]}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),Ta)}`);return n.length>0?[he(n.join(" \xB7 "),qr)]:null}return null}function ep(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 tp(e,t,n){switch(e){case"d360_create_article":{let o=ep(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 Kn(e,t=4,n,o){let r=e.replace(/\r\n/g,`
245
+ `)}async function ma(e,t){let n=t?.cwd??process.cwd();return _d(n)?Ir(n)===0?(console.log(m("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:Nr(),display:"/inbox"}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as Od,listOpenForDocs as Ud,readProjectConfig as Md}from"document360-engine";function St(e){let t=0,n=0,o=0;try{t=Od(e).length}catch{}try{let r=Ud(e);n=r.filter(s=>s.kind==="request").length,o=r.filter(s=>s.kind==="answer").length}catch{}return{hints:t,requests:n,answers:o}}function Dt(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),t.length?t.join(", "):null}function _r(e){return{publish:e.includes("--publish")}}function Or({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. Trust the inventory first \u2014 call d360_sync_status. If anything is in conflict or remote-ahead, STOP and tell me what to resolve (never write over a copy you can't trust).","2. Gather the pending work: d360_pending_hints (the builder's per-change hints) AND d360_inbox (open requests + answers).","3. Decide the right doc actions across all of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), and fold any answers into the affected article(s) + the architecture brief.","4. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","5. Write/update the articles as drafts, grounded in the cited sources.","6. Close the loop: stamp consumed hints, and mark handled messages status: done with resulting_articles.","7. Push the drafts to Document360.","8. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs \u2014 only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)"];return t.push(e?"9. Then publish the new/updated articles live (publish-to-d360 skill), respecting the production write-guard.":"Leave everything as DRAFTS for review \u2014 do not publish live (run /publish when you want them live)."),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (plus the d360_ask_builder question you left for it)."),t.join(`
246
+ `)}async function ha(e,t){let n=t?.cwd??process.cwd();if(!Md(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ie(n,t?.profileName);if(!o.ok)return console.log($(o.reason)),{kind:"continue"};let{publish:r}=_r(e),s=Dt(St(n));return console.log(m(s?`Catching up on ${s} (+ checking Document360 for drift)\u2026`:"No local queue \u2014 checking for code changes and drift\u2026")),{kind:"forward-to-agent",prompt:Or({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as Ld}from"node:child_process";var st="document360-writer",Gn=`npm i -g ${st}@latest`;async function Vn(){let e=process.platform==="win32";return new Promise(t=>{try{let n=Ld(`npm i -g ${st}@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 ga(){return console.log(m(`Updating ${st}\u2026`)),(await Vn()).ok?console.log(E("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log($(`Update failed \u2014 run manually: ${Gn}`)),{kind:"continue"}}W();ot();import{existsSync as Ur,rmSync as Wd}from"node:fs";import{basename as wa,resolve as Mr}from"node:path";import{execFileSync as Fd}from"node:child_process";import{input as Hd}from"@inquirer/prompts";import{readProjectConfig as qd,devHintsGuidePath as Bd}from"document360-engine";var Gd=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Vd=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Yn=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),ya=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function ka(e){let t=Yn(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:ya(t)?!0:Vd.has(t)}function Lr(e){let t=null;try{t=qd(e)}catch{t=null}let n=new Set(Gd);for(let o of[Yn(t?.docsDir),Yn(t?.captureDir),Yn(t?.outputDir)])o&&ya(o)&&n.add(o);return[...n].filter(o=>ka(o)&&Ur(Mr(e,o)))}function Wr(e,t){let n=[],o=[];for(let r of t){if(!ka(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Wd(Mr(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function ba(e,t){try{return Fd("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
247
+ `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Yd(e){return ba(e,".d360-writer/hints")}function zd(e){return ba(e,".d360-writer/messages")}function Fr(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Yd(e),o=zd(e),r=Ur(Mr(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: ${wa(e)}`]}async function xa(e,t){let n=Lr(t.cwd);for(let f of Fr(t.cwd,n))console.log(n.length===0?m(f):f);if(n.length===0)return{kind:"continue"};let o=wa(t.cwd);if((await t.withPausedInput(()=>Hd({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(U("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Ur(Bd(t.cwd)),{removed:c,failed:p}=Wr(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($(` \u2717 ${f.path}: ${f.error}`));if(s){for(let f of In())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 $a={help:Uo,"?":Uo,clear:Vs,exit:Mo,quit:Mo,init:ci,mcp:_n,publish:vi,audit:Jt,scope:Pi,sync:Ei,convert:Ii,write:Ui,draft:Hi,document:qi,resume:Vi,rename:Yi,profile:Ki,model:Qi,doctor:Zt,workspace:sa,project:ia,"allow-prod":aa,login:la,logout:ca,screenshot:Bn,"capture-setup":en,devhints:Zs,inbox:ma,"catch-up":ha,update:ga,reset:xa};function va(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}ot();W();var Kd={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"},Pa=160,qr=200,Ta=40;function he(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Ca(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),Ta)}`);return t.length>4&&n.push("\u2026"),he(n.join(", "),Pa)}var qe=e=>typeof e=="string"&&e?e:null,Hr=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Xd(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 Jd(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=Xd(t.local_path);return n("Create article",`"${he(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=qe(t.title),r=Hr(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)",Hr(t.article_id)?`id ${Hr(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 zn(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),c=s.join("__");if(r==="document360"){let b=Jd(c,t);if(b)return b}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Ca(t)}}let n=Kd[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:he(o,Pa)}:{title:e,sep:"",arg:Ca(t)}}function Qd(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 Zd(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Qd).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>he(r,qr))]}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),Ta)}`);return n.length>0?[he(n.join(" \xB7 "),qr)]:null}return null}function ep(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 tp(e,t,n){switch(e){case"d360_create_article":{let o=ep(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 Kn(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=tp(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let s=Zd(r)??r.split(`
249
249
  `);return{lines:s.slice(0,t).map(c=>he(c,qr)),hidden:Math.max(0,s.length-t)}}function Xn(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Jn(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 Qn(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 fp=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function mp(e,t,n,o){if(fp.test(e))try{let r=ja(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=Jn(t,n),p=Qn(n);e.endsWith("publish_article")&&p&&console.log(O(` \u2B95 Live: ${p}`)),c&&s&&console.log(O(` \u2B95 Preview: ${Xn(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function Aa(e=process.cwd(),t="auto",n){let o=op(t);o.kind==="none"&&(console.error(""),console.error($("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)),hp(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=Br({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=np({input:process.stdin,output:process.stdout}),f=[],b=null,k=!1;p.on("line",P=>{if(b){let C=b;b=null,C(P)}else f.push(P)}),p.on("close",()=>{if(k=!0,b){let P=b;b=null,P(null)}});function A(){return f.length>0?Promise.resolve(f.shift()):k?Promise.resolve(null):(process.stdout.write(O("> ")),new Promise(P=>{b=P}))}let w={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=Br({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setModel:async P=>s.setModel(P),withPausedInput:async P=>{p.pause();try{return await P()}finally{p.resume()}}};try{for(;;){let P=await A();if(P===null)break;let C=P.trim();if(C){if(C.startsWith("/")){let R=va(C);if(!R)continue;let I=$a[R.name];if(!I){console.log($(`Unknown command: /${R.name}`)),console.log(m("Type /help for the list."));continue}let H=await I(R.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=Br({cwd:e,resume:H.uuid,profileName:n,allowProdWrites:r});let se=rp(H.uuid);c={uuid:H.uuid,firstPrompt:se?.firstPrompt??null,titleFired:!0},Da(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 Sa(s,H.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=C),await Sa(s,C,o,c,e)}}}finally{s.close(),p.close()}}function hp(e,t){console.log(""),console.log(Ft("document360-writer")),console.log(m(` cwd: ${e}`));let n=cp(e);if(console.log(m(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(gp(e,t)),!up(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{An(e);for(let o of En(e))console.log(U(` ${o}`))}catch{}try{let o=Dt(St(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 gp(e,t){try{let n=ja(e,t),o=n.production?U(" \u26A0 PRODUCTION"):"",r=pp(n.name);if(!r)return m(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Ra(r.idToken)??{},...Ra(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return dp(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 wp(){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 yp(e,t,n){e.uuid=t;let o=new Date().toISOString();ap({uuid:t,name:ip(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o})}function kp(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||lp(o,t).then(r=>{r&&sp(n,r)}).catch(()=>{})}async function Sa(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))bp(c,o,r,n,s)}function bp(e,t,n,o,r){switch(e.type){case"session":t.uuid||yp(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=zn(e.name,e.input);s&&(process.stdout.write(`
250
250
 
251
- `),console.log(`${E("\u25CF")} ${Pe(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=rt(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=Kn(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?$:oe;c.lines.forEach((f,b)=>console.log(p((b===0?" \u23BF ":" ")+f))),c.hidden>0&&console.log(m(` \u2026 +${c.hidden} lines`)),e.isError||mp(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&&(Da(t.uuid),t.titleFired||kp(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&wp();break}}import{render as Df}from"ink";import{resolveAuth as jf}from"document360-engine";import{useCallback as Y,useEffect as xe,useMemo as Xr,useRef as X,useState as F}from"react";import{Box as te,Text as T,useApp as Op,useInput as Up,useStdout as Lp}from"ink";import{existsSync as jt,readFileSync as Jr,readdirSync as os}from"node:fs";import{spawnSync as Mp}from"node:child_process";import{basename as on,isAbsolute as Wp,join as At}from"node:path";import{createSession as sl,classifyClaudeAuth as rs,CLAUDE_CODE_SETUP_HINT as Fp,loginPkce as Hp,toStoredTokens as qp,saveTokens as Bp,getAccessToken as Gp,resolveActiveProfile as pe,resolveProjectId as Yp,getArticle as Vp,decodeJwtClaims as Et,isExpired as _e,loadTokens as Be,clearTokens as zp,clearProfileProject as Kp,setTitle as Xp,slugify as Jp,touchSession as Qr,upsertSession as Qp,generateTitle as il,findByName as Zp,listSessions as ef,renameSession as tf,suggestNextAction as nf,readProjectConfig as ee,writeProjectConfig as al,resolveModelSetting as ss,loadProfileMap as Zr,applyPull as of,computeSyncStatus as es,planPull as rf,establishBaselines as sf,inventoryRepo as af,knownEnvironments as lf,resolveEnvironment as cf,planPartitions as ts,partitionEvenly as uf,screenshotPlaceholderIds as df,trackedArticlePaths as pf,runPartitioned as ao,estimateBulkCost as ll,resolveModelForOperation as lo,readDocsPlan as cl,checkForUpdate as ff,detectInstallKind as mf,isSelfUpdatable as hf,devHintsGuidePath as ul,toolFeedbackPath as gf,reconcileToolFeedback as wf,DEFAULT_DOCS_DIR as uo,setProfileProject as yf}from"document360-engine";ot();import{spawn as Ea}from"node:child_process";function xp(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function $p(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?Ea([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Ea(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 Ia(e){for(let[t,n]of xp())if(await $p(t,n,e))return!0;return!1}var vp=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Gr(e,t){if(t.closed)return e;let n=e.split(`
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=rt(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=Kn(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?$:oe;c.lines.forEach((f,b)=>console.log(p((b===0?" \u23BF ":" ")+f))),c.hidden>0&&console.log(m(` \u2026 +${c.hidden} lines`)),e.isError||mp(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&&(Da(t.uuid),t.titleFired||kp(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&wp();break}}import{render as Df}from"ink";import{resolveAuth as jf}from"document360-engine";import{useCallback as V,useEffect as $e,useMemo as Xr,useRef as X,useState as F}from"react";import{Box as te,Text as T,useApp as Op,useInput as Up,useStdout as Mp}from"ink";import{existsSync as jt,readFileSync as Jr,readdirSync as os}from"node:fs";import{spawnSync as Lp}from"node:child_process";import{basename as on,isAbsolute as Wp,join as At}from"node:path";import{createSession as sl,classifyClaudeAuth as rs,CLAUDE_CODE_SETUP_HINT as Fp,loginPkce as Hp,toStoredTokens as qp,saveTokens as Bp,getAccessToken as Gp,resolveActiveProfile as pe,resolveProjectId as Vp,getArticle as Yp,decodeJwtClaims as Et,isExpired as _e,loadTokens as Be,clearTokens as zp,clearProfileProject as Kp,setTitle as Xp,slugify as Jp,touchSession as Qr,upsertSession as Qp,generateTitle as il,findByName as Zp,listSessions as ef,renameSession as tf,suggestNextAction as nf,readProjectConfig as ee,writeProjectConfig as al,resolveModelSetting as ss,loadProfileMap as Zr,applyPull as of,computeSyncStatus as es,planPull as rf,establishBaselines as sf,inventoryRepo as af,knownEnvironments as lf,resolveEnvironment as cf,planPartitions as ts,partitionEvenly as uf,screenshotPlaceholderIds as df,trackedArticlePaths as pf,runPartitioned as ao,estimateBulkCost as ll,resolveModelForOperation as lo,readDocsPlan as cl,checkForUpdate as ff,detectInstallKind as mf,isSelfUpdatable as hf,devHintsGuidePath as ul,toolFeedbackPath as gf,reconcileToolFeedback as wf,DEFAULT_DOCS_DIR as uo,setProfileProject as yf}from"document360-engine";ot();import{spawn as Ea}from"node:child_process";function xp(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function $p(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?Ea([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Ea(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 Ia(e){for(let[t,n]of xp())if(await $p(t,n,e))return!0;return!1}var vp=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Gr(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){vp.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 Cp,mkdirSync as Pp,readFileSync as Tp,writeFileSync as Rp}from"node:fs";import{join as Na}from"node:path";import{writerDir as Sp}from"document360-engine";function _a(e){return Na(Sp(e),".sessions")}function Oa(e,t){return Na(_a(e),`${t}.json`)}function Ua(e,t,n){try{Pp(_a(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Rp(Oa(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Yr(e,t){try{let n=Oa(e,t);if(!Cp(n))return[];let o=JSON.parse(Tp(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Dp=e=>`\x1B]0;${e}\x07`,jp=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function La(e){process.stdout.isTTY&&process.stdout.write(e)}function tn(e){La(Dp(e))}function Zn(e){La(jp(e))}var eo=["\xB7 "," \xB7"],Vr="\u{1F7E3}";qn();var to=[{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"}],Ma={"/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 Wa(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Ma[n])return Ma[n];let o=to.find(r=>r.name===t);return o?o.desc:""}function Fa(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return to.filter(n=>n.name.startsWith(t))}function Ha(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as qa,Text as re}from"ink";import{jsx as ie,jsxs as no}from"react/jsx-runtime";function Ap({row:e}){switch(e.t){case"head":return ie(re,{color:M,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 no(re,{children:[ie(re,{color:M,children:`${e.n}. `}),e.s]});case"cmd":return no(re,{children:[" ",ie(re,{color:M,children:e.name.padEnd(20)}),ie(re,{dimColor:!0,children:e.s})]});case"gap":return ie(re,{children:" "})}}function Ba({tab:e,width:t}){let n=Te[e]??Te[0],o="\u2500".repeat(Math.min(Math.max(t-2,20),64));return no(qa,{flexDirection:"column",paddingX:1,children:[no(re,{children:[ie(re,{color:M,bold:!0,children:"Help "}),Te.map((r,s)=>s===e?ie(re,{color:M,bold:!0,inverse:!0,children:` ${r.label} `},r.key):ie(re,{dimColor:!0,children:` ${r.label} `},r.key))]}),ie(re,{color:M,children:o}),ie(qa,{flexDirection:"column",marginTop:1,children:n.rows.map((r,s)=>ie(Ap,{row:r},s))}),ie(re,{dimColor:!0,children:`
254
+ `)}import{existsSync as Cp,mkdirSync as Pp,readFileSync as Tp,writeFileSync as Rp}from"node:fs";import{join as Na}from"node:path";import{writerDir as Sp}from"document360-engine";function _a(e){return Na(Sp(e),".sessions")}function Oa(e,t){return Na(_a(e),`${t}.json`)}function Ua(e,t,n){try{Pp(_a(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Rp(Oa(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Vr(e,t){try{let n=Oa(e,t);if(!Cp(n))return[];let o=JSON.parse(Tp(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Dp=e=>`\x1B]0;${e}\x07`,jp=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Ma(e){process.stdout.isTTY&&process.stdout.write(e)}function tn(e){Ma(Dp(e))}function Zn(e){Ma(jp(e))}var eo=["\xB7 "," \xB7"],Yr="\u{1F7E3}";qn();var to=[{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"}],La={"/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 Wa(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(La[n])return La[n];let o=to.find(r=>r.name===t);return o?o.desc:""}function Fa(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return to.filter(n=>n.name.startsWith(t))}function Ha(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as qa,Text as re}from"ink";import{jsx as ie,jsxs as no}from"react/jsx-runtime";function Ap({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 no(re,{children:[ie(re,{color:L,children:`${e.n}. `}),e.s]});case"cmd":return no(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 Ba({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 no(qa,{flexDirection:"column",paddingX:1,children:[no(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(qa,{flexDirection:"column",marginTop:1,children:n.rows.map((s,c)=>ie(Ap,{row:s},c))}),ie(re,{dimColor:!0,children:`
255
255
  \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var Ep=/^(?:\d+[.)]|[-*•])\s+/;function Ga(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
256
- `)){let c=s.trim().replace(Ep,""),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 b=`/${f[1].toLowerCase()}${f[2]?` ${f[2]}`:""}`;if(r.includes(b)||r.push(b),r.length>=n)break}return r}W();function nn(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 zr(e){return e.replace(/^[\w.-]+\//,"")}var oo=16,Ya={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Kr(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Va(e,t){let n=Kr(t);return e.some(r=>r.trim()===t.trim()||!!n&&Kr(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&Kr(r)===n)):[]}var Ip='\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 Np(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 ro(e){return e===1?"":"s"}function za(e,t,n){return[e,...t.map((o,r)=>` ${r+1} ${o.padEnd(9)} ${Np(o,n)}`),"Or just tell me what to write or update."].join(`
256
+ `)){let c=s.trim().replace(Ep,""),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 b=`/${f[1].toLowerCase()}${f[2]?` ${f[2]}`:""}`;if(r.includes(b)||r.push(b),r.length>=n)break}return r}W();function nn(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 zr(e){return e.replace(/^[\w.-]+\//,"")}var oo=16,Va={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Kr(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Ya(e,t){let n=Kr(t);return e.some(r=>r.trim()===t.trim()||!!n&&Kr(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&Kr(r)===n)):[]}var Ip='\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 Np(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 ro(e){return e===1?"":"s"}function za(e,t,n){return[e,...t.map((o,r)=>` ${r+1} ${o.padEnd(9)} ${Np(o,n)}`),"Or just tell me what to write or update."].join(`
257
257
  `)}function Ka(e){if(!e.ready)return{kind:"idle"};let t=!!e.pendingText;if(!e.hasDocs)return{kind:"noDocs",note:Ip,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${ro(e.pendingWrites)} not written yet \u2014 pick up where you left off:`;return{kind:"actions",note:za(s,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${ro(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${ro(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${ro(e.tracked)} tracked for "${e.profileName}". What next?`;return{kind:"actions",note:za(o,n,t),title:o,options:n}}var _p=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Xa(e){return e.replace(/\r\n?/g,`
258
258
  `)}function Ja(e){return e.includes(`
259
259
  `)||e.length>200}function Qa(e,t){let n=t.split(`
@@ -263,22 +263,22 @@ Articles:
263
263
  `),truncated:c>0||f>0}}}return{text:e,truncated:!1}}function rl(e){let t=!1,n=0,o=0;for(let r of e.split(`
264
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 ns,jsx as j,jsxs as B}from"react/jsx-runtime";var kf={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},dl=` 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 bf(e,t,n,o){let r=rs(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=ss(e),p=ee(e),f=(p?.docsDir??uo).replace(/\/+$/,""),b=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:kf[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:b};if(p===null)return k;try{let A=pe(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=Be(A.name);if(w){let P={...Et(w.idToken)??{},...Et(w.accessToken)??{}},C=P.email??P.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 xf(e,t){try{let n=pe(e,t),o=Be(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Et(o.idToken)??{},...Et(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 pl=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],po=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],$f="Ask me to write or update an article\u2026";function co({ch:e,dim:t}){let[n,o]=F(!0);return xe(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),j(T,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var vf=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function fl(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Cf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ml(e){try{return os(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function hl(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>ml(At(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&ml(At(e,o)))}function Pf({startTime:e,chars:t}){let[n,o]=F(0);xe(()=>{let f=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(f)},[]);let r=po[n%po.length],s=pl[Math.floor(n/16)%pl.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return B(te,{children:[j(T,{color:M,children:` ${r} ${s}\u2026 `}),j(T,{color:"gray",children:`(${zt(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var Tf=12e4;function Rf({p:e}){let[t,n]=F(0);xe(()=>{let I=setInterval(()=>n(H=>H+1),150);return()=>clearInterval(I)},[]);let o=po[t%po.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>=Tf,f=e.verb??"Converting",b=e.unit??"article",k=e.rows.reduce((I,H)=>I+H.items,0),A=f.toLowerCase(),w=e.rows,P=0;if(w.length>oo){let I=w.findIndex(se=>se.status==="active"||se.status==="pending"),H=Math.max(0,Math.min(I-2,w.length-oo));P=w.slice(0,H).filter(se=>se.status==="done").length,w=w.slice(H,H+oo)}let C=Math.min(40,Math.max(...w.map(I=>zr(I.label).length),0)),R=I=>I==="failed"?"red":I==="active"?M:void 0;return B(te,{flexDirection:"column",children:[B(te,{children:[j(T,{color:M,children:` ${o} ${f} ${k} ${b}${k===1?"":"s"} `}),j(T,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${zt(r)} \xB7 esc to stop`})]}),P>0&&j(T,{dimColor:!0,children:` \u2714 +${P} done`}),w.map(I=>B(T,{color:R(I.status),dimColor:I.status==="done"||I.status==="pending",children:[` ${Ya[I.status]} ${zr(I.label).padEnd(C)}`,I.status!=="pending"?` (${I.items} ${b}${I.items===1?"":"s"})`:"",I.status==="active"?` \u2190 ${A}\u2026`:""]},I.label)),p&&j(T,{color:"yellow",children:` \u26A0 no activity for ${zt(s)} \u2014 press esc to stop if it's wedged`})]})}var Sf=10800*1e3;function gl({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Op(),[s,c]=F(n),[p,f]=F(null),[b,k]=F({text:"",pos:0}),A=b.text,w=Y(l=>{k(a=>{let i=typeof l=="function"?l(a.text):l;return{text:i,pos:i.length}})},[]),P=Y(l=>{k(a=>({text:a.text.slice(0,a.pos)+l+a.text.slice(a.pos),pos:a.pos+l.length}))},[]),C=Y(()=>{k(l=>{if(l.pos===0)return l;let a=l.text.slice(0,l.pos),i=el(a)??a.slice(0,-1);return{text:i+l.text.slice(l.pos),pos:i.length}})},[]),[R,I]=F(!1),[H,se]=F(!1),[$e,ae]=F(0),[ve,le]=F(null),[Ge,G]=F([]),it=X(0),[vl,rn]=F(!1),[Cl,sn]=F(!1),[Pl,at]=F(0),Ye=X(0),[It,lt]=F(0),[ct,an]=F(null),cs=X(new Map),Tl=X(0),ut=X([]),ge=X(null);ge.current===null&&(ge.current=sl({cwd:e,profileName:s,allowProdWrites:!1}));let Se=X({uuid:null,firstPrompt:null,titleFired:!1}),ln=X(new Map),dt=X(!1),fo=X([]),Ue=X([]),mo=X(null),[us,pt]=F(null),[Ve,ze]=F(null),[De,ft]=F(null),[Le,mt]=F(null),[ue,ht]=F(null),[we,Ke]=F(null),[Xe,gt]=F(null),[ds,Je]=F(null),[ye,Qe]=F(null),[fe,wt]=F(null),[ps,ho]=F([]),Ze=X([]),Nt=X(!1),ke=X(null),[fs,J]=F(null),cn=X(!1),un=X(null),_t=X(null),[be,et]=F(null),[go,Ot]=F(null),[ms,yt]=F(0),[hs,kt]=F(0),[Rl,gs]=F(0),wo=Xr(()=>{try{return ss(e).model??"auto"}catch{return null}},[e,Rl]),{stdout:Ce}=Lp(),[,Sl]=F(0),ws=X(`${Ce.columns??80}x${Ce.rows??24}`),Me=Y(()=>Math.max(20,(Ce.columns??80)-1),[Ce]),d=Y(l=>{ut.current.push(l),console.log(Ko(l,Me()))},[Me]),[yo,ko]=F(null),bt=Y(l=>{ko(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]),bo=X(!1),xo=Y(async()=>{try{if(bo.current||!hf(mf())||ee(e)?.mode==="engineer")return;let l=await ff({pkg:st,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;bo.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${st} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),sn(!0),(await Yn().finally(()=>sn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),G(i=>i.includes("/exit")?i:[...i,"/exit"])):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${Gn}`})}catch{}},[e,o,d]),$o=Y(l=>{let a=Ie(e,s);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),_t.current=l,G(["/login"]),!1)},[e,s,d]),[vo,Co]=F(null),Ut=X(!0),dn=X(0),Lt=X(0);xe(()=>{let l=setInterval(()=>{if(Ut.current){dn.current=0,Lt.current=0;return}if(!R)try{if(!jt(ul(e)))return;if(Ee(e).status==="current"){Ut.current=!0,dn.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."}),ko(null),le("write the docs for this repo");return}dn.current+=1;let a=dn.current;if((a===4||a%15===0)&&Lt.current<3){Lt.current+=1;let i=Lt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Gt(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${i}`:`\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.${i}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,R,d]),xe(()=>{let l=`d360-writer \xB7 ${us??on(e)}`;if(!R){Zn(0),tn(`${Vr} ${l}`);return}Zn(3);let a=0;tn(`${eo[0]} ${l}`);let i=setInterval(()=>{a=(a+1)%eo.length,tn(`${eo[a]} ${l}`)},400);return()=>clearInterval(i)},[R,e,us]),xe(()=>()=>Zn(0),[]);let Po=Y(l=>{try{let a=ee(e);if(!a)return{kind:"idle"};let i=pe(e,s),g=Be(i.name),u=!!g&&(!_e(g)||!!g.refreshToken),h=!hl(e,a.authoritativeSourceFiles),y=rs(t).state==="missing",v=Zr(e,i.name),D=v?Object.keys(v.articles).length:0,_=At(e,(a.docsDir??uo).replace(/\/+$/,"")),K=!1;try{K=jt(_)&&os(_).length>0}catch{}let Q=0;if(v?.lastAnalyzedCommit)try{let S=Mp("git",["rev-list","--count",`${v.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:3e3});S.status===0&&(Q=parseInt((S.stdout||"").trim(),10)||0)}catch{}let N=0;try{let S=cl(e);if(S.length>0){let L=(a.docsDir??uo).replace(/\/+$/,"");N=pr(e,L,S.map(Z=>Z.path)).length}}catch{}let x={ready:u&&h&&!y,hasDocs:K,tracked:D,pendingText:Dt(St(e)),behind:Q,pendingWrites:N,autoAudit:!!a.autoAudit,profileName:i.name,allowAutoAudit:l};return Ka(x)}catch{return{kind:"idle"}}},[e,s,t]);xe(()=>{d({kind:"banner",info:bf(e,o,t,s)});let l=rs(t).state==="missing";if(l&&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 bf(e,t,n,o){let r=rs(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=ss(e),p=ee(e),f=(p?.docsDir??uo).replace(/\/+$/,""),b=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:kf[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:b};if(p===null)return k;try{let A=pe(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=Be(A.name);if(w){let P={...Et(w.idToken)??{},...Et(w.accessToken)??{}},C=P.email??P.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 xf(e,t){try{let n=pe(e,t),o=Be(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Et(o.idToken)??{},...Et(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 pl=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],po=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],$f="Ask me to write or update an article\u2026";function co({ch:e,dim:t}){let[n,o]=F(!0);return $e(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),j(T,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var vf=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function fl(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Cf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ml(e){try{return os(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function hl(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>ml(At(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&ml(At(e,o)))}function Pf({startTime:e,chars:t}){let[n,o]=F(0);$e(()=>{let f=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(f)},[]);let r=po[n%po.length],s=pl[Math.floor(n/16)%pl.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return B(te,{children:[j(T,{color:L,children:` ${r} ${s}\u2026 `}),j(T,{color:"gray",children:`(${zt(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var Tf=12e4;function Rf({p:e}){let[t,n]=F(0);$e(()=>{let I=setInterval(()=>n(H=>H+1),150);return()=>clearInterval(I)},[]);let o=po[t%po.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>=Tf,f=e.verb??"Converting",b=e.unit??"article",k=e.rows.reduce((I,H)=>I+H.items,0),A=f.toLowerCase(),w=e.rows,P=0;if(w.length>oo){let I=w.findIndex(se=>se.status==="active"||se.status==="pending"),H=Math.max(0,Math.min(I-2,w.length-oo));P=w.slice(0,H).filter(se=>se.status==="done").length,w=w.slice(H,H+oo)}let C=Math.min(40,Math.max(...w.map(I=>zr(I.label).length),0)),R=I=>I==="failed"?"red":I==="active"?L:void 0;return B(te,{flexDirection:"column",children:[B(te,{children:[j(T,{color:L,children:` ${o} ${f} ${k} ${b}${k===1?"":"s"} `}),j(T,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${zt(r)} \xB7 esc to stop`})]}),P>0&&j(T,{dimColor:!0,children:` \u2714 +${P} done`}),w.map(I=>B(T,{color:R(I.status),dimColor:I.status==="done"||I.status==="pending",children:[` ${Va[I.status]} ${zr(I.label).padEnd(C)}`,I.status!=="pending"?` (${I.items} ${b}${I.items===1?"":"s"})`:"",I.status==="active"?` \u2190 ${A}\u2026`:""]},I.label)),p&&j(T,{color:"yellow",children:` \u26A0 no activity for ${zt(s)} \u2014 press esc to stop if it's wedged`})]})}var Sf=10800*1e3;function gl({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Op(),[s,c]=F(n),[p,f]=F(null),[b,k]=F({text:"",pos:0}),A=b.text,w=V(l=>{k(a=>{let i=typeof l=="function"?l(a.text):l;return{text:i,pos:i.length}})},[]),P=V(l=>{k(a=>({text:a.text.slice(0,a.pos)+l+a.text.slice(a.pos),pos:a.pos+l.length}))},[]),C=V(()=>{k(l=>{if(l.pos===0)return l;let a=l.text.slice(0,l.pos),i=el(a)??a.slice(0,-1);return{text:i+l.text.slice(l.pos),pos:i.length}})},[]),[R,I]=F(!1),[H,se]=F(!1),[ve,ae]=F(0),[Ce,le]=F(null),[Ge,G]=F([]),it=X(0),[vl,rn]=F(!1),[Cl,sn]=F(!1),[Pl,at]=F(0),Ve=X(0),[It,lt]=F(0),[ct,an]=F(null),cs=X(new Map),Tl=X(0),ut=X([]),ge=X(null);ge.current===null&&(ge.current=sl({cwd:e,profileName:s,allowProdWrites:!1}));let Se=X({uuid:null,firstPrompt:null,titleFired:!1}),ln=X(new Map),dt=X(!1),fo=X([]),Ue=X([]),mo=X(null),[us,pt]=F(null),[Ye,ze]=F(null),[De,ft]=F(null),[Me,mt]=F(null),[ue,ht]=F(null),[we,Ke]=F(null),[Xe,gt]=F(null),[ds,Je]=F(null),[ye,Qe]=F(null),[fe,wt]=F(null),[ps,ho]=F([]),Ze=X([]),Nt=X(!1),ke=X(null),[fs,J]=F(null),cn=X(!1),un=X(null),_t=X(null),[be,et]=F(null),[go,Ot]=F(null),[ms,yt]=F(0),[hs,kt]=F(0),[Rl,gs]=F(0),wo=Xr(()=>{try{return ss(e).model??"auto"}catch{return null}},[e,Rl]),{stdout:Pe}=Mp(),[,Sl]=F(0),ws=X(`${Pe.columns??80}x${Pe.rows??24}`),Le=V(()=>Math.max(20,(Pe.columns??80)-1),[Pe]),d=V(l=>{ut.current.push(l),console.log(Ko(l,Le()))},[Le]),[yo,ko]=F(null),bt=V(l=>{ko(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]),bo=X(!1),xo=V(async()=>{try{if(bo.current||!hf(mf())||ee(e)?.mode==="engineer")return;let l=await ff({pkg:st,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;bo.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${st} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),sn(!0),(await Vn().finally(()=>sn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),G(i=>i.includes("/exit")?i:[...i,"/exit"])):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${Gn}`})}catch{}},[e,o,d]),$o=V(l=>{let a=Ie(e,s);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),_t.current=l,G(["/login"]),!1)},[e,s,d]),[vo,Co]=F(null),Ut=X(!0),dn=X(0),Mt=X(0);$e(()=>{let l=setInterval(()=>{if(Ut.current){dn.current=0,Mt.current=0;return}if(!R)try{if(!jt(ul(e)))return;if(Ee(e).status==="current"){Ut.current=!0,dn.current=0,Mt.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."}),ko(null),le("write the docs for this repo");return}dn.current+=1;let a=dn.current;if((a===4||a%15===0)&&Mt.current<3){Mt.current+=1;let i=Mt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Gt(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${i}`:`\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.${i}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,R,d]),$e(()=>{let l=`d360-writer \xB7 ${us??on(e)}`;if(!R){Zn(0),tn(`${Yr} ${l}`);return}Zn(3);let a=0;tn(`${eo[0]} ${l}`);let i=setInterval(()=>{a=(a+1)%eo.length,tn(`${eo[a]} ${l}`)},400);return()=>clearInterval(i)},[R,e,us]),$e(()=>()=>Zn(0),[]);let Po=V(l=>{try{let a=ee(e);if(!a)return{kind:"idle"};let i=pe(e,s),g=Be(i.name),u=!!g&&(!_e(g)||!!g.refreshToken),h=!hl(e,a.authoritativeSourceFiles),y=rs(t).state==="missing",v=Zr(e,i.name),D=v?Object.keys(v.articles).length:0,_=At(e,(a.docsDir??uo).replace(/\/+$/,"")),K=!1;try{K=jt(_)&&os(_).length>0}catch{}let Q=0;if(v?.lastAnalyzedCommit)try{let S=Lp("git",["rev-list","--count",`${v.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:3e3});S.status===0&&(Q=parseInt((S.stdout||"").trim(),10)||0)}catch{}let N=0;try{let S=cl(e);if(S.length>0){let M=(a.docsDir??uo).replace(/\/+$/,"");N=pr(e,M,S.map(Z=>Z.path)).length}}catch{}let x={ready:u&&h&&!y,hasDocs:K,tracked:D,pendingText:Dt(St(e)),behind:Q,pendingWrites:N,autoAudit:!!a.autoAudit,profileName:i.name,allowAutoAudit:l};return Ka(x)}catch{return{kind:"idle"}}},[e,s,t]);$e(()=>{d({kind:"banner",info:bf(e,o,t,s)});let l=rs(t).state==="missing";if(l&&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
  ${Fp}
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.)`}),!ee(e)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
269
269
  ${dl}`}),G(l?["/doctor","/init"]:["/init"]);return}l&&G(["/doctor"]);try{let i=pe(e,s),g=Be(i.name);g&&_e(g)&&g.refreshToken?Gp({profile:i.name,connection:i.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),ae(u=>u+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),G(["/login"])}):(!g||_e(g))&&(d({kind:"note",tone:"warn",text:`Profile "${i.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),G(["/login"]))}catch{}try{let i=ee(e),g=pe(e,s),u=Be(g.name);i&&u&&!_e(u)&&hl(e,i.authoritativeSourceFiles)&&(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(An(e),Ee(e).status!=="current")if(Gt(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 i=En(e);i.length&&(d({kind:"note",tone:"warn",text:i.join(`
270
- `)}),bt(nt()),Ut.current=!1)}}catch{}try{let i=wf(e);i.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${i.archived} resolved item${i.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${i.open>0?`; ${i.open} still open`:""}.`})}catch{}let a=Po(!0);a.kind==="autoAudit"?(d({kind:"note",tone:"info",text:a.note}),Jt().then(i=>{i.kind==="forward-to-agent"&&i.prompt&&ce(i.prompt,{display:i.display,quietUser:!0})})):a.kind==="noDocs"?(d({kind:"note",tone:"info",text:a.note}),le(a.ghost),G(a.options),a.title&&Je(a.title)):a.kind==="actions"&&(d({kind:"note",tone:"info",text:a.note}),G(a.options),Je(a.title)),xo()},[]),xe(()=>{let l=setInterval(()=>{xo()},Sf);return()=>clearInterval(l)},[xo]),xe(()=>{if(R||Ge.length>0)return;let l=Po(!1);(l.kind==="actions"||l.kind==="noDocs")&&(G(l.options),Je(l.title??null))},[R,Ge,$e,Po]),xe(()=>{let l=null,a=null,i=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${Ce.columns??80}x${Ce.rows??24}`;g!==ws.current&&(ws.current=g,Sl(u=>u+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+ki(ut.current,Me())+"\x1B[?2026l")},80))},400)};return Ce.on("resize",i),()=>{l&&clearTimeout(l),a&&clearTimeout(a),Ce.off("resize",i)}},[Ce,Me]);let je=Math.max(20,(Ce.columns??80)-1),ys=Xr(()=>xf(e,s),[e,s,$e]),To=(()=>{if(Cl)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};let l=ee(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let a=At(e,(l.docsDir??uo).replace(/\/+$/,"")),i=(()=>{try{return jt(a)&&os(a).length>0}catch{return!1}})();try{let g=pe(e,s),u=Be(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&&!i)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return i?{text:$f,isSetup:!1}:yo?{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}})(),Mt=Fa(A),ks=Mt.length>0&&!R,Ro=p!==null?ol(p,8,je):null,pn=ye?ye.paths.filter(l=>!ye.query||l.toLowerCase().includes(ye.query.toLowerCase())).slice(0,8):[],fn=be?be.sessions.filter(l=>{let a=be.query.toLowerCase();return!a||l.name.toLowerCase().includes(a)||l.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],me=Y((l,a)=>{ge.current?.close(),ge.current=sl({cwd:e,resume:l,profileName:a??s,allowProdWrites:dt.current}),l||(Se.current={uuid:null,firstPrompt:null,titleFired:!1},pt(null)),yt(0),kt(0)},[e,s]),bs=Y((l,a,i)=>{if(vf.test(l))try{let g=pe(e,s),u=typeof a.project_id=="string"&&a.project_id||g.project.projectId,h=Jn(a,i),y=[],v=Qn(i);l.endsWith("publish_article")&&v&&y.push(`Live: ${v}`),h&&u&&y.push(`Preview: ${Xn(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,a)=>{rn(!0),le(null),G([]),Je(null),ko(null),Co(null);let i=++it.current;a?.quietUser||d({kind:"user",text:a?.echoDisplay&&a.display?a.display:l});let g=Se.current;g.firstPrompt||(g.firstPrompt=a?.display??l),Ye.current=Date.now(),at(0),I(!0),ln.current.clear();let u="",h=!1,y=!1,v="",D={num:0,closed:!1,cueSeen:!1},_=null,K=()=>{_||(_=setTimeout(()=>{_=null,f(v.length>0?v:null)},60))},Q=()=>{_&&clearTimeout(_),_=null,f(null)},N=()=>{if(v.trim()){let x=Gr(v.trimEnd(),D);d({kind:"assistant",text:x})}v="",Q()};try{for await(let x of ge.current.send(l))if(x.type==="session"){if(!g.uuid){g.uuid=x.sessionId;let S=new Date().toISOString(),L=Jp(g.firstPrompt??"session");Qp({uuid:x.sessionId,name:L,renamed:!1,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:S,updatedAt:S}),pt(L)}}else if(x.type==="text"){v+=x.delta,u+=x.delta;let S=rl(v);if(S>0){let L=v.slice(0,S).trimEnd();L&&d({kind:"assistant",text:Gr(L,D)}),v=v.slice(S)}K(),at(L=>L+x.delta.length)}else if(x.type==="tool"){h=!0;let S=zn(x.name,x.input);S&&(N(),d({kind:"tool",title:S.title,sep:S.sep,arg:S.arg}),ln.current.set(x.id,{name:x.name,input:x.input}))}else if(x.type==="article_diff"){let S=rt(x.oldContent,x.newContent,Me());S&&(N(),d({kind:"diff",added:S.added,removed:S.removed,lines:S.lines,hidden:S.hidden}))}else if(x.type==="tool_result"){x.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(x.output)&&(cn.current=!0);let S=ln.current.get(x.id);if(S){ln.current.delete(x.id),N();let L=Kn(x.output,4,x.isError?void 0:S.name,S.input);d({kind:"tool-result",lines:L.lines,hidden:L.hidden,isError:x.isError}),x.isError||bs(S.name,S.input,x.output)}}else if(x.type==="result"){if(N(),yt(L=>L+x.outputTokens),kt(L=>L+x.costUsd),d({kind:"done",seconds:Math.round((Date.now()-Ye.current)/1e3),tokens:x.outputTokens,costUsd:x.costUsd,ok:x.ok}),!y&&!h&&!u.trim()&&!Nt.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)."}),x.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let L=gf(e);if(jt(L)){let Z=Jr(L,"utf8").trim();Z&&(Co(Z),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 S=x.ok?Ga(u,to.map(L=>L.name)):[];if(S.length>0?G(S):x.ok&&u.trim()&&nf(l,u,e).then(L=>{L&&it.current===i&&le(L)}).catch(()=>{}),g.uuid&&(Qr(g.uuid),!g.titleFired)){g.titleFired=!0;let L=g.uuid,Z=g.firstPrompt;Z&&il(Z,e).then(q=>{q&&(Xp(L,q),pt(q))}).catch(()=>{})}}else x.type==="error"&&(N(),y=!0,x.kind==="auth"&&(cn.current=!0),d({kind:"note",text:`agent error: ${x.message}`,tone:"error"}))}finally{I(!1),Q(),ae(x=>x+1),Se.current.uuid&&Ua(e,Se.current.uuid,ut.current),cn.current&&(cn.current=!1,un.current=a?.display??l,G(["/login"])),Nt.current&&(Nt.current=!1,Ze.current.length>0&&(d({kind:"note",tone:"info",text:`(${Ze.current.length} queued message(s) discarded)`}),Ze.current=[],ho([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,bs,Me]),mn=Y(async l=>{let a=ts(l),i=lo(e,"standard");Ye.current=Date.now(),at(0),I(!0);let g=new AbortController;ke.current=g,J({verb:"Publishing",total:a.length,done:0,active:[],rows:nn(a),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 ${a.length} partition${a.length===1?"":"s"} (\u2264${Kt} agents at once) on ${i.model}\u2026 (esc to stop)`});try{for await(let u of ao({cwd:e,partitions:a,promptFor:h=>Un(h.paths),concurrency:Kt,profileName:s,allowProdWrites:dt.current,model:i.model,signal:g.signal}))if(u.type==="partition_status")u.status==="running"?J(h=>h&&{...h,active:[...h.active,u.label],rows:Ne(h.rows,u.label,"active"),lastAt:Date.now()}):J(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")J(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"){kt(D=>D+u.totalCostUsd),yt(D=>D+u.results.reduce((_,K)=>_+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+er(u.results,a,y).join(`
271
- `)});let v=Zo(e,s);v&&d({kind:"note",tone:"info",text:v})}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{ke.current=null,J(null),I(!1),ae(u=>u+1)}},[e,s,d,t]),So=Y(async l=>{await ce(Qo(l),{display:`/publish ${l}`,quietUser:!0});try{let a=await Ln(e,s,l.replace(/\\/g,"/"));a.length>0&&(Je(`Related articles not yet published (${a.length}):`),G([`/publish --related ${l}`,...a.map(i=>`/publish ${i}`)]))}catch{}},[e,s,ce]),Do=Y(l=>{let a=Be(l);if(!a||_e(a)&&!a.refreshToken)return null;let i={...Et(a.idToken)??{},...Et(a.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),jo=Y((l,a)=>{if(a){let i=ee(e);i&&(i.defaultProfile=l,al(i,e))}c(l),me(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Do(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(i=>i+1)},[e,d,me,Do]),hn=Y((l,a,i)=>{xn(e,l,a,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),me(),Zr(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:Pt(Ct(e)).join(`
272
- `)}),bt(nt()),Ut.current=Ee(e).status==="current"||Gt(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,bt]),gn=Y(async l=>{let a;try{a=await Ht(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),G(["/workspace"]);return}if(a.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=a.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),g=i.length>0?i:a.workspaces;if(g.length===1){let u=g[0],h=a.workspaces.length-g.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${h>0?" (skipped the API-documentation workspace)":""}.`}),hn(a.profile,a.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),G(["/workspace"])},[e,d,hn]),wn=Y((l,a)=>{_o(e,l,a.id,a.name),d({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),me(),gn(l)},[e,d,me,gn]),xs=Y(async l=>{let a;try{a=pe(e,l)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:i}=await tt(e,a.name),g=i.find(u=>u.id===a.project.projectId);g?.name&&yf(e,a.name,{projectName:g.name})}catch{}await gn(a.name);return}try{let{projects:i}=await tt(e,a.name);if(i.length===1){let g=i[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),wn(a.name,{id:g.id,name:g.name});return}if(i.length>1){let g=i.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?"}),Ke({cursor:0,current:-1,rows:g,profile:a.name,environment:a.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),G(["/project"])}},[e,d,gn,wn]),yn=Y(()=>{let l=Ue.current[0];if(!l)return;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let i of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${i}`});l.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let a=rt(l.oldContent,l.newContent,Me());d(a?{kind:"diff",added:a.added,removed:a.removed,lines:a.lines,hidden:a.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,Me]),$s=Y(l=>{if(Ue.current.length===0)return!1;let a=l.trim().toLowerCase();if(a==="y"||a==="yes"){let i=Ue.current.shift();try{of({cwd:e,profileName:s},i),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${i.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(a==="n"||a==="no"){let i=Ue.current.shift();d({kind:"note",tone:"info",text:`Skipped ${i.path}.`})}else{let i=Ue.current.length;return Ue.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${i} article(s) left untouched).`}),!0}return yn(),!0},[e,s,yn,d]),vs=Y(l=>{let a=mo.current;if(!a)return!1;if(mo.current=null,le(null),it.current++,l.trim()!==a.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:g}=Wr(e,a.targets);d({kind:"note",tone:g.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.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 a.hadDevhints&&(d({kind:"note",tone:"warn",text:In().join(`
270
+ `)}),bt(nt()),Ut.current=!1)}}catch{}try{let i=wf(e);i.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${i.archived} resolved item${i.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${i.open>0?`; ${i.open} still open`:""}.`})}catch{}let a=Po(!0);a.kind==="autoAudit"?(d({kind:"note",tone:"info",text:a.note}),Jt().then(i=>{i.kind==="forward-to-agent"&&i.prompt&&ce(i.prompt,{display:i.display,quietUser:!0})})):a.kind==="noDocs"?(d({kind:"note",tone:"info",text:a.note}),le(a.ghost),G(a.options),a.title&&Je(a.title)):a.kind==="actions"&&(d({kind:"note",tone:"info",text:a.note}),G(a.options),Je(a.title)),xo()},[]),$e(()=>{let l=setInterval(()=>{xo()},Sf);return()=>clearInterval(l)},[xo]),$e(()=>{if(R||Ge.length>0)return;let l=Po(!1);(l.kind==="actions"||l.kind==="noDocs")&&(G(l.options),Je(l.title??null))},[R,Ge,ve,Po]),$e(()=>{let l=null,a=null,i=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${Pe.columns??80}x${Pe.rows??24}`;g!==ws.current&&(ws.current=g,Sl(u=>u+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+ki(ut.current,Le())+"\x1B[?2026l")},80))},400)};return Pe.on("resize",i),()=>{l&&clearTimeout(l),a&&clearTimeout(a),Pe.off("resize",i)}},[Pe,Le]);let je=Math.max(20,(Pe.columns??80)-1),ys=Xr(()=>xf(e,s),[e,s,ve]),To=(()=>{if(Cl)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};let l=ee(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let a=At(e,(l.docsDir??uo).replace(/\/+$/,"")),i=(()=>{try{return jt(a)&&os(a).length>0}catch{return!1}})();try{let g=pe(e,s),u=Be(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&&!i)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return i?{text:$f,isSetup:!1}:yo?{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}})(),Lt=Fa(A),ks=Lt.length>0&&!R,Ro=p!==null?ol(p,8,je):null,pn=ye?ye.paths.filter(l=>!ye.query||l.toLowerCase().includes(ye.query.toLowerCase())).slice(0,8):[],fn=be?be.sessions.filter(l=>{let a=be.query.toLowerCase();return!a||l.name.toLowerCase().includes(a)||l.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],me=V((l,a)=>{ge.current?.close(),ge.current=sl({cwd:e,resume:l,profileName:a??s,allowProdWrites:dt.current}),l||(Se.current={uuid:null,firstPrompt:null,titleFired:!1},pt(null)),yt(0),kt(0)},[e,s]),bs=V((l,a,i)=>{if(vf.test(l))try{let g=pe(e,s),u=typeof a.project_id=="string"&&a.project_id||g.project.projectId,h=Jn(a,i),y=[],v=Qn(i);l.endsWith("publish_article")&&v&&y.push(`Live: ${v}`),h&&u&&y.push(`Preview: ${Xn(g.connection.portalUrl,u,h,g.project.languageCode??"en")}`),y.length>0&&d({kind:"link",lines:y})}catch{}},[e,s,d]),ce=V(async(l,a)=>{rn(!0),le(null),G([]),Je(null),ko(null),Co(null);let i=++it.current;a?.quietUser||d({kind:"user",text:a?.echoDisplay&&a.display?a.display:l});let g=Se.current;g.firstPrompt||(g.firstPrompt=a?.display??l),Ve.current=Date.now(),at(0),I(!0),ln.current.clear();let u="",h=!1,y=!1,v="",D={num:0,closed:!1,cueSeen:!1},_=null,K=()=>{_||(_=setTimeout(()=>{_=null,f(v.length>0?v:null)},60))},Q=()=>{_&&clearTimeout(_),_=null,f(null)},N=()=>{if(v.trim()){let x=Gr(v.trimEnd(),D);d({kind:"assistant",text:x})}v="",Q()};try{for await(let x of ge.current.send(l))if(x.type==="session"){if(!g.uuid){g.uuid=x.sessionId;let S=new Date().toISOString(),M=Jp(g.firstPrompt??"session");Qp({uuid:x.sessionId,name:M,renamed:!1,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:S,updatedAt:S}),pt(M)}}else if(x.type==="text"){v+=x.delta,u+=x.delta;let S=rl(v);if(S>0){let M=v.slice(0,S).trimEnd();M&&d({kind:"assistant",text:Gr(M,D)}),v=v.slice(S)}K(),at(M=>M+x.delta.length)}else if(x.type==="tool"){h=!0;let S=zn(x.name,x.input);S&&(N(),d({kind:"tool",title:S.title,sep:S.sep,arg:S.arg}),ln.current.set(x.id,{name:x.name,input:x.input}))}else if(x.type==="article_diff"){let S=rt(x.oldContent,x.newContent,Le());S&&(N(),d({kind:"diff",added:S.added,removed:S.removed,lines:S.lines,hidden:S.hidden}))}else if(x.type==="tool_result"){x.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(x.output)&&(cn.current=!0);let S=ln.current.get(x.id);if(S){ln.current.delete(x.id),N();let M=Kn(x.output,4,x.isError?void 0:S.name,S.input);d({kind:"tool-result",lines:M.lines,hidden:M.hidden,isError:x.isError}),x.isError||bs(S.name,S.input,x.output)}}else if(x.type==="result"){if(N(),yt(M=>M+x.outputTokens),kt(M=>M+x.costUsd),d({kind:"done",seconds:Math.round((Date.now()-Ve.current)/1e3),tokens:x.outputTokens,costUsd:x.costUsd,ok:x.ok}),!y&&!h&&!u.trim()&&!Nt.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)."}),x.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let M=gf(e);if(jt(M)){let Z=Jr(M,"utf8").trim();Z&&(Co(Z),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 S=x.ok?Ga(u,to.map(M=>M.name)):[];if(S.length>0?G(S):x.ok&&u.trim()&&nf(l,u,e).then(M=>{M&&it.current===i&&le(M)}).catch(()=>{}),g.uuid&&(Qr(g.uuid),!g.titleFired)){g.titleFired=!0;let M=g.uuid,Z=g.firstPrompt;Z&&il(Z,e).then(q=>{q&&(Xp(M,q),pt(q))}).catch(()=>{})}}else x.type==="error"&&(N(),y=!0,x.kind==="auth"&&(cn.current=!0),d({kind:"note",text:`agent error: ${x.message}`,tone:"error"}))}finally{I(!1),Q(),ae(x=>x+1),Se.current.uuid&&Ua(e,Se.current.uuid,ut.current),cn.current&&(cn.current=!1,un.current=a?.display??l,G(["/login"])),Nt.current&&(Nt.current=!1,Ze.current.length>0&&(d({kind:"note",tone:"info",text:`(${Ze.current.length} queued message(s) discarded)`}),Ze.current=[],ho([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,bs,Le]),mn=V(async l=>{let a=ts(l),i=lo(e,"standard");Ve.current=Date.now(),at(0),I(!0);let g=new AbortController;ke.current=g,J({verb:"Publishing",total:a.length,done:0,active:[],rows:nn(a),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 ${a.length} partition${a.length===1?"":"s"} (\u2264${Kt} agents at once) on ${i.model}\u2026 (esc to stop)`});try{for await(let u of ao({cwd:e,partitions:a,promptFor:h=>Un(h.paths),concurrency:Kt,profileName:s,allowProdWrites:dt.current,model:i.model,signal:g.signal}))if(u.type==="partition_status")u.status==="running"?J(h=>h&&{...h,active:[...h.active,u.label],rows:Ne(h.rows,u.label,"active"),lastAt:Date.now()}):J(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")J(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"){kt(D=>D+u.totalCostUsd),yt(D=>D+u.results.reduce((_,K)=>_+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+er(u.results,a,y).join(`
271
+ `)});let v=Zo(e,s);v&&d({kind:"note",tone:"info",text:v})}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{ke.current=null,J(null),I(!1),ae(u=>u+1)}},[e,s,d,t]),So=V(async l=>{await ce(Qo(l),{display:`/publish ${l}`,quietUser:!0});try{let a=await Mn(e,s,l.replace(/\\/g,"/"));a.length>0&&(Je(`Related articles not yet published (${a.length}):`),G([`/publish --related ${l}`,...a.map(i=>`/publish ${i}`)]))}catch{}},[e,s,ce]),Do=V(l=>{let a=Be(l);if(!a||_e(a)&&!a.refreshToken)return null;let i={...Et(a.idToken)??{},...Et(a.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),jo=V((l,a)=>{if(a){let i=ee(e);i&&(i.defaultProfile=l,al(i,e))}c(l),me(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Do(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(i=>i+1)},[e,d,me,Do]),hn=V((l,a,i)=>{xn(e,l,a,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),me(),Zr(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:Pt(Ct(e)).join(`
272
+ `)}),bt(nt()),Ut.current=Ee(e).status==="current"||Gt(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,bt]),gn=V(async l=>{let a;try{a=await Ht(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),G(["/workspace"]);return}if(a.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=a.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),g=i.length>0?i:a.workspaces;if(g.length===1){let u=g[0],h=a.workspaces.length-g.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${h>0?" (skipped the API-documentation workspace)":""}.`}),hn(a.profile,a.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),G(["/workspace"])},[e,d,hn]),wn=V((l,a)=>{_o(e,l,a.id,a.name),d({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),me(),gn(l)},[e,d,me,gn]),xs=V(async l=>{let a;try{a=pe(e,l)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:i}=await tt(e,a.name),g=i.find(u=>u.id===a.project.projectId);g?.name&&yf(e,a.name,{projectName:g.name})}catch{}await gn(a.name);return}try{let{projects:i}=await tt(e,a.name);if(i.length===1){let g=i[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),wn(a.name,{id:g.id,name:g.name});return}if(i.length>1){let g=i.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?"}),Ke({cursor:0,current:-1,rows:g,profile:a.name,environment:a.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),G(["/project"])}},[e,d,gn,wn]),yn=V(()=>{let l=Ue.current[0];if(!l)return;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let i of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${i}`});l.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let a=rt(l.oldContent,l.newContent,Le());d(a?{kind:"diff",added:a.added,removed:a.removed,lines:a.lines,hidden:a.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]),$s=V(l=>{if(Ue.current.length===0)return!1;let a=l.trim().toLowerCase();if(a==="y"||a==="yes"){let i=Ue.current.shift();try{of({cwd:e,profileName:s},i),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${i.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(a==="n"||a==="no"){let i=Ue.current.shift();d({kind:"note",tone:"info",text:`Skipped ${i.path}.`})}else{let i=Ue.current.length;return Ue.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${i} article(s) left untouched).`}),!0}return yn(),!0},[e,s,yn,d]),vs=V(l=>{let a=mo.current;if(!a)return!1;if(mo.current=null,le(null),it.current++,l.trim()!==a.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:g}=Wr(e,a.targets);d({kind:"note",tone:g.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.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 a.hadDevhints&&(d({kind:"note",tone:"warn",text:In().join(`
273
273
  `)}),bt(Fo())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
274
- ${dl}`}),G(["/init"]),rn(!1),!0},[e,d,bt]),Cs=Y(async l=>{let a=l.slice(1).trim().split(/\s+/),i=(a[0]??"").toLowerCase(),g=a.slice(1);switch(rn(!0),i){case"help":Ot({tab:0});return;case"exit":case"quit":ge.current?.close(),r();return;case"clear":me(),ut.current=[],rn(!1),le(null),it.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=pe(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 Hp(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},v=>d({kind:"note",tone:"info",text:v})),y=qp(u.name,h);if(Bp(y),await Oo(y,u.name,v=>d({kind:"note",tone:"info",text:v})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${vn(y)}`}),await xs(s),_t.current){let v=_t.current;_t.current=null;let D=Ie(e,s);D.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${v}.`}),G([v])):(d({kind:"note",tone:"warn",text:`${D.reason} (then ${v}.)`}),G(["/login"]),_t.current=v)}else un.current&&(le(un.current),un.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=pe(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}dt.current=!0,me(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Pr(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??"";il(y,e).then(v=>{v?(le(`/rename ${v}`),d({kind:"note",tone:"info",text:`Suggestion: "${v}" \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}tf(h,u),pt(u),tn(`${Vr} d360-writer \xB7 ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=g[0],h=ee(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 v=y.map(([K,Q])=>({name:K,env:Q.connection?.environment??"custom",prod:Q.production===!0,who:Do(K)})),D=s??h?.defaultProfile,_=Math.max(0,v.findIndex(K=>K.name===D));ft({cursor:_,current:_,rows:v});return}if(u==="add"){let y=Tr(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]}).`}),jo(g[1],!1);return}if(!h?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}jo(u,!0);return}case"doctor":await Zt(g,{cwd:e});return;case"mcp":await _n(g);return;case"init":{if(ee(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=lf().map(h=>({name:h,apiUrl:cf(h).apiUrl}));mt({cursor:0,rows:u});return}case"resume":{let u=g.join(" ").trim(),h=ef(e).filter(D=>D.uuid!==Se.current.uuid);if(!u){if(!h.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}et({query:"",cursor:0,sessions:h});return}let y=Zp(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},pt(y.name),Qr(y.uuid),ut.current=[];let v=Yr(e,y.uuid);for(let D of v)d(D);d({kind:"note",tone:"ok",text:v.length?`Resumed "${y.name}" \u2014 restored ${v.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 Ht(e,s)}catch(v){d({kind:"note",tone:"error",text:`Could not list workspaces: ${v.message}`});return}if(!u){let v=h.workspaces.map(_=>({id:_.id,name:_.name??_.id,type:_.workspace_type}));if(v.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let D=Math.max(0,v.findIndex(_=>_.id===h.current));ht({cursor:D,current:D,rows:v,profile:h.profile,projectId:h.projectId,projectName:h.projectName,environment:h.environment});return}let y=No(h.workspaces,u);if(!y){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}hn(h.profile,h.projectId,y);return}case"project":{let u=g.join(" ").trim(),h;try{h=await tt(e,s)}catch(v){d({kind:"note",tone:"error",text:`Could not list projects: ${v.message} (signed in? try /login)`});return}if(!u){let v=h.projects.map(_=>({id:_.id,name:_.name??_.id,sub:_.sub_domain}));if(v.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let D=v.findIndex(_=>_.id===h.current);Ke({cursor:Math.max(0,D),current:D,rows:v,profile:h.profile,environment:h.environment});return}let y=Es(h.projects,u);if(!y){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${h.projects.map(v=>v.name??v.id).join(", ")}`});return}wn(h.profile,y);return}case"logout":{let u;try{u=pe(e,s).name}catch(y){d({kind:"note",tone:"error",text:y.message});return}let h=zp(u);Kp(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(!$o(l.trim()))return;if(g[0]==="--related"&&g[1]){let h=await Ln(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 mn(h);return}if(g[0]&&g[0]!=="--all"){await So(g[0]);return}let u=g[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let h=await es({cwd:e,profileName:s}),y=Xt(h.entries),v=On(h.entries);if(v>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${v} article${v===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:v>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let D=h.counts["unknown-base"]??0;D>0&&d({kind:"note",tone:"info",text:`(${D} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(u){await mn(y.map(D=>D.path));return}gt({cursor:0,rows:$i(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(Zr(e,pe(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}Qe({query:"",cursor:0,paths:y});return}let h=Wp(u)?u:At(e,u);if(jt(h)){try{d({kind:"preview",name:on(h),text:fl(Jr(h,"utf8"))})}catch(y){d({kind:"note",tone:"error",text:`Could not read ${h}: ${y.message}`})}return}if(Cf.test(u)){try{let y=pe(e,s),v={profile:y.name,connection:y.connection},D=y.project.projectId??Yp(v),_=await Vp(v,D,u);d({kind:"preview",name:_.title??u,text:_.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 D=Hn(ss(e));ze({cursor:D,current:D});return}let{lines:h,changed:y,effective:v}=Qt(e,u);for(let D of h)d({kind:"note",tone:D.startsWith("\u26A0")?"warn":D.startsWith("\u2713")?"ok":"info",text:D});y&&(gs(D=>D+1),ge.current?.setModel(v));return}case"convert":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:h}=rr(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 v=sr(y,u);if(v.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${y.length} are tracked overall.)`});return}let D=ts(v),_=3,K=`/convert${u?` --scope ${u}`:""} --run`,Q=lo(e,"light");if(!h){let x=ll({files:ir(e,v),op:"convert",model:Q.model}),S=u?`Scope: ${u} (${v.length} of ${y.length} tracked)
275
- `:"",L=`
274
+ ${dl}`}),G(["/init"]),rn(!1),!0},[e,d,bt]),Cs=V(async l=>{let a=l.slice(1).trim().split(/\s+/),i=(a[0]??"").toLowerCase(),g=a.slice(1);switch(rn(!0),i){case"help":Ot({tab:0});return;case"exit":case"quit":ge.current?.close(),r();return;case"clear":me(),ut.current=[],rn(!1),le(null),it.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=pe(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 Hp(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},v=>d({kind:"note",tone:"info",text:v})),y=qp(u.name,h);if(Bp(y),await Oo(y,u.name,v=>d({kind:"note",tone:"info",text:v})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${vn(y)}`}),await xs(s),_t.current){let v=_t.current;_t.current=null;let D=Ie(e,s);D.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${v}.`}),G([v])):(d({kind:"note",tone:"warn",text:`${D.reason} (then ${v}.)`}),G(["/login"]),_t.current=v)}else un.current&&(le(un.current),un.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=pe(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}dt.current=!0,me(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Pr(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??"";il(y,e).then(v=>{v?(le(`/rename ${v}`),d({kind:"note",tone:"info",text:`Suggestion: "${v}" \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}tf(h,u),pt(u),tn(`${Yr} d360-writer \xB7 ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=g[0],h=ee(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 v=y.map(([K,Q])=>({name:K,env:Q.connection?.environment??"custom",prod:Q.production===!0,who:Do(K)})),D=s??h?.defaultProfile,_=Math.max(0,v.findIndex(K=>K.name===D));ft({cursor:_,current:_,rows:v});return}if(u==="add"){let y=Tr(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]}).`}),jo(g[1],!1);return}if(!h?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}jo(u,!0);return}case"doctor":await Zt(g,{cwd:e});return;case"mcp":await _n(g);return;case"init":{if(ee(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=lf().map(h=>({name:h,apiUrl:cf(h).apiUrl}));mt({cursor:0,rows:u});return}case"resume":{let u=g.join(" ").trim(),h=ef(e).filter(D=>D.uuid!==Se.current.uuid);if(!u){if(!h.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}et({query:"",cursor:0,sessions:h});return}let y=Zp(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},pt(y.name),Qr(y.uuid),ut.current=[];let v=Vr(e,y.uuid);for(let D of v)d(D);d({kind:"note",tone:"ok",text:v.length?`Resumed "${y.name}" \u2014 restored ${v.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 Ht(e,s)}catch(v){d({kind:"note",tone:"error",text:`Could not list workspaces: ${v.message}`});return}if(!u){let v=h.workspaces.map(_=>({id:_.id,name:_.name??_.id,type:_.workspace_type}));if(v.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let D=Math.max(0,v.findIndex(_=>_.id===h.current));ht({cursor:D,current:D,rows:v,profile:h.profile,projectId:h.projectId,projectName:h.projectName,environment:h.environment});return}let y=No(h.workspaces,u);if(!y){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}hn(h.profile,h.projectId,y);return}case"project":{let u=g.join(" ").trim(),h;try{h=await tt(e,s)}catch(v){d({kind:"note",tone:"error",text:`Could not list projects: ${v.message} (signed in? try /login)`});return}if(!u){let v=h.projects.map(_=>({id:_.id,name:_.name??_.id,sub:_.sub_domain}));if(v.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let D=v.findIndex(_=>_.id===h.current);Ke({cursor:Math.max(0,D),current:D,rows:v,profile:h.profile,environment:h.environment});return}let y=Es(h.projects,u);if(!y){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${h.projects.map(v=>v.name??v.id).join(", ")}`});return}wn(h.profile,y);return}case"logout":{let u;try{u=pe(e,s).name}catch(y){d({kind:"note",tone:"error",text:y.message});return}let h=zp(u);Kp(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(!$o(l.trim()))return;if(g[0]==="--related"&&g[1]){let h=await Mn(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 mn(h);return}if(g[0]&&g[0]!=="--all"){await So(g[0]);return}let u=g[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let h=await es({cwd:e,profileName:s}),y=Xt(h.entries),v=On(h.entries);if(v>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${v} article${v===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:v>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let D=h.counts["unknown-base"]??0;D>0&&d({kind:"note",tone:"info",text:`(${D} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(u){await mn(y.map(D=>D.path));return}gt({cursor:0,rows:$i(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(Zr(e,pe(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}Qe({query:"",cursor:0,paths:y});return}let h=Wp(u)?u:At(e,u);if(jt(h)){try{d({kind:"preview",name:on(h),text:fl(Jr(h,"utf8"))})}catch(y){d({kind:"note",tone:"error",text:`Could not read ${h}: ${y.message}`})}return}if(Cf.test(u)){try{let y=pe(e,s),v={profile:y.name,connection:y.connection},D=y.project.projectId??Vp(v),_=await Yp(v,D,u);d({kind:"preview",name:_.title??u,text:_.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 D=Hn(ss(e));ze({cursor:D,current:D});return}let{lines:h,changed:y,effective:v}=Qt(e,u);for(let D of h)d({kind:"note",tone:D.startsWith("\u26A0")?"warn":D.startsWith("\u2713")?"ok":"info",text:D});y&&(gs(D=>D+1),ge.current?.setModel(v));return}case"convert":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:h}=rr(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 v=sr(y,u);if(v.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${y.length} are tracked overall.)`});return}let D=ts(v),_=3,K=`/convert${u?` --scope ${u}`:""} --run`,Q=lo(e,"light");if(!h){let x=ll({files:ir(e,v),op:"convert",model:Q.model}),S=u?`Scope: ${u} (${v.length} of ${y.length} tracked)
275
+ `:"",M=`
276
276
  Model: ${Q.model}${Q.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:S+lr(D,x,_).join(`
277
- `)+L}),G([K]);return}Ye.current=Date.now(),at(0),I(!0);let N=new AbortController;ke.current=N,J({verb:"Converting",total:D.length,done:0,active:[],rows:nn(D),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${v.length} articles across ${D.length} partitions (\u2264${_} agents at once) on ${Q.model}\u2026 (esc to stop)`});try{for await(let x of ao({cwd:e,partitions:D,promptFor:ar,concurrency:_,profileName:s,allowProdWrites:dt.current,model:Q.model,signal:N.signal}))if(x.type==="partition_status")x.status==="running"?J(S=>S&&{...S,active:[...S.active,x.label],rows:Ne(S.rows,x.label,"active"),lastAt:Date.now()}):J(S=>S&&{...S,active:S.active.filter(L=>L!==x.label),done:S.done+1,rows:Ne(S.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_event")J(S=>{if(!S)return S;let L={...S,lastAt:Date.now()};return x.event.type==="tool"?L.tools=S.tools+1:x.event.type==="text"&&(L.chars=S.chars+x.event.delta.length),L});else if(x.type==="run_done"){kt(Z=>Z+x.totalCostUsd),yt(Z=>Z+x.results.reduce((q,z)=>q+z.outputTokens,0));let S=x.aborted?"Stopped. ":"",L=t.kind==="api"?"api":"subscription";d({kind:"note",tone:x.aborted?"warn":x.ok?"ok":"warn",text:S+cr(x.results,D,L).join(`
277
+ `)+M}),G([K]);return}Ve.current=Date.now(),at(0),I(!0);let N=new AbortController;ke.current=N,J({verb:"Converting",total:D.length,done:0,active:[],rows:nn(D),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${v.length} articles across ${D.length} partitions (\u2264${_} agents at once) on ${Q.model}\u2026 (esc to stop)`});try{for await(let x of ao({cwd:e,partitions:D,promptFor:ar,concurrency:_,profileName:s,allowProdWrites:dt.current,model:Q.model,signal:N.signal}))if(x.type==="partition_status")x.status==="running"?J(S=>S&&{...S,active:[...S.active,x.label],rows:Ne(S.rows,x.label,"active"),lastAt:Date.now()}):J(S=>S&&{...S,active:S.active.filter(M=>M!==x.label),done:S.done+1,rows:Ne(S.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_event")J(S=>{if(!S)return S;let M={...S,lastAt:Date.now()};return x.event.type==="tool"?M.tools=S.tools+1:x.event.type==="text"&&(M.chars=S.chars+x.event.delta.length),M});else if(x.type==="run_done"){kt(Z=>Z+x.totalCostUsd),yt(Z=>Z+x.results.reduce((q,z)=>q+z.outputTokens,0));let S=x.aborted?"Stopped. ":"",M=t.kind==="api"?"api":"subscription";d({kind:"note",tone:x.aborted?"warn":x.ok?"ok":"warn",text:S+cr(x.results,D,M).join(`
278
278
  `)})}}catch(x){d({kind:"note",tone:"error",text:`Convert run failed: ${x.message}`})}finally{ke.current=null,J(null),I(!1),ae(x=>x+1)}return}case"write":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=cl(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:v,concurrency:D}=dr(g),{docsDir:_,targets:K,reason:Q}=wr(e,u,{scope:h,path:y});if(K.length===0){d({kind:"note",tone:"warn",text:Q??"Nothing to write."});return}let N=ts(K),x=ur(D),S=lo(e,"standard");if(v&&!!!y){let q=ll({files:fr(e,u,K),op:"write",model:S.model}),z=h?`Scope: ${h} (${K.length} pending)
279
279
  `:"",Ae=`
280
280
  Model: ${S.model}${S.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:z+hr(N,q,x).join(`
281
- `)+Ae}),G([`/write${h?` --scope ${h}`:""}`]);return}Ye.current=Date.now(),at(0),I(!0);let Z=new AbortController;ke.current=Z,J({verb:"Writing",total:N.length,done:0,active:[],rows:nn(N),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 ${N.length} partition${N.length===1?"":"s"} (\u2264${x} agents at once) on ${S.model}${S.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let q of ao({cwd:e,partitions:N,promptFor:z=>mr(z,_),concurrency:x,profileName:s,allowProdWrites:dt.current,model:S.model,signal:Z.signal}))if(q.type==="partition_status")q.status==="running"?J(z=>z&&{...z,active:[...z.active,q.label],rows:Ne(z.rows,q.label,"active"),lastAt:Date.now()}):J(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")J(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"){kt(Eo=>Eo+q.totalCostUsd),yt(Eo=>Eo+q.results.reduce((Al,El)=>Al+El.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+gr(q.results,N,Ae).join(`
281
+ `)+Ae}),G([`/write${h?` --scope ${h}`:""}`]);return}Ve.current=Date.now(),at(0),I(!0);let Z=new AbortController;ke.current=Z,J({verb:"Writing",total:N.length,done:0,active:[],rows:nn(N),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 ${N.length} partition${N.length===1?"":"s"} (\u2264${x} agents at once) on ${S.model}${S.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let q of ao({cwd:e,partitions:N,promptFor:z=>mr(z,_),concurrency:x,profileName:s,allowProdWrites:dt.current,model:S.model,signal:Z.signal}))if(q.type==="partition_status")q.status==="running"?J(z=>z&&{...z,active:[...z.active,q.label],rows:Ne(z.rows,q.label,"active"),lastAt:Date.now()}):J(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")J(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"){kt(Eo=>Eo+q.totalCostUsd),yt(Eo=>Eo+q.results.reduce((Al,El)=>Al+El.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+gr(q.results,N,Ae).join(`
282
282
  `)}),!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,J(null),I(!1),ae(q=>q+1)}return}case"draft":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:h}=yr(e);if(u.length===0&&h===0){d({kind:"note",tone:"info",text:br});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
283
  ${u.map(_=>` \u2022 ${_.name} (${_.docCount} doc${_.docCount===1?"":"s"})`).join(`
284
284
  `)}`}),G(u.map(_=>`/draft ${_.name}`));return}let v="",D;if(y){let _=kr(u,y);_?v=_:D=y}else v=u[0]?.name??"";await ce(Fn(v,D),{display:y?`/draft ${y}`:"/draft",quietUser:!0});return}case"sync":{if(!$o(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 es({cwd:e,profileName:s});d({kind:"note",tone:"info",text:Wn(h).join(`
@@ -286,12 +286,12 @@ ${u.map(_=>` \u2022 ${_.name} (${_.docCount} doc${_.docCount===1?"":"s"})`).joi
286
286
  ${v.skipped.map(D=>` - ${D.path} (${D.reason})`).join(`
287
287
  `)}`}),ae(D=>D+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(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=af(e);if(u.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}wt({cursor:0,rows:u.map(h=>({...h,checked:h.recommended}))});return}case"audit":{if(g[0]==="--auto"){let h=ee(e);if(!h){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=g[1]!=="off";al({...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 Jt();u.kind==="forward-to-agent"&&u.prompt&&await ce(u.prompt,{display:u.display,quietUser:!0});return}case"capture-setup":{let u=await en();u.kind==="forward-to-agent"&&u.prompt&&await ce(u.prompt,{display:u.display,quietUser:!0});let h=Er(e);h&&d({kind:"note",tone:"info",text:h.join(`
288
288
  `)});return}case"devhints":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Pt(Ct(e)).join(`
289
- `)}),bt(nt()),Ut.current=Ee(e).status==="current"||Gt(e);return}case"inbox":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Ir(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(Nr(),{display:"/inbox",quietUser:!0});return}case"document":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:h}=$r(g);if(!h&&xr(e)===0){d({kind:"note",tone:"info",text:Cr});return}let y=`/document${h?` ${h}`:""}${u?" --publish":""}`;await ce(vr(h,u),{display:y,quietUser:!0});return}case"catch-up":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!$o(l.trim()))return;let{publish:u}=_r(g),h=Dt(St(e));d({kind:"note",tone:"info",text:h?`Catching up on ${h} (+ checking Document360 for drift)\u2026`:"No local queue \u2014 checking for code changes and drift\u2026"}),await ce(Or({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{bo.current=!0,d({kind:"note",tone:"info",text:`Updating ${st}\u2026 (don\u2019t close this window)`}),sn(!0),(await Yn().finally(()=>sn(!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"])):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Gn}`});return}case"screenshot":{let u=Dr(g);if(u.mode==="list"){if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Ar(jr(e,u.scope),u.scope).join(`
290
- `)});return}if(u.mode==="single"){let N=await Bn(g);N.kind==="forward-to-agent"&&N.prompt&&await ce(N.prompt,{display:N.display,quietUser:!0});return}if(!ee(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=df(e,{scope:h}).map(N=>N.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 v=6,D=uf(y,3),_=lo(e,"standard");Ye.current=Date.now(),at(0),I(!0);let K=new AbortController;ke.current=K,J({verb:"Authoring",unit:"spec",total:D.length,done:0,active:[],rows:nn(D),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 ${D.length} partition${D.length===1?"":"s"} (\u2264${v} agents at once) on ${_.model}${_.forced?" (forced)":""}\u2026 (esc to stop)`});let Q=!1;try{for await(let N of ao({cwd:e,partitions:D,promptFor:pa,concurrency:v,profileName:s,allowProdWrites:dt.current,model:_.model,signal:K.signal}))if(N.type==="partition_status")N.status==="running"?J(x=>x&&{...x,active:[...x.active,N.label],rows:Ne(x.rows,N.label,"active"),lastAt:Date.now()}):J(x=>x&&{...x,active:x.active.filter(S=>S!==N.label),done:x.done+1,rows:Ne(x.rows,N.label,N.status==="done"?"done":"failed"),lastAt:Date.now()});else if(N.type==="partition_event")J(x=>{if(!x)return x;let S={...x,lastAt:Date.now()};return N.event.type==="tool"?S.tools=x.tools+1:N.event.type==="text"&&(S.chars=x.chars+N.event.delta.length),S});else if(N.type==="run_done"){kt(Z=>Z+N.totalCostUsd),yt(Z=>Z+N.results.reduce((q,z)=>q+z.outputTokens,0));let x=N.results.filter(Z=>Z.ok).length,S=N.aborted?"Stopped. ":"";Q=!N.aborted&&u.setup;let L=N.aborted?"":Q?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:N.aborted?"warn":N.ok?"ok":"warn",text:`${S}Authored specs \u2014 ${x}/${N.results.length} batches ok.${L}`})}}catch(N){d({kind:"note",tone:"error",text:`Spec authoring failed: ${N.message}`})}finally{ke.current=null,J(null),I(!1),ae(N=>N+1)}if(Q){let N=await en();N.kind==="forward-to-agent"&&N.prompt&&await ce(N.prompt,{display:N.display,quietUser:!0});let x=Er(e);x&&d({kind:"note",tone:"info",text:x.join(`
291
- `)})}return}case"reset":{let u=Mr(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}mo.current={repoName:on(e),targets:u,hadDevhints:jt(ul(e))},d({kind:"note",tone:"warn",text:Fr(e,u).join(`
292
- `)}),le(on(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,yn,d,me,ce,mn,So,xs]),kn=Y(l=>{let a=(l??A).trim();if(w(""),an(null),lt(0),a.startsWith("/")&&(le(null),it.current++,Je(null),G(g=>Va(g,a))),!a||vs(a)||$s(a))return;fo.current.push(a);let i=Za(a,cs.current);a.startsWith("/")?(d({kind:"user",text:a}),Cs(i)):ce(i,{display:a})},[A,vs,$s,Cs,ce]),Ps=Y(l=>{if(l.length>1){if(l.includes("\x1B"))return;let a=Xa(l);if(Ja(a)){let i=Qa(++Tl.current,a);cs.current.set(i,a),P(i)}else P(a);return}P(l)},[P]),xt=Math.max(10,je-6),Ts=Xr(()=>so(b.text,xt),[b.text,xt]),Ao=Y(l=>k(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+l))})),[]),bn=Y(l=>k(a=>({...a,pos:tl(so(a.text,xt),a.pos,l)})),[xt]),Wt=Y(l=>k(a=>({...a,pos:nl(so(a.text,xt),a.pos,l)})),[xt]),Dl=["\x1B[H","\x1B[1~","\x1BOH"],jl=["\x1B[F","\x1B[4~","\x1BOF"],Rs=Y((l,a)=>a.leftArrow?(Ao(-1),!0):a.rightArrow?(Ao(1),!0):l&&Dl.includes(l)?(Wt("start"),!0):l&&jl.includes(l)?(Wt("end"),!0):a.ctrl&&l==="a"?(Wt("start"),!0):a.ctrl&&l==="e"?(Wt("end"),!0):!1,[Ao,Wt]);return Up((l,a)=>{if(a.ctrl&&l==="c"){ge.current?.close(),r();return}if(!H){if(R){if(a.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}Nt.current||(Nt.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),ge.current?.interrupt());return}if(a.return){let i=A.trim();if(!i)return;Ze.current.push(i),ho([...Ze.current]),w("");return}if(Rs(l,a))return;if(a.upArrow){bn(-1);return}if(a.downArrow){bn(1);return}if(a.backspace||a.delete){C();return}l&&!a.ctrl&&!a.meta&&Ps(l);return}if(Ve){if(a.upArrow){ze(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ze(i=>i&&{...i,cursor:Math.min(Re.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.length){ze(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=Re[Ve.cursor];ze(null);let{lines:g,changed:u,effective:h}=Qt(e,i.value??"default");for(let y of g)d({kind:"note",tone:y.startsWith("\u26A0")?"warn":y.startsWith("\u2713")?"ok":"info",text:y});u&&(gs(y=>y+1),ge.current?.setModel(h));return}if(l==="s"){let i=Re[Ve.cursor];ze(null),ge.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){ze(null);return}return}if(De){if(a.upArrow){ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ft(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=De.rows.length){ft(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return||l==="s"){let i=De.rows[De.cursor];ft(null),jo(i.name,a.return===!0);return}if(a.escape){ft(null);return}return}if(go){if(a.escape){Ot(null);return}if(a.leftArrow||a.tab&&a.shift){Ot(i=>i&&{tab:(i.tab-1+Te.length)%Te.length});return}if(a.rightArrow||a.tab){Ot(i=>i&&{tab:(i.tab+1)%Te.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Te.length){Ot({tab:Number(l)-1});return}return}if(Le){if(a.upArrow){mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){mt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Le.rows.length){mt(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=Le.rows[Le.cursor].name;if(mt(null),!ai(e,i).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 "${i}").`});let u=!1;try{let h=Be(i);u=!!h&&!(_e(h)&&!h.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${i} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${i}) and pick your project. (press 1)`}),G(["/login"]),ae(h=>h+1);return}if(a.escape){mt(null);return}return}if(ue){if(a.upArrow){ht(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ht(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ue.rows.length){ht(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=ue.rows[ue.cursor],{profile:g,projectId:u}=ue;ht(null),hn(g,u,i);return}if(a.escape){ht(null);return}return}if(we){if(a.upArrow){Ke(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ke(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=we.rows.length){Ke(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=we.rows[we.cursor],{profile:g}=we;Ke(null),wn(g,i);return}if(a.escape){Ke(null);return}return}if(fe){if(a.upArrow){wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){wt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l===" "){wt(i=>i&&{...i,rows:i.rows.map((g,u)=>u===i.cursor?{...g,checked:!g.checked}:g)});return}if(a.return){let i=fe.rows.filter(g=>g.checked).map(g=>g.path);if(wt(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}tr(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer.json`});for(let g of i)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(a.escape){wt(null);return}return}if(Xe){if(a.upArrow){gt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){gt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Xe.rows.length){gt(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=Xe.rows[Xe.cursor];gt(null),i.kind==="article"?So(i.paths[0]):mn(i.paths);return}if(a.escape){gt(null);return}return}if(ye){if(a.escape){Qe(null);return}if(a.upArrow){Qe(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Qe(i=>i&&{...i,cursor:Math.min(Math.max(0,pn.length-1),i.cursor+1)});return}if(a.return){let i=pn[ye.cursor];if(i){Qe(null);try{d({kind:"preview",name:on(i),text:fl(Jr(At(e,i),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${i}: ${g.message}`})}}return}if(a.backspace||a.delete){Qe(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){Qe(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(be){if(a.escape){et(null);return}if(a.upArrow){et(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){et(i=>i&&{...i,cursor:Math.min(Math.max(0,fn.length-1),i.cursor+1)});return}if(a.return){let i=fn[be.cursor];if(i){et(null),me(i.uuid),Se.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},pt(i.name),Qr(i.uuid),ut.current=[];let g=Yr(e,i.uuid);for(let u of g)d(u);d({kind:"note",tone:"ok",text:g.length?`Resumed "${i.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){et(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){et(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(a.tab&&!A&&ve){w(ve),le(null),it.current++;return}if(!A&&Ge.length>0&&l&&/^[1-9]$/.test(l)){let i=Ge[Number(l)-1];if(i){w(i);return}}if(!A&&(vo||yo)&&l==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let i=vo!=null;Ia(vo??yo).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?i?"\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.":i?"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&&i&&Co(null)});return}if(!Rs(l,a)){if(ks){if(a.upArrow){lt(i=>Math.max(0,i-1));return}if(a.downArrow){lt(i=>Math.min(Mt.length-1,i+1));return}if(a.tab){w("/"+(Mt[It]?.name??"")+" "),lt(0);return}if(a.return){let i=Mt[It];if(i){let g=A.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Ha(i.usage)&&!g){w("/"+i.name+" "),lt(0);return}kn("/"+i.name+(g?" "+g:""));return}}}else{if(a.upArrow){if(A!==""&&ct===null){bn(-1);return}let i=fo.current;if(!i.length)return;let g=ct===null?i.length-1:Math.max(0,ct-1);an(g),w(i[g]??"");return}if(a.downArrow){if(A!==""&&ct===null){bn(1);return}let i=fo.current;if(ct===null)return;let g=ct+1;g>=i.length?(an(null),w("")):(an(g),w(i[g]??""));return}}if(a.return){kn();return}if(a.backspace||a.delete){C();return}if(a.escape){w(""),lt(0),le(null),G([]),Je(null);return}l&&!a.ctrl&&!a.meta&&Ps(l)}}}),xe(()=>{if(R||H)return;let l=Ze.current.shift();l!==void 0&&(ho([...Ze.current]),kn(l))},[R,H,kn]),B(te,{flexDirection:"column",width:je,children:[Ro!==null&&B(te,{marginTop:1,flexDirection:"column",children:[Ro.truncated&&j(T,{dimColor:!0,children:"\u2026"}),j(T,{children:Ro.text})]}),R&&(fs?j(Rf,{p:fs}):j(Pf,{startTime:Ye.current,chars:Pl})),j(te,{borderStyle:"round",borderColor:ys.prod?"yellow":M,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:A?Ts.map((l,a)=>{let i=b.text.slice(l.start,l.end),g=a===io(Ts,b.pos),u=Math.min(b.pos,l.end)-l.start;return B(T,{children:[j(T,{color:M,children:a===0?"> ":" "}),g?B(ns,{children:[i.slice(0,u),j(co,{ch:i[u]??" "}),i.slice(u+1)]}):i||" "]},`${a}-${l.start}`)}):B(T,{children:[j(T,{color:M,children:"> "}),ve&&!R?B(ns,{children:[j(co,{ch:ve[0],dim:!0}),j(T,{color:"gray",children:ve.slice(1)}),j(T,{dimColor:!0,children:" (tab)"})]}):(To.isSetup||!vl)&&!R?B(ns,{children:[j(co,{ch:To.text[0],dim:!0}),j(T,{color:"gray",children:To.text.slice(1)})]}):j(co,{ch:" "})]})}),ps.length>0&&j(te,{flexDirection:"column",paddingX:1,children:ps.map((l,a)=>j(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${a}-${l.slice(0,24)}`))}),go?j(Ba,{tab:go.tab,width:je}):Ve?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Select model"}),j(T,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),Re.map((l,a)=>B(T,{color:a===Ve.cursor?M:void 0,children:[a===Ve.cursor?"\u276F ":" ",`${a+1}. ${l.label}${a===Ve.current?" \u2714":""}`.padEnd(16),j(T,{color:"gray",children:l.desc})]},l.label)),j(T,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):De?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Switch connection profile"}),De.rows.map((l,a)=>B(T,{color:a===De.cursor?M:void 0,children:[a===De.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===De.current?" \u2714":""}`.padEnd(20),j(T,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?j(T,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),j(T,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Le?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Pick your Document360 environment"}),Le.rows.map((l,a)=>B(T,{color:a===Le.cursor?M:void 0,children:[a===Le.cursor?"\u276F ":" ",`${a+1}. ${l.name}`.padEnd(16),j(T,{color:"gray",children:l.apiUrl})]},l.name)),j(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ue?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Switch workspace"}),j(T,{dimColor:!0,children:`environment ${ue.environment} \xB7 project ${ue.projectName??`${ue.projectId.slice(0,8)}\u2026`}`}),ue.rows.map((l,a)=>B(T,{color:a===ue.cursor?M:void 0,children:[a===ue.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===ue.current?" \u2714":""}`.padEnd(30),j(T,{color:"gray",children:l.type??""})]},l.id)),j(T,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):we?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Choose project"}),j(T,{dimColor:!0,children:`environment ${we.environment}`}),we.rows.map((l,a)=>B(T,{color:a===we.cursor?M:void 0,children:[a===we.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===we.current?" \u2714":""}`.padEnd(30),j(T,{color:"gray",children:l.sub??""})]},l.id)),j(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?(()=>{let a=Math.min(Math.max(0,fe.cursor-Math.floor(7)),Math.max(0,fe.rows.length-14)),i=fe.rows.slice(a,a+14),g=fe.rows.filter(u=>u.checked).length;return B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:`Which folders back the user docs? (${g} selected of ${fe.rows.length})`}),a>0?j(T,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((u,h)=>{let y=a+h;return B(T,{color:y===fe.cursor?M:void 0,children:[y===fe.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,je-34)),j(T,{color:"gray",children:Mn(u)})]},u.path)}),a+14<fe.rows.length?j(T,{dimColor:!0,children:` \u2193 ${fe.rows.length-a-14} more`}):null,j(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Xe?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Xe.rows.map((l,a)=>{let i=a===Xe.cursor,g=l.indent?" ":" ",u=`${a+1}.`.padEnd(3);return B(T,{color:i?M:void 0,bold:l.kind==="category"&&!i,children:[i?"\u276F ":" ",`${g}${u} ${l.label}`.padEnd(Math.min(56,je-24)),l.note?j(T,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),j(T,{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(T,{color:M,bold:!0,children:`Preview article${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),pn.length===0?j(T,{color:"gray",children:"no articles match"}):pn.map((l,a)=>B(T,{color:a===ye.cursor?M:void 0,children:[a===ye.cursor?"\u276F ":" ",l]},l)),j(T,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):be?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:`Resume session${be.query?` \u2014 filter: ${be.query}`:" (type to filter)"}`}),fn.length===0?j(T,{color:"gray",children:"no sessions match"}):fn.map((l,a)=>B(T,{color:a===be.cursor?M:void 0,children:[a===be.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),j(T,{color:a===be.cursor?M:"gray",children:l.firstPrompt.slice(0,Math.max(10,je-40))})]},l.uuid)),j(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):ks?j(te,{flexDirection:"column",children:Mt.map((l,a)=>B(T,{color:a===It?M:void 0,children:[a===It?"\u276F ":" ",l.usage.padEnd(22)," ",j(T,{color:a===It?M:"gray",children:l.name==="model"&&wo?`${l.desc} (currently ${wo})`:l.desc})]},l.name))}):!R&&!A&&Ge.length>0?B(te,{flexDirection:"column",paddingX:1,children:[ds?j(T,{color:M,children:ds}):null,Ge.map((l,a)=>{let i=l.slice(0,Math.max(20,je-5)),g=je-i.length-7,u=g>=12?Wa(l).slice(0,g):"";return B(T,{children:[j(T,{color:M,children:a+1})," ",i,u?j(T,{dimColor:!0,children:` \u2014 ${u}`}):null]},l)}),j(T,{dimColor:!0,children:`press 1-${Ge.length} to fill the command \xB7 esc dismiss`})]}):j(te,{paddingX:1,children:B(T,{color:"gray",children:[ys.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${wo??"model n/a"}${t.kind==="api"?hs>0?` \xB7 ${de(hs)}`:"":ms>0?` \xB7 ${He(ms)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Af}from"react/jsx-runtime";async function wl(e=process.cwd(),t="auto",n,o="0.0.0"){let r=jf(t);r.kind==="none"&&(console.error(""),console.error($("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}=Df(Af(gl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
289
+ `)}),bt(nt()),Ut.current=Ee(e).status==="current"||Gt(e);return}case"inbox":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Ir(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(Nr(),{display:"/inbox",quietUser:!0});return}case"document":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:h}=$r(g);if(!h&&xr(e)===0){d({kind:"note",tone:"info",text:Cr});return}let y=`/document${h?` ${h}`:""}${u?" --publish":""}`;await ce(vr(h,u),{display:y,quietUser:!0});return}case"catch-up":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!$o(l.trim()))return;let{publish:u}=_r(g),h=Dt(St(e));d({kind:"note",tone:"info",text:h?`Catching up on ${h} (+ checking Document360 for drift)\u2026`:"No local queue \u2014 checking for code changes and drift\u2026"}),await ce(Or({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{bo.current=!0,d({kind:"note",tone:"info",text:`Updating ${st}\u2026 (don\u2019t close this window)`}),sn(!0),(await Vn().finally(()=>sn(!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"])):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Gn}`});return}case"screenshot":{let u=Dr(g);if(u.mode==="list"){if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Ar(jr(e,u.scope),u.scope).join(`
290
+ `)});return}if(u.mode==="single"){let N=await Bn(g);N.kind==="forward-to-agent"&&N.prompt&&await ce(N.prompt,{display:N.display,quietUser:!0});return}if(!ee(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=df(e,{scope:h}).map(N=>N.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 v=6,D=uf(y,3),_=lo(e,"standard");Ve.current=Date.now(),at(0),I(!0);let K=new AbortController;ke.current=K,J({verb:"Authoring",unit:"spec",total:D.length,done:0,active:[],rows:nn(D),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 ${D.length} partition${D.length===1?"":"s"} (\u2264${v} agents at once) on ${_.model}${_.forced?" (forced)":""}\u2026 (esc to stop)`});let Q=!1;try{for await(let N of ao({cwd:e,partitions:D,promptFor:pa,concurrency:v,profileName:s,allowProdWrites:dt.current,model:_.model,signal:K.signal}))if(N.type==="partition_status")N.status==="running"?J(x=>x&&{...x,active:[...x.active,N.label],rows:Ne(x.rows,N.label,"active"),lastAt:Date.now()}):J(x=>x&&{...x,active:x.active.filter(S=>S!==N.label),done:x.done+1,rows:Ne(x.rows,N.label,N.status==="done"?"done":"failed"),lastAt:Date.now()});else if(N.type==="partition_event")J(x=>{if(!x)return x;let S={...x,lastAt:Date.now()};return N.event.type==="tool"?S.tools=x.tools+1:N.event.type==="text"&&(S.chars=x.chars+N.event.delta.length),S});else if(N.type==="run_done"){kt(Z=>Z+N.totalCostUsd),yt(Z=>Z+N.results.reduce((q,z)=>q+z.outputTokens,0));let x=N.results.filter(Z=>Z.ok).length,S=N.aborted?"Stopped. ":"";Q=!N.aborted&&u.setup;let M=N.aborted?"":Q?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:N.aborted?"warn":N.ok?"ok":"warn",text:`${S}Authored specs \u2014 ${x}/${N.results.length} batches ok.${M}`})}}catch(N){d({kind:"note",tone:"error",text:`Spec authoring failed: ${N.message}`})}finally{ke.current=null,J(null),I(!1),ae(N=>N+1)}if(Q){let N=await en();N.kind==="forward-to-agent"&&N.prompt&&await ce(N.prompt,{display:N.display,quietUser:!0});let x=Er(e);x&&d({kind:"note",tone:"info",text:x.join(`
291
+ `)})}return}case"reset":{let u=Lr(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}mo.current={repoName:on(e),targets:u,hadDevhints:jt(ul(e))},d({kind:"note",tone:"warn",text:Fr(e,u).join(`
292
+ `)}),le(on(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,yn,d,me,ce,mn,So,xs]),kn=V(l=>{let a=(l??A).trim();if(w(""),an(null),lt(0),a.startsWith("/")&&(le(null),it.current++,Je(null),G(g=>Ya(g,a))),!a||vs(a)||$s(a))return;fo.current.push(a);let i=Za(a,cs.current);a.startsWith("/")?(d({kind:"user",text:a}),Cs(i)):ce(i,{display:a})},[A,vs,$s,Cs,ce]),Ps=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let a=Xa(l);if(Ja(a)){let i=Qa(++Tl.current,a);cs.current.set(i,a),P(i)}else P(a);return}P(l)},[P]),xt=Math.max(10,je-6),Ts=Xr(()=>so(b.text,xt),[b.text,xt]),Ao=V(l=>k(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+l))})),[]),bn=V(l=>k(a=>({...a,pos:tl(so(a.text,xt),a.pos,l)})),[xt]),Wt=V(l=>k(a=>({...a,pos:nl(so(a.text,xt),a.pos,l)})),[xt]),Dl=["\x1B[H","\x1B[1~","\x1BOH"],jl=["\x1B[F","\x1B[4~","\x1BOF"],Rs=V((l,a)=>a.leftArrow?(Ao(-1),!0):a.rightArrow?(Ao(1),!0):l&&Dl.includes(l)?(Wt("start"),!0):l&&jl.includes(l)?(Wt("end"),!0):a.ctrl&&l==="a"?(Wt("start"),!0):a.ctrl&&l==="e"?(Wt("end"),!0):!1,[Ao,Wt]);return Up((l,a)=>{if(a.ctrl&&l==="c"){ge.current?.close(),r();return}if(!H){if(R){if(a.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}Nt.current||(Nt.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),ge.current?.interrupt());return}if(a.return){let i=A.trim();if(!i)return;Ze.current.push(i),ho([...Ze.current]),w("");return}if(Rs(l,a))return;if(a.upArrow){bn(-1);return}if(a.downArrow){bn(1);return}if(a.backspace||a.delete){C();return}l&&!a.ctrl&&!a.meta&&Ps(l);return}if(Ye){if(a.upArrow){ze(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ze(i=>i&&{...i,cursor:Math.min(Re.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.length){ze(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=Re[Ye.cursor];ze(null);let{lines:g,changed:u,effective:h}=Qt(e,i.value??"default");for(let y of g)d({kind:"note",tone:y.startsWith("\u26A0")?"warn":y.startsWith("\u2713")?"ok":"info",text:y});u&&(gs(y=>y+1),ge.current?.setModel(h));return}if(l==="s"){let i=Re[Ye.cursor];ze(null),ge.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){ze(null);return}return}if(De){if(a.upArrow){ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ft(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=De.rows.length){ft(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return||l==="s"){let i=De.rows[De.cursor];ft(null),jo(i.name,a.return===!0);return}if(a.escape){ft(null);return}return}if(go){if(a.escape){Ot(null);return}if(a.leftArrow||a.tab&&a.shift){Ot(i=>i&&{tab:(i.tab-1+xe.length)%xe.length});return}if(a.rightArrow||a.tab){Ot(i=>i&&{tab:(i.tab+1)%xe.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=xe.length){Ot({tab:Number(l)-1});return}return}if(Me){if(a.upArrow){mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){mt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Me.rows.length){mt(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=Me.rows[Me.cursor].name;if(mt(null),!ai(e,i).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 "${i}").`});let u=!1;try{let h=Be(i);u=!!h&&!(_e(h)&&!h.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${i} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${i}) and pick your project. (press 1)`}),G(["/login"]),ae(h=>h+1);return}if(a.escape){mt(null);return}return}if(ue){if(a.upArrow){ht(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ht(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ue.rows.length){ht(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=ue.rows[ue.cursor],{profile:g,projectId:u}=ue;ht(null),hn(g,u,i);return}if(a.escape){ht(null);return}return}if(we){if(a.upArrow){Ke(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ke(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=we.rows.length){Ke(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=we.rows[we.cursor],{profile:g}=we;Ke(null),wn(g,i);return}if(a.escape){Ke(null);return}return}if(fe){if(a.upArrow){wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){wt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l===" "){wt(i=>i&&{...i,rows:i.rows.map((g,u)=>u===i.cursor?{...g,checked:!g.checked}:g)});return}if(a.return){let i=fe.rows.filter(g=>g.checked).map(g=>g.path);if(wt(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}tr(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer.json`});for(let g of i)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(a.escape){wt(null);return}return}if(Xe){if(a.upArrow){gt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){gt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Xe.rows.length){gt(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=Xe.rows[Xe.cursor];gt(null),i.kind==="article"?So(i.paths[0]):mn(i.paths);return}if(a.escape){gt(null);return}return}if(ye){if(a.escape){Qe(null);return}if(a.upArrow){Qe(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Qe(i=>i&&{...i,cursor:Math.min(Math.max(0,pn.length-1),i.cursor+1)});return}if(a.return){let i=pn[ye.cursor];if(i){Qe(null);try{d({kind:"preview",name:on(i),text:fl(Jr(At(e,i),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${i}: ${g.message}`})}}return}if(a.backspace||a.delete){Qe(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){Qe(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(be){if(a.escape){et(null);return}if(a.upArrow){et(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){et(i=>i&&{...i,cursor:Math.min(Math.max(0,fn.length-1),i.cursor+1)});return}if(a.return){let i=fn[be.cursor];if(i){et(null),me(i.uuid),Se.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},pt(i.name),Qr(i.uuid),ut.current=[];let g=Vr(e,i.uuid);for(let u of g)d(u);d({kind:"note",tone:"ok",text:g.length?`Resumed "${i.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){et(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){et(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(a.tab&&!A&&Ce){w(Ce),le(null),it.current++;return}if(!A&&Ge.length>0&&l&&/^[1-9]$/.test(l)){let i=Ge[Number(l)-1];if(i){w(i);return}}if(!A&&(vo||yo)&&l==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let i=vo!=null;Ia(vo??yo).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?i?"\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.":i?"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&&i&&Co(null)});return}if(!Rs(l,a)){if(ks){if(a.upArrow){lt(i=>Math.max(0,i-1));return}if(a.downArrow){lt(i=>Math.min(Lt.length-1,i+1));return}if(a.tab){w("/"+(Lt[It]?.name??"")+" "),lt(0);return}if(a.return){let i=Lt[It];if(i){let g=A.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Ha(i.usage)&&!g){w("/"+i.name+" "),lt(0);return}kn("/"+i.name+(g?" "+g:""));return}}}else{if(a.upArrow){if(A!==""&&ct===null){bn(-1);return}let i=fo.current;if(!i.length)return;let g=ct===null?i.length-1:Math.max(0,ct-1);an(g),w(i[g]??"");return}if(a.downArrow){if(A!==""&&ct===null){bn(1);return}let i=fo.current;if(ct===null)return;let g=ct+1;g>=i.length?(an(null),w("")):(an(g),w(i[g]??""));return}}if(a.return){kn();return}if(a.backspace||a.delete){C();return}if(a.escape){w(""),lt(0),le(null),G([]),Je(null);return}l&&!a.ctrl&&!a.meta&&Ps(l)}}}),$e(()=>{if(R||H)return;let l=Ze.current.shift();l!==void 0&&(ho([...Ze.current]),kn(l))},[R,H,kn]),B(te,{flexDirection:"column",width:je,children:[Ro!==null&&B(te,{marginTop:1,flexDirection:"column",children:[Ro.truncated&&j(T,{dimColor:!0,children:"\u2026"}),j(T,{children:Ro.text})]}),R&&(fs?j(Rf,{p:fs}):j(Pf,{startTime:Ve.current,chars:Pl})),j(te,{borderStyle:"round",borderColor:ys.prod?"yellow":L,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:A?Ts.map((l,a)=>{let i=b.text.slice(l.start,l.end),g=a===io(Ts,b.pos),u=Math.min(b.pos,l.end)-l.start;return B(T,{children:[j(T,{color:L,children:a===0?"> ":" "}),g?B(ns,{children:[i.slice(0,u),j(co,{ch:i[u]??" "}),i.slice(u+1)]}):i||" "]},`${a}-${l.start}`)}):B(T,{children:[j(T,{color:L,children:"> "}),Ce&&!R?B(ns,{children:[j(co,{ch:Ce[0],dim:!0}),j(T,{color:"gray",children:Ce.slice(1)}),j(T,{dimColor:!0,children:" (tab)"})]}):(To.isSetup||!vl)&&!R?B(ns,{children:[j(co,{ch:To.text[0],dim:!0}),j(T,{color:"gray",children:To.text.slice(1)})]}):j(co,{ch:" "})]})}),ps.length>0&&j(te,{flexDirection:"column",paddingX:1,children:ps.map((l,a)=>j(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${a}-${l.slice(0,24)}`))}),go?j(Ba,{tab:go.tab,width:je}):Ye?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:L,bold:!0,children:"Select model"}),j(T,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),Re.map((l,a)=>B(T,{color:a===Ye.cursor?L:void 0,children:[a===Ye.cursor?"\u276F ":" ",`${a+1}. ${l.label}${a===Ye.current?" \u2714":""}`.padEnd(16),j(T,{color:"gray",children:l.desc})]},l.label)),j(T,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):De?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:L,bold:!0,children:"Switch connection profile"}),De.rows.map((l,a)=>B(T,{color:a===De.cursor?L:void 0,children:[a===De.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===De.current?" \u2714":""}`.padEnd(20),j(T,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?j(T,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),j(T,{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(T,{color:L,bold:!0,children:"Pick your Document360 environment"}),Me.rows.map((l,a)=>B(T,{color:a===Me.cursor?L:void 0,children:[a===Me.cursor?"\u276F ":" ",`${a+1}. ${l.name}`.padEnd(16),j(T,{color:"gray",children:l.apiUrl})]},l.name)),j(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ue?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:L,bold:!0,children:"Switch workspace"}),j(T,{dimColor:!0,children:`environment ${ue.environment} \xB7 project ${ue.projectName??`${ue.projectId.slice(0,8)}\u2026`}`}),ue.rows.map((l,a)=>B(T,{color:a===ue.cursor?L:void 0,children:[a===ue.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===ue.current?" \u2714":""}`.padEnd(30),j(T,{color:"gray",children:l.type??""})]},l.id)),j(T,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):we?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:L,bold:!0,children:"Choose project"}),j(T,{dimColor:!0,children:`environment ${we.environment}`}),we.rows.map((l,a)=>B(T,{color:a===we.cursor?L:void 0,children:[a===we.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===we.current?" \u2714":""}`.padEnd(30),j(T,{color:"gray",children:l.sub??""})]},l.id)),j(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?(()=>{let a=Math.min(Math.max(0,fe.cursor-Math.floor(7)),Math.max(0,fe.rows.length-14)),i=fe.rows.slice(a,a+14),g=fe.rows.filter(u=>u.checked).length;return B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:L,bold:!0,children:`Which folders back the user docs? (${g} selected of ${fe.rows.length})`}),a>0?j(T,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((u,h)=>{let y=a+h;return B(T,{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(T,{color:"gray",children:Ln(u)})]},u.path)}),a+14<fe.rows.length?j(T,{dimColor:!0,children:` \u2193 ${fe.rows.length-a-14} more`}):null,j(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Xe?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:L,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Xe.rows.map((l,a)=>{let i=a===Xe.cursor,g=l.indent?" ":" ",u=`${a+1}.`.padEnd(3);return B(T,{color:i?L:void 0,bold:l.kind==="category"&&!i,children:[i?"\u276F ":" ",`${g}${u} ${l.label}`.padEnd(Math.min(56,je-24)),l.note?j(T,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),j(T,{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(T,{color:L,bold:!0,children:`Preview article${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),pn.length===0?j(T,{color:"gray",children:"no articles match"}):pn.map((l,a)=>B(T,{color:a===ye.cursor?L:void 0,children:[a===ye.cursor?"\u276F ":" ",l]},l)),j(T,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):be?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:L,bold:!0,children:`Resume session${be.query?` \u2014 filter: ${be.query}`:" (type to filter)"}`}),fn.length===0?j(T,{color:"gray",children:"no sessions match"}):fn.map((l,a)=>B(T,{color:a===be.cursor?L:void 0,children:[a===be.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),j(T,{color:a===be.cursor?L:"gray",children:l.firstPrompt.slice(0,Math.max(10,je-40))})]},l.uuid)),j(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):ks?B(te,{flexDirection:"column",children:[Lt.map((l,a)=>B(T,{color:a===It?L:void 0,children:[a===It?"\u276F ":" ",l.usage.padEnd(22)," ",j(T,{color:a===It?L:"gray",children:l.name==="model"&&wo?`${l.desc} (currently ${wo})`:l.desc})]},l.name)),j(T,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!R&&!A&&Ge.length>0?B(te,{flexDirection:"column",paddingX:1,children:[ds?j(T,{color:L,children:ds}):null,Ge.map((l,a)=>{let i=l.slice(0,Math.max(20,je-5)),g=je-i.length-7,u=g>=12?Wa(l).slice(0,g):"";return B(T,{children:[j(T,{color:L,children:a+1})," ",i,u?j(T,{dimColor:!0,children:` \u2014 ${u}`}):null]},l)}),j(T,{dimColor:!0,children:`press 1-${Ge.length} to fill the command \xB7 esc dismiss`})]}):j(te,{paddingX:1,children:B(T,{color:"gray",children:[ys.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${wo??"model n/a"}${t.kind==="api"?hs>0?` \xB7 ${de(hs)}`:"":ms>0?` \xB7 ${He(ms)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Af}from"react/jsx-runtime";async function wl(e=process.cwd(),t="auto",n,o="0.0.0"){let r=jf(t);r.kind==="none"&&(console.error(""),console.error($("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}=Df(Af(gl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
293
293
  `),process.exit(0)}W();import{writeCrashLog as yl,isBenignTransportError as Ef}from"document360-engine";var kl=!1;function is(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function bl(e){if(kl)return;kl=!0;let t=(n,o)=>{if(Ef(o)){yl({kind:n,level:"transport",message:is(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=yl({kind:n,level:"fatal",message:is(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
294
294
  `+$(`\u2717 d360-writer crashed: ${is(o)}`)+`
295
295
  `),r&&process.stderr.write(m(` Crash details: ${r}`)+`
296
296
  `+m(" Run: d360-writer logs")+`
297
- `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Of=Nf(import.meta.url),xl=Of("../package.json");bl("d360-writer");var Oe=new If;function as(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Oe.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{as(e),await Cn({profile:e.profile,manual:e.manual})});Oe.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{as(e),await Ms({profile:e.profile})});Oe.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{as(e),await Ls({profile:e.profile})});var ls=Oe.command("profile").description("Manage connection profiles for the current repo");ls.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Pn(process.cwd()));ls.command("use <name>").description("Set the default profile for this repo").action(e=>Tn(process.cwd(),e));ls.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Rn(process.cwd(),e));var $l=Oe.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");$l.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>$t(process.cwd(),e.profile));$l.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await js(process.cwd(),e,t.profile)});Oe.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>qs());Oe.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(qn(),ra)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Oe.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(xl.version,"-v, --version").option("-p, --prompt <text>","One-shot prompt mode (non-interactive)").option("-r, --resume <name>","Resume a saved session (with --prompt; use /resume inside the REPL)").option("-C, --cwd <dir>","Working directory",process.cwd()).option("--auth <mode>","Auth mode: auto | api | subscription","auto").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--yes","Skip the production write confirmation (for one-shot/CI)").option("--classic","Use the plain readline REPL instead of the Ink TUI").action(async e=>{if(_f.includes(e.auth)||(console.error(`\u2717 Invalid --auth mode: ${e.auth}`),console.error("Run: d360-writer --auth auto | api | subscription"),process.exit(2)),e.prompt){await Bs(e.cwd,e.prompt,e.auth,e.resume,e.profile,e.yes);return}e.resume&&(console.error("\u2717 --resume requires --prompt. In the interactive REPL, use /resume instead."),process.exit(2)),e.classic||!process.stdin.isTTY?await Aa(e.cwd,e.auth,e.profile):await wl(e.cwd,e.auth,e.profile,xl.version)});Oe.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
297
+ `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Of=Nf(import.meta.url),xl=Of("../package.json");bl("d360-writer");var Oe=new If;function as(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Oe.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{as(e),await Cn({profile:e.profile,manual:e.manual})});Oe.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{as(e),await Ls({profile:e.profile})});Oe.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{as(e),await Ms({profile:e.profile})});var ls=Oe.command("profile").description("Manage connection profiles for the current repo");ls.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Pn(process.cwd()));ls.command("use <name>").description("Set the default profile for this repo").action(e=>Tn(process.cwd(),e));ls.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Rn(process.cwd(),e));var $l=Oe.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");$l.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>$t(process.cwd(),e.profile));$l.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await js(process.cwd(),e,t.profile)});Oe.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>qs());Oe.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(qn(),ra)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Oe.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(xl.version,"-v, --version").option("-p, --prompt <text>","One-shot prompt mode (non-interactive)").option("-r, --resume <name>","Resume a saved session (with --prompt; use /resume inside the REPL)").option("-C, --cwd <dir>","Working directory",process.cwd()).option("--auth <mode>","Auth mode: auto | api | subscription","auto").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--yes","Skip the production write confirmation (for one-shot/CI)").option("--classic","Use the plain readline REPL instead of the Ink TUI").action(async e=>{if(_f.includes(e.auth)||(console.error(`\u2717 Invalid --auth mode: ${e.auth}`),console.error("Run: d360-writer --auth auto | api | subscription"),process.exit(2)),e.prompt){await Bs(e.cwd,e.prompt,e.auth,e.resume,e.profile,e.yes);return}e.resume&&(console.error("\u2717 --resume requires --prompt. In the interactive REPL, use /resume instead."),process.exit(2)),e.classic||!process.stdin.isTTY?await Aa(e.cwd,e.auth,e.profile):await wl(e.cwd,e.auth,e.profile,xl.version)});Oe.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "document360-writer",
3
- "version": "0.5.12",
3
+ "version": "0.5.14",
4
4
  "description": "Standalone documentation agent CLI. Reads your code, writes your docs. Specialized for Document360 publishing.",
5
5
  "type": "module",
6
6
  "bin": {