document360-writer 0.5.62 → 0.5.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var xc=Object.defineProperty;var En=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var ri=(e,t)=>{for(var n in t)xc(e,n,{get:t[n],enumerable:!0})};import Be from"picocolors";var H,$c,vc,Cc,si,Kt,f,$,L,j,_,ie,Pe,W=En(()=>{"use strict";H="#7f56d9",[$c,vc,Cc]=[127,86,217],si=e=>Be.isColorSupported?`\x1B[38;2;${$c};${vc};${Cc}m${e}\x1B[39m`:e,Kt=e=>Be.bold(si(e)),f=e=>Be.dim(e),$=e=>Be.red(e),L=e=>Be.yellow(e),j=e=>Be.green(e),_=si,ie=e=>Be.gray(e),Pe=e=>Be.bold(e)});import{existsSync as qn,writeFileSync as Zt,readFileSync as lu,readdirSync as cu}from"node:fs";import{join as uu}from"node:path";import{devHintsGuidePath as Bn,hintsDir as vi,architectureDir as Ri,messagesDir as rr,creatorNotesPath as Ci,devhintsStatePath as Ti,ensureDir as Hn,writeMessage as du,listOpenForDev as pu}from"document360-engine";function Si(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var Tc=Object.defineProperty;var Nn=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var ai=(e,t)=>{for(var n in t)Tc(e,n,{get:t[n],enumerable:!0})};import Be from"picocolors";var q,Sc,Dc,jc,li,Qt,f,$,O,A,_,ie,Re,W=Nn(()=>{"use strict";q="#7f56d9",[Sc,Dc,jc]=[127,86,217],li=e=>Be.isColorSupported?`\x1B[38;2;${Sc};${Dc};${jc}m${e}\x1B[39m`:e,Qt=e=>Be.bold(li(e)),f=e=>Be.dim(e),$=e=>Be.red(e),O=e=>Be.yellow(e),A=e=>Be.green(e),_=li,ie=e=>Be.gray(e),Re=e=>Be.bold(e)});import{existsSync as Bn,writeFileSync as en,readFileSync as mu,readdirSync as hu}from"node:fs";import{join as gu}from"node:path";import{devHintsGuidePath as Yn,hintsDir as Ri,architectureDir as Di,messagesDir as rr,creatorNotesPath as Ti,devhintsStatePath as ji,ensureDir as qn,writeMessage as wu,listOpenForDev as yu}from"document360-engine";function Ai(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
3
3
 
4
4
  <!-- devhints script v${re} \xB7 maintained by document360-writer (/devhints). -->
5
5
 
@@ -159,7 +159,7 @@ whenever \`git status\` shows changes under \`.d360-writer/\`, commit them (e.g.
159
159
  \`git add .d360-writer && git commit -m "docs: sync d360-writer output"\`) before you push. The docs agent
160
160
  will remind you when it leaves changes, but it's your call to commit them. Without this, the team's docs
161
161
  and \u2014 critically \u2014 the sync map are stranded on one machine.
162
- `}function fu(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
162
+ `}function ku(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
163
163
 
164
164
  <!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
165
165
  The builder agent reads this FIRST and treats it as authoritative when writing the architecture
@@ -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 It(e){Hn(vi(e)),Hn(Ri(e)),Hn(rr(e));for(let n of[vi(e),rr(e)]){let o=uu(n,".gitkeep");qn(o)||Zt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
177
- `)}qn(Ci(e))||Zt(Ci(e),fu()),Zt(Bn(e),Si());let t=Le(e);return ji(e,new Date().toISOString()),t}async function Di(e,t){for(let n of _t(It(t.cwd)))console.log(n);return{kind:"continue"}}function lt(){return[`This is document360-writer's dev hand-off setup (v${re}).`,'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": ${re},`,' "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
- `)}function sr(e){try{let t=lu(Ti(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function ji(e,t){let o={...sr(e)??{},emittedVersion:re,emittedAt:t};Zt(Ti(e),`${JSON.stringify(o,null,2)}
179
- `)}function en(e){try{return cu(Ri(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Le(e){let n=sr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<re?"stale":"current",completedVersion:n}}function Yn(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:re};try{if(!qn(Bn(e)))return n;let o=sr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;re>r&&(Hn(rr(e)),Zt(Bn(e),Si()),ji(e,t),n.guideRefreshed=!0),re>s&&(pu(e).some(p=>p.kind==="request"&&p.subject.startsWith(Pi))||(du(e,{id:`onb${re}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Pi}${re})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${re}${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:","",lt()].join(`
180
- `)}),n.notifiedBuilder=!0))}catch{}return n}function Gn(e){if(!qn(Bn(e)))return[];let t=Le(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${re}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Nt,lt(),Nt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function ir(){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 Vn(){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):",Nt,ir(),Nt]}function _t(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${re}.`," 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):",Nt,lt(),Nt,"","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 Nt,re,Pi,ct=En(()=>{"use strict";Nt="-".repeat(64),re=5;Pi="Re-run dev\u2194docs onboarding (protocol v"});var Wi={};ri(Wi,{initCommand:()=>lr,scaffoldInit:()=>ar});import{input as tn,confirm as mu}from"@inquirer/prompts";import{basename as Ai,join as zn}from"node:path";import{existsSync as Lt,readFileSync as hu,readdirSync as gu,writeFileSync as wu}from"node:fs";import{writeProjectConfig as Ei,readProjectConfig as yu,projectConfigPath as Ni,writerDir as ku,DEFAULT_DOCS_DIR as Ii,DEFAULT_CAPTURE_DIR as _i,DEFAULT_OUTPUT_DIR as Li}from"document360-engine";function ar(e,t="berlin"){let n=Ni(e);if(Lt(n))return{created:!1,path:n,profileName:""};let o={projectId:Mi(e)??Ai(e),docsDir:Ii,captureDir:_i,outputDir:Li,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Ui(e)};return Ei(o,e),Oi(e),{created:!0,path:n,profileName:t}}function Oi(e){let t=zn(ku(e),".gitignore");Lt(t)||wu(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
182
- `),"utf8")}async function lr(){let e=process.cwd(),t=Ni(e);if(Lt(t)&&!await mu({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Mi(e)??Ai(e),o=await tn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await tn({message:"Capture directory (where document360-capture .spec.ts files live):",default:_i}),s=await tn({message:"Screenshot output directory:",default:Li}),c=await tn({message:"Default connection profile name:",default:"berlin"}),p=await tn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),h={projectId:o,docsDir:Ii,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Ui(e)},k=yu(e);k?.terminologyGlossary&&(h.terminologyGlossary=k.terminologyGlossary),Ei(h,e),Oi(e);let x=It(e);console.log(""),console.log(j(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of _t(x))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Mi(e){let t=zn(e,"package.json");if(!Lt(t))return null;try{return JSON.parse(hu(t,"utf8")).name??null}catch{return null}}function Ui(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Lt(zn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=zn(e,n);Lt(o)&&!bu(o)&&t.push(n)}return t}function bu(e){try{return gu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Xn=En(()=>{"use strict";W();ct()});var La={};ri(La,{doctorCommand:()=>cn,renderDoctorChecks:()=>_a,runDoctorChecks:()=>Ia});import{existsSync as Xd}from"node:fs";import{d360GetAll as Kd,getAccessToken as Qd,isExpired as Zr,loadProfileMap as Jd,loadTokens as Zd,packageSkillsDir as Ea,projectConfigPath as ep,readProjectConfig as tp,DEFAULT_DOCS_DIR as np,fetchManifestSummary as op,resolveActiveProfile as rp,classifyClaudeAuth as sp,CLAUDE_CODE_SETUP_HINT as Na,resolveModelSetting as ip,probeModel as ap,D360AuthError as lp}from"document360-engine";async function Ia(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=sp();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. ${Na}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Na});let r=ip(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let b=await ap(e,r.model??void 0);b.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(b.latencyMs/1e3).toFixed(1)}s`}):b.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 ${b.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=tp(e);if(!s)return t.push({level:"fail",label:`No ${ep(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??np).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 h;try{h=rp(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(b){return t.push({level:"fail",label:`Profile config: ${b.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=Zd(h.name);k?Zr(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Zr(k)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(k.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${h.name})`}),t.push(h.project.workspaceId?{level:"ok",label:`Workspace: ${h.project.workspaceName??h.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let x=Jd(e,h.name);x?x.projectId&&h.project.projectId&&x.projectId!==h.project.projectId?t.push({level:"fail",label:`Category map projectId (${x.projectId}) \u2260 profile projectId (${h.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(x.articles).length} articles, ${Object.keys(x.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${h.name}" (created on first /publish)`}),t.push(Xd(Ea())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Ea()}`,fix:"Reinstall document360-writer (broken install)"});let D=Le(e);if(D.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${re})`}):D.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${D.completedVersion}, current is v${re}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!Zr(k)||k.refreshToken)){let b={profile:h.name,connection:h.connection};try{await Qd(b);let C=await Kd(b,"/v3/projects");t.push({level:"ok",label:`API reachable (${h.connection.apiUrl}) \u2014 ${C.length} project(s) visible`})}catch(C){t.push({level:"fail",label:`API call failed: ${C.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let T=x?.projectId??h.project.projectId;if(T&&h.project.workspaceId)try{let C=await op(b,T,h.project.workspaceId);if(C){let I=(C.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${h.connection.name} (${C.languages?.length??0} language${(C.languages?.length??0)===1?"":"s"}) \xB7 hash ${I||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${h.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(C){C instanceof lp||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(C.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${h.project.projectName??T})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):t.push({level:"warn",label:`Workspace sync manifest: probe failed (${C.message.slice(0,80)})`})}}return t}function _a(e){let t=[""];for(let r of e){let s=r.level==="ok"?j("\u2713"):r.level==="warn"?L("\u26A0"):$("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${_(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?j(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function cn(e,t){console.log(f("Running checks\u2026"));for(let n of _a(await Ia(t.cwd)))console.log(n);return{kind:"continue"}}var so=En(()=>{"use strict";ct();W()});import{Command as Ym}from"commander";import{createRequire as Gm}from"node:module";import{AUTH_MODES as Vm}from"document360-engine";import{input as Mc}from"@inquirer/prompts";import{loginPkce as Uc,refreshTokens as Wc,toStoredTokens as di,clearTokens as Fc,decodeJwtClaims as ui,isExpired as Hc,loadTokens as qc,saveTokens as pi,resolveActiveProfile as Ln,setProfileProject as Bc,readProjectConfig as Yc}from"document360-engine";W();import{select as Pc}from"@inquirer/prompts";import{resolveActiveProfile as Rc,setProfileProject as Tc,resolveProjectId as Sc,listWorkspaces as Dc}from"document360-engine";async function Qt(e,t){let n=Rc(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Sc(o);return{workspaces:await Dc(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var ii=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Zo(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 Nn(e,t,n,o,r){Tc(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ai(e,t,n){let o;try{o=await Qt(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=Zo(o.workspaces,t);return r?(Nn(e,o.profile,o.projectId,r.id,r.name),console.log(j(`\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 Et(e,t){let n;try{n=await Qt(e,t)}catch(k){console.log($(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===c?_("\u25CF"):" "} ${ii(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Pc({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${ii(k)}${k.id===c?" (current)":""}`,value:k.id}))}),h=o.find(k=>k.id===p);Nn(e,s,r,p,h?.name),console.log(j(`\u2713 Workspace set to "${h?.name??p}" for profile "${s}".`))}W();import{select as jc}from"@inquirer/prompts";import{resolveActiveProfile as Ac,setProfileProject as Ec,listProjects as Nc}from"document360-engine";async function Ye(e,t){let n=Ac(e,t),o={profile:n.name,connection:n.connection};return{projects:await Nc(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var li=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function er(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 In(e,t,n,o){Ec(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function ci(e,t,n){let o;try{o=await Ye(e,n)}catch(s){return console.log($(`Could not list projects: ${s.message}`)),1}let r=er(o.projects,t);return r?(In(e,o.profile,r.id,r.name),console.log(j(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log($(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function _n(e,t){let n;try{n=await Ye(e,t)}catch(h){console.log($(`Could not list projects: ${h.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===s?_("\u25CF"):" "} ${li(h)} ${f(h.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await jc({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${li(h)}${h.id===s?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===c);In(e,r,c,p?.name),console.log(j(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import Ic from"picocolors";function _c(e=process.env){return e.FORCE_HYPERLINK==="0"||!Ic.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 Lc(e,t=e,n){return _c(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Oc=/https?:\/\/[^\s\x1b]+/g;function Jt(e,t){return e.replace(Oc,n=>Lc(n,n,t))}function fi(e){return{...ui(e.idToken)??{},...ui(e.accessToken)??{}}}function On(e){let t=fi(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 Mn(e){let t=Ln(process.cwd(),e.profile),n=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Uc(n,{manual:e.manual,promptForRedirect:s=>Mc({message:s})},s=>console.log(Jt(s))),r=di(t.name,o);if(pi(r),await tr(r,t.name,s=>console.log(f(s))),console.log(""),console.log(j(`\u2713 Logged in to "${t.name}" as ${On(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Yc(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Et(process.cwd(),t.name))}catch{}}async function tr(e,t,n){let r=fi(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Ln(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await Ye(process.cwd(),t);c=p.find(h=>h.id===r)?.name}catch{}Bc(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function mi(e){let t=Ln(process.cwd(),e.profile),n=t.connection,o=qc(t.name);if(!o){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${_(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${On(o)}`),Hc(o))if(o.refreshToken)try{let r=di(t.name,await Wc(n,o.refreshToken));pi(r),console.log(j(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(L("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function hi(e){let t=Ln(process.cwd(),e.profile);Fc(t.name)?console.log(j(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as gi,writeProjectConfig as Gc,resolveActiveProfile as Vc,loadTokens as zc,isExpired as Xc}from"document360-engine";function Un(e){let t=gi(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?_("\u25CF "):" ",s=o.production?L(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=zc(n),h=p?Xc(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${c}${s} [${h}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Wn(e,t){let n=gi(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,Gc(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(j(`\u2713 Default profile is now "${t}"${o}`))}function Fn(e,t){try{let n=Vc(e,t);console.log(""),console.log(`Profile ${_(n.name)}${n.production?L(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}W();import{existsSync as Kc,readdirSync as Qc,statSync as wi}from"node:fs";import{join as yi}from"node:path";import{apiLogDir as Jc}from"document360-engine";function ki(){let e=Jc();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Kc(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Qc(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(wi(yi(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(wi(yi(e,r)).size/1024).toFixed(1);console.log(` ${$(r)} ${f(`${s} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as Zc,resolveAuth as eu,findByName as tu,slugify as nu,touchSession as ou,upsertSession as ru,resolveActiveProfile as su}from"document360-engine";async function bi(e,t,n,o,r,s){let c=eu(n);c.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=su(e,r)}catch(b){console.error($(`Document360 profile error: ${b.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let h;if(o){let b=tu(e,o);b||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),h=b.uuid,console.error(f(`Resuming "${b.name}"`))}let k=Zc({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),x=h??null,D=1;for await(let b of k.send(t))switch(b.type){case"session":if(!x){x=b.sessionId;let T=new Date().toISOString();ru({uuid:x,name:nu(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:T,updatedAt:T})}break;case"text":process.stdout.write(b.delta);break;case"tool":console.error(ie(` \u2699 ${b.name}`));break;case"result":D=b.ok?0:1,console.error(f(`(${b.inputTokens}\u2192${b.outputTokens} tokens`+(b.costUsd>0?`, $${b.costUsd<.01?b.costUsd.toFixed(4):b.costUsd.toFixed(2)}`:"")+")")),b.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${b.message}`)),process.exit(1)}x&&ou(x),process.stdout.write(`
183
- `),process.exit(D)}import{createInterface as cf}from"node:readline/promises";import{createSession as xs,resolveAuth as uf,getSession as df,setTitle as pf,slugify as ff,touchSession as ul,upsertSession as mf,generateTitle as hf,resolveActiveProfile as dl,resolveModelSetting as gf,readProjectConfig as wf,decodeJwtClaims as ll,isExpired as yf,loadTokens as kf}from"document360-engine";var Re=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --all to author capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then run d360-capture in your app's repo \u2014 it signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot --list",s:"See capture status \u2014 which specs exist and which are done."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"d360-capture is a separate Playwright CLI \u2014 run it in the app's repo (needs its URL + a login)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"Author capture specs (--all / --list)."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function iu(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 xi(){let e=["document360-writer \u2014 help",""];for(let t of Re){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push(iu(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function nr(){console.log("");for(let e of xi())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 au}from"document360-engine";async function $i(e,t){let n=t.currentUuid(),o=n?au(n):void 0;return console.log(o?f(`
176
+ `}function It(e){qn(Ri(e)),qn(Di(e)),qn(rr(e));for(let n of[Ri(e),rr(e)]){let o=gu(n,".gitkeep");Bn(o)||en(o,`# Keeps this document360-writer inbox tracked in git even when empty.
177
+ `)}Bn(Ti(e))||en(Ti(e),ku()),en(Yn(e),Ai());let t=Oe(e);return Ni(e,new Date().toISOString()),t}async function Ei(e,t){for(let n of _t(It(t.cwd)))console.log(n);return{kind:"continue"}}function lt(){return[`This is document360-writer's dev hand-off setup (v${re}).`,'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": ${re},`,' "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
+ `)}function sr(e){try{let t=mu(ji(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Ni(e,t){let o={...sr(e)??{},emittedVersion:re,emittedAt:t};en(ji(e),`${JSON.stringify(o,null,2)}
179
+ `)}function tn(e){try{return hu(Di(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Oe(e){let n=sr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<re?"stale":"current",completedVersion:n}}function Gn(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:re};try{if(!Bn(Yn(e)))return n;let o=sr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;re>r&&(qn(rr(e)),en(Yn(e),Ai()),Ni(e,t),n.guideRefreshed=!0),re>s&&(yu(e).some(p=>p.kind==="request"&&p.subject.startsWith(Si))||(wu(e,{id:`onb${re}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Si}${re})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${re}${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:","",lt()].join(`
180
+ `)}),n.notifiedBuilder=!0))}catch{}return n}function Vn(e){if(!Bn(Yn(e)))return[];let t=Oe(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${re}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Nt,lt(),Nt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function ir(){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 zn(){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):",Nt,ir(),Nt]}function _t(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${re}.`," 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):",Nt,lt(),Nt,"","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 Nt,re,Si,ct=Nn(()=>{"use strict";Nt="-".repeat(64),re=5;Si="Re-run dev\u2194docs onboarding (protocol v"});var qi={};ai(qi,{initCommand:()=>lr,scaffoldInit:()=>ar});import{input as nn,confirm as bu}from"@inquirer/prompts";import{basename as Ii,join as Xn}from"node:path";import{existsSync as Ot,readFileSync as xu,readdirSync as $u,writeFileSync as vu}from"node:fs";import{writeProjectConfig as _i,readProjectConfig as Cu,projectConfigPath as Oi,writerDir as Pu,DEFAULT_DOCS_DIR as Li,DEFAULT_CAPTURE_DIR as Mi,DEFAULT_OUTPUT_DIR as Ui}from"document360-engine";function ar(e,t="berlin"){let n=Oi(e);if(Ot(n))return{created:!1,path:n,profileName:""};let o={projectId:Fi(e)??Ii(e),docsDir:Li,captureDir:Mi,outputDir:Ui,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Hi(e)};return _i(o,e),Wi(e),{created:!0,path:n,profileName:t}}function Wi(e){let t=Xn(Pu(e),".gitignore");Ot(t)||vu(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
182
+ `),"utf8")}async function lr(){let e=process.cwd(),t=Oi(e);if(Ot(t)&&!await bu({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Fi(e)??Ii(e),o=await nn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await nn({message:"Capture directory (where document360-capture .spec.ts files live):",default:Mi}),s=await nn({message:"Screenshot output directory:",default:Ui}),l=await nn({message:"Default connection profile name:",default:"berlin"}),p=await nn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),h={projectId:o,docsDir:Li,captureDir:r,outputDir:s,profiles:{[l]:{connection:{environment:p},production:!1}},defaultProfile:l,authoritativeSourceFiles:Hi(e)},k=Cu(e);k?.terminologyGlossary&&(h.terminologyGlossary=k.terminologyGlossary),_i(h,e),Wi(e);let x=It(e);console.log(""),console.log(A(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${l}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of _t(x))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Fi(e){let t=Xn(e,"package.json");if(!Ot(t))return null;try{return JSON.parse(xu(t,"utf8")).name??null}catch{return null}}function Hi(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Ot(Xn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Xn(e,n);Ot(o)&&!Ru(o)&&t.push(n)}return t}function Ru(e){try{return $u(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Kn=Nn(()=>{"use strict";W();ct()});var Ua={};ai(Ua,{doctorCommand:()=>un,renderDoctorChecks:()=>Ma,runDoctorChecks:()=>La});import{existsSync as tp}from"node:fs";import{d360GetAll as np,getAccessToken as op,isExpired as Zr,loadProfileMap as rp,loadTokens as sp,packageSkillsDir as _a,projectConfigPath as ip,readProjectConfig as ap,DEFAULT_DOCS_DIR as lp,fetchManifestSummary as cp,resolveActiveProfile as up,classifyClaudeAuth as dp,CLAUDE_CODE_SETUP_HINT as Oa,resolveModelSetting as pp,probeModel as fp,D360AuthError as mp}from"document360-engine";async function La(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=dp();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. ${Oa}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Oa});let r=pp(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let b=await fp(e,r.model??void 0);b.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(b.latencyMs/1e3).toFixed(1)}s`}):b.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 ${b.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=ap(e);if(!s)return t.push({level:"fail",label:`No ${ip(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let l=(s.docsDir??lp).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 ${l}/ 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 h;try{h=up(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(b){return t.push({level:"fail",label:`Profile config: ${b.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=sp(h.name);k?Zr(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Zr(k)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(k.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${h.name})`}),t.push(h.project.workspaceId?{level:"ok",label:`Workspace: ${h.project.workspaceName??h.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let x=rp(e,h.name);x?x.projectId&&h.project.projectId&&x.projectId!==h.project.projectId?t.push({level:"fail",label:`Category map projectId (${x.projectId}) \u2260 profile projectId (${h.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(x.articles).length} articles, ${Object.keys(x.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${h.name}" (created on first /publish)`}),t.push(tp(_a())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${_a()}`,fix:"Reinstall document360-writer (broken install)"});let D=Oe(e);if(D.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${re})`}):D.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${D.completedVersion}, current is v${re}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!Zr(k)||k.refreshToken)){let b={profile:h.name,connection:h.connection};try{await op(b);let C=await np(b,"/v3/projects");t.push({level:"ok",label:`API reachable (${h.connection.apiUrl}) \u2014 ${C.length} project(s) visible`})}catch(C){t.push({level:"fail",label:`API call failed: ${C.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let T=x?.projectId??h.project.projectId;if(T&&h.project.workspaceId)try{let C=await cp(b,T,h.project.workspaceId);if(C){let N=(C.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${h.connection.name} (${C.languages?.length??0} language${(C.languages?.length??0)===1?"":"s"}) \xB7 hash ${N||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${h.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(C){C instanceof mp||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(C.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${h.project.projectName??T})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):t.push({level:"warn",label:`Workspace sync manifest: probe failed (${C.message.slice(0,80)})`})}}return t}function Ma(e){let t=[""];for(let r of e){let s=r.level==="ok"?A("\u2713"):r.level==="warn"?O("\u26A0"):$("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${_(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?A(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function un(e,t){console.log(f("Running checks\u2026"));for(let n of Ma(await La(t.cwd)))console.log(n);return{kind:"continue"}}var io=Nn(()=>{"use strict";ct();W()});import{Command as oh}from"commander";import{createRequire as rh}from"node:module";import{AUTH_MODES as sh}from"document360-engine";import{input as Bc}from"@inquirer/prompts";import{loginPkce as Yc,refreshTokens as Gc,toStoredTokens as mi,clearTokens as Vc,decodeJwtClaims as fi,isExpired as zc,loadTokens as Xc,saveTokens as hi,resolveActiveProfile as Ln,setProfileProject as Kc,readProjectConfig as Qc}from"document360-engine";W();import{select as Ac}from"@inquirer/prompts";import{resolveActiveProfile as Ec,setProfileProject as Nc,resolveProjectId as Ic,listWorkspaces as _c}from"document360-engine";async function Jt(e,t){let n=Ec(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Ic(o);return{workspaces:await _c(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var ci=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Zo(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 In(e,t,n,o,r){Nc(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ui(e,t,n){let o;try{o=await Jt(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=Zo(o.workspaces,t);return r?(In(e,o.profile,o.projectId,r.id,r.name),console.log(A(`\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 Et(e,t){let n;try{n=await Jt(e,t)}catch(k){console.log($(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:l}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===l?_("\u25CF"):" "} ${ci(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Ac({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${ci(k)}${k.id===l?" (current)":""}`,value:k.id}))}),h=o.find(k=>k.id===p);In(e,s,r,p,h?.name),console.log(A(`\u2713 Workspace set to "${h?.name??p}" for profile "${s}".`))}W();import{select as Oc}from"@inquirer/prompts";import{resolveActiveProfile as Lc,setProfileProject as Mc,listProjects as Uc}from"document360-engine";async function Ye(e,t){let n=Lc(e,t),o={profile:n.name,connection:n.connection};return{projects:await Uc(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var di=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function er(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 _n(e,t,n,o){Mc(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function pi(e,t,n){let o;try{o=await Ye(e,n)}catch(s){return console.log($(`Could not list projects: ${s.message}`)),1}let r=er(o.projects,t);return r?(_n(e,o.profile,r.id,r.name),console.log(A(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log($(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function On(e,t){let n;try{n=await Ye(e,t)}catch(h){console.log($(`Could not list projects: ${h.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===s?_("\u25CF"):" "} ${di(h)} ${f(h.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let l=await Oc({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${di(h)}${h.id===s?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===l);_n(e,r,l,p?.name),console.log(A(`\u2713 Project set to "${p?.name??l}" for profile "${r}". Next: pick a workspace.`))}W();import Wc from"picocolors";function Fc(e=process.env){return e.FORCE_HYPERLINK==="0"||!Wc.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 Hc(e,t=e,n){return Fc(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var qc=/https?:\/\/[^\s\x1b]+/g;function Zt(e,t){return e.replace(qc,n=>Hc(n,n,t))}function gi(e){return{...fi(e.idToken)??{},...fi(e.accessToken)??{}}}function Mn(e){let t=gi(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 Un(e){let t=Ln(process.cwd(),e.profile),n=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Yc(n,{manual:e.manual,promptForRedirect:s=>Bc({message:s})},s=>console.log(Zt(s))),r=mi(t.name,o);if(hi(r),await tr(r,t.name,s=>console.log(f(s))),console.log(""),console.log(A(`\u2713 Logged in to "${t.name}" as ${Mn(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Qc(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Et(process.cwd(),t.name))}catch{}}async function tr(e,t,n){let r=gi(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Ln(process.cwd(),t).project.projectId)return;let l;try{let{projects:p}=await Ye(process.cwd(),t);l=p.find(h=>h.id===r)?.name}catch{}Kc(process.cwd(),t,{projectId:r,projectName:l}),n(` Project "${l??r}" written to profile "${t}".`)}catch{}}async function wi(e){let t=Ln(process.cwd(),e.profile),n=t.connection,o=Xc(t.name);if(!o){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${_(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Mn(o)}`),zc(o))if(o.refreshToken)try{let r=mi(t.name,await Gc(n,o.refreshToken));hi(r),console.log(A(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(O(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(O("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function yi(e){let t=Ln(process.cwd(),e.profile);Vc(t.name)?console.log(A(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as ki,writeProjectConfig as Jc,resolveActiveProfile as Zc,loadTokens as eu,isExpired as tu}from"document360-engine";function Wn(e){let t=ki(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?_("\u25CF "):" ",s=o.production?O(" \u26A0 PRODUCTION"):"",l=o.connection.environment??"(inline)",p=eu(n),h=p?tu(p)&&!p.refreshToken?O("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${l}${s} [${h}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Fn(e,t){let n=ki(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,Jc(n,e);let o=n.profiles[t].production?O(" \u26A0 PRODUCTION"):"";console.log(A(`\u2713 Default profile is now "${t}"${o}`))}function Hn(e,t){try{let n=Zc(e,t);console.log(""),console.log(`Profile ${_(n.name)}${n.production?O(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}W();import{existsSync as nu,readdirSync as ou,statSync as bi}from"node:fs";import{join as xi}from"node:path";import{apiLogDir as ru}from"document360-engine";function $i(){let e=ru();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!nu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=ou(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(bi(xi(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(bi(xi(e,r)).size/1024).toFixed(1);console.log(` ${$(r)} ${f(`${s} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as su,resolveAuth as iu,findByName as au,slugify as lu,touchSession as cu,upsertSession as uu,resolveActiveProfile as du}from"document360-engine";async function vi(e,t,n,o,r,s){let l=iu(n);l.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2)),l.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=du(e,r)}catch(b){console.error($(`Document360 profile error: ${b.message}`)),process.exit(2)}p.production&&(console.error(O(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let h;if(o){let b=au(e,o);b||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),h=b.uuid,console.error(f(`Resuming "${b.name}"`))}let k=su({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),x=h??null,D=1;for await(let b of k.send(t))switch(b.type){case"session":if(!x){x=b.sessionId;let T=new Date().toISOString();uu({uuid:x,name:lu(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:T,updatedAt:T})}break;case"text":process.stdout.write(b.delta);break;case"tool":console.error(ie(` \u2699 ${b.name}`));break;case"result":D=b.ok?0:1,console.error(f(`(${b.inputTokens}\u2192${b.outputTokens} tokens`+(b.costUsd>0?`, $${b.costUsd<.01?b.costUsd.toFixed(4):b.costUsd.toFixed(2)}`:"")+")")),b.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${b.message}`)),process.exit(1)}x&&cu(x),process.stdout.write(`
183
+ `),process.exit(D)}import{createInterface as bf}from"node:readline/promises";import{createSession as $s,resolveAuth as xf,getSession as $f,setTitle as vf,slugify as Cf,touchSession as gl,upsertSession as Pf,generateTitle as Rf,resolveActiveProfile as wl,resolveModelSetting as Tf,readProjectConfig as Sf,decodeJwtClaims as ml,isExpired as Df,loadTokens as jf}from"document360-engine";var Te=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --all to author capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then run d360-capture in your app's repo \u2014 it signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot --list",s:"See capture status \u2014 which specs exist and which are done."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"d360-capture is a separate Playwright CLI \u2014 run it in the app's repo (needs its URL + a login)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"Author capture specs (--all / --list)."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function pu(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 Ci(){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(pu(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function nr(){console.log("");for(let e of Ci())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 fu}from"document360-engine";async function Pi(e,t){let n=t.currentUuid(),o=n?fu(n):void 0;return console.log(o?f(`
184
184
  (conversation reset \u2014 "${o.name}" is still available via /resume)
185
185
  `):f(`
186
186
  (conversation reset \u2014 agent will start fresh on the next prompt)
187
- `)),{kind:"clear"}}async function or(){return{kind:"exit"}}Xn();W();import{readMcpConfig as cr,writeMcpConfig as Fi}from"document360-engine";async function Kn(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(xu(),{kind:"continue"}):t==="add"?($u(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(vu(e.slice(1)),{kind:"continue"}):(console.log($(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function xu(){let e=cr(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
187
+ `)),{kind:"clear"}}async function or(){return{kind:"exit"}}Kn();W();import{readMcpConfig as cr,writeMcpConfig as Bi}from"document360-engine";async function Qn(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Tu(),{kind:"continue"}):t==="add"?(Su(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Du(e.slice(1)),{kind:"continue"}):(console.log($(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Tu(){let e=cr(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
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(` ${_(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${_(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function $u(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=cr(),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 h=o[++p],k=h?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log($(`-H expects key:value (no spaces). Got: ${h??"(nothing)"}`));return}c[k[1].trim()]=k[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,Fi(r),console.log(""),console.log(j(`\u2713 Registered "${t}" (${n})`)),console.log(L(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function vu(e){let t=e[0];if(!t){console.log($("Usage: /mcp remove <name>"));return}let n=cr();if(!n.servers[t]){console.log($(`No server named "${t}".`));return}delete n.servers[t],Fi(n),console.log(j(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as Mu}from"node:fs";import{join as Uu}from"node:path";import{select as Wu}from"@inquirer/prompts";import{computeSyncStatus as yr,planPartitions as Fu,relatedArticlePaths as Hu,resolveModelForOperation as qu,runPartitioned as Bu,loadProfileMap as Yu,resolveActiveProfile as Gu,resolveCrossLinks as Vu,applyStructureOrder as Qi,orderSyncLine as Ji,applyRelatedArticles as Zi,relatedSyncLine as ea}from"document360-engine";import X from"picocolors";import Vi from"wrap-ansi";import hr from"string-width";W();import Ge from"picocolors";import ur from"wrap-ansi";import dr from"string-width";var Hi=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),qi=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Bi=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Cu(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(Hi(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&qi(t[o+1])){let p=Bi(r);o+=2;let h=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)h.push(Bi(t[o++]));n.push({kind:"table",header:p,rows:h});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])&&!Hi(t[o])&&!(t[o].includes("|")&&o+1<t.length&&qi(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function pr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ge.bold(t.slice(2,-2)):t.startsWith("`")?_(t.slice(1,-1)):Ge.italic(t.slice(1,-1)))}var Pu=(e,t)=>e+" ".repeat(Math.max(0,t-dr(e)));function Ru(e,t,n){let o=e.length,r=e.map((C,I)=>Math.max(dr(C),...t.map(N=>dr(N[I]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],h=()=>p.reduce((C,I)=>C+I,0)+c,k=0;for(;h()>s&&k++<1e4;){let C=-1,I=6;for(let N=0;N<o;N++)p[N]>I&&(I=p[N],C=N);if(C===-1)break;p[C]-=1}let x=(C,I,N)=>Ge.gray(C+p.map(M=>"\u2500".repeat(M+2)).join(I)+N),D=Ge.gray("\u2502"),b=(C,I)=>{let N=p.map((pe,ne)=>{let De=C[ne]??"",ue=I?Ge.bold(De):pr(De);return ur(ue,pe,{hard:!0}).split(`
191
- `)}),M=Math.max(...N.map(pe=>pe.length)),J=[];for(let pe=0;pe<M;pe++)J.push(p.map((ne,De)=>`${D} ${Pu(N[De][pe]??"",ne)} `).join("")+D);return J.join(`
192
- `)},T=[x("\u250C","\u252C","\u2510"),b(e,!0)];return T.push(t.length===0?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524")),t.forEach((C,I)=>{T.push(b(C,!1)),T.push(I===t.length-1?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524"))}),T.join(`
193
- `)}function Tu(e,t){switch(e.kind){case"heading":return Ge.bold(e.text);case"hr":return Ge.gray("\u2500".repeat(t));case"para":return ur(pr(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=ur(pr(n),Math.max(10,t-4)).split(`
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(` ${_(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${_(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Su(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=cr(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let l={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let h=o[++p],k=h?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log($(`-H expects key:value (no spaces). Got: ${h??"(nothing)"}`));return}l[k[1].trim()]=k[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(l).length>0?l:void 0}}r.servers[t]=s,Bi(r),console.log(""),console.log(A(`\u2713 Registered "${t}" (${n})`)),console.log(O(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Du(e){let t=e[0];if(!t){console.log($("Usage: /mcp remove <name>"));return}let n=cr();if(!n.servers[t]){console.log($(`No server named "${t}".`));return}delete n.servers[t],Bi(n),console.log(A(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as Bu}from"node:fs";import{join as Yu}from"node:path";import{select as Gu}from"@inquirer/prompts";import{computeSyncStatus as yr,planPartitions as Vu,relatedArticlePaths as zu,resolveModelForOperation as Xu,runPartitioned as Ku,loadProfileMap as Qu,resolveActiveProfile as Ju,resolveCrossLinks as Zu,applyStructureOrder as ea,orderSyncLine as ta,applyRelatedArticles as na,relatedSyncLine as oa}from"document360-engine";import X from"picocolors";import Ki from"wrap-ansi";import hr from"string-width";W();import Ge from"picocolors";import ur from"wrap-ansi";import dr from"string-width";var Yi=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Gi=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Vi=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function ju(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(Yi(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Gi(t[o+1])){let p=Vi(r);o+=2;let h=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)h.push(Vi(t[o++]));n.push({kind:"table",header:p,rows:h});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 l=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Yi(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Gi(t[o+1]));)l.push(t[o++]);n.push({kind:"para",text:l.join(" ")})}return n}function pr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ge.bold(t.slice(2,-2)):t.startsWith("`")?_(t.slice(1,-1)):Ge.italic(t.slice(1,-1)))}var Au=(e,t)=>e+" ".repeat(Math.max(0,t-dr(e)));function Eu(e,t,n){let o=e.length,r=e.map((C,N)=>Math.max(dr(C),...t.map(I=>dr(I[N]??"")))),s=Math.max(24,n),l=3*o+1,p=[...r],h=()=>p.reduce((C,N)=>C+N,0)+l,k=0;for(;h()>s&&k++<1e4;){let C=-1,N=6;for(let I=0;I<o;I++)p[I]>N&&(N=p[I],C=I);if(C===-1)break;p[C]-=1}let x=(C,N,I)=>Ge.gray(C+p.map(M=>"\u2500".repeat(M+2)).join(N)+I),D=Ge.gray("\u2502"),b=(C,N)=>{let I=p.map((fe,oe)=>{let De=C[oe]??"",ue=N?Ge.bold(De):pr(De);return ur(ue,fe,{hard:!0}).split(`
191
+ `)}),M=Math.max(...I.map(fe=>fe.length)),J=[];for(let fe=0;fe<M;fe++)J.push(p.map((oe,De)=>`${D} ${Au(I[De][fe]??"",oe)} `).join("")+D);return J.join(`
192
+ `)},T=[x("\u250C","\u252C","\u2510"),b(e,!0)];return T.push(t.length===0?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524")),t.forEach((C,N)=>{T.push(b(C,!1)),T.push(N===t.length-1?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524"))}),T.join(`
193
+ `)}function Nu(e,t){switch(e.kind){case"heading":return Ge.bold(e.text);case"hr":return Ge.gray("\u2500".repeat(t));case"para":return ur(pr(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=ur(pr(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=>Ge.gray(" "+n)).join(`
197
- `);case"table":return Ru(e.header,e.rows,t)}}function fr(e,t){let n=Math.max(20,t);return Cu(e).map(o=>Tu(o,n)).join(`
198
-
199
- `)}W();import Su from"picocolors";var Du=[127,86,217],ju=[22,38,43],Yi={T:Du,E:ju},nn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],mr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Au=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Gi(){if(!Su.isColorSupported)return[];let e=nn[0].length,t=[];for(let n=0;n<nn.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Yi[nn[n][r]],c=n+1<nn.length?Yi[nn[n+1][r]]:void 0;s&&c?o+=`${mr(s)}${Au(c)}\u2580\x1B[49m\x1B[39m`:s?o+=`${mr(s)}\u2580\x1B[39m`:c?o+=`${mr(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function on(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function he(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Ve(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Ot=(e,t)=>` ${e.padEnd(13)}${t}`;function Eu(e,t){let n=[Kt("\u270E document360-writer")+X.gray(` v${e.version}`),X.gray(" Reads your code, writes your docs."),"",Ot("Claude:",`${e.claude}${X.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Ot("Document360:",e.configured?e.loggedOut?X.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?X.gray(` (${e.sessionHint})`):""}`:X.yellow("not set up \u2014 run /init")),Ot("Profile:",e.configured?`${e.profile}${X.gray(` (${e.apiUrl})`)}${e.prod?X.bold(X.yellow(" \u26A0 PRODUCTION")):""}`:X.gray("\u2014 (run /init)")),Ot("Project:",e.project),Ot("Mode:",X.gray(e.mode)),Ot("cwd:",X.gray(e.cwd))],o=Gi();if(o.length===0)return n.join(`
200
- `);let r=2,s=3,c=hr(o[0]);if(!(t>=r+c+s+Math.max(...n.map(x=>hr(x)))))return[...o.map(x=>" "+x),...n].join(`
201
- `);let h=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let x=0;x<Math.max(o.length+h,n.length);x++){let D=o[x-h]??" ".repeat(c);k.push((" ".repeat(r)+D+" ".repeat(s)+(n[x]??"")).trimEnd())}return k.join(`
202
- `)}var Nu={error:X.red,warn:X.yellow,ok:X.green,info:X.gray};function gr(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Eu(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
- `).flatMap(k=>Vi(k,s,{hard:!0}).split(`
204
- `)),h=Math.max(0,p.length-c);return h>0&&(p=[...p.slice(0,c),X.dim(`\u2026 +${h} more lines`)]),`
197
+ `);case"table":return Eu(e.header,e.rows,t)}}function fr(e,t){let n=Math.max(20,t);return ju(e).map(o=>Nu(o,n)).join(`
198
+
199
+ `)}W();import Iu from"picocolors";var _u=[127,86,217],Ou=[22,38,43],zi={T:_u,E:Ou},on=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],mr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Lu=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Xi(){if(!Iu.isColorSupported)return[];let e=on[0].length,t=[];for(let n=0;n<on.length;n+=2){let o="";for(let r=0;r<e;r++){let s=zi[on[n][r]],l=n+1<on.length?zi[on[n+1][r]]:void 0;s&&l?o+=`${mr(s)}${Lu(l)}\u2580\x1B[49m\x1B[39m`:s?o+=`${mr(s)}\u2580\x1B[39m`:l?o+=`${mr(l)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function rn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function he(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Ve(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Lt=(e,t)=>` ${e.padEnd(13)}${t}`;function Mu(e,t){let n=[Qt("\u270E document360-writer")+X.gray(` v${e.version}`),X.gray(" Reads your code, writes your docs."),"",Lt("Claude:",`${e.claude}${X.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Lt("Document360:",e.configured?e.loggedOut?X.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?X.gray(` (${e.sessionHint})`):""}`:X.yellow("not set up \u2014 run /init")),Lt("Profile:",e.configured?`${e.profile}${X.gray(` (${e.apiUrl})`)}${e.prod?X.bold(X.yellow(" \u26A0 PRODUCTION")):""}`:X.gray("\u2014 (run /init)")),Lt("Project:",e.project),Lt("Mode:",X.gray(e.mode)),Lt("cwd:",X.gray(e.cwd))],o=Xi();if(o.length===0)return n.join(`
200
+ `);let r=2,s=3,l=hr(o[0]);if(!(t>=r+l+s+Math.max(...n.map(x=>hr(x)))))return[...o.map(x=>" "+x),...n].join(`
201
+ `);let h=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let x=0;x<Math.max(o.length+h,n.length);x++){let D=o[x-h]??" ".repeat(l);k.push((" ".repeat(r)+D+" ".repeat(s)+(n[x]??"")).trimEnd())}return k.join(`
202
+ `)}var Uu={error:X.red,warn:X.yellow,ok:X.green,info:X.gray};function gr(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Mu(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),l=50,p=e.text.split(`
203
+ `).flatMap(k=>Ki(k,s,{hard:!0}).split(`
204
+ `)),h=Math.max(0,p.length-l);return h>0&&(p=[...p.slice(0,l),X.dim(`\u2026 +${h} more lines`)]),`
205
205
  `+p.map((k,x)=>o+(x===0?_(" \u276F "):" ")+k+" ".repeat(Math.max(0,s-hr(k))+1)+r).join(`
206
206
  `)}case"assistant":return`
207
207
  `+fr(e.text,n);case"tool":{let o=e.arg!==null?X.gray(`${e.sep}(${e.arg})`):"";return`
208
- `+Vi(X.green("\u25CF ")+X.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?X.red:X.gray,r=e.lines.map((s,c)=>o((c===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(X.dim(` \u2026 +${e.hidden} lines`)),r.join(`
209
- `)}case"diff":{let o=c=>c===1?"":"s",s=[X.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(X.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
210
- `)}case"link":return e.lines.map(o=>_(Jt(` \u2B95 ${o}`))).join(`
208
+ `+Ki(X.green("\u25CF ")+X.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?X.red:X.gray,r=e.lines.map((s,l)=>o((l===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(X.dim(` \u2026 +${e.hidden} lines`)),r.join(`
209
+ `)}case"diff":{let o=l=>l===1?"":"s",s=[X.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(X.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
210
+ `)}case"link":return e.lines.map(o=>_(Zt(` \u2B95 ${o}`))).join(`
211
211
  `);case"preview":return`
212
- `+Kt(`\u25A3 Preview \u2014 ${e.name}`)+`
212
+ `+Qt(`\u25A3 Preview \u2014 ${e.name}`)+`
213
213
 
214
214
  `+fr(e.text,n);case"note":return`
215
- `+Nu[e.tone](Jt(e.text));case"done":return`
216
- `+(e.ok?X.magenta("\u2736 "):X.red("\u2736 "))+X.gray(`Cooked for ${on(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${he(e.costUsd)}`:""))}}function zi(e,t){return e.map(n=>gr(n,t)).join(`
217
- `)}import{resolveActiveProfile as Iu,loadTokens as _u,isExpired as Lu,decodeJwtClaims as Xi}from"document360-engine";function Ou(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Oe(e,t){try{let n=Iu(e,t),o=_u(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Lu(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={...Xi(o.idToken)??{},...Xi(o.accessToken)??{}}.doc360_project_id;if(typeof c=="string"&&c&&c!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${Ou(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var rn=3;function kr(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
- `)}var Ki={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function sn(e){return e.filter(t=>t.path!==null&&t.status in Ki&&!t.link).map(t=>({path:t.path,label:Ki[t.status]}))}function Qn(e){return e.filter(t=>t.link).length}function br(e,t){try{let n=Yu(e,Gu(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Vu(Mu(Uu(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 zu(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 ta(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:`${zu(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 Jn(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 xr(e,t,n){let o=b=>t[b.index]?.paths.length??0,r=e.filter(b=>b.ok),s=e.filter(b=>!b.ok),c=e.reduce((b,T)=>b+o(T),0),p=r.reduce((b,T)=>b+o(T),0),h=n==="api"?`${he(e.reduce((b,T)=>b+T.costUsd,0))} total`:Ve(e.reduce((b,T)=>b+T.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,x=b=>`${b} article${b===1?"":"s"}`,D=[];if(s.length===0)D.push(`Published ${x(c)} (${k}) successfully \xB7 ${h}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${x(c)} (${k}) \xB7 ${h}.`),D.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 b of s)D.push(` \u2717 ${b.label}${b.error?` \u2014 ${b.error}`:""}`)}return D}async function wr(e,t){let n=Fu(t),{model:o}=qu(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${rn} agents at once) on ${o}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let r of Bu({cwd:e.cwd,partitions:n,promptFor:s=>Jn(s.paths),concurrency:rn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:o}))if(r.type==="partition_status")r.status==="running"?console.log(f(` \u25B8 ${r.label} \u2014 publishing\u2026`)):r.status==="done"?console.log(j(` \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 xr(r.results,n,s))console.log(r.ok?j(p):L(p));let c=br(e.cwd,e.profileName);c&&console.log(f(c));try{let p=Ji(await Qi({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}try{let p=ea(await Zi({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}}}catch(r){console.log($(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Zn(e,t,n){let o=Hu(e,n);if(o.length===0)return[];let r=new Set(sn((await yr({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function na(e,t){let n=Oe(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 Zn(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(j("\u2713 All related articles are already published.")),{kind:"continue"}):await wr(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await yr({cwd:t?.cwd??process.cwd()}),s=sn(r.entries),c=Qn(r.entries);if(c>0&&console.log(L(`\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){if(console.log(j(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let p=Ji(await Qi({cwd:t.cwd,profileName:t.profileName}));p&&console.log(f(p));let h=ea(await Zi({cwd:t.cwd,profileName:t.profileName}));h&&console.log(f(h))}catch{}return{kind:"continue"}}return t?await wr(t,s.map(p=>p.path)):{kind:"forward-to-agent",prompt:Jn(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(f("Checking what needs publishing\u2026"));let r;try{let s=await yr({cwd:t?.cwd??process.cwd()});r=sn(s.entries);let c=Qn(s.entries);c>0&&console.log(L(`\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(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(j("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(f(" (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} ${f(`(${s.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>Wu({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(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await wr(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:kr(o),display:`/publish ${o}`}}async function an(){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 Xu}from"@inquirer/prompts";import{inventoryRepo as Ku,readProjectConfig as oa,writeProjectConfig as Qu}from"document360-engine";function $r(e,t){let n=oa(e);n&&(n.authoritativeSourceFiles=t,Qu(n,e))}function eo(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 ra(e,t){let n=t?.cwd??process.cwd();if(!oa(n))return console.log($("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Ku(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(_("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(eo(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Xu({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${eo(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(f("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};$r(n,r),console.log(j(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as od}from"@inquirer/prompts";import{applyPull as Cr,computeSyncStatus as ca,compareRemoteSources as rd,planPull as ua,planImport as sd,applyImport as id,establishBaselines as ad,rebaselineServerMeta as ld,D360AuthError as cd}from"document360-engine";W();var sa=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:$,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:L,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:_,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:ie,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:f,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:f,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:ie,mark:"\xB7"}];function Ju(e){return e.path?e.path:`${e.title??"(untitled)"} ${ie(`[${e.articleId}]`)}`}function Zu(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60);return`${n}m ${Math.round(t-n*60)}s`}function to(e,t){let n=[],o=e.entries.filter(x=>x.link);if(o.length>0){n.push(""),n.push(Pe("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let x of o)n.push(` ${L("~")} ${L(x.path??"")} ${ie(`\u2192 "${x.link.title}"`)}`)}for(let x of sa){let D=e.entries.filter(b=>b.status===x.status&&!(x.status==="untracked-local"&&b.link));if(D.length!==0){n.push(""),n.push(Pe(x.header));for(let b of D)n.push(` ${x.paint(x.mark)} ${x.paint(Ju(b))}${b.detail?ie(` (${b.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let c={"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"},p=o.length,h=s===r?j("\u2713 everything up to date"):[r>0?j(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...sa.map(x=>{let D=(e.counts[x.status]??0)-(x.status==="untracked-local"?p:0);return D>0?`${D} ${c[x.status]}`:null})].filter(Boolean).join(ie(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${Zu(t)}`:"";return n.push(h+ie(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as ed}from"diff";import ia from"picocolors";var aa=80,td="\x1B[48;2;74;28;28m",nd="\x1B[48;2;24;66;24m",la="\x1B[49m",vr=e=>String(e).padStart(5);function ut(e,t,n){let o=b=>{let T=b.replace(/\r\n/g,`
215
+ `+Uu[e.tone](Zt(e.text));case"done":return`
216
+ `+(e.ok?X.magenta("\u2736 "):X.red("\u2736 "))+X.gray(`Cooked for ${rn(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${he(e.costUsd)}`:""))}}function Qi(e,t){return e.map(n=>gr(n,t)).join(`
217
+ `)}import{resolveActiveProfile as Wu,loadTokens as Fu,isExpired as Hu,decodeJwtClaims as Ji}from"document360-engine";function qu(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Le(e,t){try{let n=Wu(e,t),o=Fu(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Hu(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let l={...Ji(o.idToken)??{},...Ji(o.accessToken)??{}}.doc360_project_id;if(typeof l=="string"&&l&&l!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${qu(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var sn=3;function kr(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
+ `)}var Zi={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function an(e){return e.filter(t=>t.path!==null&&t.status in Zi&&!t.link).map(t=>({path:t.path,label:Zi[t.status]}))}function Jn(e){return e.filter(t=>t.link).length}function br(e,t){try{let n=Qu(e,Ju(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Zu(Bu(Yu(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 ed(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 ra(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,l)=>s.path.localeCompare(l.path));t.push({kind:"category",label:`${ed(o)} (${r.length})`,paths:r.map(s=>s.path),indent:!1});for(let s of r){let l=s.path.replace(/\\/g,"/").split("/").pop()??s.path;t.push({kind:"article",label:l,paths:[s.path],indent:!0,note:s.label})}}return t}function Zn(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 xr(e,t,n){let o=b=>t[b.index]?.paths.length??0,r=e.filter(b=>b.ok),s=e.filter(b=>!b.ok),l=e.reduce((b,T)=>b+o(T),0),p=r.reduce((b,T)=>b+o(T),0),h=n==="api"?`${he(e.reduce((b,T)=>b+T.costUsd,0))} total`:Ve(e.reduce((b,T)=>b+T.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,x=b=>`${b} article${b===1?"":"s"}`,D=[];if(s.length===0)D.push(`Published ${x(l)} (${k}) successfully \xB7 ${h}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${x(l)} (${k}) \xB7 ${h}.`),D.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 b of s)D.push(` \u2717 ${b.label}${b.error?` \u2014 ${b.error}`:""}`)}return D}async function wr(e,t){let n=Vu(t),{model:o}=Xu(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${sn} agents at once) on ${o}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let r of Ku({cwd:e.cwd,partitions:n,promptFor:s=>Zn(s.paths),concurrency:sn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:o}))if(r.type==="partition_status")r.status==="running"?console.log(f(` \u25B8 ${r.label} \u2014 publishing\u2026`)):r.status==="done"?console.log(A(` \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 xr(r.results,n,s))console.log(r.ok?A(p):O(p));let l=br(e.cwd,e.profileName);l&&console.log(f(l));try{let p=ta(await ea({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}try{let p=oa(await na({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}}}catch(r){console.log($(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function eo(e,t,n){let o=zu(e,n);if(o.length===0)return[];let r=new Set(an((await yr({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function sa(e,t){let n=Le(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 eo(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(A("\u2713 All related articles are already published.")),{kind:"continue"}):await wr(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await yr({cwd:t?.cwd??process.cwd()}),s=an(r.entries),l=Jn(r.entries);if(l>0&&console.log(O(`\u26A0 ${l} 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){if(console.log(A(l>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let p=ta(await ea({cwd:t.cwd,profileName:t.profileName}));p&&console.log(f(p));let h=oa(await na({cwd:t.cwd,profileName:t.profileName}));h&&console.log(f(h))}catch{}return{kind:"continue"}}return t?await wr(t,s.map(p=>p.path)):{kind:"forward-to-agent",prompt:Zn(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(f("Checking what needs publishing\u2026"));let r;try{let s=await yr({cwd:t?.cwd??process.cwd()});r=an(s.entries);let l=Jn(s.entries);l>0&&console.log(O(`\u26A0 ${l} 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(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(A("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(f(" (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} ${f(`(${s.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>Gu({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(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await wr(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:kr(o),display:`/publish ${o}`}}async function ln(){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 td}from"@inquirer/prompts";import{inventoryRepo as nd,readProjectConfig as ia,writeProjectConfig as od}from"document360-engine";function $r(e,t){let n=ia(e);n&&(n.authoritativeSourceFiles=t,od(n,e))}function to(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 aa(e,t){let n=t?.cwd??process.cwd();if(!ia(n))return console.log($("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=nd(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(_("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(to(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>td({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${to(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(f("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};$r(n,r),console.log(A(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as cd}from"@inquirer/prompts";import{applyPull as Cr,computeSyncStatus as pa,compareRemoteSources as ud,planPull as fa,planImport as dd,applyImport as pd,establishBaselines as fd,rebaselineServerMeta as md,D360AuthError as hd}from"document360-engine";W();var la=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:$,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:O,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:_,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:ie,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:f,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:f,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:ie,mark:"\xB7"}];function rd(e){return e.path?e.path:`${e.title??"(untitled)"} ${ie(`[${e.articleId}]`)}`}function sd(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60);return`${n}m ${Math.round(t-n*60)}s`}function no(e,t){let n=[],o=e.entries.filter(x=>x.link);if(o.length>0){n.push(""),n.push(Re("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let x of o)n.push(` ${O("~")} ${O(x.path??"")} ${ie(`\u2192 "${x.link.title}"`)}`)}for(let x of la){let D=e.entries.filter(b=>b.status===x.status&&!(x.status==="untracked-local"&&b.link));if(D.length!==0){n.push(""),n.push(Re(x.header));for(let b of D)n.push(` ${x.paint(x.mark)} ${x.paint(rd(b))}${b.detail?ie(` (${b.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let l={"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"},p=o.length,h=s===r?A("\u2713 everything up to date"):[r>0?A(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...la.map(x=>{let D=(e.counts[x.status]??0)-(x.status==="untracked-local"?p:0);return D>0?`${D} ${l[x.status]}`:null})].filter(Boolean).join(ie(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${sd(t)}`:"";return n.push(h+ie(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as id}from"diff";import ca from"picocolors";var ua=80,ad="\x1B[48;2;74;28;28m",ld="\x1B[48;2;24;66;24m",da="\x1B[49m",vr=e=>String(e).padStart(5);function ut(e,t,n){let o=b=>{let T=b.replace(/\r\n/g,`
221
221
  `);return T.endsWith(`
222
222
  `)||T===""?T:T+`
223
- `},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=ed("a","b",r,s,"","",{context:3}),h=0,k=0,x=[];p.hunks.forEach((b,T)=>{T>0&&x.push(ia.gray(" \u2026"));let C=b.oldStart,I=b.newStart;for(let N of b.lines){let M=N[0],J=N.slice(1).slice(0,c);M==="-"?(k++,x.push(`${td}${vr(C++)} - ${J}${la}`)):M==="+"?(h++,x.push(`${nd}${vr(I++)} + ${J}${la}`)):(x.push(ia.gray(vr(I))+" "+J),C++,I++)}});let D=x.slice(0,aa);return{added:h,removed:k,lines:D,hidden:Math.max(0,x.length-aa)}}async function da(e,t){let n=Oe(t.cwd,t.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await ud(t),{kind:"continue"};if(o==="--baseline")return await dd(t,e.filter(c=>c!=="--baseline")),{kind:"continue"};if(o==="--compare")return await pd(t),{kind:"continue"};if(o)return console.log($(`Unknown option: ${o}`)),console.log(f("Usage: /pull pull portal edits + import new portal articles")),console.log(f(" /pull <path> pull one article (or resolve a conflict)")),console.log(f(" /pull --status drift report only (no writes)")),console.log(f(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await fd(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await Pr({cwd:t.cwd,profileName:t.profileName});for(let c of Rr(s))console.log(c.tone==="ok"?j(c.text):c.tone==="warn"?L(c.text):f(c.text));console.log("")}catch(r){r instanceof cd?console.log($(r.message)):console.log($(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Pr(e){let t=await ca({cwd:e.cwd,profileName:e.profileName}),n={pulled:[],imported:[],conflicts:[],toPublish:0,failed:[]};for(let o of t.entries)if(o.status==="remote-ahead"&&o.path)try{let r=await ua({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Cr({cwd:e.cwd,profileName:e.profileName},r),n.pulled.push(o.path)}catch(r){n.failed.push({ref:o.path,error:r.message})}else if(o.status==="untracked-remote"&&o.articleId)try{let r=await sd({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});id({cwd:e.cwd,profileName:e.profileName},r),n.imported.push({title:r.title,path:r.path})}catch(r){n.failed.push({ref:o.title??o.articleId,error:r.message})}else o.status==="conflict"&&o.path?n.conflicts.push(o.path):(o.status==="local-ahead"||o.status==="untracked-local"&&!o.link)&&o.path&&n.toPublish++;return n}var no=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,dt=e=>e===1?"":"s";function Rr(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${dt(e.pulled.length)} into local: ${no(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${dt(e.imported.length)}: ${no(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${dt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${dt(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Take the portal copy: /pull <path> \xB7 keep yours: /publish <path>. (${no(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${dt(e.failed.length)} failed: ${no(e.failed.map(n=>n.ref))}`}),t.length===0&&t.push({tone:"ok",text:"\u2713 Already in sync with Document360 \u2014 nothing to pull."}),t}async function ud(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await ca({cwd:e.cwd,profileName:e.profileName});for(let o of to(n,Date.now()-t))console.log(o);console.log("")}async function dd(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(f(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await ad({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await ld({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(j("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(j(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(j(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(L(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(f(` - ${s.path} (${s.reason})`))}}async function pd(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await rd({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Pe(String(t.legacyCount))} \xB7 Manifest: ${Pe(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(j("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log($(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(L(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(L(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(f(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function fd(e,t){let n=t.replace(/\\/g,"/"),o=await ua({cwd:e.cwd,profileName:e.profileName,relPath:n});console.log(""),console.log(`${_("\u25CF")} ${Pe(o.title)} ${ie(`(${o.path})`)}`);for(let c of o.notes)console.log(L(` \u26A0 ${c}`));o.overwritesLocalChanges&&console.log(L(" \u26A0 This OVERWRITES local edits made since the last sync."));let r=ut(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(f(" Local file already matches the remote content \u2014 advancing the sync base only.")),Cr({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ie(` \u23BF Added ${r.added} line${dt(r.added)}, removed ${r.removed} line${dt(r.removed)}`));for(let c of r.lines)console.log(c);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>od({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}Cr({cwd:e.cwd,profileName:e.profileName},o),console.log(j(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as md}from"node:fs";import{resolve as hd}from"node:path";import{estimateBulkCost as gd,planPartitions as wd,readProjectConfig as yd,resolveModelForOperation as kd,runPartitioned as bd,trackedArticlePaths as xd}from"document360-engine";var Tr=3;function Sr(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 Dr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function jr(e,t){return t.map(n=>{let o=0;try{o=md(hd(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 l=Math.max(20,n-10),p=id("a","b",r,s,"","",{context:3}),h=0,k=0,x=[];p.hunks.forEach((b,T)=>{T>0&&x.push(ca.gray(" \u2026"));let C=b.oldStart,N=b.newStart;for(let I of b.lines){let M=I[0],J=I.slice(1).slice(0,l);M==="-"?(k++,x.push(`${ad}${vr(C++)} - ${J}${da}`)):M==="+"?(h++,x.push(`${ld}${vr(N++)} + ${J}${da}`)):(x.push(ca.gray(vr(N))+" "+J),C++,N++)}});let D=x.slice(0,ua);return{added:h,removed:k,lines:D,hidden:Math.max(0,x.length-ua)}}async function ma(e,t){let n=Le(t.cwd,t.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await gd(t),{kind:"continue"};if(o==="--baseline")return await wd(t,e.filter(l=>l!=="--baseline")),{kind:"continue"};if(o==="--compare")return await yd(t),{kind:"continue"};if(o)return console.log($(`Unknown option: ${o}`)),console.log(f("Usage: /pull pull portal edits + import new portal articles")),console.log(f(" /pull <path> pull one article (or resolve a conflict)")),console.log(f(" /pull --status drift report only (no writes)")),console.log(f(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await kd(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await Pr({cwd:t.cwd,profileName:t.profileName});for(let l of Rr(s))console.log(l.tone==="ok"?A(l.text):l.tone==="warn"?O(l.text):f(l.text));console.log("")}catch(r){r instanceof hd?console.log($(r.message)):console.log($(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Pr(e){let t=await pa({cwd:e.cwd,profileName:e.profileName}),n={pulled:[],imported:[],conflicts:[],toPublish:0,failed:[]};for(let o of t.entries)if(o.status==="remote-ahead"&&o.path)try{let r=await fa({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Cr({cwd:e.cwd,profileName:e.profileName},r),n.pulled.push(o.path)}catch(r){n.failed.push({ref:o.path,error:r.message})}else if(o.status==="untracked-remote"&&o.articleId)try{let r=await dd({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});pd({cwd:e.cwd,profileName:e.profileName},r),n.imported.push({title:r.title,path:r.path})}catch(r){n.failed.push({ref:o.title??o.articleId,error:r.message})}else o.status==="conflict"&&o.path?n.conflicts.push(o.path):(o.status==="local-ahead"||o.status==="untracked-local"&&!o.link)&&o.path&&n.toPublish++;return n}var oo=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,dt=e=>e===1?"":"s";function Rr(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${dt(e.pulled.length)} into local: ${oo(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${dt(e.imported.length)}: ${oo(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${dt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${dt(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Take the portal copy: /pull <path> \xB7 keep yours: /publish <path>. (${oo(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${dt(e.failed.length)} failed: ${oo(e.failed.map(n=>n.ref))}`}),t.length===0&&t.push({tone:"ok",text:"\u2713 Already in sync with Document360 \u2014 nothing to pull."}),t}async function gd(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await pa({cwd:e.cwd,profileName:e.profileName});for(let o of no(n,Date.now()-t))console.log(o);console.log("")}async function wd(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(f(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await fd({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await md({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(A("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(A(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(A(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(O(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(f(` - ${s.path} (${s.reason})`))}}async function yd(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await ud({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Re(String(t.legacyCount))} \xB7 Manifest: ${Re(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(A("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log($(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(O(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(O(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(f(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function kd(e,t){let n=t.replace(/\\/g,"/"),o=await fa({cwd:e.cwd,profileName:e.profileName,relPath:n});console.log(""),console.log(`${_("\u25CF")} ${Re(o.title)} ${ie(`(${o.path})`)}`);for(let l of o.notes)console.log(O(` \u26A0 ${l}`));o.overwritesLocalChanges&&console.log(O(" \u26A0 This OVERWRITES local edits made since the last sync."));let r=ut(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(f(" Local file already matches the remote content \u2014 advancing the sync base only.")),Cr({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ie(` \u23BF Added ${r.added} line${dt(r.added)}, removed ${r.removed} line${dt(r.removed)}`));for(let l of r.lines)console.log(l);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>cd({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}Cr({cwd:e.cwd,profileName:e.profileName},o),console.log(A(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as bd}from"node:fs";import{resolve as xd}from"node:path";import{estimateBulkCost as $d,planPartitions as vd,readProjectConfig as Cd,resolveModelForOperation as Pd,runPartitioned as Rd,trackedArticlePaths as Td}from"document360-engine";var Tr=3;function Sr(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 Dr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function jr(e,t){return t.map(n=>{let o=0;try{o=bd(xd(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 Er(e,t,n){let o=e.reduce((p,h)=>p+h.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: ${he(r)}\u2013${he(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Nr(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,I)=>C+o(I),0),p=r.reduce((C,I)=>C+o(I),0),h=e.reduce((C,I)=>C+I.costUsd,0),k=e.reduce((C,I)=>C+I.outputTokens,0),x=n==="api"?`${he(h)} total`:Ve(k),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=C=>`${C} article${C===1?"":"s"}`,T=[];if(s.length===0)T.push(`Converted ${b(c)} (${D}) successfully \xB7 ${x}.`);else{T.push(`Converted ${p}/${b(c)} (${D}) \xB7 ${x}.`),T.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)T.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return T}async function pa(e,t){if(!yd(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Sr(e),r=xd(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=Dr(r,n);if(s.length===0)return console.log($(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=wd(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:h,forced:k}=kd(t.cwd,"light");if(!o){let x=gd({files:jr(t.cwd,s),op:"convert",model:h});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let D of Er(c,x,Tr))console.log(D);return console.log(f(`Model: ${h}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${c.length} partitions (\u2264${Tr} agents at once) on ${h}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let x of bd({cwd:t.cwd,partitions:c,promptFor:Ar,concurrency:Tr,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:h}))if(x.type==="partition_status")x.status==="running"?console.log(f(` \u25B8 ${x.label} \u2014 converting\u2026`)):x.status==="done"?console.log(j(` \u2713 ${x.label}`)):console.log($(` \u2717 ${x.label}`));else if(x.type==="run_done"){console.log("");let D=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let b of Nr(x.results,c,D))console.log(x.ok?j(b):L(b))}}catch(x){console.log($(`Convert run failed: ${x.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as fa}from"node:fs";import{resolve as ma}from"node:path";import{estimateBulkCost as $d,lintDocs as vd,planPartitions as Cd,readDocsPlan as Pd,readProjectConfig as ha,DEFAULT_DOCS_DIR as Rd,resolveModelForOperation as Td,runPartitioned as Sd}from"document360-engine";var Dd=3,jd=8;function Ir(e){return e===void 0||!Number.isFinite(e)?Dd:Math.max(1,Math.min(Math.floor(e),jd))}function _r(e){let t,n,o=!1,r=!1,s,c=h=>{let k=Number(h);return h!==void 0&&Number.isFinite(k)?k:void 0};for(let h=0;h<e.length;h++){let k=e[h];if(k==="--preview"||k==="--dry-run")o=!0;else if(k==="--rewrite"||k==="--force")r=!0;else{if(k==="--run"||k==="--yes"||k==="--all")continue;k==="--scope"?t=e[++h]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?s=c(e[++h]):k?.startsWith("--concurrency=")?s=c(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=h=>h?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function Ad(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Ed(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Lr(e,t,n){return n.filter(o=>{try{return fa(ma(e,t,o)).size===0}catch{return!0}})}function Or(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+=fa(ma(e,c)).size}catch{}return{path:r,bytes:s}})}function Mr(e,t,n={}){let o=n.rewrite?`- Some or all of these articles ALREADY EXIST on disk \u2014 this is a re-author (rewrite/upgrade), NOT a first draft. For any that exist, do NOT preserve or lightly-edit the current file: RE-AUTHOR it from scratch against the plan + sources + the active doc-type playbook standard. The existing file is what you're replacing \u2014 its structure is NOT the target; match only the project's voice/terminology.
229
+ `)}function Er(e,t,n){let o=e.reduce((p,h)=>p+h.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: ${he(r)}\u2013${he(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Nr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),l=e.reduce((C,N)=>C+o(N),0),p=r.reduce((C,N)=>C+o(N),0),h=e.reduce((C,N)=>C+N.costUsd,0),k=e.reduce((C,N)=>C+N.outputTokens,0),x=n==="api"?`${he(h)} total`:Ve(k),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=C=>`${C} article${C===1?"":"s"}`,T=[];if(s.length===0)T.push(`Converted ${b(l)} (${D}) successfully \xB7 ${x}.`);else{T.push(`Converted ${p}/${b(l)} (${D}) \xB7 ${x}.`),T.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)T.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return T}async function ha(e,t){if(!Cd(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Sr(e),r=Td(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=Dr(r,n);if(s.length===0)return console.log($(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let l=vd(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:h,forced:k}=Pd(t.cwd,"light");if(!o){let x=$d({files:jr(t.cwd,s),op:"convert",model:h});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let D of Er(l,x,Tr))console.log(D);return console.log(f(`Model: ${h}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${l.length} partitions (\u2264${Tr} agents at once) on ${h}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let x of Rd({cwd:t.cwd,partitions:l,promptFor:Ar,concurrency:Tr,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:h}))if(x.type==="partition_status")x.status==="running"?console.log(f(` \u25B8 ${x.label} \u2014 converting\u2026`)):x.status==="done"?console.log(A(` \u2713 ${x.label}`)):console.log($(` \u2717 ${x.label}`));else if(x.type==="run_done"){console.log("");let D=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let b of Nr(x.results,l,D))console.log(x.ok?A(b):O(b))}}catch(x){console.log($(`Convert run failed: ${x.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as ga}from"node:fs";import{resolve as wa}from"node:path";import{estimateBulkCost as Sd,lintDocs as Dd,planPartitions as jd,readDocsPlan as Ad,readProjectConfig as ya,DEFAULT_DOCS_DIR as Ed,resolveModelForOperation as Nd,runPartitioned as Id}from"document360-engine";var _d=3,Od=8;function Ir(e){return e===void 0||!Number.isFinite(e)?_d:Math.max(1,Math.min(Math.floor(e),Od))}function _r(e){let t,n,o=!1,r=!1,s,l=h=>{let k=Number(h);return h!==void 0&&Number.isFinite(k)?k:void 0};for(let h=0;h<e.length;h++){let k=e[h];if(k==="--preview"||k==="--dry-run")o=!0;else if(k==="--rewrite"||k==="--force")r=!0;else{if(k==="--run"||k==="--yes"||k==="--all")continue;k==="--scope"?t=e[++h]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?s=l(e[++h]):k?.startsWith("--concurrency=")?s=l(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=h=>h?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function Ld(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Md(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Or(e,t,n){return n.filter(o=>{try{return ga(wa(e,t,o)).size===0}catch{return!0}})}function Lr(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let l of o.get(r)?.sources??[])try{s+=ga(wa(e,l)).size}catch{}return{path:r,bytes:s}})}function Mr(e,t,n={}){let o=n.rewrite?`- Some or all of these articles ALREADY EXIST on disk \u2014 this is a re-author (rewrite/upgrade), NOT a first draft. For any that exist, do NOT preserve or lightly-edit the current file: RE-AUTHOR it from scratch against the plan + sources + the active doc-type playbook standard. The existing file is what you're replacing \u2014 its structure is NOT the target; match only the project's voice/terminology.
230
230
  `:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
231
231
  - 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).
232
232
  - 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.
@@ -235,73 +235,74 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
235
235
  - 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.
236
236
  Articles:
237
237
  `+e.paths.map(r=>`- ${r}`).join(`
238
- `)}function Ur(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: ${he(r)}\u2013${he(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Wr(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,I)=>C+o(I),0),p=r.reduce((C,I)=>C+o(I),0),h=e.reduce((C,I)=>C+I.costUsd,0),k=e.reduce((C,I)=>C+I.outputTokens,0),x=n==="api"?`${he(h)} total`:Ve(k),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=C=>`${C} article${C===1?"":"s"}`,T=[];if(s.length===0)T.push(`Wrote ${b(c)} (${D}) successfully \xB7 ${x}.`),T.push("Next \u2014 push them to Document360:"),T.push("/publish --all"),T.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{T.push(`Wrote ${p}/${b(c)} (${D}) \xB7 ${x}.`),T.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)T.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return T}function Fr(e,t,n){try{let o=vd({cwd:e,paths:n.map(s=>`${t}/${s}`)});if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 /check --fix corrects them.`}catch{return null}}function Hr(e,t,n){let o=(ha(e)?.docsDir??Rd).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Ad(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=Ed(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let c=Lr(e,o,s);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"",h=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${h} --rewrite to regenerate them all.`}}return{docsDir:o,targets:c,planCount:r.length}}async function ga(e,t){if(!ha(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=Pd(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,rewrite:p}=_r(e),{docsDir:h,targets:k,reason:x,rewriting:D}=Hr(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(x?L(x):L("Nothing to write.")),{kind:"continue"};D&&console.log(L(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let b=Cd(k),T=Ir(c),{model:C,forced:I}=Td(t.cwd,"standard"),N=!!r;if(s&&!N){let M=$d({files:Or(t.cwd,n,k),op:"write",model:C});o&&console.log(f(`Scope: ${o} (${k.length} pending).`));for(let J of Ur(b,M,T))console.log(J);return console.log(f(`Model: ${C}${I?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${k.length} article${k.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${T} agents at once) on ${C}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let M of Sd({cwd:t.cwd,partitions:b,promptFor:J=>Mr(J,h,{rewrite:D||N}),concurrency:T,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(M.type==="partition_status")M.status==="running"?console.log(f(` \u25B8 ${M.label} \u2014 writing\u2026`)):M.status==="done"?console.log(j(` \u2713 ${M.label}`)):console.log($(` \u2717 ${M.label}`));else if(M.type==="run_done"){console.log("");let J=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let ne of Wr(M.results,b,J))console.log(M.ok?j(ne):L(ne));let pe=Fr(t.cwd,h,k);pe&&console.log(L(pe))}}catch(M){console.log($(`Write run failed: ${M.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as Nd,readdirSync as wa,statSync as ya}from"node:fs";import{join as ka}from"node:path";import{inputDir as Id,readProjectConfig as _d}from"document360-engine";var ba=/\.(md|markdown|pdf|txt)$/i;function qr(e){let t=Id(e);if(!Nd(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of wa(t)){let s=ka(t,r),c=!1;try{c=ya(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=Ld(s);p>0&&n.push({name:r,docCount:p})}else ba.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Ld(e){let t=0;for(let n of wa(e))try{ya(ka(e,n)).isFile()&&ba.test(n)&&t++}catch{}return t}function Br(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 oo(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(`
239
- `)}var Yr="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function xa(e,t){let n=t?.cwd??process.cwd();if(!_d(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=qr(n);if(o.length===0&&r===0)return console.log(f(Yr)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let h of o)console.log(` ${h.name} ${f(`(${h.docCount} doc${h.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:oo(p),display:p?`/draft ${p}`:"/draft"}}let c=Br(o,s);return{kind:"forward-to-agent",prompt:oo(c??"",c?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as Od,readProjectConfig as Md}from"document360-engine";function Gr(e){try{return Od(e).filter(t=>t.kind==="request").length}catch{return 0}}function Vr(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function zr(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(`
240
- `)}var Xr="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 $a(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{publish:o,what:r}=Vr(e);if(!r&&Gr(n)===0)return console.log(f(Xr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:zr(r,o),display:s}}W();import{search as Ud}from"@inquirer/prompts";import{findByName as Wd,getSession as Fd,listSessions as Hd,relativeTime as Ca}from"document360-engine";async function Pa(e,t){let n=Hd(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(f("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=Wd(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),va(n),{kind:"continue"})}if(!process.stdin.isTTY)return va(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Ud({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} ${Ca(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Fd(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function va(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${f(Ca(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as qd}from"document360-engine";function Kr(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 Ra(e,t){let n=Kr(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(qd(o,n)?console.log(j(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(j(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Ta,readProjectConfig as Bd,writeProjectConfig as Yd}from"document360-engine";W();function Qr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Bd(e);if(!o)return"No .d360-writer/config.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return Ta().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Yd(o,e),null):`Unknown environment "${r}". Known: ${Ta().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function Sa(e,t){let n=e[0];if(!n)return Un(t.cwd),{kind:"continue"};if(n==="add"){let o=Qr(t.cwd,e[1],e[2]);return o?(console.log($(o)),{kind:"continue"}):(console.log(j(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/login")}`),{kind:"continue"})}return Wn(t.cwd,n),Fn(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Gd}from"@inquirer/prompts";import{readProjectConfig as Vd,readUserConfig as Da,resolveModelSetting as Jr,writeUserConfig as ja}from"document360-engine";var Ee=[{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 ro(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=Ee.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function zd(e){switch(e.source){case"project":return".d360-writer/config.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"claude-settings":return"Claude Code's own settings (~/.claude/settings.json)";case"claude-default":return"Claude Code default (no override configured)"}}function ln(e,t){let n=()=>{let s=Jr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Da();return s.defaultModel?(delete s.defaultModel,ja(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Jr(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}}ja({...Da(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Vd(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer/config.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function Aa(e,t){let n=e[0]?.trim();if(!n){let c=Jr(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${_(c.model??"Claude Code default")}`),console.log(f(` source: ${zd(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=ro(c),h;try{h=await t.withPausedInput(()=>Gd({message:`Select model (current: ${c.model??"Claude Code default"})`,default:Ee[p].value,choices:Ee.map((b,T)=>({name:`${b.label}${T===p?" \u2714":""}`,value:b.value,description:b.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:x,effective:D}=ln(t.cwd,h??"default");for(let b of k)console.log(b.startsWith("\u26A0")?L(b):b.startsWith("\u2713")?j(b):f(b));return x&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:s}=ln(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?L(c):c.startsWith("\u2713")?j(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}so();async function Oa(e,t){return await t.withPausedInput(()=>Et(t.cwd)),{kind:"clear"}}async function Ma(e,t){return await t.withPausedInput(()=>_n(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as cp}from"document360-engine";async function Ua(e,t){let n=!1;try{n=cp(t.cwd).production}catch{}return n?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var Wa=async(e,t)=>{try{await t.withPausedInput(()=>Mn({}))}catch(n){console.log($(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as up,clearTokens as dp,clearProfileProject as pp}from"document360-engine";async function Fa(e,t){let n;try{n=up(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let o=dp(n);return pp(t.cwd,n),console.log(o?j(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):f(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(f("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as Ha}from"node:fs";import{isAbsolute as fp,join as mp,resolve as hp}from"node:path";import{readProjectConfig as gp,screenshotPlaceholderIds as wp,DEFAULT_CAPTURE_DIR as yp,DEFAULT_OUTPUT_DIR as kp}from"document360-engine";var qa=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function es(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?qa(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:qa(o),setup:t}:{mode:"single",id:o}}function ts(e,t){let n=gp(e),o=n?.captureDir??yp,r=n?.outputDir??kp,s=(c,p)=>fp(c)?mp(c,p):hp(e,c,p);return wp(e,{scope:t}).map(({id:c,file:p})=>{let h=Ha(s(r,`${c}.png`))?"captured":Ha(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:h}})}var bp={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},xp={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function ns(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(` ${bp[c.state]} ${c.id.padEnd(34)} ${xp[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Ba(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(`
238
+ `)}function Ur(e,t,n){let o=e.reduce((l,p)=>l+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(l=>` \u2022 ${l.label} \u2014 ${l.paths.length} article${l.paths.length===1?"":"s"}`),"",`Estimated cost: ${he(r)}\u2013${he(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Wr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),l=e.reduce((C,N)=>C+o(N),0),p=r.reduce((C,N)=>C+o(N),0),h=e.reduce((C,N)=>C+N.costUsd,0),k=e.reduce((C,N)=>C+N.outputTokens,0),x=n==="api"?`${he(h)} total`:Ve(k),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=C=>`${C} article${C===1?"":"s"}`,T=[];if(s.length===0)T.push(`Wrote ${b(l)} (${D}) successfully \xB7 ${x}.`),T.push("Next \u2014 push them to Document360:"),T.push("/publish --all"),T.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{T.push(`Wrote ${p}/${b(l)} (${D}) \xB7 ${x}.`),T.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)T.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return T}function Fr(e,t,n){try{let o=Dd({cwd:e,paths:n.map(s=>`${t}/${s}`)});if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 /check --fix corrects them.`}catch{return null}}function Hr(e,t,n){let o=(ya(e)?.docsDir??Ed).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Ld(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=Md(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let l=Or(e,o,s);if(l.length===0){let p=n.scope?` under "${n.scope}"`:"",h=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${h} --rewrite to regenerate them all.`}}return{docsDir:o,targets:l,planCount:r.length}}async function ka(e,t){if(!ya(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=Ad(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:l,rewrite:p}=_r(e),{docsDir:h,targets:k,reason:x,rewriting:D}=Hr(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(x?O(x):O("Nothing to write.")),{kind:"continue"};D&&console.log(O(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let b=jd(k),T=Ir(l),{model:C,forced:N}=Nd(t.cwd,"standard"),I=!!r;if(s&&!I){let M=Sd({files:Lr(t.cwd,n,k),op:"write",model:C});o&&console.log(f(`Scope: ${o} (${k.length} pending).`));for(let J of Ur(b,M,T))console.log(J);return console.log(f(`Model: ${C}${N?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${k.length} article${k.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${T} agents at once) on ${C}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let M of Id({cwd:t.cwd,partitions:b,promptFor:J=>Mr(J,h,{rewrite:D||I}),concurrency:T,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(M.type==="partition_status")M.status==="running"?console.log(f(` \u25B8 ${M.label} \u2014 writing\u2026`)):M.status==="done"?console.log(A(` \u2713 ${M.label}`)):console.log($(` \u2717 ${M.label}`));else if(M.type==="run_done"){console.log("");let J=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let oe of Wr(M.results,b,J))console.log(M.ok?A(oe):O(oe));let fe=Fr(t.cwd,h,k);fe&&console.log(O(fe))}}catch(M){console.log($(`Write run failed: ${M.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as Ud,readdirSync as ba,statSync as xa}from"node:fs";import{join as $a}from"node:path";import{inputDir as Wd,readProjectConfig as Fd}from"document360-engine";var va=/\.(md|markdown|pdf|txt)$/i;function qr(e){let t=Wd(e);if(!Ud(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of ba(t)){let s=$a(t,r),l=!1;try{l=xa(s).isDirectory()}catch{continue}if(l){if(r.startsWith("."))continue;let p=Hd(s);p>0&&n.push({name:r,docCount:p})}else va.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Hd(e){let t=0;for(let n of ba(e))try{xa($a(e,n)).isFile()&&va.test(n)&&t++}catch{}return t}function Br(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 ro(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(`
239
+ `)}var Yr="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Ca(e,t){let n=t?.cwd??process.cwd();if(!Fd(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=qr(n);if(o.length===0&&r===0)return console.log(f(Yr)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let h of o)console.log(` ${h.name} ${f(`(${h.docCount} doc${h.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:ro(p),display:p?`/draft ${p}`:"/draft"}}let l=Br(o,s);return{kind:"forward-to-agent",prompt:ro(l??"",l?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as qd,readProjectConfig as Bd}from"document360-engine";function Gr(e){try{return qd(e).filter(t=>t.kind==="request").length}catch{return 0}}function Vr(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function zr(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(`
240
+ `)}var Xr="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 Pa(e,t){let n=t?.cwd??process.cwd();if(!Bd(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Vr(e);if(!r&&Gr(n)===0)return console.log(f(Xr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:zr(r,o),display:s}}W();import{search as Yd}from"@inquirer/prompts";import{findByName as Gd,getSession as Vd,listSessions as zd,relativeTime as Ta}from"document360-engine";async function Sa(e,t){let n=zd(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(f("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=Gd(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),Ra(n),{kind:"continue"})}if(!process.stdin.isTTY)return Ra(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Yd({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let l=(s??"").toLowerCase();return n.filter(p=>!l||p.name.toLowerCase().includes(l)||p.firstPrompt.toLowerCase().includes(l)).map(p=>({name:`${p.name} ${Ta(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Vd(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Ra(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${f(Ta(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Xd}from"document360-engine";function Kr(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 Da(e,t){let n=Kr(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Xd(o,n)?console.log(A(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(A(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as ja,readProjectConfig as Kd,writeProjectConfig as Qd}from"document360-engine";W();function Qr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Kd(e);if(!o)return"No .d360-writer/config.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return ja().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Qd(o,e),null):`Unknown environment "${r}". Known: ${ja().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function Aa(e,t){let n=e[0];if(!n)return Wn(t.cwd),{kind:"continue"};if(n==="add"){let o=Qr(t.cwd,e[1],e[2]);return o?(console.log($(o)),{kind:"continue"}):(console.log(A(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/login")}`),{kind:"continue"})}return Fn(t.cwd,n),Hn(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Jd}from"@inquirer/prompts";import{readProjectConfig as Zd,readUserConfig as Ea,resolveModelSetting as Jr,writeUserConfig as Na}from"document360-engine";var Ee=[{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 so(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=Ee.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function ep(e){switch(e.source){case"project":return".d360-writer/config.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"claude-settings":return"Claude Code's own settings (~/.claude/settings.json)";case"claude-default":return"Claude Code default (no override configured)"}}function cn(e,t){let n=()=>{let s=Jr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Ea();return s.defaultModel?(delete s.defaultModel,Na(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Jr(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}}Na({...Ea(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Zd(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer/config.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function Ia(e,t){let n=e[0]?.trim();if(!n){let l=Jr(t.cwd);if(!process.stdin.isTTY)return console.log(`${Re("Model:")} ${_(l.model??"Claude Code default")}`),console.log(f(` source: ${ep(l)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=so(l),h;try{h=await t.withPausedInput(()=>Jd({message:`Select model (current: ${l.model??"Claude Code default"})`,default:Ee[p].value,choices:Ee.map((b,T)=>({name:`${b.label}${T===p?" \u2714":""}`,value:b.value,description:b.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:x,effective:D}=cn(t.cwd,h??"default");for(let b of k)console.log(b.startsWith("\u26A0")?O(b):b.startsWith("\u2713")?A(b):f(b));return x&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:s}=cn(t.cwd,n);for(let l of o)console.log(l.startsWith("\u26A0")?O(l):l.startsWith("\u2713")?A(l):f(l));return r&&await t.setModel(s),{kind:"continue"}}io();async function Wa(e,t){return await t.withPausedInput(()=>Et(t.cwd)),{kind:"clear"}}async function Fa(e,t){return await t.withPausedInput(()=>On(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as hp}from"document360-engine";async function Ha(e,t){let n=!1;try{n=hp(t.cwd).production}catch{}return n?(console.log(O("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var qa=async(e,t)=>{try{await t.withPausedInput(()=>Un({}))}catch(n){console.log($(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as gp,clearTokens as wp,clearProfileProject as yp}from"document360-engine";async function Ba(e,t){let n;try{n=gp(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let o=wp(n);return yp(t.cwd,n),console.log(o?A(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):f(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(f("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as Ya}from"node:fs";import{isAbsolute as kp,join as bp,resolve as xp}from"node:path";import{readProjectConfig as $p,screenshotPlaceholderIds as vp,DEFAULT_CAPTURE_DIR as Cp,DEFAULT_OUTPUT_DIR as Pp}from"document360-engine";var Ga=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function es(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Ga(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Ga(o),setup:t}:{mode:"single",id:o}}function ts(e,t){let n=$p(e),o=n?.captureDir??Cp,r=n?.outputDir??Pp,s=(l,p)=>kp(l)?bp(l,p):xp(e,l,p);return vp(e,{scope:t}).map(({id:l,file:p})=>{let h=Ya(s(r,`${l}.png`))?"captured":Ya(s(o,`${l}.spec.ts`))?"spec":"placeholder";return{id:l,file:p,state:h}})}var Rp={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Tp={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function ns(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 l of e.filter(p=>p.file===s))r.push(` ${Rp[l.state]} ${l.id.padEnd(34)} ${Tp[l.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Va(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(`
241
241
  `),"","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(`
242
- `)}async function io(e,t){let n=es(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of ns(ts(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
+ `)}async function ao(e,t){let n=es(e);if(n.mode==="list"){let l=t?.cwd??process.cwd();for(let p of ns(ts(l,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(`
243
243
  `),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(`
244
- `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as $p,readFileSync as vp}from"node:fs";import{isAbsolute as Cp,join as Pp,resolve as Rp}from"node:path";import{readProjectConfig as Tp,DEFAULT_CAPTURE_DIR as Sp}from"document360-engine";async function un(){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(`
245
- `),display:"/capture-setup"}}var Ya="-".repeat(64);function os(e){let t=Sp;try{let x=Tp(e);x?.captureDir&&(t=x.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Cp(t)?Pp(t,"CAPTURE-TESTID-REQUESTS.json"):Rp(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!$p(n))return null;let o;try{let x=JSON.parse(vp(n,"utf8").replace(/^/,""));o=Array.isArray(x?.requests)?x.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(x=>x.file).filter(Boolean)).size,s=o.length,c=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,h=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${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.","",Ya,`Read ${h} and ${k}. 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.",Ya]}ct();W();import{listOpenForDocs as Dp,readProjectConfig as jp}from"document360-engine";function rs(e){try{return Dp(e).length}catch{return 0}}function ss(){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(`
246
- `)}async function Ga(e,t){let n=t?.cwd??process.cwd();return jp(n)?rs(n)===0?(console.log(f("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:ss(),display:"/inbox"}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as Ap,listOpenForDocs as Ep,readProjectConfig as Np,computeSyncStatus as Ip,planPull as _p,applyPull as Lp}from"document360-engine";function Mt(e){let t=0,n=0,o=0;try{t=Ap(e).length}catch{}try{let r=Ep(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 Ut(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 as(e){return{publish:e.includes("--publish")}}function ls({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already reconciled before this run: clean portal edits were pulled into local, and any conflicts / new-portal-articles were surfaced to the user. Do NOT re-pull. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.","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(`
247
- `)}var Op={status:Ip,plan:_p,apply:Lp};async function cs(e,t=Op){let n={pulled:[],conflicts:[],untrackedRemote:[],failed:[]},o;try{o=await t.status({cwd:e.cwd,profileName:e.profileName})}catch(r){return n.error=r.message,n}for(let r of o.entries)if(r.status==="conflict"&&r.path)n.conflicts.push(r.path);else if(r.status==="untracked-remote")n.untrackedRemote.push(r.title??r.articleId??"(untitled)");else if(r.status==="remote-ahead"&&r.path)try{let s=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},s),n.pulled.push(r.path)}catch(s){n.failed.push({path:r.path,error:s.message})}return n}var is=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,ao=e=>e===1?"":"s";function us(e){if(e.error)return[`\u26A0 Couldn't check Document360 for portal changes (${e.error.slice(0,100)}) \u2014 proceeding; the agent will re-check.`];let t=[];return e.pulled.length&&t.push(`\u2713 Pulled ${e.pulled.length} portal edit${ao(e.pulled.length)} into local: ${is(e.pulled)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${ao(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${is(e.conflicts)}`),e.untrackedRemote.length&&t.push(`\u2139 ${e.untrackedRemote.length} new article${ao(e.untrackedRemote.length)} in the portal ${e.untrackedRemote.length===1?"isn't":"aren't"} local yet \u2014 run /pull to bring ${e.untrackedRemote.length===1?"it":"them"} in: ${is(e.untrackedRemote)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull${ao(e.failed.length)} failed \u2014 left for /pull.`),t}async function Va(e,t){let n=t?.cwd??process.cwd();if(!Np(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Oe(n,t?.profileName);if(!o.ok)return console.log($(o.reason)),{kind:"continue"};let{publish:r}=as(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await cs({cwd:n,profileName:t?.profileName});for(let p of us(s))console.log(p.startsWith("\u2713")?j(p):p.startsWith("\u2139")?f(p):L(p));let c=Ut(Mt(n));return console.log(f(c?`Catching up on ${c}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:ls({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as Mp}from"node:child_process";var pt="document360-writer",lo=`npm i -g ${pt}@latest`;async function co(){let e=process.platform==="win32";return new Promise(t=>{try{let n=Mp(`npm i -g ${pt}@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 za(){return console.log(f(`Updating ${pt}\u2026`)),(await co()).ok?console.log(j("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log($(`Update failed \u2014 run manually: ${lo}`)),{kind:"continue"}}W();ct();import{existsSync as ds,rmSync as Up}from"node:fs";import{basename as Xa,resolve as ps}from"node:path";import{execFileSync as Wp}from"node:child_process";import{input as Fp}from"@inquirer/prompts";import{readProjectConfig as Hp,devHintsGuidePath as qp}from"document360-engine";var Bp=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Yp=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),uo=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Ka=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Qa(e){let t=uo(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Ka(t)?!0:Yp.has(t)}function fs(e){let t=null;try{t=Hp(e)}catch{t=null}let n=new Set(Bp);for(let o of[uo(t?.docsDir),uo(t?.captureDir),uo(t?.outputDir)])o&&Ka(o)&&n.add(o);return[...n].filter(o=>Qa(o)&&ds(ps(e,o)))}function ms(e,t){let n=[],o=[];for(let r of t){if(!Qa(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Up(ps(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Ja(e,t){try{return Wp("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
248
- `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Gp(e){return Ja(e,".d360-writer/hints")}function Vp(e){return Ja(e,".d360-writer/messages")}function hs(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Gp(e),o=Vp(e),r=ds(ps(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(s=>` \u2022 ${s}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o>0?[`\u26A0 ${o} message(s) under .d360-writer/messages/ are not committed \u2014 commit them first or they're gone.`]:[],...r?["Note: a repo-root user-docs/ is NOT touched (only .d360-writer/ is removed)."]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${Xa(e)}`]}async function Za(e,t){let n=fs(t.cwd);for(let h of hs(t.cwd,n))console.log(n.length===0?f(h):h);if(n.length===0)return{kind:"continue"};let o=Xa(t.cwd);if((await t.withPausedInput(()=>Fp({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=ds(qp(t.cwd)),{removed:c,failed:p}=ms(t.cwd,n);console.log(j(`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`));for(let h of p)console.log($(` \u2717 ${h.path}: ${h.error}`));if(s){for(let h of Vn())console.log(h);console.log(f("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}W();import{lintDocs as zp}from"document360-engine";function po(e){if(e.length===0)return["\u2713 No issues found \u2014 no leaked internals, unknown commands, or stale version facts in the docs."];let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}let n=[`\u26A0 ${e.length} doc issue${e.length===1?"":"s"} in ${t.size} article${t.size===1?"":"s"} (leaked internals / unknown commands / stale facts):`];for(let[o,r]of t){n.push(` ${o}`);for(let s of r)n.push(` L${s.line}: "${s.term}" \u2014 ${s.message}`)}return n}function gs(e){let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}return["The documentation quality check found issues in already-written articles. FIX each one by EDITING the","article in place \u2014 do not rewrite whole articles, just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","How to fix, by issue type:","- internal-leak (an agent codename, an internal skill name, or a d360_* tool name): this is the"," documentation engine's own machinery and must NOT appear in user docs. Reword the sentence to describe"," the behavior in plain user terms, or delete the internal aside. Do NOT swap it for another internal term.","- unknown-command: the named /command or --flag does not exist in the product source. Find the correct"," command/flag in the source and use it; if there is no real equivalent, remove the claim.","- stale-fact: the version contradicts the product's package.json engines \u2014 correct it to the real value.","","Rules: edit ONLY the listed articles; do not touch others; do not publish; introduce no new internal","nouns, invented commands, or wrong facts. When done, every listed issue should be gone.","","Issues:",[...t.entries()].map(([o,r])=>[o,...r.map(s=>` - L${s.line} [${s.kind}]: "${s.term}" \u2014 ${s.message}`)].join(`
244
+ `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as Sp,readFileSync as Dp}from"node:fs";import{isAbsolute as jp,join as Ap,resolve as Ep}from"node:path";import{readProjectConfig as Np,DEFAULT_CAPTURE_DIR as Ip}from"document360-engine";async function dn(){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(`
245
+ `),display:"/capture-setup"}}var za="-".repeat(64);function os(e){let t=Ip;try{let x=Np(e);x?.captureDir&&(t=x.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=jp(t)?Ap(t,"CAPTURE-TESTID-REQUESTS.json"):Ep(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Sp(n))return null;let o;try{let x=JSON.parse(Dp(n,"utf8").replace(/^/,""));o=Array.isArray(x?.requests)?x.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(x=>x.file).filter(Boolean)).size,s=o.length,l=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,h=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${l} 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.","",za,`Read ${h} and ${k}. They list ${l} 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.",za]}ct();W();import{listOpenForDocs as _p,readProjectConfig as Op}from"document360-engine";function rs(e){try{return _p(e).length}catch{return 0}}function ss(){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(`
246
+ `)}async function Xa(e,t){let n=t?.cwd??process.cwd();return Op(n)?rs(n)===0?(console.log(f("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:ss(),display:"/inbox"}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as Lp,listOpenForDocs as Mp,readProjectConfig as Up,computeSyncStatus as Wp,planPull as Fp,applyPull as Hp}from"document360-engine";function Mt(e){let t=0,n=0,o=0;try{t=Lp(e).length}catch{}try{let r=Mp(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 Ut(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 as(e){return{publish:e.includes("--publish")}}function ls({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already reconciled before this run: clean portal edits were pulled into local, and any conflicts / new-portal-articles were surfaced to the user. Do NOT re-pull. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.","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(`
247
+ `)}var qp={status:Wp,plan:Fp,apply:Hp};async function cs(e,t=qp){let n={pulled:[],conflicts:[],untrackedRemote:[],failed:[]},o;try{o=await t.status({cwd:e.cwd,profileName:e.profileName})}catch(r){return n.error=r.message,n}for(let r of o.entries)if(r.status==="conflict"&&r.path)n.conflicts.push(r.path);else if(r.status==="untracked-remote")n.untrackedRemote.push(r.title??r.articleId??"(untitled)");else if(r.status==="remote-ahead"&&r.path)try{let s=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},s),n.pulled.push(r.path)}catch(s){n.failed.push({path:r.path,error:s.message})}return n}var is=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,lo=e=>e===1?"":"s";function us(e){if(e.error)return[`\u26A0 Couldn't check Document360 for portal changes (${e.error.slice(0,100)}) \u2014 proceeding; the agent will re-check.`];let t=[];return e.pulled.length&&t.push(`\u2713 Pulled ${e.pulled.length} portal edit${lo(e.pulled.length)} into local: ${is(e.pulled)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${lo(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${is(e.conflicts)}`),e.untrackedRemote.length&&t.push(`\u2139 ${e.untrackedRemote.length} new article${lo(e.untrackedRemote.length)} in the portal ${e.untrackedRemote.length===1?"isn't":"aren't"} local yet \u2014 run /pull to bring ${e.untrackedRemote.length===1?"it":"them"} in: ${is(e.untrackedRemote)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull${lo(e.failed.length)} failed \u2014 left for /pull.`),t}async function Ka(e,t){let n=t?.cwd??process.cwd();if(!Up(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Le(n,t?.profileName);if(!o.ok)return console.log($(o.reason)),{kind:"continue"};let{publish:r}=as(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await cs({cwd:n,profileName:t?.profileName});for(let p of us(s))console.log(p.startsWith("\u2713")?A(p):p.startsWith("\u2139")?f(p):O(p));let l=Ut(Mt(n));return console.log(f(l?`Catching up on ${l}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:ls({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as Bp}from"node:child_process";var pt="document360-writer",co=`npm i -g ${pt}@latest`;async function uo(){let e=process.platform==="win32";return new Promise(t=>{try{let n=Bp(`npm i -g ${pt}@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 Qa(){return console.log(f(`Updating ${pt}\u2026`)),(await uo()).ok?console.log(A("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log($(`Update failed \u2014 run manually: ${co}`)),{kind:"continue"}}W();ct();import{existsSync as ds,rmSync as Yp}from"node:fs";import{basename as Ja,resolve as ps}from"node:path";import{execFileSync as Gp}from"node:child_process";import{input as Vp}from"@inquirer/prompts";import{readProjectConfig as zp,devHintsGuidePath as Xp}from"document360-engine";var Kp=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Qp=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),po=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Za=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function el(e){let t=po(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Za(t)?!0:Qp.has(t)}function fs(e){let t=null;try{t=zp(e)}catch{t=null}let n=new Set(Kp);for(let o of[po(t?.docsDir),po(t?.captureDir),po(t?.outputDir)])o&&Za(o)&&n.add(o);return[...n].filter(o=>el(o)&&ds(ps(e,o)))}function ms(e,t){let n=[],o=[];for(let r of t){if(!el(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Yp(ps(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function tl(e,t){try{return Gp("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
248
+ `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Jp(e){return tl(e,".d360-writer/hints")}function Zp(e){return tl(e,".d360-writer/messages")}function hs(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Jp(e),o=Zp(e),r=ds(ps(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(s=>` \u2022 ${s}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o>0?[`\u26A0 ${o} message(s) under .d360-writer/messages/ are not committed \u2014 commit them first or they're gone.`]:[],...r?["Note: a repo-root user-docs/ is NOT touched (only .d360-writer/ is removed)."]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${Ja(e)}`]}async function nl(e,t){let n=fs(t.cwd);for(let h of hs(t.cwd,n))console.log(n.length===0?f(h):h);if(n.length===0)return{kind:"continue"};let o=Ja(t.cwd);if((await t.withPausedInput(()=>Vp({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(O("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=ds(Xp(t.cwd)),{removed:l,failed:p}=ms(t.cwd,n);console.log(A(`\u2713 Reset complete \u2014 removed ${l.length} item${l.length===1?"":"s"}. The repo is back to its original state.`));for(let h of p)console.log($(` \u2717 ${h.path}: ${h.error}`));if(s){for(let h of zn())console.log(h);console.log(f("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}W();import{lintDocs as ef}from"document360-engine";function fo(e){if(e.length===0)return["\u2713 No issues found \u2014 no leaked internals, unknown commands, or stale version facts in the docs."];let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}let n=[`\u26A0 ${e.length} doc issue${e.length===1?"":"s"} in ${t.size} article${t.size===1?"":"s"} (leaked internals / unknown commands / stale facts):`];for(let[o,r]of t){n.push(` ${o}`);for(let s of r)n.push(` L${s.line}: "${s.term}" \u2014 ${s.message}`)}return n}function gs(e){let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}return["The documentation quality check found issues in already-written articles. FIX each one by EDITING the","article in place \u2014 do not rewrite whole articles, just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","How to fix, by issue type:","- internal-leak (an agent codename, an internal skill name, or a d360_* tool name): this is the"," documentation engine's own machinery and must NOT appear in user docs. Reword the sentence to describe"," the behavior in plain user terms, or delete the internal aside. Do NOT swap it for another internal term.","- unknown-command: the named /command or --flag does not exist in the product source. Find the correct"," command/flag in the source and use it; if there is no real equivalent, remove the claim.","- stale-fact: the version contradicts the product's package.json engines \u2014 correct it to the real value.","","Rules: edit ONLY the listed articles; do not touch others; do not publish; introduce no new internal","nouns, invented commands, or wrong facts. When done, every listed issue should be gone.","","Issues:",[...t.entries()].map(([o,r])=>[o,...r.map(s=>` - L${s.line} [${s.kind}]: "${s.term}" \u2014 ${s.message}`)].join(`
249
249
  `)).join(`
250
250
  `)].join(`
251
- `)}async function el(e,t){let n=e.includes("--fix"),o=e.find(c=>!c.startsWith("--")),r=o?` ${o}`:"",s=zp({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(j("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:gs(s),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts)\u2026"));for(let c of po(s))console.log(s.length===0?j(c):L(c));return s.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}W();import{lintDocs as Xp,loadStyleGuide as Kp,buildReviewPrompt as Qp,readProjectConfig as Jp,DEFAULT_DOCS_DIR as Zp}from"document360-engine";function ws(e,t){let n=Jp(e);if(!n)return null;let o=(n.docsDir??Zp).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(k=>!k.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),c=Xp({cwd:e}),p=s?c.filter(k=>k.path===`${o}/${s}`||k.path.startsWith(`${o}/${s}/`)):c;return{prompt:Qp({docsRoot:o,scope:s,styleGuide:Kp(e),deterministicFindings:p,fix:r}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function tl(e,t){let n=ws(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as ef}from"document360-engine";function ys(e,t){if(!ef(e))return null;let n=t.find(r=>!r.startsWith("--"));return{prompt:[`Reorder the articles within ${n?`the "${n}" category`:"each category"} to the best reading order.`,"Follow the manage-structure skill: decide the ideal order with senior-editor judgment per the doc-genre","playbook (overview / mental-model first; reference and troubleshooting/FAQ last), then APPLY it with the","d360_reorder_articles tool \u2014 one category at a time, all paths in the same category folder. Do not rename","files or edit the map by hand; the tool handles it. Report the new order, and remind me it reaches","Document360 on the next /publish."].join(`
252
- `),display:`/reorder${n?` ${n}`:""}`}}async function nl(e,t){let n=ys(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}var ol={help:nr,"?":nr,clear:$i,exit:or,quit:or,init:lr,mcp:Kn,publish:na,audit:an,scope:ra,pull:da,convert:pa,write:ga,draft:xa,document:$a,resume:Pa,rename:Ra,profile:Sa,model:Aa,doctor:cn,workspace:Oa,project:Ma,"allow-prod":Ua,login:Wa,logout:Fa,screenshot:io,"capture-setup":un,devhints:Di,inbox:Ga,"catch-up":Va,update:za,reset:Za,check:el,review:tl,reorder:nl};function rl(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}ct();W();var tf={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"},il=160,bs=200,al=40;function ke(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function sl(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}: ${ke(typeof r=="string"?r:JSON.stringify(r),al)}`);return t.length>4&&n.push("\u2026"),ke(n.join(", "),il)}var ze=e=>typeof e=="string"&&e?e:null,ks=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function nf(e){let t=ze(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 of(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=ze(t.title);if(!o)return null;let r=nf(t.local_path);return n("Create article",`"${ke(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=ze(t.title),r=ks(t.article_id);return n("Update article",o?`"${ke(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",ks(t.article_id)?`id ${ks(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",ze(t.name)?`"${ke(ze(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=ze(t.file_path);return n("Upload image",o?ke(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function fo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),c=s.join("__");if(r==="document360"){let k=of(c,t);if(k)return k}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:sl(t)}}let n=tf[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:ke(o,il)}:{title:e,sep:"",arg:sl(t)}}function rf(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 sf(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(rf).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>ke(r,bs))]}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}: ${ke(String(r),al)}`);return n.length>0?[ke(n.join(" \xB7 "),bs)]:null}return null}function af(e){let t=ze(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function lf(e,t,n){switch(e){case"d360_create_article":{let o=af(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=ze(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 ${ke(o[0],120)}`:""}`]}default:return null}}function mo(e,t=4,n,o){let r=e.replace(/\r\n/g,`
253
- `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=lf(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let s=sf(r)??r.split(`
254
- `);return{lines:s.slice(0,t).map(c=>ke(c,bs)),hidden:Math.max(0,s.length-t)}}function ho(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function go(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 wo(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 bf=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function xf(e,t,n,o){if(bf.test(e))try{let r=dl(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=go(t,n),p=wo(n);e.endsWith("publish_article")&&p&&console.log(_(` \u2B95 Live: ${p}`)),c&&s&&console.log(_(` \u2B95 Preview: ${ho(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function pl(e=process.cwd(),t="auto",n){let o=uf(t);o.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${_("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${_('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),$f(e,n),o.kind==="subscription"&&(o.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,s=xs({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=cf({input:process.stdin,output:process.stdout}),h=[],k=null,x=!1;p.on("line",T=>{if(k){let C=k;k=null,C(T)}else h.push(T)}),p.on("close",()=>{if(x=!0,k){let T=k;k=null,T(null)}});function D(){return h.length>0?Promise.resolve(h.shift()):x?Promise.resolve(null):(process.stdout.write(_("> ")),new Promise(T=>{k=T}))}let b={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=xs({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setPendingName:T=>{c.pendingName=T},setModel:async T=>s.setModel(T),withPausedInput:async T=>{p.pause();try{return await T()}finally{p.resume()}}};try{for(;;){let T=await D();if(T===null)break;let C=T.trim();if(C){if(C.startsWith("/")){let I=rl(C);if(!I)continue;let N=ol[I.name];if(!N){console.log($(`Unknown command: /${I.name}`)),console.log(f("Type /help for the list."));continue}let M=await N(I.args,b);if(M.kind==="exit")break;if(M.kind==="clear"){b.restartAgent();continue}if(M.kind==="allow-prod"){r=!0,b.restartAgent(),console.log(j("\u2713 Production writes authorized for this session.")),console.log("");continue}if(M.kind==="resume"){s.close(),s=xs({cwd:e,resume:M.uuid,profileName:n,allowProdWrites:r});let J=df(M.uuid);c={uuid:M.uuid,firstPrompt:J?.firstPrompt??null,titleFired:!0},ul(M.uuid),console.log(j(`\u2713 Resumed "${M.name}"`)),console.log("");continue}M.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=M.display??M.prompt),await cl(s,M.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=C),await cl(s,C,o,c,e)}}}finally{s.close(),p.close()}}function $f(e,t){console.log(""),console.log(Kt("document360-writer")),console.log(f(` cwd: ${e}`));let n=gf(e);if(console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(vf(e,t)),!wf(e))console.log(L(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{try{Yn(e);for(let o of Gn(e))console.log(L(` ${o}`))}catch{}try{let o=Ut(Mt(e));o&&console.log(L(` \u{1F4CB} ${o} from the repo's coding agent \u2014 run /catch-up.`))}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function vf(e,t){try{let n=dl(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=kf(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...ll(r.idToken)??{},...ll(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return yf(r)&&!r.refreshToken?L(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function Cf(){console.error(""),console.error(`Sign in with your Claude subscription: run ${_("claude")} once, then retry.`),console.error(` (No Claude Code? ${_("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${_("https://console.anthropic.com/settings/keys")}`)}function Pf(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;mf({uuid:t,name:r??ff(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Rf(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||hf(o,t).then(r=>{r&&pf(n,r)}).catch(()=>{})}async function cl(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))Tf(c,o,r,n,s)}function Tf(e,t,n,o,r){switch(e.type){case"session":t.uuid||Pf(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=fo(e.name,e.input);s&&(process.stdout.write(`
255
-
256
- `),console.log(`${j("\u25CF")} ${Pe(s.title)}${s.arg!==null?ie(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=ut(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=p=>p===1?"":"s";console.log(ie(` \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(f(` \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=mo(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?$:ie;c.lines.forEach((h,k)=>console.log(p((k===0?" \u23BF ":" ")+h))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||xf(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
257
- `),console.log(f(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(ul(t.uuid),t.titleFired||Rf(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Cf();break}}import{render as Fm}from"ink";import{resolveAuth as Hm}from"document360-engine";import{useCallback as V,useEffect as Te,useMemo as Ts,useRef as Q,useState as q}from"react";import{Box as oe,Text as S,useApp as Yf,useInput as Gf,useStdout as Vf}from"ink";import{existsSync as Xe,readFileSync as Ss,readdirSync as jo}from"node:fs";import{spawnSync as zf}from"node:child_process";import{basename as pn,isAbsolute as Xf,join as mt}from"node:path";import{createSession as Hl,classifyClaudeAuth as Es,CLAUDE_CODE_SETUP_HINT as Kf,loginPkce as Qf,toStoredTokens as Jf,saveTokens as Zf,getAccessToken as em,resolveActiveProfile as de,resolveProjectId as tm,getArticle as nm,decodeJwtClaims as Ft,isExpired as We,loadTokens as Ke,clearTokens as om,clearProfileProject as rm,setTitle as sm,slugify as im,touchSession as Ds,upsertSession as am,generateTitle as ql,findByName as lm,listSessions as cm,renameSession as um,suggestNextAction as dm,readProjectConfig as Z,writeProjectConfig as Bl,resolveModelSetting as Ns,loadProfileMap as Do,applyPull as pm,computeSyncStatus as Yl,countLocalAhead as fm,lintDocs as Gl,compareRemoteSources as mm,planPull as hm,establishBaselines as gm,rebaselineServerMeta as wm,inventoryRepo as ym,knownEnvironments as km,resolveEnvironment as bm,planPartitions as js,partitionEvenly as xm,screenshotPlaceholderIds as $m,trackedArticlePaths as vm,runPartitioned as Ro,estimateBulkCost as Vl,resolveModelForOperation as To,readDocsPlan as zl,checkForUpdate as Cm,detectInstallKind as Pm,isSelfUpdatable as Rm,devHintsGuidePath as Is,toolFeedbackPath as Tm,reconcileToolFeedback as Sm,DEFAULT_DOCS_DIR as fn,setProfileProject as Dm,writeCrashLog as jm,applyStructureOrder as Xl,orderSyncLine as Kl,applyRelatedArticles as Ql,relatedSyncLine as Jl}from"document360-engine";ct();import{spawn as fl}from"node:child_process";function Sf(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Df(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?fl([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):fl(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 ml(e){for(let[t,n]of Sf())if(await Df(t,n,e))return!0;return!1}var jf=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function $s(e,t){if(t.closed)return e;let n=e.split(`
258
- `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){jf.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(`
259
- `)}import{existsSync as Af,mkdirSync as Ef,readFileSync as Nf,writeFileSync as If}from"node:fs";import{join as hl}from"node:path";import{writerDir as _f}from"document360-engine";function gl(e){return hl(_f(e),".sessions")}function wl(e,t){return hl(gl(e),`${t}.json`)}function yl(e,t,n){try{Ef(gl(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");If(wl(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function vs(e,t){try{let n=wl(e,t);if(!Af(n))return[];let o=JSON.parse(Nf(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Lf=e=>`\x1B]0;${e}\x07`,Of=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function kl(e){process.stdout.isTTY&&process.stdout.write(e)}function Wt(e){kl(Lf(e))}function yo(e){kl(Of(e))}var ko=["\xB7 "," \xB7"],bo="\u{1F7E3}";so();Xn();var xo=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"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>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--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:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path>] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Reports issues; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category>]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); new order syncs to Document360 on next /publish",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"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"}],bl={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function xl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(bl[n])return bl[n];let o=xo.find(r=>r.name===t);return o?o.desc:""}function $l(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return xo.filter(n=>n.name.startsWith(t))}function vl(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as Cl,Text as ae}from"ink";import{jsx as le,jsxs as $o}from"react/jsx-runtime";function Mf({row:e}){switch(e.t){case"head":return le(ae,{color:H,bold:!0,children:e.s});case"text":return le(ae,{children:e.s});case"dim":return le(ae,{dimColor:!0,children:e.s});case"sub":return le(ae,{bold:!0,dimColor:!0,children:e.s});case"good":return le(ae,{color:"green",children:e.s});case"step":return $o(ae,{children:[le(ae,{color:H,children:`${e.n}. `}),e.s]});case"cmd":return $o(ae,{children:[" ",le(ae,{color:H,children:e.name.padEnd(20)}),le(ae,{dimColor:!0,children:e.s})]});case"gap":return le(ae,{children:" "})}}function Pl({tab:e,width:t}){let n=Re[e]??Re[0],o=6+Re.reduce((s,c)=>s+c.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return $o(Cl,{flexDirection:"column",paddingX:1,children:[$o(ae,{children:[le(ae,{color:H,bold:!0,children:"Help "}),Re.map((s,c)=>c===e?le(ae,{color:"white",backgroundColor:H,bold:!0,children:` ${s.label} `},s.key):le(ae,{dimColor:!0,children:` ${s.label} `},s.key))]}),le(ae,{color:H,children:r}),le(Cl,{flexDirection:"column",marginTop:1,children:n.rows.map((s,c)=>le(Mf,{row:s},c))}),le(ae,{dimColor:!0,children:`
260
- \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var Uf=/^(?:\d+[.)]|[-*•])\s+/;function Rl(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
261
- `)){let c=s.trim().replace(Uf,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let h=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!h||!o.has(h[1].toLowerCase()))continue;let k=`/${h[1].toLowerCase()}${h[2]?` ${h[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}W();function dn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Me(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Tl(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Wf=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Sl(e,t,n){if(!Wf.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(s=>{let c=s.replace(/\\/g,"/");return r===c||r.endsWith(`/${c}`)})??null}function Cs(e){return e.replace(/^[\w.-]+\//,"")}var vo=16,Dl={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function ft(e){return typeof e=="string"?e:e.cmd}function jl(e){return typeof e=="string"?void 0:e.desc}function Ps(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Al(e,t){let n=Ps(t);return e.some(r=>ft(r).trim()===t.trim()||!!n&&Ps(ft(r))===n)?e.filter(r=>ft(r).trim()!==t.trim()&&!(n&&Ps(ft(r))===n)):[]}var Ff='\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 Hf(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"/pull":return"pull edits + new articles from Document360";case"/publish":return"push your local changes up to Document360";default:return""}}function Ue(e){return e===1?"":"s"}function qf(e){switch(e){case"/write":return"it finishes the articles already planned";case"/catch-up":return"it clears everything your builder queued";case"/audit":return"it shows what the latest code changes touch";case"/pull":return"it reconciles anything changed on Document360";case"/publish":return"it pushes your local edits up to Document360";default:return"it\u2019s the most useful next step"}}function Rs(e,t,n){let o=[];e.pendingWrites>0&&o.push(` \u2022 ${e.pendingWrites} planned article${Ue(e.pendingWrites)} still unwritten`),e.localAhead>0&&o.push(` \u2022 ${e.localAhead} article${Ue(e.localAhead)} changed locally \u2014 ready to publish`),e.pendingText&&o.push(` \u2022 your builder left ${e.pendingText}`),e.behind>0&&o.push(` \u2022 ${e.behind} code change${Ue(e.behind)} since your last docs check`);let r=o.length>0?["Welcome back \u2014 where your docs stand:",...o,`I\u2019d start with ${t[0]} \u2014 ${qf(t[0])}.`]:[`Welcome back. Your ${e.tracked} tracked article${Ue(e.tracked)} are all in sync.`];return r.push("",...t.map((s,c)=>` ${c+1} ${s.padEnd(9)} ${Hf(s,n)}`),"Or just tell me what to write or update."),r.join(`
262
- `)}function El(e){if(!e.ready)return{kind:"idle"};let t=!!e.pendingText;if(!e.hasDocs)return{kind:"noDocs",note:Ff,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${Ue(e.pendingWrites)} not written yet \u2014 pick up where you left off:`;return{kind:"actions",note:Rs(e,r,t),title:s,options:r}}if(e.localAhead>0){let r=t?["/publish","/catch-up"]:["/publish","/audit"],s=`\u{1F4E4} ${e.localAhead} article${Ue(e.localAhead)} changed locally \u2014 ready to publish to Document360:`;return{kind:"actions",note:Rs(e,r,t),title:s,options:r}}if(!t&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${Ue(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`};let n=t?["/catch-up","/audit"]:["/audit","/pull"],o=t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:e.behind>0?`\u{1F4CB} ${e.behind} code change${Ue(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${Ue(e.tracked)} tracked for "${e.profileName}". What next?`;return{kind:"actions",note:Rs(e,n,t),title:o,options:n}}var Bf=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Nl(e){return e.replace(/\r\n?/g,`
263
- `)}function Il(e){return e.includes(`
264
- `)||e.length>200}function _l(e,t){let n=t.split(`
265
- `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Ll(e,t){return e.replace(Bf,n=>t.get(n)??n)}function Ol(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Co(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
266
- `)){if(s.length===0)o.push({start:r,end:r});else for(let c=0;c<s.length;c+=n)o.push({start:r+c,end:r+Math.min(c+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function Po(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Ml(e,t,n){let o=Po(e,t),r=o+n;if(r<0||r>=e.length)return t;let s=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+s,e[r].end)}function Ul(e,t,n){let o=e[Po(e,t)];return n==="start"?o.start:o.end}function Wl(e,t,n){let o=Math.max(1,n),r=e.split(`
267
- `),s=0;for(let c=r.length-1;c>=0;c--){let p=r[c];if(s+=Math.max(1,Math.ceil(p.length/o)),s>=t){let h=s-t;return{text:[h>0?p.slice(h*o):p,...r.slice(c+1)].join(`
268
- `),truncated:c>0||h>0}}}return{text:e,truncated:!1}}function Fl(e){let t=!1,n=0,o=0;for(let r of e.split(`
269
- `)){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 As,jsx as E,jsxs as Y}from"react/jsx-runtime";var Am={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},Zl=` 1. /init \u2014 pick your Document360 environment & scaffold config
251
+ `)}async function ol(e,t){let n=e.includes("--fix"),o=e.find(l=>!l.startsWith("--")),r=o?` ${o}`:"",s=ef({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(A("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:gs(s),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts)\u2026"));for(let l of fo(s))console.log(s.length===0?A(l):O(l));return s.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}W();import{lintDocs as tf,loadStyleGuide as nf,buildReviewPrompt as of,readProjectConfig as rf,DEFAULT_DOCS_DIR as sf}from"document360-engine";function ws(e,t){let n=rf(e);if(!n)return null;let o=(n.docsDir??sf).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(k=>!k.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),l=tf({cwd:e}),p=s?l.filter(k=>k.path===`${o}/${s}`||k.path.startsWith(`${o}/${s}/`)):l;return{prompt:of({docsRoot:o,scope:s,styleGuide:nf(e),deterministicFindings:p,fix:r}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function rl(e,t){let n=ws(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as af}from"document360-engine";function ys(e,t){if(!af(e))return null;let n=t.find(r=>!r.startsWith("--"));return{prompt:[`Reorder the articles within ${n?`the "${n}" category`:"each category"} to the best reading order.`,"Follow the manage-structure skill: decide the ideal order with senior-editor judgment per the doc-genre","playbook (overview / mental-model first; reference and troubleshooting/FAQ last), then APPLY it with the","d360_reorder_articles tool \u2014 one category at a time, all paths in the same category folder. Do not rename","files or edit the map by hand; the tool handles it. Report the new order, and remind me it reaches","Document360 on the next /publish."].join(`
252
+ `),display:`/reorder${n?` ${n}`:""}`}}async function sl(e,t){let n=ys(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as lf,loadProfileMap as cf,resolveActiveProfile as uf,desiredCategoryOrder as df,desiredArticleOrder as pf}from"document360-engine";function il(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var al=e=>e.replace(/\\/g,"/").split("/").pop()??e;function ks(e,t){if(!lf(e))return[];let n=uf(e,t),o=cf(e,n.name);if(!o)return[];let r=new Map;for(let l of pf(o)){let p=r.get(l.categoryPath);p?p.push(l):r.set(l.categoryPath,[l])}let s=[];for(let l of df(o)){s.push(il(al(l.path)));for(let p of(r.get(l.path)??[]).sort((h,k)=>h.order-k.order))s.push(` ${il(al(p.path))}`)}return s}async function ll(e,t){let n=ks(t.cwd,t.profileName);if(n.length===0)return console.log(f("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(_("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}var cl={help:nr,"?":nr,clear:Pi,exit:or,quit:or,init:lr,mcp:Qn,publish:sa,audit:ln,scope:aa,pull:ma,convert:ha,write:ka,draft:Ca,document:Pa,resume:Sa,rename:Da,profile:Aa,model:Ia,doctor:un,workspace:Wa,project:Fa,"allow-prod":Ha,login:qa,logout:Ba,screenshot:ao,"capture-setup":dn,devhints:Ei,inbox:Xa,"catch-up":Ka,update:Qa,reset:nl,check:ol,review:rl,reorder:sl,structure:ll};function ul(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}ct();W();var ff={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"},pl=160,xs=200,fl=40;function ke(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function dl(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}: ${ke(typeof r=="string"?r:JSON.stringify(r),fl)}`);return t.length>4&&n.push("\u2026"),ke(n.join(", "),pl)}var ze=e=>typeof e=="string"&&e?e:null,bs=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function mf(e){let t=ze(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 hf(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=ze(t.title);if(!o)return null;let r=mf(t.local_path);return n("Create article",`"${ke(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=ze(t.title),r=bs(t.article_id);return n("Update article",o?`"${ke(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",bs(t.article_id)?`id ${bs(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",ze(t.name)?`"${ke(ze(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=ze(t.file_path);return n("Upload image",o?ke(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function mo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),l=s.join("__");if(r==="document360"){let k=hf(l,t);if(k)return k}let p=l.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:dl(t)}}let n=ff[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:ke(o,pl)}:{title:e,sep:"",arg:dl(t)}}function gf(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 wf(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(gf).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>ke(r,xs))]}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}: ${ke(String(r),fl)}`);return n.length>0?[ke(n.join(" \xB7 "),xs)]:null}return null}function yf(e){let t=ze(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function kf(e,t,n){switch(e){case"d360_create_article":{let o=yf(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=ze(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 ${ke(o[0],120)}`:""}`]}default:return null}}function ho(e,t=4,n,o){let r=e.replace(/\r\n/g,`
253
+ `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let l=kf(n.slice(18),o,r);if(l)return{lines:l,hidden:0}}let s=wf(r)??r.split(`
254
+ `);return{lines:s.slice(0,t).map(l=>ke(l,xs)),hidden:Math.max(0,s.length-t)}}function go(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function wo(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 yo(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 Af=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Ef(e,t,n,o){if(Af.test(e))try{let r=wl(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,l=wo(t,n),p=yo(n);e.endsWith("publish_article")&&p&&console.log(_(` \u2B95 Live: ${p}`)),l&&s&&console.log(_(` \u2B95 Preview: ${go(r.connection.portalUrl,s,l,r.project.languageCode??"en")}`))}catch{}}async function yl(e=process.cwd(),t="auto",n){let o=xf(t);o.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${_("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${_('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Nf(e,n),o.kind==="subscription"&&(o.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,s=$s({cwd:e,profileName:n,allowProdWrites:r}),l={uuid:null,firstPrompt:null,titleFired:!1},p=bf({input:process.stdin,output:process.stdout}),h=[],k=null,x=!1;p.on("line",T=>{if(k){let C=k;k=null,C(T)}else h.push(T)}),p.on("close",()=>{if(x=!0,k){let T=k;k=null,T(null)}});function D(){return h.length>0?Promise.resolve(h.shift()):x?Promise.resolve(null):(process.stdout.write(_("> ")),new Promise(T=>{k=T}))}let b={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=$s({cwd:e,profileName:n,allowProdWrites:r}),l={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>l.uuid,setPendingName:T=>{l.pendingName=T},setModel:async T=>s.setModel(T),withPausedInput:async T=>{p.pause();try{return await T()}finally{p.resume()}}};try{for(;;){let T=await D();if(T===null)break;let C=T.trim();if(C){if(C.startsWith("/")){let N=ul(C);if(!N)continue;let I=cl[N.name];if(!I){console.log($(`Unknown command: /${N.name}`)),console.log(f("Type /help for the list."));continue}let M=await I(N.args,b);if(M.kind==="exit")break;if(M.kind==="clear"){b.restartAgent();continue}if(M.kind==="allow-prod"){r=!0,b.restartAgent(),console.log(A("\u2713 Production writes authorized for this session.")),console.log("");continue}if(M.kind==="resume"){s.close(),s=$s({cwd:e,resume:M.uuid,profileName:n,allowProdWrites:r});let J=$f(M.uuid);l={uuid:M.uuid,firstPrompt:J?.firstPrompt??null,titleFired:!0},gl(M.uuid),console.log(A(`\u2713 Resumed "${M.name}"`)),console.log("");continue}M.kind==="forward-to-agent"&&(l.firstPrompt||(l.firstPrompt=M.display??M.prompt),await hl(s,M.prompt,o,l,e));continue}l.firstPrompt||(l.firstPrompt=C),await hl(s,C,o,l,e)}}}finally{s.close(),p.close()}}function Nf(e,t){console.log(""),console.log(Qt("document360-writer")),console.log(f(` cwd: ${e}`));let n=Tf(e);if(console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(If(e,t)),!Sf(e))console.log(O(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{try{Gn(e);for(let o of Vn(e))console.log(O(` ${o}`))}catch{}try{let o=Ut(Mt(e));o&&console.log(O(` \u{1F4CB} ${o} from the repo's coding agent \u2014 run /catch-up.`))}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function If(e,t){try{let n=wl(e,t),o=n.production?O(" \u26A0 PRODUCTION"):"",r=jf(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...ml(r.idToken)??{},...ml(r.accessToken)??{}},l=s.email??s.preferred_username??"signed in";return Df(r)&&!r.refreshToken?O(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${l} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function _f(){console.error(""),console.error(`Sign in with your Claude subscription: run ${_("claude")} once, then retry.`),console.error(` (No Claude Code? ${_("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${_("https://console.anthropic.com/settings/keys")}`)}function Of(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Pf({uuid:t,name:r??Cf(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Lf(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Rf(o,t).then(r=>{r&&vf(n,r)}).catch(()=>{})}async function hl(e,t,n,o,r){let s=new Map;for await(let l of e.send(t))Mf(l,o,r,n,s)}function Mf(e,t,n,o,r){switch(e.type){case"session":t.uuid||Of(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=mo(e.name,e.input);s&&(process.stdout.write(`
255
+
256
+ `),console.log(`${A("\u25CF")} ${Re(s.title)}${s.arg!==null?ie(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=ut(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let l=p=>p===1?"":"s";console.log(ie(` \u23BF Added ${s.added} line${l(s.added)}, removed ${s.removed} line${l(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(f(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let l=ho(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?$:ie;l.lines.forEach((h,k)=>console.log(p((k===0?" \u23BF ":" ")+h))),l.hidden>0&&console.log(f(` \u2026 +${l.hidden} lines`)),e.isError||Ef(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
257
+ `),console.log(f(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(gl(t.uuid),t.titleFired||Lf(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&_f();break}}import{render as Zm}from"ink";import{resolveAuth as eh}from"document360-engine";import{useCallback as V,useEffect as be,useMemo as Ss,useRef as Q,useState as H}from"react";import{Box as ne,Text as S,useApp as nm,useInput as om,useStdout as rm}from"ink";import{existsSync as Xe,readFileSync as Ds,readdirSync as Ao}from"node:fs";import{spawnSync as sm}from"node:child_process";import{basename as fn,isAbsolute as im,join as mt}from"node:path";import{createSession as zl,classifyClaudeAuth as Ns,CLAUDE_CODE_SETUP_HINT as am,loginPkce as lm,toStoredTokens as cm,saveTokens as um,getAccessToken as dm,resolveActiveProfile as pe,resolveProjectId as pm,getArticle as fm,decodeJwtClaims as Ft,isExpired as We,loadTokens as Ke,clearTokens as mm,clearProfileProject as hm,setTitle as gm,slugify as wm,touchSession as js,upsertSession as ym,generateTitle as Xl,findByName as km,listSessions as bm,renameSession as xm,suggestNextAction as $m,readProjectConfig as Z,writeProjectConfig as Kl,resolveModelSetting as Is,loadProfileMap as jo,applyPull as vm,computeSyncStatus as Ql,countLocalAhead as Cm,lintDocs as Jl,compareRemoteSources as Pm,planPull as Rm,establishBaselines as Tm,rebaselineServerMeta as Sm,inventoryRepo as Dm,knownEnvironments as jm,resolveEnvironment as Am,planPartitions as As,partitionEvenly as Em,screenshotPlaceholderIds as Nm,trackedArticlePaths as Im,runPartitioned as To,estimateBulkCost as Zl,resolveModelForOperation as So,readDocsPlan as ec,checkForUpdate as _m,detectInstallKind as Om,isSelfUpdatable as Lm,devHintsGuidePath as _s,toolFeedbackPath as Mm,reconcileToolFeedback as Um,DEFAULT_DOCS_DIR as mn,setProfileProject as Wm,writeCrashLog as Fm,applyStructureOrder as tc,orderSyncLine as nc,applyRelatedArticles as oc,relatedSyncLine as rc}from"document360-engine";ct();import{spawn as kl}from"node:child_process";function Uf(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Wf(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?kl([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):kl(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",l=>o(l===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 bl(e){for(let[t,n]of Uf())if(await Wf(t,n,e))return!0;return!1}var Ff=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function vs(e,t){if(t.closed)return e;let n=e.split(`
258
+ `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){Ff.test(s)&&(t.cueSeen=!0);continue}let l=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);l?(n[r]=`${l[1]}${++t.num}. ${l[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
259
+ `)}import{existsSync as Hf,mkdirSync as qf,readFileSync as Bf,writeFileSync as Yf}from"node:fs";import{join as xl}from"node:path";import{writerDir as Gf}from"document360-engine";function $l(e){return xl(Gf(e),".sessions")}function vl(e,t){return xl($l(e),`${t}.json`)}function Cl(e,t,n){try{qf($l(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Yf(vl(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Cs(e,t){try{let n=vl(e,t);if(!Hf(n))return[];let o=JSON.parse(Bf(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Vf=e=>`\x1B]0;${e}\x07`,zf=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Pl(e){process.stdout.isTTY&&process.stdout.write(e)}function Wt(e){Pl(Vf(e))}function ko(e){Pl(zf(e))}var bo=["\xB7 "," \xB7"],xo="\u{1F7E3}";io();Kn();var $o=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"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>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--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:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path>] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Reports issues; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category>]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"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:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"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"}],Rl={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function Tl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Rl[n])return Rl[n];let o=$o.find(r=>r.name===t);return o?o.desc:""}function Sl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return $o.filter(n=>n.name.startsWith(t))}function Dl(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as jl,Text as ae}from"ink";import{jsx as le,jsxs as vo}from"react/jsx-runtime";function Xf({row:e}){switch(e.t){case"head":return le(ae,{color:q,bold:!0,children:e.s});case"text":return le(ae,{children:e.s});case"dim":return le(ae,{dimColor:!0,children:e.s});case"sub":return le(ae,{bold:!0,dimColor:!0,children:e.s});case"good":return le(ae,{color:"green",children:e.s});case"step":return vo(ae,{children:[le(ae,{color:q,children:`${e.n}. `}),e.s]});case"cmd":return vo(ae,{children:[" ",le(ae,{color:q,children:e.name.padEnd(20)}),le(ae,{dimColor:!0,children:e.s})]});case"gap":return le(ae,{children:" "})}}function Al({tab:e,width:t}){let n=Te[e]??Te[0],o=6+Te.reduce((s,l)=>s+l.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return vo(jl,{flexDirection:"column",paddingX:1,children:[vo(ae,{children:[le(ae,{color:q,bold:!0,children:"Help "}),Te.map((s,l)=>l===e?le(ae,{color:"white",backgroundColor:q,bold:!0,children:` ${s.label} `},s.key):le(ae,{dimColor:!0,children:` ${s.label} `},s.key))]}),le(ae,{color:q,children:r}),le(jl,{flexDirection:"column",marginTop:1,children:n.rows.map((s,l)=>le(Xf,{row:s},l))}),le(ae,{dimColor:!0,children:`
260
+ \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var Kf=/^(?:\d+[.)]|[-*•])\s+/;function El(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
261
+ `)){let l=s.trim().replace(Kf,""),p=l.match(/^`([^`]+)`$/);p&&(l=p[1].trim());let h=l.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!h||!o.has(h[1].toLowerCase()))continue;let k=`/${h[1].toLowerCase()}${h[2]?` ${h[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}W();function pn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Me(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Nl(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Qf=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Il(e,t,n){if(!Qf.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(s=>{let l=s.replace(/\\/g,"/");return r===l||r.endsWith(`/${l}`)})??null}function Ps(e){return e.replace(/^[\w.-]+\//,"")}var Co=16,_l={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function ft(e){return typeof e=="string"?e:e.cmd}function Ol(e){return typeof e=="string"?void 0:e.desc}function Rs(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Ll(e,t){let n=Rs(t);return e.some(r=>ft(r).trim()===t.trim()||!!n&&Rs(ft(r))===n)?e.filter(r=>ft(r).trim()!==t.trim()&&!(n&&Rs(ft(r))===n)):[]}var Jf='\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 Zf(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"/pull":return"pull edits + new articles from Document360";case"/publish":return"push your local changes up to Document360";default:return""}}function Ue(e){return e===1?"":"s"}function em(e){switch(e){case"/write":return"it finishes the articles already planned";case"/catch-up":return"it clears everything your builder queued";case"/audit":return"it shows what the latest code changes touch";case"/pull":return"it reconciles anything changed on Document360";case"/publish":return"it pushes your local edits up to Document360";default:return"it\u2019s the most useful next step"}}function Ts(e,t,n){let o=[];e.pendingWrites>0&&o.push(` \u2022 ${e.pendingWrites} planned article${Ue(e.pendingWrites)} still unwritten`),e.localAhead>0&&o.push(` \u2022 ${e.localAhead} article${Ue(e.localAhead)} changed locally \u2014 ready to publish`),e.pendingText&&o.push(` \u2022 your builder left ${e.pendingText}`),e.behind>0&&o.push(` \u2022 ${e.behind} code change${Ue(e.behind)} since your last docs check`);let r=o.length>0?["Welcome back \u2014 where your docs stand:",...o,`I\u2019d start with ${t[0]} \u2014 ${em(t[0])}.`]:[`Welcome back. Your ${e.tracked} tracked article${Ue(e.tracked)} are all in sync.`];return r.push("",...t.map((s,l)=>` ${l+1} ${s.padEnd(9)} ${Zf(s,n)}`),"Or just tell me what to write or update."),r.join(`
262
+ `)}function Ml(e){if(!e.ready)return{kind:"idle"};let t=!!e.pendingText;if(!e.hasDocs)return{kind:"noDocs",note:Jf,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${Ue(e.pendingWrites)} not written yet \u2014 pick up where you left off:`;return{kind:"actions",note:Ts(e,r,t),title:s,options:r}}if(e.localAhead>0){let r=t?["/publish","/catch-up"]:["/publish","/audit"],s=`\u{1F4E4} ${e.localAhead} article${Ue(e.localAhead)} changed locally \u2014 ready to publish to Document360:`;return{kind:"actions",note:Ts(e,r,t),title:s,options:r}}if(!t&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${Ue(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`};let n=t?["/catch-up","/audit"]:["/audit","/pull"],o=t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:e.behind>0?`\u{1F4CB} ${e.behind} code change${Ue(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${Ue(e.tracked)} tracked for "${e.profileName}". What next?`;return{kind:"actions",note:Ts(e,n,t),title:o,options:n}}var tm=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Ul(e){return e.replace(/\r\n?/g,`
263
+ `)}function Wl(e){return e.includes(`
264
+ `)||e.length>200}function Fl(e,t){let n=t.split(`
265
+ `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Hl(e,t){return e.replace(tm,n=>t.get(n)??n)}function ql(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Po(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
266
+ `)){if(s.length===0)o.push({start:r,end:r});else for(let l=0;l<s.length;l+=n)o.push({start:r+l,end:r+Math.min(l+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function Ro(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Bl(e,t,n){let o=Ro(e,t),r=o+n;if(r<0||r>=e.length)return t;let s=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+s,e[r].end)}function Yl(e,t,n){let o=e[Ro(e,t)];return n==="start"?o.start:o.end}function Gl(e,t,n){let o=Math.max(1,n),r=e.split(`
267
+ `),s=0;for(let l=r.length-1;l>=0;l--){let p=r[l];if(s+=Math.max(1,Math.ceil(p.length/o)),s>=t){let h=s-t;return{text:[h>0?p.slice(h*o):p,...r.slice(l+1)].join(`
268
+ `),truncated:l>0||h>0}}}return{text:e,truncated:!1}}function Vl(e){let t=!1,n=0,o=0;for(let r of e.split(`
269
+ `)){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 Es,jsx as j,jsxs as Y}from"react/jsx-runtime";var Hm={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},sc=` 1. /init \u2014 pick your Document360 environment & scaffold config
270
270
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
271
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Em(e,t,n,o){let r=Es(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=Ns(e),p=Z(e),h=(p?.docsDir??fn).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${h}/ + config`,x={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:Am[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:k};if(p===null)return x;try{let D=de(e,o);x.profile=D.name,x.apiUrl=D.connection.apiUrl,x.prod=D.production,x.project=D.project.projectName??D.project.projectId??"(chosen at login)";let b=Ke(D.name);if(b){let T={...Ft(b.idToken)??{},...Ft(b.accessToken)??{}},C=T.email??T.preferred_username??"signed in";We(b)?b.refreshToken&&(x.who=C,x.loggedOut=!1,x.sessionHint="session expired \u2014 refreshing\u2026"):(x.who=C,x.loggedOut=!1,x.sessionHint=`session valid until ${new Date(b.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return x}function Nm(e,t){try{let n=de(e,t),o=Ke(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Ft(o.idToken)??{},...Ft(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return We(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 ec=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Ao=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Im="Ask me to write or update an article\u2026";function So({ch:e,dim:t}){let[n,o]=q(!0);return Te(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),E(S,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var _m=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function tc(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Lm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function nc(e){try{return jo(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function oc(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>nc(mt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&nc(mt(e,o)))}function rc(e,t){try{let n=Z(e);if(!n)return!1;let o=de(e,t),r=Do(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=mt(e,(n.docsDir??fn).replace(/\/+$/,""));return!!(Xe(s)&&jo(s).length>0||Xe(Is(e)))}catch{return!1}}function Om({startTime:e,chars:t}){let[n,o]=q(0);Te(()=>{let h=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(h)},[]);let r=Ao[n%Ao.length],s=ec[Math.floor(n/16)%ec.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return Y(oe,{children:[E(S,{color:H,children:` ${r} ${s}\u2026 `}),E(S,{color:"gray",children:`(${on(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var Mm=12e4;function Um({p:e}){let[t,n]=q(0);Te(()=>{let N=setInterval(()=>n(M=>M+1),150);return()=>clearInterval(N)},[]);let o=Ao[t%Ao.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>=Mm,h=e.verb??"Converting",k=e.unit??"article",x=e.rows.reduce((N,M)=>N+M.items,0),D=h.toLowerCase(),b=e.rows,T=0;if(b.length>vo){let N=b.findIndex(J=>J.status==="active"||J.status==="pending"),M=Math.max(0,Math.min(N-2,b.length-vo));T=b.slice(0,M).filter(J=>J.status==="done").length,b=b.slice(M,M+vo)}let C=Math.min(40,Math.max(...b.map(N=>Cs(N.label).length),0)),I=N=>N==="failed"?"red":N==="active"?H:void 0;return Y(oe,{flexDirection:"column",children:[Y(oe,{children:[E(S,{color:H,children:` ${o} ${h} ${x} ${k}${x===1?"":"s"} `}),E(S,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${on(r)} \xB7 esc to stop`})]}),T>0&&E(S,{dimColor:!0,children:` \u2714 +${T} done`}),b.map(N=>Y(S,{color:I(N.status),dimColor:N.status==="done"||N.status==="pending",children:[` ${Dl[N.status]} ${Cs(N.label).padEnd(C)}`,N.status==="active"&&N.itemsDone!==void 0?` (${N.itemsDone}/${N.items} ${k}${N.items===1?"":"s"})`:N.status!=="pending"?` (${N.items} ${k}${N.items===1?"":"s"})`:"",N.status==="active"?` \u2190 ${D}\u2026`:""]},N.label)),p&&E(S,{color:"yellow",children:` \u26A0 no activity for ${on(s)} \u2014 press esc to stop if it's wedged`})]})}var Wm=10800*1e3;function sc({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Yf(),[s,c]=q(n),[p,h]=q(null),[k,x]=q({text:"",pos:0}),D=k.text,b=V(l=>{x(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),T=V(l=>{x(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),C=V(()=>{x(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=Ol(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[I,N]=q(!1),[M,J]=q(!1),[pe,ne]=q(0),[De,ue]=q(null),[Qe,B]=q([]),ht=Q(0),[fc,mn]=q(!1),[mc,hn]=q(!1),[Eo,Ms]=q(null),[hc,gt]=q(0),Je=Q(0),[Ht,wt]=q(0),[yt,gn]=q(null),Us=Q(new Map),gc=Q(0),kt=Q([]),be=Q(null);be.current===null&&(be.current=Hl({cwd:e,profileName:s,allowProdWrites:!1}));let Ne=Q({uuid:null,firstPrompt:null,titleFired:!1}),wn=Q(new Map),bt=Q(!1),No=Q([]),Fe=Q([]),Io=Q(null),[Ws,Ze]=q(null),_o=Q(null),[et,tt]=q(null),[Ie,xt]=q(null),[He,$t]=q(null),[fe,vt]=q(null),[xe,nt]=q(null),[ot,Ct]=q(null),[Fs,me]=q(null),[$e,rt]=q(null),[ge,Pt]=q(null),[Hs,Lo]=q([]),st=Q([]),qt=Q(!1),ve=Q(null),[yn,ee]=q(null),kn=Q(!1),bn=Q(null),Bt=Q(null),[Ce,it]=q(null),[Oo,Yt]=q(null),[qs,Rt]=q(0),[Bs,Tt]=q(0),[wc,Ys]=q(0),Mo=Ts(()=>{try{return Ns(e).model??"auto"}catch{return null}},[e,wc]),{stdout:je}=Vf(),[,yc]=q(0),Gs=Q(`${je.columns??80}x${je.rows??24}`),qe=V(()=>Math.max(20,(je.columns??80)-1),[je]),d=V(l=>{kt.current.push(l),console.log(gr(l,qe()))},[qe]),[Uo,Wo]=q(null),St=V(l=>{Wo(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]),Fo=Q(!1),Ho=V(async()=>{try{if(Fo.current||!Rm(Pm())||Z(e)?.mode==="engineer")return;let l=await Cm({pkg:pt,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;Fo.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${pt} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),hn(!0),(await co().finally(()=>hn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),B(a=>a.includes("/exit")?a:[...a,"/exit"]),Ms(l.latest)):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${lo}`})}catch{}},[e,o,d]),qo=V(l=>{let i=Oe(e,s);return i.ok?!0:(d({kind:"note",tone:"warn",text:i.reason}),Bt.current=l,B(["/login"]),!1)},[e,s,d]),[Bo,Yo]=q(null),Gt=Q(!0),xn=Q(0),Vt=Q(0);Te(()=>{let l=setInterval(()=>{if(Gt.current){xn.current=0,Vt.current=0;return}if(!I)try{if(!Xe(Is(e)))return;if(Le(e).status==="current"){Gt.current=!0,xn.current=0,Vt.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."}),Wo(null),ue("write the docs for this repo");return}xn.current+=1;let i=xn.current;if((i===4||i%15===0)&&Vt.current<3){Vt.current+=1;let a=Vt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:en(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${a}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${a}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,I,d]),Te(()=>{let l=Ws??pn(e);if(!I){yo(0),Wt(`${bo} ${l}`);return}yo(3);let i=0;Wt(`${ko[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%ko.length,Wt(`${ko[i]} ${l}`)},400);return()=>clearInterval(a)},[I,e,Ws]),Te(()=>()=>yo(0),[]);let Go=V(l=>{try{let i=Z(e);if(!i)return{kind:"idle"};let a=de(e,s),g=Ke(a.name),u=!!g&&(!We(g)||!!g.refreshToken),m=rc(e,s)||!oc(e,i.authoritativeSourceFiles),w=Es(t).state==="missing",y=Do(e,a.name),P=y?Object.keys(y.articles).length:0,R=mt(e,(i.docsDir??fn).replace(/\/+$/,"")),z=!1;try{z=Xe(R)&&jo(R).length>0}catch{}let F=0;if(y?.lastAnalyzedCommit)try{let U=zf("git",["rev-list","--count",`${y.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});U.status===0&&(F=parseInt((U.stdout||"").trim(),10)||0)}catch{}let O=0;try{let U=zl(e);if(U.length>0){let K=(i.docsDir??fn).replace(/\/+$/,"");O=Lr(e,K,U.map(ye=>ye.path)).length}}catch{}let v=fm(e,s),A={ready:u&&m&&!w,hasDocs:z,tracked:P,pendingText:Ut(Mt(e)),behind:F,pendingWrites:O,localAhead:v,autoAudit:!!i.autoAudit,profileName:a.name,allowAutoAudit:l};return El(A)}catch{return{kind:"idle"}}},[e,s,t]);Te(()=>{let l=performance.now(),i=[],a=(w,y)=>{let P=performance.now();try{return y()}finally{let R=Math.round(performance.now()-P);R>=80&&i.push(`${w}: ${R}ms`)}};d({kind:"banner",info:a("banner",()=>Em(e,o,t,s))});let g=Es(t).state==="missing";if(g&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
272
- ${Kf}
271
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function qm(e,t,n,o){let r=Ns(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)",l=Is(e),p=Z(e),h=(p?.docsDir??mn).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${h}/ + config`,x={version:t,claude:s,model:l.model??"Claude Code default model",modelSource:Hm[l.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:k};if(p===null)return x;try{let D=pe(e,o);x.profile=D.name,x.apiUrl=D.connection.apiUrl,x.prod=D.production,x.project=D.project.projectName??D.project.projectId??"(chosen at login)";let b=Ke(D.name);if(b){let T={...Ft(b.idToken)??{},...Ft(b.accessToken)??{}},C=T.email??T.preferred_username??"signed in";We(b)?b.refreshToken&&(x.who=C,x.loggedOut=!1,x.sessionHint="session expired \u2014 refreshing\u2026"):(x.who=C,x.loggedOut=!1,x.sessionHint=`session valid until ${new Date(b.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return x}function Bm(e,t){try{let n=pe(e,t),o=Ke(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Ft(o.idToken)??{},...Ft(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return We(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 ic=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Ht=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ym="Ask me to write or update an article\u2026";function Do({ch:e,dim:t}){let[n,o]=H(!0);return be(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),j(S,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Gm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function ac(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Vm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function lc(e){try{return Ao(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function cc(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>lc(mt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&lc(mt(e,o)))}function uc(e,t){try{let n=Z(e);if(!n)return!1;let o=pe(e,t),r=jo(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=mt(e,(n.docsDir??mn).replace(/\/+$/,""));return!!(Xe(s)&&Ao(s).length>0||Xe(_s(e)))}catch{return!1}}function zm({startTime:e,chars:t}){let[n,o]=H(0);be(()=>{let h=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(h)},[]);let r=Ht[n%Ht.length],s=ic[Math.floor(n/16)%ic.length],l=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return Y(ne,{children:[j(S,{color:q,children:` ${r} ${s}\u2026 `}),j(S,{color:"gray",children:`(${rn(l)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function Xm({text:e}){let[t,n]=H(0);return be(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),j(ne,{paddingX:1,children:j(S,{color:q,children:`${Ht[t%Ht.length]} ${e}`})})}var Km=12e4;function Qm({p:e}){let[t,n]=H(0);be(()=>{let I=setInterval(()=>n(M=>M+1),150);return()=>clearInterval(I)},[]);let o=Ht[t%Ht.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),l=Math.round(e.chars/4),p=Date.now()-e.lastAt>=Km,h=e.verb??"Converting",k=e.unit??"article",x=e.rows.reduce((I,M)=>I+M.items,0),D=h.toLowerCase(),b=e.rows,T=0;if(b.length>Co){let I=b.findIndex(J=>J.status==="active"||J.status==="pending"),M=Math.max(0,Math.min(I-2,b.length-Co));T=b.slice(0,M).filter(J=>J.status==="done").length,b=b.slice(M,M+Co)}let C=Math.min(40,Math.max(...b.map(I=>Ps(I.label).length),0)),N=I=>I==="failed"?"red":I==="active"?q:void 0;return Y(ne,{flexDirection:"column",children:[Y(ne,{children:[j(S,{color:q,children:` ${o} ${h} ${x} ${k}${x===1?"":"s"} `}),j(S,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${l} tokens \xB7 ${rn(r)} \xB7 esc to stop`})]}),T>0&&j(S,{dimColor:!0,children:` \u2714 +${T} done`}),b.map(I=>Y(S,{color:N(I.status),dimColor:I.status==="done"||I.status==="pending",children:[` ${_l[I.status]} ${Ps(I.label).padEnd(C)}`,I.status==="active"&&I.itemsDone!==void 0?` (${I.itemsDone}/${I.items} ${k}${I.items===1?"":"s"})`:I.status!=="pending"?` (${I.items} ${k}${I.items===1?"":"s"})`:"",I.status==="active"?` \u2190 ${D}\u2026`:""]},I.label)),p&&j(S,{color:"yellow",children:` \u26A0 no activity for ${rn(s)} \u2014 press esc to stop if it's wedged`})]})}var Jm=10800*1e3;function dc({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=nm(),[s,l]=H(n),[p,h]=H(null),[k,x]=H({text:"",pos:0}),D=k.text,b=V(c=>{x(i=>{let a=typeof c=="function"?c(i.text):c;return{text:a,pos:a.length}})},[]),T=V(c=>{x(i=>({text:i.text.slice(0,i.pos)+c+i.text.slice(i.pos),pos:i.pos+c.length}))},[]),C=V(()=>{x(c=>{if(c.pos===0)return c;let i=c.text.slice(0,c.pos),a=ql(i)??i.slice(0,-1);return{text:a+c.text.slice(c.pos),pos:a.length}})},[]),[N,I]=H(!1),[M,J]=H(!1),[fe,oe]=H(0),[De,ue]=H(null),[Qe,B]=H([]),ht=Q(0),[kc,hn]=H(!1),[bc,gn]=H(!1),[Eo,Us]=H(null),[xc,gt]=H(0),Je=Q(0),[qt,wt]=H(0),[yt,wn]=H(null),Ws=Q(new Map),$c=Q(0),kt=Q([]),xe=Q(null);xe.current===null&&(xe.current=zl({cwd:e,profileName:s,allowProdWrites:!1}));let Ne=Q({uuid:null,firstPrompt:null,titleFired:!1}),yn=Q(new Map),bt=Q(!1),No=Q([]),Fe=Q([]),Io=Q(null),[Fs,Ze]=H(null),_o=Q(null),[et,tt]=H(null),[Ie,xt]=H(null),[He,$t]=H(null),[me,vt]=H(null),[$e,nt]=H(null),[ot,Ct]=H(null),[Hs,de]=H(null),[ve,rt]=H(null),[ge,Pt]=H(null),[qs,Oo]=H([]),st=Q([]),Bt=Q(!1),Ce=Q(null),[kn,ee]=H(null),[Bs,Ys]=H(null),bn=Q(!1),xn=Q(null),Yt=Q(null),[Pe,it]=H(null),[Lo,Gt]=H(null),[Gs,Rt]=H(0),[Vs,Tt]=H(0),[vc,zs]=H(0),Mo=Ss(()=>{try{return Is(e).model??"auto"}catch{return null}},[e,vc]),{stdout:je}=rm(),[,Cc]=H(0),Xs=Q(`${je.columns??80}x${je.rows??24}`),qe=V(()=>Math.max(20,(je.columns??80)-1),[je]),d=V(c=>{kt.current.push(c),console.log(gr(c,qe()))},[qe]),[Uo,Wo]=H(null),St=V(c=>{Wo(c),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]),Fo=Q(!1),Ho=V(async()=>{try{if(Fo.current||!Lm(Om())||Z(e)?.mode==="engineer")return;let c=await _m({pkg:pt,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;Fo.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${pt} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),gn(!0),(await uo().finally(()=>gn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),B(a=>a.includes("/exit")?a:[...a,"/exit"]),Us(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${co}`})}catch{}},[e,o,d]),qo=V(c=>{let i=Le(e,s);return i.ok?!0:(d({kind:"note",tone:"warn",text:i.reason}),Yt.current=c,B(["/login"]),!1)},[e,s,d]),[Bo,Yo]=H(null),Vt=Q(!0),$n=Q(0),zt=Q(0);be(()=>{let c=setInterval(()=>{if(Vt.current){$n.current=0,zt.current=0;return}if(!N)try{if(!Xe(_s(e)))return;if(Oe(e).status==="current"){Vt.current=!0,$n.current=0,zt.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."}),Wo(null),ue("write the docs for this repo");return}$n.current+=1;let i=$n.current;if((i===4||i%15===0)&&zt.current<3){zt.current+=1;let a=zt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:tn(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${a}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${a}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,N,d]),be(()=>{let c=Fs??fn(e);if(!N){ko(0),Wt(`${xo} ${c}`);return}ko(3);let i=0;Wt(`${bo[0]} ${c}`);let a=setInterval(()=>{i=(i+1)%bo.length,Wt(`${bo[i]} ${c}`)},400);return()=>clearInterval(a)},[N,e,Fs]),be(()=>()=>ko(0),[]);let Go=V(c=>{try{let i=Z(e);if(!i)return{kind:"idle"};let a=pe(e,s),g=Ke(a.name),u=!!g&&(!We(g)||!!g.refreshToken),m=uc(e,s)||!cc(e,i.authoritativeSourceFiles),w=Ns(t).state==="missing",y=jo(e,a.name),P=y?Object.keys(y.articles).length:0,R=mt(e,(i.docsDir??mn).replace(/\/+$/,"")),z=!1;try{z=Xe(R)&&Ao(R).length>0}catch{}let F=0;if(y?.lastAnalyzedCommit)try{let U=sm("git",["rev-list","--count",`${y.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});U.status===0&&(F=parseInt((U.stdout||"").trim(),10)||0)}catch{}let L=0;try{let U=ec(e);if(U.length>0){let K=(i.docsDir??mn).replace(/\/+$/,"");L=Or(e,K,U.map(ye=>ye.path)).length}}catch{}let v=Cm(e,s),E={ready:u&&m&&!w,hasDocs:z,tracked:P,pendingText:Ut(Mt(e)),behind:F,pendingWrites:L,localAhead:v,autoAudit:!!i.autoAudit,profileName:a.name,allowAutoAudit:c};return Ml(E)}catch{return{kind:"idle"}}},[e,s,t]);be(()=>{let c=performance.now(),i=[],a=(w,y)=>{let P=performance.now();try{return y()}finally{let R=Math.round(performance.now()-P);R>=80&&i.push(`${w}: ${R}ms`)}};d({kind:"banner",info:a("banner",()=>qm(e,o,t,s))});let g=Ns(t).state==="missing";if(g&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
272
+ ${am}
273
273
  Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!Z(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:
274
- ${Zl}`}),B(g?["/doctor","/init"]:["/init"]);return}g&&B(["/doctor"]);try{let w=de(e,s),y=Ke(w.name);y&&We(y)&&y.refreshToken?em({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),ne(P=>P+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),B(["/login"])}):(!y||We(y))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),B(["/login"]))}catch{}try{let w=Z(e),y=de(e,s),P=Ke(y.name);w&&P&&!We(P)&&oc(e,w.authoritativeSourceFiles)&&!rc(e,s)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),B(["/scope"]))}catch{}try{if(a("reconcile-devhints",()=>Yn(e)),Le(e).status!=="current")if(en(e))d({kind:"note",tone:"info",text:`\u{1F514} A newer dev\u2194docs protocol (v${re}) is available \u2014 your builder can re-run /devhints when convenient. Your docs aren't blocked.`});else{let w=Gn(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
275
- `)}),St(lt()),Gt.current=!1)}}catch{}try{let w=a("reconcile-feedback",()=>Sm(e));w.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}let u=a("ready-decision",()=>Go(!0));u.kind==="autoAudit"?(d({kind:"note",tone:"info",text:u.note}),an().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&se(w.prompt,{display:w.display,quietUser:!0})})):u.kind==="noDocs"?(d({kind:"note",tone:"info",text:u.note}),ue(u.ghost),B(u.options),u.title&&me(u.title)):u.kind==="actions"&&(d({kind:"note",tone:"info",text:u.note}),B(u.options),me(u.title));let m=Math.round(performance.now()-l);m>=800&&jm({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${m}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${i.length?i.join(`
274
+ ${sc}`}),B(g?["/doctor","/init"]:["/init"]);return}g&&B(["/doctor"]);try{let w=pe(e,s),y=Ke(w.name);y&&We(y)&&y.refreshToken?dm({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),oe(P=>P+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),B(["/login"])}):(!y||We(y))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),B(["/login"]))}catch{}try{let w=Z(e),y=pe(e,s),P=Ke(y.name);w&&P&&!We(P)&&cc(e,w.authoritativeSourceFiles)&&!uc(e,s)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),B(["/scope"]))}catch{}try{if(a("reconcile-devhints",()=>Gn(e)),Oe(e).status!=="current")if(tn(e))d({kind:"note",tone:"info",text:`\u{1F514} A newer dev\u2194docs protocol (v${re}) is available \u2014 your builder can re-run /devhints when convenient. Your docs aren't blocked.`});else{let w=Vn(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
275
+ `)}),St(lt()),Vt.current=!1)}}catch{}try{let w=a("reconcile-feedback",()=>Um(e));w.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}let u=a("ready-decision",()=>Go(!0));u.kind==="autoAudit"?(d({kind:"note",tone:"info",text:u.note}),ln().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&se(w.prompt,{display:w.display,quietUser:!0})})):u.kind==="noDocs"?(d({kind:"note",tone:"info",text:u.note}),ue(u.ghost),B(u.options),u.title&&de(u.title)):u.kind==="actions"&&(d({kind:"note",tone:"info",text:u.note}),B(u.options),de(u.title));let m=Math.round(performance.now()-c);m>=800&&Fm({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${m}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${i.length?i.join(`
276
276
  `):"no single phase \u226580ms"}
277
- cwd: ${e}`}),Ho()},[]),Te(()=>{let l=setInterval(()=>{Ho()},Wm);return()=>clearInterval(l)},[Ho]),Te(()=>{if(I||Qe.length>0)return;let l=Go(!1);(l.kind==="actions"||l.kind==="noDocs")&&(B(l.options),me(l.title??null))},[I,Qe,pe,Go]),Te(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${je.columns??80}x${je.rows??24}`;g!==Gs.current&&(Gs.current=g,yc(u=>u+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+zi(kt.current,qe())+"\x1B[?2026l")},80))},400)};return je.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),je.off("resize",a)}},[je,qe]);let _e=Math.max(20,(je.columns??80)-1),Vs=Ts(()=>Nm(e,s),[e,s,pe]),Vo=(()=>{if(mc)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Eo!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Eo?` v${Eo}`:""}\u2026`,isSetup:!0};let l=Z(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=mt(e,(l.docsDir??fn).replace(/\/+$/,"")),a=(()=>{try{return Xe(i)&&jo(i).length>0}catch{return!1}})();try{let g=de(e,s),u=Ke(g.name);if(!(!!u&&!(We(u)&&!u.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${g.name}")\u2026`,isSetup:!0};if(!g.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!g.project.workspaceId&&!a)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return a?{text:Im,isSetup:!1}:Uo?{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}})(),zt=$l(D),zs=zt.length>0&&!I,zo=p!==null?Wl(p,8,_e):null,$n=$e?$e.paths.filter(l=>!$e.query||l.toLowerCase().includes($e.query.toLowerCase())).slice(0,8):[],vn=Ce?Ce.sessions.filter(l=>{let i=Ce.query.toLowerCase();return!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],we=V((l,i)=>{be.current?.close(),be.current=Hl({cwd:e,resume:l,profileName:i??s,allowProdWrites:bt.current}),l||(Ne.current={uuid:null,firstPrompt:null,titleFired:!1},Ze(null)),Rt(0),Tt(0)},[e,s]),Xs=V((l,i,a)=>{if(_m.test(l))try{let g=de(e,s),u=typeof i.project_id=="string"&&i.project_id||g.project.projectId,m=go(i,a),w=[],y=wo(a);l.endsWith("publish_article")&&y&&w.push(`Live: ${y}`),m&&u&&w.push(`Preview: ${ho(g.connection.portalUrl,u,m,g.project.languageCode??"en")}`),w.length>0&&d({kind:"link",lines:w})}catch{}},[e,s,d]),se=V(async(l,i)=>{mn(!0),ue(null),B([]),me(null),Wo(null),Yo(null);let a=++ht.current;i?.quietUser||d({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let g=Ne.current;g.firstPrompt||(g.firstPrompt=i?.display??l),Je.current=Date.now(),gt(0),N(!0),wn.current.clear();let u="",m=!1,w=!1,y="",P={num:0,closed:!1,cueSeen:!1},R=null,z=()=>{R||(R=setTimeout(()=>{R=null,h(y.length>0?y:null)},60))},F=()=>{R&&clearTimeout(R),R=null,h(null)},O=()=>{if(y.trim()){let v=$s(y.trimEnd(),P);d({kind:"assistant",text:v})}y="",F()};try{for await(let v of be.current.send(l))if(v.type==="session"){if(!g.uuid){g.uuid=v.sessionId;let A=new Date().toISOString(),U=_o.current,K=U??im(g.firstPrompt??"session");am({uuid:v.sessionId,name:K,renamed:!!U,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:A,updatedAt:A}),Ze(K),_o.current=null}}else if(v.type==="text"){y+=v.delta,u+=v.delta;let A=Fl(y);if(A>0){let U=y.slice(0,A).trimEnd();U&&d({kind:"assistant",text:$s(U,P)}),y=y.slice(A)}z(),gt(U=>U+v.delta.length)}else if(v.type==="tool"){m=!0;let A=fo(v.name,v.input);A&&(O(),d({kind:"tool",title:A.title,sep:A.sep,arg:A.arg}),wn.current.set(v.id,{name:v.name,input:v.input}))}else if(v.type==="article_diff"){let A=ut(v.oldContent,v.newContent,qe());A&&(O(),d({kind:"diff",added:A.added,removed:A.removed,lines:A.lines,hidden:A.hidden}))}else if(v.type==="tool_result"){v.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(v.output)&&(kn.current=!0);let A=wn.current.get(v.id);if(A){wn.current.delete(v.id),O();let U=mo(v.output,4,v.isError?void 0:A.name,A.input);d({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:v.isError}),v.isError||Xs(A.name,A.input,v.output)}}else if(v.type==="result"){if(O(),Rt(U=>U+v.outputTokens),Tt(U=>U+v.costUsd),d({kind:"done",seconds:Math.round((Date.now()-Je.current)/1e3),tokens:v.outputTokens,costUsd:v.costUsd,ok:v.ok}),!w&&!m&&!u.trim()&&!qt.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)."}),v.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let U=Tm(e);if(Xe(U)){let K=Ss(U,"utf8").trim();K&&(Yo(K),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 A=v.ok?Rl(u,xo.map(U=>U.name)):[];if(A.length>0?B(A):v.ok&&u.trim()&&dm(l,u,e).then(U=>{U&&ht.current===a&&ue(U)}).catch(()=>{}),g.uuid&&(Ds(g.uuid),!g.titleFired)){g.titleFired=!0;let U=g.uuid,K=g.firstPrompt;K&&ql(K,e).then(ye=>{ye&&(sm(U,ye),Ze(ye))}).catch(()=>{})}}else v.type==="error"&&(O(),w=!0,v.kind==="auth"&&(kn.current=!0),d({kind:"note",text:`agent error: ${v.message}`,tone:"error"}))}finally{N(!1),F(),ne(v=>v+1),Ne.current.uuid&&yl(e,Ne.current.uuid,kt.current),kn.current&&(kn.current=!1,bn.current=i?.display??l,B(["/login"])),qt.current&&(qt.current=!1,st.current.length>0&&(d({kind:"note",tone:"info",text:`(${st.current.length} queued message(s) discarded)`}),st.current=[],Lo([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Xs,qe]),Cn=V(async l=>{let i=js(l),a=To(e,"standard");Je.current=Date.now(),gt(0),N(!0);let g=new AbortController;ve.current=g,ee({verb:"Publishing",total:i.length,done:0,active:[],rows:dn(i),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${rn} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let u of Ro({cwd:e,partitions:i,promptFor:m=>Jn(m.paths),concurrency:rn,profileName:s,allowProdWrites:bt.current,model:a.model,signal:g.signal}))if(u.type==="partition_status")u.status==="running"?ee(m=>m&&{...m,active:[...m.active,u.label],rows:Me(m.rows,u.label,"active"),lastAt:Date.now()}):ee(m=>m&&{...m,active:m.active.filter(w=>w!==u.label),done:m.done+1,rows:Me(m.rows,u.label,u.status==="done"?"done":"failed"),lastAt:Date.now()});else if(u.type==="partition_event")ee(m=>{if(!m)return m;let w={...m,lastAt:Date.now()};return u.event.type==="tool"?w.tools=m.tools+1:u.event.type==="text"&&(w.chars=m.chars+u.event.delta.length),w});else if(u.type==="run_done"){Tt(P=>P+u.totalCostUsd),Rt(P=>P+u.results.reduce((R,z)=>R+z.outputTokens,0));let m=u.aborted?"Stopped. ":"",w=t.kind==="api"?"api":"subscription";d({kind:"note",tone:u.aborted?"warn":u.ok?"ok":"warn",text:m+xr(u.results,i,w).join(`
278
- `)});let y=br(e,s);if(y&&d({kind:"note",tone:"info",text:y}),!u.aborted){try{let P=await Xl({cwd:e,profileName:s}),R=Kl(P);R?d({kind:"note",tone:"info",text:R}):P.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${P.skipped}`})}catch(P){d({kind:"note",tone:"warn",text:`Order sync failed: ${P.message}`})}try{let P=Jl(await Ql({cwd:e,profileName:s}));P&&d({kind:"note",tone:"info",text:P})}catch(P){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${P.message}`})}}}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{ve.current=null,ee(null),N(!1),ne(u=>u+1)}},[e,s,d,t]),Xo=V(async l=>{await se(kr(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await Zn(e,s,l.replace(/\\/g,"/"));i.length>0&&(me(`Related articles not yet published (${i.length}):`),B([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,se]),Ko=V(l=>{let i=Ke(l);if(!i||We(i)&&!i.refreshToken)return null;let a={...Ft(i.idToken)??{},...Ft(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),Qo=V((l,i)=>{if(i){let a=Z(e);a&&(a.defaultProfile=l,Bl(a,e))}c(l),we(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Ko(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),B(["/login"])),ne(a=>a+1)},[e,d,we,Ko]),Pn=V((l,i,a)=>{Nn(e,l,i,a.id,a.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),we(),Do(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:_t(It(e)).join(`
279
- `)}),St(lt()),Gt.current=Le(e).status==="current"||en(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,we,St]),Rn=V(async l=>{let i;try{i=await Qt(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),B(["/workspace"]);return}if(i.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),g=a.length>0?a:i.workspaces;if(g.length===1){let u=g[0],m=i.workspaces.length-g.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),Pn(i.profile,i.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),B(["/workspace"])},[e,d,Pn]),Tn=V((l,i)=>{In(e,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),we(),Rn(l)},[e,d,we,Rn]),Ks=V(async l=>{let i;try{i=de(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await Ye(e,i.name),g=a.find(u=>u.id===i.project.projectId);g?.name&&Dm(e,i.name,{projectName:g.name})}catch{}await Rn(i.name);return}try{let{projects:a}=await Ye(e,i.name);if(a.length===1){let g=a[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),Tn(i.name,{id:g.id,name:g.name});return}if(a.length>1){let g=a.map(u=>({id:u.id,name:u.name??u.id,sub:u.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),nt({cursor:0,current:-1,rows:g,profile:i.name,environment:i.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),B(["/project"])}},[e,d,Rn,Tn]),Sn=V(()=>{let l=Fe.current[0];if(!l)return;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let a of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${a}`});l.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let i=ut(l.oldContent,l.newContent,qe());d(i?{kind:"diff",added:i.added,removed:i.removed,lines:i.lines,hidden:i.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,qe]),Qs=V(l=>{if(Fe.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Fe.current.shift();try{pm({cwd:e,profileName:s},a),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Fe.current.length===0&&B(g=>g.length>0?g:["/pull"])}catch(g){d({kind:"note",tone:"error",text:`Pull failed: ${g.message}`})}}else if(i==="n"||i==="no"){let a=Fe.current.shift();d({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Fe.current.length;return Fe.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return Sn(),!0},[e,s,Sn,d]),Js=V(l=>{let i=Io.current;if(!i)return!1;if(Io.current=null,ue(null),ht.current++,l.trim()!==i.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:g}=ms(e,i.targets);d({kind:"note",tone:g.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let u of g)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return i.hadDevhints&&(d({kind:"note",tone:"warn",text:Vn().join(`
277
+ cwd: ${e}`}),Ho()},[]),be(()=>{let c=setInterval(()=>{Ho()},Jm);return()=>clearInterval(c)},[Ho]),be(()=>{if(N||Qe.length>0)return;let c=Go(!1);(c.kind==="actions"||c.kind==="noDocs")&&(B(c.options),de(c.title??null))},[N,Qe,fe,Go]),be(()=>{let c=null,i=null,a=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let g=`${je.columns??80}x${je.rows??24}`;g!==Xs.current&&(Xs.current=g,Cc(u=>u+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Qi(kt.current,qe())+"\x1B[?2026l")},80))},400)};return je.on("resize",a),()=>{c&&clearTimeout(c),i&&clearTimeout(i),je.off("resize",a)}},[je,qe]);let _e=Math.max(20,(je.columns??80)-1),Ks=Ss(()=>Bm(e,s),[e,s,fe]),Vo=(()=>{if(bc)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Eo!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Eo?` v${Eo}`:""}\u2026`,isSetup:!0};let c=Z(e);if(!c)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=mt(e,(c.docsDir??mn).replace(/\/+$/,"")),a=(()=>{try{return Xe(i)&&Ao(i).length>0}catch{return!1}})();try{let g=pe(e,s),u=Ke(g.name);if(!(!!u&&!(We(u)&&!u.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${g.name}")\u2026`,isSetup:!0};if(!g.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!g.project.workspaceId&&!a)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return a?{text:Ym,isSetup:!1}:Uo?{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}})(),Xt=Sl(D),Qs=Xt.length>0&&!N,zo=p!==null?Gl(p,8,_e):null,vn=ve?ve.paths.filter(c=>!ve.query||c.toLowerCase().includes(ve.query.toLowerCase())).slice(0,8):[],Cn=Pe?Pe.sessions.filter(c=>{let i=Pe.query.toLowerCase();return!i||c.name.toLowerCase().includes(i)||c.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],we=V((c,i)=>{xe.current?.close(),xe.current=zl({cwd:e,resume:c,profileName:i??s,allowProdWrites:bt.current}),c||(Ne.current={uuid:null,firstPrompt:null,titleFired:!1},Ze(null)),Rt(0),Tt(0)},[e,s]),Js=V((c,i,a)=>{if(Gm.test(c))try{let g=pe(e,s),u=typeof i.project_id=="string"&&i.project_id||g.project.projectId,m=wo(i,a),w=[],y=yo(a);c.endsWith("publish_article")&&y&&w.push(`Live: ${y}`),m&&u&&w.push(`Preview: ${go(g.connection.portalUrl,u,m,g.project.languageCode??"en")}`),w.length>0&&d({kind:"link",lines:w})}catch{}},[e,s,d]),se=V(async(c,i)=>{hn(!0),ue(null),B([]),de(null),Wo(null),Yo(null);let a=++ht.current;i?.quietUser||d({kind:"user",text:i?.echoDisplay&&i.display?i.display:c});let g=Ne.current;g.firstPrompt||(g.firstPrompt=i?.display??c),Je.current=Date.now(),gt(0),I(!0),yn.current.clear();let u="",m=!1,w=!1,y="",P={num:0,closed:!1,cueSeen:!1},R=null,z=()=>{R||(R=setTimeout(()=>{R=null,h(y.length>0?y:null)},60))},F=()=>{R&&clearTimeout(R),R=null,h(null)},L=()=>{if(y.trim()){let v=vs(y.trimEnd(),P);d({kind:"assistant",text:v})}y="",F()};try{for await(let v of xe.current.send(c))if(v.type==="session"){if(!g.uuid){g.uuid=v.sessionId;let E=new Date().toISOString(),U=_o.current,K=U??wm(g.firstPrompt??"session");ym({uuid:v.sessionId,name:K,renamed:!!U,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:E,updatedAt:E}),Ze(K),_o.current=null}}else if(v.type==="text"){y+=v.delta,u+=v.delta;let E=Vl(y);if(E>0){let U=y.slice(0,E).trimEnd();U&&d({kind:"assistant",text:vs(U,P)}),y=y.slice(E)}z(),gt(U=>U+v.delta.length)}else if(v.type==="tool"){m=!0;let E=mo(v.name,v.input);E&&(L(),d({kind:"tool",title:E.title,sep:E.sep,arg:E.arg}),yn.current.set(v.id,{name:v.name,input:v.input}))}else if(v.type==="article_diff"){let E=ut(v.oldContent,v.newContent,qe());E&&(L(),d({kind:"diff",added:E.added,removed:E.removed,lines:E.lines,hidden:E.hidden}))}else if(v.type==="tool_result"){v.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(v.output)&&(bn.current=!0);let E=yn.current.get(v.id);if(E){yn.current.delete(v.id),L();let U=ho(v.output,4,v.isError?void 0:E.name,E.input);d({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:v.isError}),v.isError||Js(E.name,E.input,v.output)}}else if(v.type==="result"){if(L(),Rt(U=>U+v.outputTokens),Tt(U=>U+v.costUsd),d({kind:"done",seconds:Math.round((Date.now()-Je.current)/1e3),tokens:v.outputTokens,costUsd:v.costUsd,ok:v.ok}),!w&&!m&&!u.trim()&&!Bt.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)."}),v.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let U=Mm(e);if(Xe(U)){let K=Ds(U,"utf8").trim();K&&(Yo(K),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 E=v.ok?El(u,$o.map(U=>U.name)):[];if(E.length>0?B(E):v.ok&&u.trim()&&$m(c,u,e).then(U=>{U&&ht.current===a&&ue(U)}).catch(()=>{}),g.uuid&&(js(g.uuid),!g.titleFired)){g.titleFired=!0;let U=g.uuid,K=g.firstPrompt;K&&Xl(K,e).then(ye=>{ye&&(gm(U,ye),Ze(ye))}).catch(()=>{})}}else v.type==="error"&&(L(),w=!0,v.kind==="auth"&&(bn.current=!0),d({kind:"note",text:`agent error: ${v.message}`,tone:"error"}))}finally{I(!1),F(),oe(v=>v+1),Ne.current.uuid&&Cl(e,Ne.current.uuid,kt.current),bn.current&&(bn.current=!1,xn.current=i?.display??c,B(["/login"])),Bt.current&&(Bt.current=!1,st.current.length>0&&(d({kind:"note",tone:"info",text:`(${st.current.length} queued message(s) discarded)`}),st.current=[],Oo([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Js,qe]),Pn=V(async c=>{let i=As(c),a=So(e,"standard");Je.current=Date.now(),gt(0),I(!0);let g=new AbortController;Ce.current=g,ee({verb:"Publishing",total:i.length,done:0,active:[],rows:pn(i),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Publishing ${c.length} article${c.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${sn} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let u of To({cwd:e,partitions:i,promptFor:m=>Zn(m.paths),concurrency:sn,profileName:s,allowProdWrites:bt.current,model:a.model,signal:g.signal}))if(u.type==="partition_status")u.status==="running"?ee(m=>m&&{...m,active:[...m.active,u.label],rows:Me(m.rows,u.label,"active"),lastAt:Date.now()}):ee(m=>m&&{...m,active:m.active.filter(w=>w!==u.label),done:m.done+1,rows:Me(m.rows,u.label,u.status==="done"?"done":"failed"),lastAt:Date.now()});else if(u.type==="partition_event")ee(m=>{if(!m)return m;let w={...m,lastAt:Date.now()};return u.event.type==="tool"?w.tools=m.tools+1:u.event.type==="text"&&(w.chars=m.chars+u.event.delta.length),w});else if(u.type==="run_done"){Tt(P=>P+u.totalCostUsd),Rt(P=>P+u.results.reduce((R,z)=>R+z.outputTokens,0));let m=u.aborted?"Stopped. ":"",w=t.kind==="api"?"api":"subscription";d({kind:"note",tone:u.aborted?"warn":u.ok?"ok":"warn",text:m+xr(u.results,i,w).join(`
278
+ `)});let y=br(e,s);if(y&&d({kind:"note",tone:"info",text:y}),!u.aborted){try{let P=await tc({cwd:e,profileName:s}),R=nc(P);R?d({kind:"note",tone:"info",text:R}):P.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${P.skipped}`})}catch(P){d({kind:"note",tone:"warn",text:`Order sync failed: ${P.message}`})}try{let P=rc(await oc({cwd:e,profileName:s}));P&&d({kind:"note",tone:"info",text:P})}catch(P){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${P.message}`})}}}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{Ce.current=null,ee(null),I(!1),oe(u=>u+1)}},[e,s,d,t]),Xo=V(async c=>{await se(kr(c),{display:`/publish ${c}`,quietUser:!0});try{let i=await eo(e,s,c.replace(/\\/g,"/"));i.length>0&&(de(`Related articles not yet published (${i.length}):`),B([`/publish --related ${c}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,se]),Ko=V(c=>{let i=Ke(c);if(!i||We(i)&&!i.refreshToken)return null;let a={...Ft(i.idToken)??{},...Ft(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),Qo=V((c,i)=>{if(i){let a=Z(e);a&&(a.defaultProfile=c,Kl(a,e))}l(c),we(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Ko(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 do you want to log in now? (press 1)`}),B(["/login"])),oe(a=>a+1)},[e,d,we,Ko]),Rn=V((c,i,a)=>{In(e,c,i,a.id,a.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),we(),jo(e,c)||(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:_t(It(e)).join(`
279
+ `)}),St(lt()),Vt.current=Oe(e).status==="current"||tn(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,we,St]),Tn=V(async c=>{let i;try{i=await Jt(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),B(["/workspace"]);return}if(i.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),g=a.length>0?a:i.workspaces;if(g.length===1){let u=g[0],m=i.workspaces.length-g.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),Rn(i.profile,i.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),B(["/workspace"])},[e,d,Rn]),Sn=V((c,i)=>{_n(e,c,i.id,i.name),d({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),we(),Tn(c)},[e,d,we,Tn]),Zs=V(async c=>{let i;try{i=pe(e,c)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await Ye(e,i.name),g=a.find(u=>u.id===i.project.projectId);g?.name&&Wm(e,i.name,{projectName:g.name})}catch{}await Tn(i.name);return}try{let{projects:a}=await Ye(e,i.name);if(a.length===1){let g=a[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),Sn(i.name,{id:g.id,name:g.name});return}if(a.length>1){let g=a.map(u=>({id:u.id,name:u.name??u.id,sub:u.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),nt({cursor:0,current:-1,rows:g,profile:i.name,environment:i.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),B(["/project"])}},[e,d,Tn,Sn]),Dn=V(()=>{let c=Fe.current[0];if(!c)return;d({kind:"note",tone:"info",text:`\u25CF ${c.title} (${c.path})`});for(let a of c.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${a}`});c.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let i=ut(c.oldContent,c.newContent,qe());d(i?{kind:"diff",added:i.added,removed:i.removed,lines:i.lines,hidden:i.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),d({kind:"note",tone:"info",text:`Write ${c.path}? (y/n \u2014 anything else cancels)`})},[d,qe]),ei=V(c=>{if(Fe.current.length===0)return!1;let i=c.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Fe.current.shift();try{vm({cwd:e,profileName:s},a),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Fe.current.length===0&&B(g=>g.length>0?g:["/pull"])}catch(g){d({kind:"note",tone:"error",text:`Pull failed: ${g.message}`})}}else if(i==="n"||i==="no"){let a=Fe.current.shift();d({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Fe.current.length;return Fe.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return Dn(),!0},[e,s,Dn,d]),ti=V(c=>{let i=Io.current;if(!i)return!1;if(Io.current=null,ue(null),ht.current++,c.trim()!==i.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:g}=ms(e,i.targets);d({kind:"note",tone:g.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let u of g)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return i.hadDevhints&&(d({kind:"note",tone:"warn",text:zn().join(`
280
280
  `)}),St(ir())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
281
- ${Zl}`}),B(["/init"]),mn(!1),!0},[e,d,St]),Zs=V(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),g=i.slice(1);switch(mn(!0),a){case"help":Yt({tab:0});return;case"exit":case"quit":be.current?.close(),r();return;case"clear":we(),kt.current=[],mn(!1),ue(null),ht.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=de(e,s)}catch(m){d({kind:"note",tone:"error",text:m.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),J(!0);try{let m=await Qf(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},y=>d({kind:"note",tone:"info",text:y})),w=Jf(u.name,m);if(Zf(w),await tr(w,u.name,y=>d({kind:"note",tone:"info",text:y})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${On(w)}`}),await Ks(s),Bt.current){let y=Bt.current;Bt.current=null;let P=Oe(e,s);P.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${y}.`}),B([y])):(d({kind:"note",tone:"warn",text:`${P.reason} (then ${y}.)`}),B(["/login"]),Bt.current=y)}else bn.current&&(ue(bn.current),bn.current=null,d({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(m){d({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{J(!1),ne(m=>m+1)}return}case"allow-prod":{let u=!1;try{u=de(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}bt.current=!0,we(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Kr(g.join(" ")),m=Ne.current.uuid;if(!m){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}_o.current=u,Ze(u),Wt(`${bo} ${u}`),d({kind:"note",tone:"ok",text:`Session will be named "${u}" once it starts.`});return}if(!u){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Ne.current.firstPrompt??"";ql(w,e).then(y=>{y?(ue(`/rename ${y}`),d({kind:"note",tone:"info",text:`Suggestion: "${y}" \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}um(m,u),Ze(u),Wt(`${bo} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=g[0],m=Z(e);if(!u){let w=Object.entries(m?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let y=w.map(([z,F])=>({name:z,env:F.connection?.environment??"custom",prod:F.production===!0,who:Ko(z)})),P=s??m?.defaultProfile,R=Math.max(0,y.findIndex(z=>z.name===P));xt({cursor:R,current:R,rows:y});return}if(u==="add"){let w=Qr(e,g[1],g[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),Qo(g[1],!1);return}if(!m?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}Qo(u,!0);return}case"doctor":await cn(g,{cwd:e});return;case"mcp":await Kn(g);return;case"init":{if(Z(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let u=km().map(m=>({name:m,apiUrl:bm(m).apiUrl}));$t({cursor:0,rows:u});return}case"resume":{let u=g.join(" ").trim(),m=cm(e).filter(P=>P.uuid!==Ne.current.uuid);if(!u){if(!m.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}it({query:"",cursor:0,sessions:m});return}let w=lm(e,u);if(!w){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}we(w.uuid),Ne.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},Ze(w.name),Ds(w.uuid),kt.current=[];let y=vs(e,w.uuid);for(let P of y)d(P);d({kind:"note",tone:"ok",text:y.length?`Resumed "${w.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=g.join(" ").trim(),m;try{m=await Qt(e,s)}catch(y){d({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!u){let y=m.workspaces.map(R=>({id:R.id,name:R.name??R.id,type:R.workspace_type}));if(y.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let P=Math.max(0,y.findIndex(R=>R.id===m.current));vt({cursor:P,current:P,rows:y,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let w=Zo(m.workspaces,u);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}Pn(m.profile,m.projectId,w);return}case"project":{let u=g.join(" ").trim(),m;try{m=await Ye(e,s)}catch(y){d({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!u){let y=m.projects.map(R=>({id:R.id,name:R.name??R.id,sub:R.sub_domain}));if(y.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let P=y.findIndex(R=>R.id===m.current);nt({cursor:Math.max(0,P),current:P,rows:y,profile:m.profile,environment:m.environment});return}let w=er(m.projects,u);if(!w){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${m.projects.map(y=>y.name??y.id).join(", ")}`});return}Tn(m.profile,w);return}case"logout":{let u;try{u=de(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let m=om(u);rm(e,u),we(),ne(w=>w+1),d({kind:"note",tone:m?"ok":"info",text:m?`\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."}),B(["/login"]);return}case"publish":{if(!qo(l.trim()))return;if(g[0]==="--related"&&g[1]){let m=await Zn(e,s,g[1].replace(/\\/g,"/"));if(m.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Cn(m);return}if(g[0]&&g[0]!=="--all"){await Xo(g[0]);return}let u=g[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Yl({cwd:e,profileName:s}),w=sn(m.entries),y=Qn(m.entries);if(y>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${y} article${y===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),w.length===0){d({kind:"note",tone:"ok",text:y>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let P=m.counts["unknown-base"]??0;P>0&&d({kind:"note",tone:"info",text:`(${P} article(s) have no sync base yet \u2014 publish those by path if needed.)`});try{let R=await Xl({cwd:e,profileName:s}),z=Kl(R);z?d({kind:"note",tone:"info",text:z}):R.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${R.skipped}`});let F=Jl(await Ql({cwd:e,profileName:s}));F&&d({kind:"note",tone:"info",text:F}),!z&&!F&&!R.skipped&&d({kind:"note",tone:"info",text:"Category + article order and related articles already match your structure."})}catch(R){d({kind:"note",tone:"warn",text:`Structure sync failed: ${R.message}`})}return}if(u){await Cn(w.map(P=>P.path));return}Ct({cursor:0,rows:ta(w)})}catch(m){d({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let u=g.join(" ").trim();if(!u){let w=[];try{w=Object.keys(Do(e,de(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}rt({query:"",cursor:0,paths:w});return}let m=Xf(u)?u:mt(e,u);if(Xe(m)){try{d({kind:"preview",name:pn(m),text:tc(Ss(m,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${m}: ${w.message}`})}return}if(Lm.test(u)){try{let w=de(e,s),y={profile:w.name,connection:w.connection},P=w.project.projectId??tm(y),R=await nm(y,P,u);d({kind:"preview",name:R.title??u,text:R.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${u}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let u=g[0]?.trim();if(!u){let P=ro(Ns(e));tt({cursor:P,current:P});return}let{lines:m,changed:w,effective:y}=ln(e,u);for(let P of m)d({kind:"note",tone:P.startsWith("\u26A0")?"warn":P.startsWith("\u2713")?"ok":"info",text:P});w&&(Ys(P=>P+1),be.current?.setModel(y));return}case"convert":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:m}=Sr(g),w=vm(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let y=Dr(w,u);if(y.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${w.length} are tracked overall.)`});return}let P=js(y),R=3,z=`/convert${u?` --scope ${u}`:""} --run`,F=To(e,"light");if(!m){let v=Vl({files:jr(e,y),op:"convert",model:F.model}),A=u?`Scope: ${u} (${y.length} of ${w.length} tracked)
281
+ ${sc}`}),B(["/init"]),hn(!1),!0},[e,d,St]),ni=V(async c=>{let i=c.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),g=i.slice(1);switch(hn(!0),a){case"help":Gt({tab:0});return;case"exit":case"quit":xe.current?.close(),r();return;case"clear":we(),kt.current=[],hn(!1),ue(null),ht.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(m){d({kind:"note",tone:"error",text:m.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),J(!0);try{let m=await lm(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},y=>d({kind:"note",tone:"info",text:y})),w=cm(u.name,m);if(um(w),await tr(w,u.name,y=>d({kind:"note",tone:"info",text:y})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${Mn(w)}`}),await Zs(s),Yt.current){let y=Yt.current;Yt.current=null;let P=Le(e,s);P.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${y}.`}),B([y])):(d({kind:"note",tone:"warn",text:`${P.reason} (then ${y}.)`}),B(["/login"]),Yt.current=y)}else xn.current&&(ue(xn.current),xn.current=null,d({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(m){d({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{J(!1),oe(m=>m+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}bt.current=!0,we(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Kr(g.join(" ")),m=Ne.current.uuid;if(!m){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}_o.current=u,Ze(u),Wt(`${xo} ${u}`),d({kind:"note",tone:"ok",text:`Session will be named "${u}" once it starts.`});return}if(!u){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Ne.current.firstPrompt??"";Xl(w,e).then(y=>{y?(ue(`/rename ${y}`),d({kind:"note",tone:"info",text:`Suggestion: "${y}" \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}xm(m,u),Ze(u),Wt(`${xo} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=g[0],m=Z(e);if(!u){let w=Object.entries(m?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let y=w.map(([z,F])=>({name:z,env:F.connection?.environment??"custom",prod:F.production===!0,who:Ko(z)})),P=s??m?.defaultProfile,R=Math.max(0,y.findIndex(z=>z.name===P));xt({cursor:R,current:R,rows:y});return}if(u==="add"){let w=Qr(e,g[1],g[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),Qo(g[1],!1);return}if(!m?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}Qo(u,!0);return}case"doctor":await un(g,{cwd:e});return;case"mcp":await Qn(g);return;case"init":{if(Z(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let u=jm().map(m=>({name:m,apiUrl:Am(m).apiUrl}));$t({cursor:0,rows:u});return}case"resume":{let u=g.join(" ").trim(),m=bm(e).filter(P=>P.uuid!==Ne.current.uuid);if(!u){if(!m.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}it({query:"",cursor:0,sessions:m});return}let w=km(e,u);if(!w){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}we(w.uuid),Ne.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},Ze(w.name),js(w.uuid),kt.current=[];let y=Cs(e,w.uuid);for(let P of y)d(P);d({kind:"note",tone:"ok",text:y.length?`Resumed "${w.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=g.join(" ").trim(),m;try{m=await Jt(e,s)}catch(y){d({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!u){let y=m.workspaces.map(R=>({id:R.id,name:R.name??R.id,type:R.workspace_type}));if(y.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let P=Math.max(0,y.findIndex(R=>R.id===m.current));vt({cursor:P,current:P,rows:y,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let w=Zo(m.workspaces,u);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}Rn(m.profile,m.projectId,w);return}case"project":{let u=g.join(" ").trim(),m;try{m=await Ye(e,s)}catch(y){d({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!u){let y=m.projects.map(R=>({id:R.id,name:R.name??R.id,sub:R.sub_domain}));if(y.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let P=y.findIndex(R=>R.id===m.current);nt({cursor:Math.max(0,P),current:P,rows:y,profile:m.profile,environment:m.environment});return}let w=er(m.projects,u);if(!w){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${m.projects.map(y=>y.name??y.id).join(", ")}`});return}Sn(m.profile,w);return}case"logout":{let u;try{u=pe(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let m=mm(u);hm(e,u),we(),oe(w=>w+1),d({kind:"note",tone:m?"ok":"info",text:m?`\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."}),B(["/login"]);return}case"publish":{if(!qo(c.trim()))return;if(g[0]==="--related"&&g[1]){let m=await eo(e,s,g[1].replace(/\\/g,"/"));if(m.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Pn(m);return}if(g[0]&&g[0]!=="--all"){await Xo(g[0]);return}let u=g[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Ql({cwd:e,profileName:s}),w=an(m.entries),y=Jn(m.entries);if(y>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${y} article${y===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),w.length===0){d({kind:"note",tone:"ok",text:y>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let P=m.counts["unknown-base"]??0;P>0&&d({kind:"note",tone:"info",text:`(${P} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Ys("Reconciling structure on Document360 (order + related articles)\u2026");try{let R=await tc({cwd:e,profileName:s}),z=rc(await oc({cwd:e,profileName:s})),F=nc(R);F?d({kind:"note",tone:"info",text:F}):R.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${R.skipped}`}),z&&d({kind:"note",tone:"info",text:z}),d({kind:"note",tone:"ok",text:F||z?"\u2713 Structure synced to Document360.":"\u2713 Already in order \u2014 nothing to change."}),de(null),B([{cmd:"/structure",desc:"see the new category + article order"}])}catch(R){d({kind:"note",tone:"warn",text:`Structure sync failed: ${R.message}`})}finally{Ys(null)}return}if(u){await Pn(w.map(P=>P.path));return}Ct({cursor:0,rows:ra(w)})}catch(m){d({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let u=g.join(" ").trim();if(!u){let w=[];try{w=Object.keys(jo(e,pe(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}rt({query:"",cursor:0,paths:w});return}let m=im(u)?u:mt(e,u);if(Xe(m)){try{d({kind:"preview",name:fn(m),text:ac(Ds(m,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${m}: ${w.message}`})}return}if(Vm.test(u)){try{let w=pe(e,s),y={profile:w.name,connection:w.connection},P=w.project.projectId??pm(y),R=await fm(y,P,u);d({kind:"preview",name:R.title??u,text:R.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${u}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let u=g[0]?.trim();if(!u){let P=so(Is(e));tt({cursor:P,current:P});return}let{lines:m,changed:w,effective:y}=cn(e,u);for(let P of m)d({kind:"note",tone:P.startsWith("\u26A0")?"warn":P.startsWith("\u2713")?"ok":"info",text:P});w&&(zs(P=>P+1),xe.current?.setModel(y));return}case"convert":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:m}=Sr(g),w=Im(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let y=Dr(w,u);if(y.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${w.length} are tracked overall.)`});return}let P=As(y),R=3,z=`/convert${u?` --scope ${u}`:""} --run`,F=So(e,"light");if(!m){let v=Zl({files:jr(e,y),op:"convert",model:F.model}),E=u?`Scope: ${u} (${y.length} of ${w.length} tracked)
282
282
  `:"",U=`
283
- Model: ${F.model}${F.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:A+Er(P,v,R).join(`
284
- `)+U}),B([z]);return}Je.current=Date.now(),gt(0),N(!0);let O=new AbortController;ve.current=O,ee({verb:"Converting",total:P.length,done:0,active:[],rows:dn(P),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${y.length} articles across ${P.length} partitions (\u2264${R} agents at once) on ${F.model}\u2026 (esc to stop)`});try{for await(let v of Ro({cwd:e,partitions:P,promptFor:Ar,concurrency:R,profileName:s,allowProdWrites:bt.current,model:F.model,signal:O.signal}))if(v.type==="partition_status")v.status==="running"?ee(A=>A&&{...A,active:[...A.active,v.label],rows:Me(A.rows,v.label,"active"),lastAt:Date.now()}):ee(A=>A&&{...A,active:A.active.filter(U=>U!==v.label),done:A.done+1,rows:Me(A.rows,v.label,v.status==="done"?"done":"failed"),lastAt:Date.now()});else if(v.type==="partition_event")ee(A=>{if(!A)return A;let U={...A,lastAt:Date.now()};return v.event.type==="tool"?U.tools=A.tools+1:v.event.type==="text"&&(U.chars=A.chars+v.event.delta.length),U});else if(v.type==="run_done"){Tt(K=>K+v.totalCostUsd),Rt(K=>K+v.results.reduce((ye,jt)=>ye+jt.outputTokens,0));let A=v.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";d({kind:"note",tone:v.aborted?"warn":v.ok?"ok":"warn",text:A+Nr(v.results,P,U).join(`
285
- `)})}}catch(v){d({kind:"note",tone:"error",text:`Convert run failed: ${v.message}`})}finally{ve.current=null,ee(null),N(!1),ne(v=>v+1)}return}case"write":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=zl(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:m,path:w,preview:y,concurrency:P,rewrite:R}=_r(g),{docsDir:z,targets:F,reason:O,rewriting:v}=Hr(e,u,{scope:m,path:w,rewrite:R});if(F.length===0){d({kind:"note",tone:"warn",text:O??"Nothing to write."});return}v&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${F.length} already-written article${F.length===1?"":"s"} (overwrites them; git has your baseline).`});let A=js(F),U=Ir(P),K=To(e,"standard"),ye=!!w;if(y&&!ye){let G=Vl({files:Or(e,u,F),op:"write",model:K.model}),te=m?`Scope: ${m} (${F.length} pending)
283
+ Model: ${F.model}${F.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:E+Er(P,v,R).join(`
284
+ `)+U}),B([z]);return}Je.current=Date.now(),gt(0),I(!0);let L=new AbortController;Ce.current=L,ee({verb:"Converting",total:P.length,done:0,active:[],rows:pn(P),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${y.length} articles across ${P.length} partitions (\u2264${R} agents at once) on ${F.model}\u2026 (esc to stop)`});try{for await(let v of To({cwd:e,partitions:P,promptFor:Ar,concurrency:R,profileName:s,allowProdWrites:bt.current,model:F.model,signal:L.signal}))if(v.type==="partition_status")v.status==="running"?ee(E=>E&&{...E,active:[...E.active,v.label],rows:Me(E.rows,v.label,"active"),lastAt:Date.now()}):ee(E=>E&&{...E,active:E.active.filter(U=>U!==v.label),done:E.done+1,rows:Me(E.rows,v.label,v.status==="done"?"done":"failed"),lastAt:Date.now()});else if(v.type==="partition_event")ee(E=>{if(!E)return E;let U={...E,lastAt:Date.now()};return v.event.type==="tool"?U.tools=E.tools+1:v.event.type==="text"&&(U.chars=E.chars+v.event.delta.length),U});else if(v.type==="run_done"){Tt(K=>K+v.totalCostUsd),Rt(K=>K+v.results.reduce((ye,jt)=>ye+jt.outputTokens,0));let E=v.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";d({kind:"note",tone:v.aborted?"warn":v.ok?"ok":"warn",text:E+Nr(v.results,P,U).join(`
285
+ `)})}}catch(v){d({kind:"note",tone:"error",text:`Convert run failed: ${v.message}`})}finally{Ce.current=null,ee(null),I(!1),oe(v=>v+1)}return}case"write":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=ec(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:m,path:w,preview:y,concurrency:P,rewrite:R}=_r(g),{docsDir:z,targets:F,reason:L,rewriting:v}=Hr(e,u,{scope:m,path:w,rewrite:R});if(F.length===0){d({kind:"note",tone:"warn",text:L??"Nothing to write."});return}v&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${F.length} already-written article${F.length===1?"":"s"} (overwrites them; git has your baseline).`});let E=As(F),U=Ir(P),K=So(e,"standard"),ye=!!w;if(y&&!ye){let G=Zl({files:Lr(e,u,F),op:"write",model:K.model}),te=m?`Scope: ${m} (${F.length} pending)
286
286
  `:"",ce=`
287
- Model: ${K.model}${K.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:te+Ur(A,G,U).join(`
288
- `)+ce}),B([`/write${m?` --scope ${m}`:""}`]);return}Je.current=Date.now(),gt(0),N(!0);let jt=new AbortController;ve.current=jt,ee({verb:"Writing",total:A.length,done:0,active:[],rows:dn(A),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${F.length} article${F.length===1?"":"s"} across ${A.length} partition${A.length===1?"":"s"} (\u2264${U} agents at once) on ${K.model}${K.forced?" (forced)":""}\u2026 (esc to stop)`});let oi=new Set;try{for await(let G of Ro({cwd:e,partitions:A,promptFor:te=>Mr(te,z,{rewrite:v||ye}),concurrency:U,profileName:s,allowProdWrites:bt.current,model:K.model,signal:jt.signal}))if(G.type==="partition_status")G.status==="running"?ee(te=>te&&{...te,active:[...te.active,G.label],rows:Me(te.rows,G.label,"active"),lastAt:Date.now()}):ee(te=>te&&{...te,active:te.active.filter(ce=>ce!==G.label),done:te.done+1,rows:Me(te.rows,G.label,G.status==="done"?"done":"failed"),lastAt:Date.now()});else if(G.type==="partition_event"){let te=null;if(G.event.type==="tool"){let ce=Sl(G.event.name,G.event.input,A[G.index]?.paths??[]);ce&&!oi.has(ce)&&(oi.add(ce),te=G.label)}ee(ce=>{if(!ce)return ce;let Ae={...ce,lastAt:Date.now()};return G.event.type==="tool"?Ae.tools=ce.tools+1:G.event.type==="text"&&(Ae.chars=ce.chars+G.event.delta.length),te&&(Ae.rows=Tl(Ae.rows,te)),Ae})}else if(G.type==="run_done"){Tt(At=>At+G.totalCostUsd),Rt(At=>At+G.results.reduce((An,at)=>An+at.outputTokens,0));let te=G.aborted?"Stopped. ":"",ce=t.kind==="api"?"api":"subscription";d({kind:"note",tone:G.aborted?"warn":G.ok?"ok":"warn",text:te+Wr(G.results,A,ce).join(`
289
- `)});let Ae=G.aborted?null:Fr(e,z,F);if(Ae&&d({kind:"note",tone:"warn",text:Ae}),!G.aborted&&G.ok){let At=m??w??"",An=At?` ${At}`:"",at=[];Ae&&at.push({cmd:`/check${An} --fix`,desc:"fix the issues the checker just flagged"}),at.push({cmd:`/review${An} --fix`,desc:"editorial review + apply fixes (style, grammar, structure)"}),at.push({cmd:"/publish --all",desc:"publish the drafts to Document360"}),at.push({cmd:"/screenshot --all",desc:"add screenshots first (optional)"}),B(at),me(Ae?"Written \u2014 but the checker flagged issues. Fix, review, then publish:":"Written. Review for quality, then publish:")}}}catch(G){d({kind:"note",tone:"error",text:`Write run failed: ${G.message}`})}finally{ve.current=null,ee(null),N(!1),ne(G=>G+1)}return}case"draft":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:m}=qr(e);if(u.length===0&&m===0){d({kind:"note",tone:"info",text:Yr});return}let w=g.join(" ").trim();if(!w&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
287
+ Model: ${K.model}${K.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:te+Ur(E,G,U).join(`
288
+ `)+ce}),B([`/write${m?` --scope ${m}`:""}`]);return}Je.current=Date.now(),gt(0),I(!0);let jt=new AbortController;Ce.current=jt,ee({verb:"Writing",total:E.length,done:0,active:[],rows:pn(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${F.length} article${F.length===1?"":"s"} across ${E.length} partition${E.length===1?"":"s"} (\u2264${U} agents at once) on ${K.model}${K.forced?" (forced)":""}\u2026 (esc to stop)`});let ii=new Set;try{for await(let G of To({cwd:e,partitions:E,promptFor:te=>Mr(te,z,{rewrite:v||ye}),concurrency:U,profileName:s,allowProdWrites:bt.current,model:K.model,signal:jt.signal}))if(G.type==="partition_status")G.status==="running"?ee(te=>te&&{...te,active:[...te.active,G.label],rows:Me(te.rows,G.label,"active"),lastAt:Date.now()}):ee(te=>te&&{...te,active:te.active.filter(ce=>ce!==G.label),done:te.done+1,rows:Me(te.rows,G.label,G.status==="done"?"done":"failed"),lastAt:Date.now()});else if(G.type==="partition_event"){let te=null;if(G.event.type==="tool"){let ce=Il(G.event.name,G.event.input,E[G.index]?.paths??[]);ce&&!ii.has(ce)&&(ii.add(ce),te=G.label)}ee(ce=>{if(!ce)return ce;let Ae={...ce,lastAt:Date.now()};return G.event.type==="tool"?Ae.tools=ce.tools+1:G.event.type==="text"&&(Ae.chars=ce.chars+G.event.delta.length),te&&(Ae.rows=Nl(Ae.rows,te)),Ae})}else if(G.type==="run_done"){Tt(At=>At+G.totalCostUsd),Rt(At=>At+G.results.reduce((En,at)=>En+at.outputTokens,0));let te=G.aborted?"Stopped. ":"",ce=t.kind==="api"?"api":"subscription";d({kind:"note",tone:G.aborted?"warn":G.ok?"ok":"warn",text:te+Wr(G.results,E,ce).join(`
289
+ `)});let Ae=G.aborted?null:Fr(e,z,F);if(Ae&&d({kind:"note",tone:"warn",text:Ae}),!G.aborted&&G.ok){let At=m??w??"",En=At?` ${At}`:"",at=[];Ae&&at.push({cmd:`/check${En} --fix`,desc:"fix the issues the checker just flagged"}),at.push({cmd:`/review${En} --fix`,desc:"editorial review + apply fixes (style, grammar, structure)"}),at.push({cmd:"/publish --all",desc:"publish the drafts to Document360"}),at.push({cmd:"/screenshot --all",desc:"add screenshots first (optional)"}),B(at),de(Ae?"Written \u2014 but the checker flagged issues. Fix, review, then publish:":"Written. Review for quality, then publish:")}}}catch(G){d({kind:"note",tone:"error",text:`Write run failed: ${G.message}`})}finally{Ce.current=null,ee(null),I(!1),oe(G=>G+1)}return}case"draft":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:m}=qr(e);if(u.length===0&&m===0){d({kind:"note",tone:"info",text:Yr});return}let w=g.join(" ").trim();if(!w&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
290
290
  ${u.map(R=>` \u2022 ${R.name} (${R.docCount} doc${R.docCount===1?"":"s"})`).join(`
291
- `)}`}),B(u.map(R=>`/draft ${R.name}`));return}let y="",P;if(w){let R=Br(u,w);R?y=R:P=w}else y=u[0]?.name??"";await se(oo(y,P),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!qo(l.trim()))return;let u=g.find(m=>m.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let y=Date.now(),P=await Yl({cwd:e,profileName:s});d({kind:"note",tone:"info",text:to(P,Date.now()-y).join(`
292
- `)});return}if(u==="--baseline"){let y=g.find(F=>!F.startsWith("--")),P=y?y.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:P?`Setting the sync baseline for ${P}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let R=await gm({cwd:e,profileName:s,relPaths:P?[P]:void 0}),z=P?{rebaselined:[],skipped:[]}:await wm({cwd:e,profileName:s});if(R.baselined.length===0&&R.skipped.length===0&&z.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}R.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${R.baselined.length} article${R.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),z.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${z.rebaselined.length} article${z.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),R.skipped.length>0&&d({kind:"note",tone:"warn",text:`${R.skipped.length} skipped:
291
+ `)}`}),B(u.map(R=>`/draft ${R.name}`));return}let y="",P;if(w){let R=Br(u,w);R?y=R:P=w}else y=u[0]?.name??"";await se(ro(y,P),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!qo(c.trim()))return;let u=g.find(m=>m.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let y=Date.now(),P=await Ql({cwd:e,profileName:s});d({kind:"note",tone:"info",text:no(P,Date.now()-y).join(`
292
+ `)});return}if(u==="--baseline"){let y=g.find(F=>!F.startsWith("--")),P=y?y.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:P?`Setting the sync baseline for ${P}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let R=await Tm({cwd:e,profileName:s,relPaths:P?[P]:void 0}),z=P?{rebaselined:[],skipped:[]}:await Sm({cwd:e,profileName:s});if(R.baselined.length===0&&R.skipped.length===0&&z.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}R.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${R.baselined.length} article${R.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),z.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${z.rebaselined.length} article${z.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),R.skipped.length>0&&d({kind:"note",tone:"warn",text:`${R.skipped.length} skipped:
293
293
  ${R.skipped.map(F=>` - ${F.path} (${F.reason})`).join(`
294
- `)}`}),ne(F=>F+1);return}if(u==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let y=await mm({cwd:e,profileName:s}),P=y.onlyInLegacy.length===0&&y.onlyInManifest.length===0&&y.mappedMissingFromManifest.length===0,R=[`Legacy listing: ${y.legacyCount} \xB7 Manifest: ${y.manifestCount} \xB7 in both: ${y.inBoth}`];P?R.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(y.mappedMissingFromManifest.length&&R.push(`\u2717 ${y.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${y.mappedMissingFromManifest.slice(0,5).join(", ")}`),y.onlyInLegacy.length&&R.push(`\u26A0 ${y.onlyInLegacy.length} only in the legacy listing: ${y.onlyInLegacy.slice(0,5).join(", ")}`),y.onlyInManifest.length&&R.push(`\u26A0 ${y.onlyInManifest.length} only in the manifest: ${y.onlyInManifest.slice(0,5).join(", ")}`),R.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:P?"ok":"warn",text:R.join(`
295
- `)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=g[0];if(m){let y=await hm({cwd:e,profileName:s,relPath:m.replace(/\\/g,"/")});Fe.current=[y],Sn();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let w=await Pr({cwd:e,profileName:s});for(let y of Rr(w))d({kind:"note",tone:y.tone,text:y.text});ne(y=>y+1)}catch(m){d({kind:"note",tone:"error",text:`Pull failed: ${m.message}`})}return}case"scope":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=ym(e);if(u.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Pt({cursor:0,rows:u.map(m=>({...m,checked:m.recommended}))});return}case"audit":{if(g[0]==="--auto"){let m=Z(e);if(!m){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=g[1]!=="off";Bl({...m,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let u=await an();u.kind==="forward-to-agent"&&u.prompt&&await se(u.prompt,{display:u.display,quietUser:!0});return}case"check":{let u=g.find(y=>!y.startsWith("--")),m=u?` ${u}`:"",w=Gl({cwd:e,scope:u});if(g.includes("--fix")){if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}d({kind:"note",tone:"info",text:`Fixing ${w.length} doc issue${w.length===1?"":"s"}\u2026`}),await se(gs(w),{display:`/check${m} --fix`,quietUser:!0});let y=Gl({cwd:e,scope:u});d({kind:"note",tone:y.length===0?"ok":"warn",text:y.length===0?"\u2713 Doc-checker: all issues resolved.":po(y).join(`
296
- `)}),B([{cmd:`/review${m} --fix`,desc:"editorial review + apply fixes (style, grammar, structure)"},{cmd:"/publish --all",desc:"publish the corrected docs to Document360"}]),me(y.length===0?"Deterministic issues fixed. Review for quality, then publish:":"Some issues remain \u2014 review, then publish:");return}d({kind:"note",tone:w.length===0?"ok":"warn",text:po(w).join(`
297
- `)}),w.length>0&&(B([{cmd:`/check${m} --fix`,desc:"have the agent fix these in place"},{cmd:`/review${m} --fix`,desc:"also run the editorial review (style, grammar, structure)"},{cmd:"/publish --all",desc:"skip fixing \u2014 publish the docs as-is"}]),me(`Found ${w.length} doc issue${w.length===1?"":"s"} above \u2014 fix them, or publish as-is:`));return}case"reorder":{let u=ys(e,g);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await se(u.prompt,{display:u.display,quietUser:!0}),B([{cmd:"/publish --all",desc:"sync the new order to Document360"}]),me("Reordered locally \u2014 publish to sync the new order:");return}case"review":{let u=ws(e,g);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=g.includes("--fix");if(await se(u.prompt,{display:u.display,quietUser:!0}),m)B([{cmd:"/publish --all",desc:"publish the corrected docs to Document360"},{cmd:"/check",desc:"optional: instant re-scan for leaks/bad commands (no tokens)"}]),me("\u2713 Editor applied its fixes \u2014 your docs are corrected. Publish them, or re-scan first:");else{let w=g.filter(y=>y!=="--fix").join(" ");B([{cmd:`/review${w?` ${w}`:""} --fix`,desc:"let the editor apply all the fixes it listed above"},{cmd:"/check --fix",desc:"fix just the deterministic issues (leaks, bad commands)"},{cmd:"/publish --all",desc:"skip fixing \u2014 publish the docs as-is"}]),me("The review listed issues above. Apply the fixes, or publish as-is:")}return}case"capture-setup":{let u=await un();u.kind==="forward-to-agent"&&u.prompt&&await se(u.prompt,{display:u.display,quietUser:!0});let m=os(e);m&&d({kind:"note",tone:"info",text:m.join(`
294
+ `)}`}),oe(F=>F+1);return}if(u==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let y=await Pm({cwd:e,profileName:s}),P=y.onlyInLegacy.length===0&&y.onlyInManifest.length===0&&y.mappedMissingFromManifest.length===0,R=[`Legacy listing: ${y.legacyCount} \xB7 Manifest: ${y.manifestCount} \xB7 in both: ${y.inBoth}`];P?R.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(y.mappedMissingFromManifest.length&&R.push(`\u2717 ${y.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${y.mappedMissingFromManifest.slice(0,5).join(", ")}`),y.onlyInLegacy.length&&R.push(`\u26A0 ${y.onlyInLegacy.length} only in the legacy listing: ${y.onlyInLegacy.slice(0,5).join(", ")}`),y.onlyInManifest.length&&R.push(`\u26A0 ${y.onlyInManifest.length} only in the manifest: ${y.onlyInManifest.slice(0,5).join(", ")}`),R.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:P?"ok":"warn",text:R.join(`
295
+ `)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=g[0];if(m){let y=await Rm({cwd:e,profileName:s,relPath:m.replace(/\\/g,"/")});Fe.current=[y],Dn();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let w=await Pr({cwd:e,profileName:s});for(let y of Rr(w))d({kind:"note",tone:y.tone,text:y.text});oe(y=>y+1)}catch(m){d({kind:"note",tone:"error",text:`Pull failed: ${m.message}`})}return}case"scope":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Dm(e);if(u.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Pt({cursor:0,rows:u.map(m=>({...m,checked:m.recommended}))});return}case"audit":{if(g[0]==="--auto"){let m=Z(e);if(!m){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=g[1]!=="off";Kl({...m,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let u=await ln();u.kind==="forward-to-agent"&&u.prompt&&await se(u.prompt,{display:u.display,quietUser:!0});return}case"check":{let u=g.find(y=>!y.startsWith("--")),m=u?` ${u}`:"",w=Jl({cwd:e,scope:u});if(g.includes("--fix")){if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}d({kind:"note",tone:"info",text:`Fixing ${w.length} doc issue${w.length===1?"":"s"}\u2026`}),await se(gs(w),{display:`/check${m} --fix`,quietUser:!0});let y=Jl({cwd:e,scope:u});d({kind:"note",tone:y.length===0?"ok":"warn",text:y.length===0?"\u2713 Doc-checker: all issues resolved.":fo(y).join(`
296
+ `)}),B([{cmd:`/review${m} --fix`,desc:"editorial review + apply fixes (style, grammar, structure)"},{cmd:"/publish --all",desc:"publish the corrected docs to Document360"}]),de(y.length===0?"Deterministic issues fixed. Review for quality, then publish:":"Some issues remain \u2014 review, then publish:");return}d({kind:"note",tone:w.length===0?"ok":"warn",text:fo(w).join(`
297
+ `)}),w.length>0&&(B([{cmd:`/check${m} --fix`,desc:"have the agent fix these in place"},{cmd:`/review${m} --fix`,desc:"also run the editorial review (style, grammar, structure)"},{cmd:"/publish --all",desc:"skip fixing \u2014 publish the docs as-is"}]),de(`Found ${w.length} doc issue${w.length===1?"":"s"} above \u2014 fix them, or publish as-is:`));return}case"structure":{let u=ks(e,s);if(u.length===0){d({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}d({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...u].join(`
298
+ `)});return}case"reorder":{let u=ys(e,g);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await se(u.prompt,{display:u.display,quietUser:!0}),B([{cmd:"/publish --all",desc:"sync the new order to Document360"}]),de("Reordered locally \u2014 publish to sync the new order:");return}case"review":{let u=ws(e,g);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=g.includes("--fix");if(await se(u.prompt,{display:u.display,quietUser:!0}),m)B([{cmd:"/publish --all",desc:"publish the corrected docs to Document360"},{cmd:"/check",desc:"optional: instant re-scan for leaks/bad commands (no tokens)"}]),de("\u2713 Editor applied its fixes \u2014 your docs are corrected. Publish them, or re-scan first:");else{let w=g.filter(y=>y!=="--fix").join(" ");B([{cmd:`/review${w?` ${w}`:""} --fix`,desc:"let the editor apply all the fixes it listed above"},{cmd:"/check --fix",desc:"fix just the deterministic issues (leaks, bad commands)"},{cmd:"/publish --all",desc:"skip fixing \u2014 publish the docs as-is"}]),de("The review listed issues above. Apply the fixes, or publish as-is:")}return}case"capture-setup":{let u=await dn();u.kind==="forward-to-agent"&&u.prompt&&await se(u.prompt,{display:u.display,quietUser:!0});let m=os(e);m&&d({kind:"note",tone:"info",text:m.join(`
298
299
  `)});return}case"devhints":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:_t(It(e)).join(`
299
- `)}),St(lt()),Gt.current=Le(e).status==="current"||en(e);return}case"inbox":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(rs(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 se(ss(),{display:"/inbox",quietUser:!0});return}case"document":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:m}=Vr(g);if(!m&&Gr(e)===0){d({kind:"note",tone:"info",text:Xr});return}let w=`/document${m?` ${m}`:""}${u?" --publish":""}`;await se(zr(m,u),{display:w,quietUser:!0});return}case"catch-up":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!qo(l.trim()))return;let{publish:u}=as(g);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let m=await cs({cwd:e,profileName:s});for(let y of us(m))d({kind:"note",tone:y.startsWith("\u2713")?"ok":y.startsWith("\u2139")?"info":"warn",text:y});let w=Ut(Mt(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await se(ls({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{Fo.current=!0,d({kind:"note",tone:"info",text:`Updating ${pt}\u2026 (don\u2019t close this window)`}),hn(!0),(await co().finally(()=>hn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),B(m=>m.includes("/exit")?m:[...m,"/exit"]),Ms("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${lo}`});return}case"screenshot":{let u=es(g);if(u.mode==="list"){if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:ns(ts(e,u.scope),u.scope).join(`
300
- `)});return}if(u.mode==="single"){let O=await io(g);O.kind==="forward-to-agent"&&O.prompt&&await se(O.prompt,{display:O.display,quietUser:!0});return}if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=u.mode==="scope"?u.scope:void 0,w=$m(e,{scope:m}).map(O=>O.id);if(w.length===0){d({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let y=6,P=xm(w,3),R=To(e,"standard");Je.current=Date.now(),gt(0),N(!0);let z=new AbortController;ve.current=z,ee({verb:"Authoring",unit:"spec",total:P.length,done:0,active:[],rows:dn(P),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${w.length} screenshot spec${w.length===1?"":"s"} across ${P.length} partition${P.length===1?"":"s"} (\u2264${y} agents at once) on ${R.model}${R.forced?" (forced)":""}\u2026 (esc to stop)`});let F=!1;try{for await(let O of Ro({cwd:e,partitions:P,promptFor:Ba,concurrency:y,profileName:s,allowProdWrites:bt.current,model:R.model,signal:z.signal}))if(O.type==="partition_status")O.status==="running"?ee(v=>v&&{...v,active:[...v.active,O.label],rows:Me(v.rows,O.label,"active"),lastAt:Date.now()}):ee(v=>v&&{...v,active:v.active.filter(A=>A!==O.label),done:v.done+1,rows:Me(v.rows,O.label,O.status==="done"?"done":"failed"),lastAt:Date.now()});else if(O.type==="partition_event")ee(v=>{if(!v)return v;let A={...v,lastAt:Date.now()};return O.event.type==="tool"?A.tools=v.tools+1:O.event.type==="text"&&(A.chars=v.chars+O.event.delta.length),A});else if(O.type==="run_done"){Tt(K=>K+O.totalCostUsd),Rt(K=>K+O.results.reduce((ye,jt)=>ye+jt.outputTokens,0));let v=O.results.filter(K=>K.ok).length,A=O.aborted?"Stopped. ":"";F=!O.aborted&&u.setup;let U=O.aborted?"":F?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:O.aborted?"warn":O.ok?"ok":"warn",text:`${A}Authored specs \u2014 ${v}/${O.results.length} batches ok.${U}`})}}catch(O){d({kind:"note",tone:"error",text:`Spec authoring failed: ${O.message}`})}finally{ve.current=null,ee(null),N(!1),ne(O=>O+1)}if(F){let O=await un();O.kind==="forward-to-agent"&&O.prompt&&await se(O.prompt,{display:O.display,quietUser:!0});let v=os(e);v&&d({kind:"note",tone:"info",text:v.join(`
301
- `)})}return}case"reset":{let u=fs(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Io.current={repoName:pn(e),targets:u,hadDevhints:Xe(Is(e))},d({kind:"note",tone:"warn",text:hs(e,u).join(`
302
- `)}),ue(pn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,Sn,d,we,se,Cn,Xo,Ks]),Dn=V(l=>{let i=(l??D).trim();if(b(""),gn(null),wt(0),i.startsWith("/")&&(ue(null),ht.current++,me(null),B(g=>Al(g,i))),!i||Js(i)||Qs(i))return;No.current.push(i);let a=Ll(i,Us.current);i.startsWith("/")?(d({kind:"user",text:i}),Zs(a)):se(a,{display:i})},[D,Js,Qs,Zs,se]),ei=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=Nl(l);if(Il(i)){let a=_l(++gc.current,i);Us.current.set(a,i),T(a)}else T(i);return}T(l)},[T]),Dt=Math.max(10,_e-6),ti=Ts(()=>Co(k.text,Dt),[k.text,Dt]),Jo=V(l=>x(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),jn=V(l=>x(i=>({...i,pos:Ml(Co(i.text,Dt),i.pos,l)})),[Dt]),Xt=V(l=>x(i=>({...i,pos:Ul(Co(i.text,Dt),i.pos,l)})),[Dt]),kc=["\x1B[H","\x1B[1~","\x1BOH"],bc=["\x1B[F","\x1B[4~","\x1BOF"],ni=V((l,i)=>i.leftArrow?(Jo(-1),!0):i.rightArrow?(Jo(1),!0):l&&kc.includes(l)?(Xt("start"),!0):l&&bc.includes(l)?(Xt("end"),!0):i.ctrl&&l==="a"?(Xt("start"),!0):i.ctrl&&l==="e"?(Xt("end"),!0):!1,[Jo,Xt]);return Gf((l,i)=>{if(i.ctrl&&l==="c"){be.current?.close(),r();return}if(!M){if(I){if(i.escape){if(ve.current){if(!ve.current.signal.aborted){let a=(yn?.verb??"work").toLowerCase(),g=yn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${g}s)\u2026`}),ve.current.abort()}return}qt.current||(qt.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),be.current?.interrupt());return}if(i.return){let a=D.trim();if(!a)return;st.current.push(a),Lo([...st.current]),b("");return}if(ni(l,i))return;if(i.upArrow){jn(-1);return}if(i.downArrow){jn(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&ei(l);return}if(et){if(i.upArrow){tt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){tt(a=>a&&{...a,cursor:Math.min(Ee.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ee.length){tt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Ee[et.cursor];tt(null);let{lines:g,changed:u,effective:m}=ln(e,a.value??"default");for(let w of g)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});u&&(Ys(w=>w+1),be.current?.setModel(m));return}if(l==="s"){let a=Ee[et.cursor];tt(null),be.current?.setModel(a.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){tt(null);return}return}if(Ie){if(i.upArrow){xt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){xt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ie.rows.length){xt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=Ie.rows[Ie.cursor];xt(null),Qo(a.name,i.return===!0);return}if(i.escape){xt(null);return}return}if(Oo){if(i.escape){Yt(null);return}if(i.leftArrow||i.tab&&i.shift){Yt(a=>a&&{tab:(a.tab-1+Re.length)%Re.length});return}if(i.rightArrow||i.tab){Yt(a=>a&&{tab:(a.tab+1)%Re.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.length){Yt({tab:Number(l)-1});return}return}if(He){if(i.upArrow){$t(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){$t(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=He.rows.length){$t(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=He.rows[He.cursor].name;if($t(null),!ar(e,a).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${a}").`});let u=!1;try{let m=Ke(a);u=!!m&&!(We(m)&&!m.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),B(["/login"]),ne(m=>m+1);return}if(i.escape){$t(null);return}return}if(fe){if(i.upArrow){vt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){vt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=fe.rows.length){vt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=fe.rows[fe.cursor],{profile:g,projectId:u}=fe;vt(null),Pn(g,u,a);return}if(i.escape){vt(null);return}return}if(xe){if(i.upArrow){nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){nt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=xe.rows.length){nt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=xe.rows[xe.cursor],{profile:g}=xe;nt(null),Tn(g,a);return}if(i.escape){nt(null);return}return}if(ge){if(i.upArrow){Pt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Pt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){Pt(a=>a&&{...a,rows:a.rows.map((g,u)=>u===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=ge.rows.filter(g=>g.checked).map(g=>g.path);if(Pt(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}$r(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let g of a)d({kind:"note",tone:"info",text:` ${g}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){Pt(null);return}return}if(ot){if(i.upArrow){Ct(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ct(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ot.rows.length){Ct(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ot.rows[ot.cursor];Ct(null),a.kind==="article"?Xo(a.paths[0]):Cn(a.paths);return}if(i.escape){Ct(null);return}return}if($e){if(i.escape){rt(null);return}if(i.upArrow){rt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){rt(a=>a&&{...a,cursor:Math.min(Math.max(0,$n.length-1),a.cursor+1)});return}if(i.return){let a=$n[$e.cursor];if(a){rt(null);try{d({kind:"preview",name:pn(a),text:tc(Ss(mt(e,a),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){rt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){rt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(Ce){if(i.escape){it(null);return}if(i.upArrow){it(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){it(a=>a&&{...a,cursor:Math.min(Math.max(0,vn.length-1),a.cursor+1)});return}if(i.return){let a=vn[Ce.cursor];if(a){it(null),we(a.uuid),Ne.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Ze(a.name),Ds(a.uuid),kt.current=[];let g=vs(e,a.uuid);for(let u of g)d(u);d({kind:"note",tone:"ok",text:g.length?`Resumed "${a.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){it(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){it(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!D&&De){b(De),ue(null),ht.current++;return}if(!D&&Qe.length>0&&l&&/^[1-9]$/.test(l)){let a=Qe[Number(l)-1];if(a){b(ft(a));return}}if(!D&&(Bo||Uo)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=Bo!=null;ml(Bo??Uo).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?a?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&a&&Yo(null)});return}if(!ni(l,i)){if(zs){if(i.upArrow){wt(a=>Math.max(0,a-1));return}if(i.downArrow){wt(a=>Math.min(zt.length-1,a+1));return}if(i.tab){b("/"+(zt[Ht]?.name??"")+" "),wt(0);return}if(i.return){let a=zt[Ht];if(a){let g=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(vl(a.usage)&&!g){b("/"+a.name+" "),wt(0);return}Dn("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(D!==""&&yt===null){jn(-1);return}let a=No.current;if(!a.length)return;let g=yt===null?a.length-1:Math.max(0,yt-1);gn(g),b(a[g]??"");return}if(i.downArrow){if(D!==""&&yt===null){jn(1);return}let a=No.current;if(yt===null)return;let g=yt+1;g>=a.length?(gn(null),b("")):(gn(g),b(a[g]??""));return}}if(i.return){Dn();return}if(i.backspace||i.delete){C();return}if(i.escape){b(""),wt(0),ue(null),B([]),me(null);return}l&&!i.ctrl&&!i.meta&&ei(l)}}}),Te(()=>{if(I||M)return;let l=st.current.shift();l!==void 0&&(Lo([...st.current]),Dn(l))},[I,M,Dn]),Y(oe,{flexDirection:"column",width:_e,children:[zo!==null&&Y(oe,{marginTop:1,flexDirection:"column",children:[zo.truncated&&E(S,{dimColor:!0,children:"\u2026"}),E(S,{children:zo.text})]}),I&&(yn?E(Um,{p:yn}):E(Om,{startTime:Je.current,chars:hc})),E(oe,{borderStyle:"round",borderColor:Vs.prod?"yellow":H,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?ti.map((l,i)=>{let a=k.text.slice(l.start,l.end),g=i===Po(ti,k.pos),u=Math.min(k.pos,l.end)-l.start;return Y(S,{children:[E(S,{color:H,children:i===0?"> ":" "}),g?Y(As,{children:[a.slice(0,u),E(So,{ch:a[u]??" "}),a.slice(u+1)]}):a||" "]},`${i}-${l.start}`)}):Y(S,{children:[E(S,{color:H,children:"> "}),De&&!I?Y(As,{children:[E(So,{ch:De[0],dim:!0}),E(S,{color:"gray",children:De.slice(1)}),E(S,{dimColor:!0,children:" (tab)"})]}):(Vo.isSetup||!fc)&&!I?Y(As,{children:[E(So,{ch:Vo.text[0],dim:!0}),E(S,{color:"gray",children:Vo.text.slice(1)})]}):E(So,{ch:" "})]})}),Hs.length>0&&E(oe,{flexDirection:"column",paddingX:1,children:Hs.map((l,i)=>E(S,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Oo?E(Pl,{tab:Oo.tab,width:_e}):et?Y(oe,{flexDirection:"column",paddingX:1,children:[E(S,{color:H,bold:!0,children:"Select model"}),E(S,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ee.map((l,i)=>Y(S,{color:i===et.cursor?H:void 0,children:[i===et.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===et.current?" \u2714":""}`.padEnd(16),E(S,{color:"gray",children:l.desc})]},l.label)),E(S,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Ie?Y(oe,{flexDirection:"column",paddingX:1,children:[E(S,{color:H,bold:!0,children:"Switch connection profile"}),Ie.rows.map((l,i)=>Y(S,{color:i===Ie.cursor?H:void 0,children:[i===Ie.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===Ie.current?" \u2714":""}`.padEnd(20),E(S,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?E(S,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),E(S,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):He?Y(oe,{flexDirection:"column",paddingX:1,children:[E(S,{color:H,bold:!0,children:"Pick your Document360 environment"}),He.rows.map((l,i)=>Y(S,{color:i===He.cursor?H:void 0,children:[i===He.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),E(S,{color:"gray",children:l.apiUrl})]},l.name)),E(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?Y(oe,{flexDirection:"column",paddingX:1,children:[E(S,{color:H,bold:!0,children:"Switch workspace"}),E(S,{dimColor:!0,children:`environment ${fe.environment} \xB7 project ${fe.projectName??`${fe.projectId.slice(0,8)}\u2026`}`}),fe.rows.map((l,i)=>Y(S,{color:i===fe.cursor?H:void 0,children:[i===fe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===fe.current?" \u2714":""}`.padEnd(30),E(S,{color:"gray",children:l.type??""})]},l.id)),E(S,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):xe?Y(oe,{flexDirection:"column",paddingX:1,children:[E(S,{color:H,bold:!0,children:"Choose project"}),E(S,{dimColor:!0,children:`environment ${xe.environment}`}),xe.rows.map((l,i)=>Y(S,{color:i===xe.cursor?H:void 0,children:[i===xe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===xe.current?" \u2714":""}`.padEnd(30),E(S,{color:"gray",children:l.sub??""})]},l.id)),E(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ge?(()=>{let i=Math.min(Math.max(0,ge.cursor-Math.floor(7)),Math.max(0,ge.rows.length-14)),a=ge.rows.slice(i,i+14),g=ge.rows.filter(u=>u.checked).length;return Y(oe,{flexDirection:"column",paddingX:1,children:[E(S,{color:H,bold:!0,children:`Which folders back the user docs? (${g} selected of ${ge.rows.length})`}),i>0?E(S,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((u,m)=>{let w=i+m;return Y(S,{color:w===ge.cursor?H:void 0,children:[w===ge.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,_e-34)),E(S,{color:"gray",children:eo(u)})]},u.path)}),i+14<ge.rows.length?E(S,{dimColor:!0,children:` \u2193 ${ge.rows.length-i-14} more`}):null,E(S,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():ot?Y(oe,{flexDirection:"column",paddingX:1,children:[E(S,{color:H,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),ot.rows.map((l,i)=>{let a=i===ot.cursor,g=l.indent?" ":" ",u=`${i+1}.`.padEnd(3);return Y(S,{color:a?H:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${u} ${l.label}`.padEnd(Math.min(56,_e-24)),l.note?E(S,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),E(S,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):$e?Y(oe,{flexDirection:"column",paddingX:1,children:[E(S,{color:H,bold:!0,children:`Preview article${$e.query?` \u2014 filter: ${$e.query}`:" (type to filter)"}`}),$n.length===0?E(S,{color:"gray",children:"no articles match"}):$n.map((l,i)=>Y(S,{color:i===$e.cursor?H:void 0,children:[i===$e.cursor?"\u276F ":" ",l]},l)),E(S,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ce?Y(oe,{flexDirection:"column",paddingX:1,children:[E(S,{color:H,bold:!0,children:`Resume session${Ce.query?` \u2014 filter: ${Ce.query}`:" (type to filter)"}`}),vn.length===0?E(S,{color:"gray",children:"no sessions match"}):vn.map((l,i)=>Y(S,{color:i===Ce.cursor?H:void 0,children:[i===Ce.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),E(S,{color:i===Ce.cursor?H:"gray",children:l.firstPrompt.slice(0,Math.max(10,_e-40))})]},l.uuid)),E(S,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):zs?Y(oe,{flexDirection:"column",children:[zt.map((l,i)=>Y(S,{color:i===Ht?H:void 0,children:[i===Ht?"\u276F ":" ",l.usage.padEnd(22)," ",E(S,{color:i===Ht?H:"gray",children:l.name==="model"&&Mo?`${l.desc} (currently ${Mo})`:l.desc})]},l.name)),E(S,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!I&&!D&&Qe.length>0?Y(oe,{flexDirection:"column",paddingX:1,children:[Fs?E(S,{color:H,children:Fs}):null,Qe.map((l,i)=>{let a=ft(l),g=a.slice(0,Math.max(20,_e-5)),u=_e-g.length-7,m=u>=12?(jl(l)??xl(a)).slice(0,u):"";return Y(S,{children:[E(S,{color:H,children:i+1})," ",g,m?E(S,{dimColor:!0,children:` \u2014 ${m}`}):null]},a)}),E(S,{dimColor:!0,children:`press 1-${Qe.length} to fill the command \xB7 esc dismiss`})]}):E(oe,{paddingX:1,children:Y(S,{color:"gray",children:[Vs.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Mo??"model n/a"}${t.kind==="api"?Bs>0?` \xB7 ${he(Bs)}`:"":qs>0?` \xB7 ${Ve(qs)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as qm}from"react/jsx-runtime";async function ic(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Hm(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Fm(qm(sc,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
303
- `),process.exit(0)}W();import{writeCrashLog as ac,isBenignTransportError as Bm}from"document360-engine";var lc=!1;function _s(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function cc(e){if(lc)return;lc=!0;let t=(n,o)=>{if(Bm(o)){ac({kind:n,level:"transport",message:_s(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=ac({kind:n,level:"fatal",message:_s(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
304
- `+$(`\u2717 d360-writer crashed: ${_s(o)}`)+`
300
+ `)}),St(lt()),Vt.current=Oe(e).status==="current"||tn(e);return}case"inbox":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(rs(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 se(ss(),{display:"/inbox",quietUser:!0});return}case"document":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:m}=Vr(g);if(!m&&Gr(e)===0){d({kind:"note",tone:"info",text:Xr});return}let w=`/document${m?` ${m}`:""}${u?" --publish":""}`;await se(zr(m,u),{display:w,quietUser:!0});return}case"catch-up":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!qo(c.trim()))return;let{publish:u}=as(g);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let m=await cs({cwd:e,profileName:s});for(let y of us(m))d({kind:"note",tone:y.startsWith("\u2713")?"ok":y.startsWith("\u2139")?"info":"warn",text:y});let w=Ut(Mt(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await se(ls({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{Fo.current=!0,d({kind:"note",tone:"info",text:`Updating ${pt}\u2026 (don\u2019t close this window)`}),gn(!0),(await uo().finally(()=>gn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),B(m=>m.includes("/exit")?m:[...m,"/exit"]),Us("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${co}`});return}case"screenshot":{let u=es(g);if(u.mode==="list"){if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:ns(ts(e,u.scope),u.scope).join(`
301
+ `)});return}if(u.mode==="single"){let L=await ao(g);L.kind==="forward-to-agent"&&L.prompt&&await se(L.prompt,{display:L.display,quietUser:!0});return}if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=u.mode==="scope"?u.scope:void 0,w=Nm(e,{scope:m}).map(L=>L.id);if(w.length===0){d({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let y=6,P=Em(w,3),R=So(e,"standard");Je.current=Date.now(),gt(0),I(!0);let z=new AbortController;Ce.current=z,ee({verb:"Authoring",unit:"spec",total:P.length,done:0,active:[],rows:pn(P),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${w.length} screenshot spec${w.length===1?"":"s"} across ${P.length} partition${P.length===1?"":"s"} (\u2264${y} agents at once) on ${R.model}${R.forced?" (forced)":""}\u2026 (esc to stop)`});let F=!1;try{for await(let L of To({cwd:e,partitions:P,promptFor:Va,concurrency:y,profileName:s,allowProdWrites:bt.current,model:R.model,signal:z.signal}))if(L.type==="partition_status")L.status==="running"?ee(v=>v&&{...v,active:[...v.active,L.label],rows:Me(v.rows,L.label,"active"),lastAt:Date.now()}):ee(v=>v&&{...v,active:v.active.filter(E=>E!==L.label),done:v.done+1,rows:Me(v.rows,L.label,L.status==="done"?"done":"failed"),lastAt:Date.now()});else if(L.type==="partition_event")ee(v=>{if(!v)return v;let E={...v,lastAt:Date.now()};return L.event.type==="tool"?E.tools=v.tools+1:L.event.type==="text"&&(E.chars=v.chars+L.event.delta.length),E});else if(L.type==="run_done"){Tt(K=>K+L.totalCostUsd),Rt(K=>K+L.results.reduce((ye,jt)=>ye+jt.outputTokens,0));let v=L.results.filter(K=>K.ok).length,E=L.aborted?"Stopped. ":"";F=!L.aborted&&u.setup;let U=L.aborted?"":F?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:L.aborted?"warn":L.ok?"ok":"warn",text:`${E}Authored specs \u2014 ${v}/${L.results.length} batches ok.${U}`})}}catch(L){d({kind:"note",tone:"error",text:`Spec authoring failed: ${L.message}`})}finally{Ce.current=null,ee(null),I(!1),oe(L=>L+1)}if(F){let L=await dn();L.kind==="forward-to-agent"&&L.prompt&&await se(L.prompt,{display:L.display,quietUser:!0});let v=os(e);v&&d({kind:"note",tone:"info",text:v.join(`
302
+ `)})}return}case"reset":{let u=fs(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Io.current={repoName:fn(e),targets:u,hadDevhints:Xe(_s(e))},d({kind:"note",tone:"warn",text:hs(e,u).join(`
303
+ `)}),ue(fn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,Dn,d,we,se,Pn,Xo,Zs]),jn=V(c=>{let i=(c??D).trim();if(b(""),wn(null),wt(0),i.startsWith("/")&&(ue(null),ht.current++,de(null),B(g=>Ll(g,i))),!i||ti(i)||ei(i))return;No.current.push(i);let a=Hl(i,Ws.current);i.startsWith("/")?(d({kind:"user",text:i}),ni(a)):se(a,{display:i})},[D,ti,ei,ni,se]),oi=V(c=>{if(c.length>1){if(c.includes("\x1B"))return;let i=Ul(c);if(Wl(i)){let a=Fl(++$c.current,i);Ws.current.set(a,i),T(a)}else T(i);return}T(c)},[T]),Dt=Math.max(10,_e-6),ri=Ss(()=>Po(k.text,Dt),[k.text,Dt]),Jo=V(c=>x(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+c))})),[]),An=V(c=>x(i=>({...i,pos:Bl(Po(i.text,Dt),i.pos,c)})),[Dt]),Kt=V(c=>x(i=>({...i,pos:Yl(Po(i.text,Dt),i.pos,c)})),[Dt]),Pc=["\x1B[H","\x1B[1~","\x1BOH"],Rc=["\x1B[F","\x1B[4~","\x1BOF"],si=V((c,i)=>i.leftArrow?(Jo(-1),!0):i.rightArrow?(Jo(1),!0):c&&Pc.includes(c)?(Kt("start"),!0):c&&Rc.includes(c)?(Kt("end"),!0):i.ctrl&&c==="a"?(Kt("start"),!0):i.ctrl&&c==="e"?(Kt("end"),!0):!1,[Jo,Kt]);return om((c,i)=>{if(i.ctrl&&c==="c"){xe.current?.close(),r();return}if(!M){if(N){if(i.escape){if(Ce.current){if(!Ce.current.signal.aborted){let a=(kn?.verb??"work").toLowerCase(),g=kn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${g}s)\u2026`}),Ce.current.abort()}return}Bt.current||(Bt.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),xe.current?.interrupt());return}if(i.return){let a=D.trim();if(!a)return;st.current.push(a),Oo([...st.current]),b("");return}if(si(c,i))return;if(i.upArrow){An(-1);return}if(i.downArrow){An(1);return}if(i.backspace||i.delete){C();return}c&&!i.ctrl&&!i.meta&&oi(c);return}if(et){if(i.upArrow){tt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){tt(a=>a&&{...a,cursor:Math.min(Ee.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ee.length){tt(a=>a&&{...a,cursor:Number(c)-1});return}if(i.return){let a=Ee[et.cursor];tt(null);let{lines:g,changed:u,effective:m}=cn(e,a.value??"default");for(let w of g)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});u&&(zs(w=>w+1),xe.current?.setModel(m));return}if(c==="s"){let a=Ee[et.cursor];tt(null),xe.current?.setModel(a.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){tt(null);return}return}if(Ie){if(i.upArrow){xt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){xt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ie.rows.length){xt(a=>a&&{...a,cursor:Number(c)-1});return}if(i.return||c==="s"){let a=Ie.rows[Ie.cursor];xt(null),Qo(a.name,i.return===!0);return}if(i.escape){xt(null);return}return}if(Lo){if(i.escape){Gt(null);return}if(i.leftArrow||i.tab&&i.shift){Gt(a=>a&&{tab:(a.tab-1+Te.length)%Te.length});return}if(i.rightArrow||i.tab){Gt(a=>a&&{tab:(a.tab+1)%Te.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Te.length){Gt({tab:Number(c)-1});return}return}if(He){if(i.upArrow){$t(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){$t(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=He.rows.length){$t(a=>a&&{...a,cursor:Number(c)-1});return}if(i.return){let a=He.rows[He.cursor].name;if($t(null),!ar(e,a).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${a}").`});let u=!1;try{let m=Ke(a);u=!!m&&!(We(m)&&!m.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),B(["/login"]),oe(m=>m+1);return}if(i.escape){$t(null);return}return}if(me){if(i.upArrow){vt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){vt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=me.rows.length){vt(a=>a&&{...a,cursor:Number(c)-1});return}if(i.return){let a=me.rows[me.cursor],{profile:g,projectId:u}=me;vt(null),Rn(g,u,a);return}if(i.escape){vt(null);return}return}if($e){if(i.upArrow){nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){nt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=$e.rows.length){nt(a=>a&&{...a,cursor:Number(c)-1});return}if(i.return){let a=$e.rows[$e.cursor],{profile:g}=$e;nt(null),Sn(g,a);return}if(i.escape){nt(null);return}return}if(ge){if(i.upArrow){Pt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Pt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c===" "){Pt(a=>a&&{...a,rows:a.rows.map((g,u)=>u===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=ge.rows.filter(g=>g.checked).map(g=>g.path);if(Pt(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}$r(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let g of a)d({kind:"note",tone:"info",text:` ${g}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){Pt(null);return}return}if(ot){if(i.upArrow){Ct(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ct(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ot.rows.length){Ct(a=>a&&{...a,cursor:Number(c)-1});return}if(i.return){let a=ot.rows[ot.cursor];Ct(null),a.kind==="article"?Xo(a.paths[0]):Pn(a.paths);return}if(i.escape){Ct(null);return}return}if(ve){if(i.escape){rt(null);return}if(i.upArrow){rt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){rt(a=>a&&{...a,cursor:Math.min(Math.max(0,vn.length-1),a.cursor+1)});return}if(i.return){let a=vn[ve.cursor];if(a){rt(null);try{d({kind:"preview",name:fn(a),text:ac(Ds(mt(e,a),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){rt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(c&&!i.ctrl&&!i.meta&&c.length===1){rt(a=>a&&{...a,query:a.query+c,cursor:0});return}return}if(Pe){if(i.escape){it(null);return}if(i.upArrow){it(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){it(a=>a&&{...a,cursor:Math.min(Math.max(0,Cn.length-1),a.cursor+1)});return}if(i.return){let a=Cn[Pe.cursor];if(a){it(null),we(a.uuid),Ne.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Ze(a.name),js(a.uuid),kt.current=[];let g=Cs(e,a.uuid);for(let u of g)d(u);d({kind:"note",tone:"ok",text:g.length?`Resumed "${a.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){it(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(c&&!i.ctrl&&!i.meta&&c.length===1){it(a=>a&&{...a,query:a.query+c,cursor:0});return}return}if(i.tab&&!D&&De){b(De),ue(null),ht.current++;return}if(!D&&Qe.length>0&&c&&/^[1-9]$/.test(c)){let a=Qe[Number(c)-1];if(a){b(ft(a));return}}if(!D&&(Bo||Uo)&&c==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=Bo!=null;bl(Bo??Uo).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?a?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&a&&Yo(null)});return}if(!si(c,i)){if(Qs){if(i.upArrow){wt(a=>Math.max(0,a-1));return}if(i.downArrow){wt(a=>Math.min(Xt.length-1,a+1));return}if(i.tab){b("/"+(Xt[qt]?.name??"")+" "),wt(0);return}if(i.return){let a=Xt[qt];if(a){let g=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Dl(a.usage)&&!g){b("/"+a.name+" "),wt(0);return}jn("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(D!==""&&yt===null){An(-1);return}let a=No.current;if(!a.length)return;let g=yt===null?a.length-1:Math.max(0,yt-1);wn(g),b(a[g]??"");return}if(i.downArrow){if(D!==""&&yt===null){An(1);return}let a=No.current;if(yt===null)return;let g=yt+1;g>=a.length?(wn(null),b("")):(wn(g),b(a[g]??""));return}}if(i.return){jn();return}if(i.backspace||i.delete){C();return}if(i.escape){b(""),wt(0),ue(null),B([]),de(null);return}c&&!i.ctrl&&!i.meta&&oi(c)}}}),be(()=>{if(N||M)return;let c=st.current.shift();c!==void 0&&(Oo([...st.current]),jn(c))},[N,M,jn]),Y(ne,{flexDirection:"column",width:_e,children:[zo!==null&&Y(ne,{marginTop:1,flexDirection:"column",children:[zo.truncated&&j(S,{dimColor:!0,children:"\u2026"}),j(S,{children:zo.text})]}),N&&(kn?j(Qm,{p:kn}):j(zm,{startTime:Je.current,chars:xc})),!N&&Bs?j(Xm,{text:Bs}):null,j(ne,{borderStyle:"round",borderColor:Ks.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?ri.map((c,i)=>{let a=k.text.slice(c.start,c.end),g=i===Ro(ri,k.pos),u=Math.min(k.pos,c.end)-c.start;return Y(S,{children:[j(S,{color:q,children:i===0?"> ":" "}),g?Y(Es,{children:[a.slice(0,u),j(Do,{ch:a[u]??" "}),a.slice(u+1)]}):a||" "]},`${i}-${c.start}`)}):Y(S,{children:[j(S,{color:q,children:"> "}),De&&!N?Y(Es,{children:[j(Do,{ch:De[0],dim:!0}),j(S,{color:"gray",children:De.slice(1)}),j(S,{dimColor:!0,children:" (tab)"})]}):(Vo.isSetup||!kc)&&!N?Y(Es,{children:[j(Do,{ch:Vo.text[0],dim:!0}),j(S,{color:"gray",children:Vo.text.slice(1)})]}):j(Do,{ch:" "})]})}),qs.length>0&&j(ne,{flexDirection:"column",paddingX:1,children:qs.map((c,i)=>j(S,{color:"gray",children:`\u29D7 queued: ${c}`},`${i}-${c.slice(0,24)}`))}),Lo?j(Al,{tab:Lo.tab,width:_e}):et?Y(ne,{flexDirection:"column",paddingX:1,children:[j(S,{color:q,bold:!0,children:"Select model"}),j(S,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ee.map((c,i)=>Y(S,{color:i===et.cursor?q:void 0,children:[i===et.cursor?"\u276F ":" ",`${i+1}. ${c.label}${i===et.current?" \u2714":""}`.padEnd(16),j(S,{color:"gray",children:c.desc})]},c.label)),j(S,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Ie?Y(ne,{flexDirection:"column",paddingX:1,children:[j(S,{color:q,bold:!0,children:"Switch connection profile"}),Ie.rows.map((c,i)=>Y(S,{color:i===Ie.cursor?q:void 0,children:[i===Ie.cursor?"\u276F ":" ",`${i+1}. ${c.name}${i===Ie.current?" \u2714":""}`.padEnd(20),j(S,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?j(S,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),j(S,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):He?Y(ne,{flexDirection:"column",paddingX:1,children:[j(S,{color:q,bold:!0,children:"Pick your Document360 environment"}),He.rows.map((c,i)=>Y(S,{color:i===He.cursor?q:void 0,children:[i===He.cursor?"\u276F ":" ",`${i+1}. ${c.name}`.padEnd(16),j(S,{color:"gray",children:c.apiUrl})]},c.name)),j(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):me?Y(ne,{flexDirection:"column",paddingX:1,children:[j(S,{color:q,bold:!0,children:"Switch workspace"}),j(S,{dimColor:!0,children:`environment ${me.environment} \xB7 project ${me.projectName??`${me.projectId.slice(0,8)}\u2026`}`}),me.rows.map((c,i)=>Y(S,{color:i===me.cursor?q:void 0,children:[i===me.cursor?"\u276F ":" ",`${i+1}. ${c.name}${i===me.current?" \u2714":""}`.padEnd(30),j(S,{color:"gray",children:c.type??""})]},c.id)),j(S,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):$e?Y(ne,{flexDirection:"column",paddingX:1,children:[j(S,{color:q,bold:!0,children:"Choose project"}),j(S,{dimColor:!0,children:`environment ${$e.environment}`}),$e.rows.map((c,i)=>Y(S,{color:i===$e.cursor?q:void 0,children:[i===$e.cursor?"\u276F ":" ",`${i+1}. ${c.name}${i===$e.current?" \u2714":""}`.padEnd(30),j(S,{color:"gray",children:c.sub??""})]},c.id)),j(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ge?(()=>{let i=Math.min(Math.max(0,ge.cursor-Math.floor(7)),Math.max(0,ge.rows.length-14)),a=ge.rows.slice(i,i+14),g=ge.rows.filter(u=>u.checked).length;return Y(ne,{flexDirection:"column",paddingX:1,children:[j(S,{color:q,bold:!0,children:`Which folders back the user docs? (${g} selected of ${ge.rows.length})`}),i>0?j(S,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((u,m)=>{let w=i+m;return Y(S,{color:w===ge.cursor?q:void 0,children:[w===ge.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,_e-34)),j(S,{color:"gray",children:to(u)})]},u.path)}),i+14<ge.rows.length?j(S,{dimColor:!0,children:` \u2193 ${ge.rows.length-i-14} more`}):null,j(S,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():ot?Y(ne,{flexDirection:"column",paddingX:1,children:[j(S,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),ot.rows.map((c,i)=>{let a=i===ot.cursor,g=c.indent?" ":" ",u=`${i+1}.`.padEnd(3);return Y(S,{color:a?q:void 0,bold:c.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${u} ${c.label}`.padEnd(Math.min(56,_e-24)),c.note?j(S,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),j(S,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ve?Y(ne,{flexDirection:"column",paddingX:1,children:[j(S,{color:q,bold:!0,children:`Preview article${ve.query?` \u2014 filter: ${ve.query}`:" (type to filter)"}`}),vn.length===0?j(S,{color:"gray",children:"no articles match"}):vn.map((c,i)=>Y(S,{color:i===ve.cursor?q:void 0,children:[i===ve.cursor?"\u276F ":" ",c]},c)),j(S,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Pe?Y(ne,{flexDirection:"column",paddingX:1,children:[j(S,{color:q,bold:!0,children:`Resume session${Pe.query?` \u2014 filter: ${Pe.query}`:" (type to filter)"}`}),Cn.length===0?j(S,{color:"gray",children:"no sessions match"}):Cn.map((c,i)=>Y(S,{color:i===Pe.cursor?q:void 0,children:[i===Pe.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),j(S,{color:i===Pe.cursor?q:"gray",children:c.firstPrompt.slice(0,Math.max(10,_e-40))})]},c.uuid)),j(S,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Qs?Y(ne,{flexDirection:"column",children:[Xt.map((c,i)=>Y(S,{color:i===qt?q:void 0,children:[i===qt?"\u276F ":" ",c.usage.padEnd(22)," ",j(S,{color:i===qt?q:"gray",children:c.name==="model"&&Mo?`${c.desc} (currently ${Mo})`:c.desc})]},c.name)),j(S,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!D&&Qe.length>0?Y(ne,{flexDirection:"column",paddingX:1,children:[Hs?j(S,{color:q,children:Hs}):null,Qe.map((c,i)=>{let a=ft(c),g=a.slice(0,Math.max(20,_e-5)),u=_e-g.length-7,m=u>=12?(Ol(c)??Tl(a)).slice(0,u):"";return Y(S,{children:[j(S,{color:q,children:i+1})," ",g,m?j(S,{dimColor:!0,children:` \u2014 ${m}`}):null]},a)}),j(S,{dimColor:!0,children:`press 1-${Qe.length} to fill the command \xB7 esc dismiss`})]}):j(ne,{paddingX:1,children:Y(S,{color:"gray",children:[Ks.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Mo??"model n/a"}${t.kind==="api"?Vs>0?` \xB7 ${he(Vs)}`:"":Gs>0?` \xB7 ${Ve(Gs)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as th}from"react/jsx-runtime";async function pc(e=process.cwd(),t="auto",n,o="0.0.0"){let r=eh(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Zm(th(dc,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
304
+ `),process.exit(0)}W();import{writeCrashLog as fc,isBenignTransportError as nh}from"document360-engine";var mc=!1;function Os(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function hc(e){if(mc)return;mc=!0;let t=(n,o)=>{if(nh(o)){fc({kind:n,level:"transport",message:Os(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=fc({kind:n,level:"fatal",message:Os(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
305
+ `+$(`\u2717 d360-writer crashed: ${Os(o)}`)+`
305
306
  `),r&&process.stderr.write(f(` Crash details: ${r}`)+`
306
307
  `+f(" Run: d360-writer logs")+`
307
- `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var zm=Gm(import.meta.url),uc=zm("../package.json");cc("d360-writer");var Se=new Ym;function Ls(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Se.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=>{Ls(e),await Mn({profile:e.profile,manual:e.manual})});Se.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ls(e),await hi({profile:e.profile})});Se.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ls(e),await mi({profile:e.profile})});var Os=Se.command("profile").description("Manage connection profiles for the current repo");Os.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Un(process.cwd()));Os.command("use <name>").description("Set the default profile for this repo").action(e=>Wn(process.cwd(),e));Os.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Fn(process.cwd(),e));var dc=Se.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");dc.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Et(process.cwd(),e.profile));dc.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await ai(process.cwd(),e,t.profile)});var pc=Se.command("project").description("Choose the Document360 project for this repo (active profile's identity)");pc.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>_n(process.cwd(),e.profile));pc.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await ci(process.cwd(),e,t.profile)});Se.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Xn(),Wi));await e()});Se.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>ki());Se.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(()=>(so(),La)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Se.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(uc.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(Vm.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 bi(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 pl(e.cwd,e.auth,e.profile):await ic(e.cwd,e.auth,e.profile,uc.version)});Se.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
308
+ `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var ih=rh(import.meta.url),gc=ih("../package.json");hc("d360-writer");var Se=new oh;function Ls(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Se.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=>{Ls(e),await Un({profile:e.profile,manual:e.manual})});Se.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ls(e),await yi({profile:e.profile})});Se.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ls(e),await wi({profile:e.profile})});var Ms=Se.command("profile").description("Manage connection profiles for the current repo");Ms.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Wn(process.cwd()));Ms.command("use <name>").description("Set the default profile for this repo").action(e=>Fn(process.cwd(),e));Ms.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Hn(process.cwd(),e));var wc=Se.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");wc.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Et(process.cwd(),e.profile));wc.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await ui(process.cwd(),e,t.profile)});var yc=Se.command("project").description("Choose the Document360 project for this repo (active profile's identity)");yc.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>On(process.cwd(),e.profile));yc.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await pi(process.cwd(),e,t.profile)});Se.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Kn(),qi));await e()});Se.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>$i());Se.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(()=>(io(),Ua)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Se.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(gc.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(sh.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 vi(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 yl(e.cwd,e.auth,e.profile):await pc(e.cwd,e.auth,e.profile,gc.version)});Se.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});