document360-writer 0.5.93 → 0.5.95

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +81 -81
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var Ld=Object.defineProperty;var to=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Qs=(e,t)=>{for(var n in t)Ld(e,n,{get:t[n],enumerable:!0})};import Ke from"picocolors";var q,Md,Ud,Wd,Js,hn,f,C,L,j,O,ae,ge,W=to(()=>{"use strict";q="#7f56d9",[Md,Ud,Wd]=[127,86,217],Js=e=>Ke.isColorSupported?`\x1B[38;2;${Md};${Ud};${Wd}m${e}\x1B[39m`:e,hn=e=>Ke.bold(Js(e)),f=e=>Ke.dim(e),C=e=>Ke.red(e),L=e=>Ke.yellow(e),j=e=>Ke.green(e),O=Js,ae=e=>Ke.gray(e),ge=e=>Ke.bold(e)});import{existsSync as qt,writeFileSync as mt,readFileSync as Ru,readdirSync as Pu}from"node:fs";import{join as Tu}from"node:path";import{devHintsGuidePath as fo,hintsDir as ga,architectureDir as va,messagesDir as Er,creatorNotesPath as wa,devhintsStatePath as $a,directivesPath as ya,DIRECTIVES_HEADER as Su,roadmapPath as ka,ROADMAP_HEADER as Du,ensureDir as po,writeMessage as ju,listOpenForDev as Au}from"document360-engine";function xa(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var Md=Object.defineProperty;var to=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Qs=(e,t)=>{for(var n in t)Md(e,n,{get:t[n],enumerable:!0})};import Ke from"picocolors";var q,Ud,Wd,Fd,Js,hn,f,C,L,j,O,ae,ge,W=to(()=>{"use strict";q="#7f56d9",[Ud,Wd,Fd]=[127,86,217],Js=e=>Ke.isColorSupported?`\x1B[38;2;${Ud};${Wd};${Fd}m${e}\x1B[39m`:e,hn=e=>Ke.bold(Js(e)),f=e=>Ke.dim(e),C=e=>Ke.red(e),L=e=>Ke.yellow(e),j=e=>Ke.green(e),O=Js,ae=e=>Ke.gray(e),ge=e=>Ke.bold(e)});import{existsSync as qt,writeFileSync as mt,readFileSync as Pu,readdirSync as Tu}from"node:fs";import{join as Su}from"node:path";import{devHintsGuidePath as fo,hintsDir as ga,architectureDir as va,messagesDir as Er,creatorNotesPath as wa,devhintsStatePath as $a,directivesPath as ya,DIRECTIVES_HEADER as Du,roadmapPath as ka,ROADMAP_HEADER as ju,ensureDir as po,writeMessage as Au,listOpenForDev as Eu}from"document360-engine";function xa(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
3
3
 
4
4
  <!-- devhints script v${ce} \xB7 maintained by document360-writer (/devhints). -->
5
5
 
@@ -206,7 +206,7 @@ do it**:
206
206
  **Do NOT write or action the documentation yourself** \u2014 same boundary as Part 2. Writing the article is the
207
207
  docs agent's job; it actions open directives on its next \`/catch-up\` (as drafts) and flips each to \`[done]\`
208
208
  with the article it wrote. You are only the relay so the ask is captured durably and travels via git.
209
- `}function Eu(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
209
+ `}function Nu(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
210
210
 
211
211
  <!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
212
212
  The builder agent reads this FIRST and treats it as authoritative when writing the architecture
@@ -220,33 +220,33 @@ Anything only a human knows that would help document this product. For example:
220
220
  - Gotchas or non-obvious behavior.
221
221
 
222
222
  (Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
223
- `}function Vt(e){po(ga(e)),po(va(e)),po(Er(e));for(let n of[ga(e),Er(e)]){let o=Tu(n,".gitkeep");qt(o)||mt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
224
- `)}qt(wa(e))||mt(wa(e),Eu()),qt(ya(e))||mt(ya(e),Su),qt(ka(e))||mt(ka(e),Du),mt(fo(e),xa());let t=De(e);return Ra(e,new Date().toISOString()),t}async function Ca(e,t){for(let n of Gt(Vt(t.cwd)))console.log(n);return{kind:"continue"}}function gt(){return[`This is document360-writer's dev hand-off setup (v${ce}).`,'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\u20136). 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 \u2014 and SURFACE each hint drop in"," your reply (name the file + the one-line surface), never silently; NEVER write or publish the"," user-facing articles yourself (that is the docs agent's job \u2014 you only hand off); each session,"," check `.d360-writer/messages/` for open questions from the docs agent and answer them promptly and"," in full \u2014 an open docs question BLOCKS the documentation, and `[discovery]` questions define the"," whole product brief, so answer those in depth; AND when the"," human types `@d360-writer <directive>` in your session, append it as an `## [open] <directive>` block"," to `.d360-writer/directives.md` (create if absent) and commit \u2014 do NOT action it yourself (the docs"," agent picks it up on its next /catch-up) \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 IN FULL \u2014 an open docs question blocks the documentation,"," and `[discovery]`-tagged questions (what the product is, who it's for, its core mental model,"," misconceptions, positioning, terminology) define the whole product brief, so answer those in depth."," Fold durable facts into the architecture brief and 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": ${ce},`,' "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(`
225
- `)}function Nr(e){try{let t=Ru($a(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Ra(e,t){let o={...Nr(e)??{},emittedVersion:ce,emittedAt:t};mt($a(e),`${JSON.stringify(o,null,2)}
226
- `)}function Fe(e){try{return Pu(va(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function De(e){let n=Nr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ce?"stale":"current",completedVersion:n}}function ho(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ce};try{if(!qt(fo(e)))return n;let o=Nr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let i=o?.completedVersion??0;ce>r&&(po(Er(e)),mt(fo(e),xa()),Ra(e,t),n.guideRefreshed=!0),ce>i&&(Au(e).some(p=>p.kind==="request"&&p.subject.startsWith(ba))||(ju(e,{id:`onb${ce}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${ba}${ce})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${ce}${i?` (you last completed v${i})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",gt()].join(`
227
- `)}),n.notifiedBuilder=!0))}catch{}return n}function mo(e){if(!qt(fo(e)))return[];let t=De(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${ce}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Bt,gt(),Bt,"(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, checking"," `.d360-writer/messages/`, and relaying `@d360-writer` directives to `.d360-writer/directives.md`)."," Leave everything else in that file untouched.","2. The `.d360-writer/` folder is already deleted on disk. If it was committed, remove it from version"," control too \u2014 `git rm -r --cached .d360-writer` (if it still resolves) \u2014 and commit the deletions.","3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
228
- `)}function go(){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):",Bt,Ir(),Bt]}function Gt(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${ce}.`," 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):",Bt,gt(),Bt,"","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 Bt,ce,ba,Qe=to(()=>{"use strict";Bt="-".repeat(64),ce=8;ba="Re-run dev\u2194docs onboarding (protocol v"});var _a={};Qs(_a,{initCommand:()=>Or,scaffoldInit:()=>_r});import{input as wn,confirm as Nu}from"@inquirer/prompts";import{basename as Pa,join as wo}from"node:path";import{existsSync as Yt,readFileSync as Iu,readdirSync as _u,writeFileSync as Ou}from"node:fs";import{writeProjectConfig as Ta,readProjectConfig as Lu,projectConfigPath as Sa,writerDir as Mu,DEFAULT_DOCS_DIR as Da,DEFAULT_CAPTURE_DIR as ja,DEFAULT_OUTPUT_DIR as Aa}from"document360-engine";function _r(e,t="berlin"){let n=Sa(e);if(Yt(n))return{created:!1,path:n,profileName:""};let o={projectId:Na(e)??Pa(e),docsDir:Da,captureDir:ja,outputDir:Aa,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Ia(e)};return Ta(o,e),Ea(e),{created:!0,path:n,profileName:t}}function Ea(e){let t=wo(Mu(e),".gitignore");Yt(t)||Ou(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
229
- `),"utf8")}async function Or(){let e=process.cwd(),t=Sa(e);if(Yt(t)&&!await Nu({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Na(e)??Pa(e),o=await wn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await wn({message:"Capture directory (where document360-capture .spec.ts files live):",default:ja}),i=await wn({message:"Screenshot output directory:",default:Aa}),l=await wn({message:"Default connection profile name:",default:"berlin"}),p=await wn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),m={projectId:o,docsDir:Da,captureDir:r,outputDir:i,profiles:{[l]:{connection:{environment:p},production:!1}},defaultProfile:l,authoritativeSourceFiles:Ia(e)},k=Lu(e);k?.terminologyGlossary&&(m.terminologyGlossary=k.terminologyGlossary),Ta(m,e),Ea(e);let g=Vt(e);console.log(""),console.log(j(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${O(`d360-writer login --profile ${l}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let T of Gt(g))console.log(T);return console.log(""),console.log(`${f("Then ask:")} ${O('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Na(e){let t=wo(e,"package.json");if(!Yt(t))return null;try{return JSON.parse(Iu(t,"utf8")).name??null}catch{return null}}function Ia(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Yt(wo(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=wo(e,n);Yt(o)&&!Uu(o)&&t.push(n)}return t}function Uu(e){try{return _u(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var yo=to(()=>{"use strict";W();Qe()});var Ol={};Qs(Ol,{doctorCommand:()=>Cn,renderDoctorChecks:()=>_l,runDoctorChecks:()=>Il});import{existsSync as jf}from"node:fs";import{d360GetAll as Af,getAccessToken as Ef,isExpired as ji,loadProfileMap as Nf,loadTokens as If,packageSkillsDir as El,ENGINE_VERSION as _f,projectConfigPath as Of,readProjectConfig as Lf,DEFAULT_DOCS_DIR as Mf,fetchManifestSummary as Uf,resolveActiveProfile as Wf,classifyClaudeAuth as Ff,CLAUDE_CODE_SETUP_HINT as Nl,resolveModelSetting as Hf,probeModel as qf,detectAppType as Bf,playbookSkillName as Vf,D360AuthError as Gf}from"document360-engine";async function Il(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${_f}`});let o=Number(process.versions.node.split(".")[0]);n.push(o>=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 r=Ff();r.state==="ready"?n.push({level:"ok",label:`Claude auth: ${r.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):r.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${Nl}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Nl});let i=Hf(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),r.state==="ready"){let P=await qf(e,i.model??void 0);P.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(P.latencyMs/1e3).toFixed(1)}s`}):P.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${P.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 l=Lf(e);if(!l)return n.push({level:"fail",label:`No ${Of(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${l.projectId}`});let p=(l.docsDir??Mf).replace(/\/+$/,"");n.push(l.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 ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let m=l.authoritativeSourceFiles??[];n.push(m.length>0?{level:"ok",label:`Sources: docs grounded in ${m.length} path(s) (${m.slice(0,3).join(", ")}${m.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 k=l.appType??Bf(e);if(k){let P=l.appType?"from config":"auto-detected",N=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${P})${N?` \u2192 ${Vf(k)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let g;try{g=Wf(e),n.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(P){return n.push({level:"fail",label:`Profile config: ${P.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let T=If(g.name);T?ji(T)&&!T.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):ji(T)?n.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(T.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${g.name})`}),n.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let v=Nf(e,g.name);v?v.projectId&&g.project.projectId&&v.projectId!==g.project.projectId?n.push({level:"fail",label:`Category map projectId (${v.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(v.articles).length} articles, ${Object.keys(v.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),n.push(jf(El())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${El()}`,fix:"Reinstall document360-writer (broken install)"});let _=De(e);if(_.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ce})`}):_.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${_.completedVersion}, current is v${ce}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),T&&(!ji(T)||T.refreshToken)){let P={profile:g.name,connection:g.connection};try{await Ef(P);let D=await Af(P,"/v3/projects");n.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${D.length} project(s) visible`})}catch(D){n.push({level:"fail",label:`API call failed: ${D.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=v?.projectId??g.project.projectId;if(N&&g.project.workspaceId)try{let D=await Uf(P,N,g.project.workspaceId);if(D){let M=(D.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${g.connection.name} (${D.languages?.length??0} language${(D.languages?.length??0)===1?"":"s"}) \xB7 hash ${M||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${g.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(D){D instanceof Gf||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(D.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??N})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${D.message.slice(0,80)})`})}}return n}function _l(e){let t=[""];for(let r of e){let i=r.level==="ok"?j("\u2713"):r.level==="warn"?L("\u26A0"):C("\u2717");t.push(` ${i} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${O(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?j(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):C(`\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 _l(await Il(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Eo=to(()=>{"use strict";Qe();W()});import{Command as cw}from"commander";import{createRequire as dw}from"node:module";import{AUTH_MODES as uw}from"document360-engine";import{input as eu}from"@inquirer/prompts";import{loginPkce as tu,refreshTokens as nu,toStoredTokens as ra,clearTokens as ou,decodeJwtClaims as oa,isExpired as ru,loadTokens as iu,saveTokens as ia,resolveActiveProfile as io,setProfileProject as su,readProjectConfig as au}from"document360-engine";W();import{select as Fd}from"@inquirer/prompts";import{resolveActiveProfile as Hd,setProfileProject as qd,resolveProjectId as Bd,listWorkspaces as Vd}from"document360-engine";async function mn(e,t){let n=Hd(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Bd(o);return{workspaces:await Vd(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Zs=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Tr(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 no(e,t,n,o,r){qd(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ea(e,t,n){let o;try{o=await mn(e,n)}catch(i){return console.log(C(`Could not list workspaces: ${i.message}`)),1}let r=Tr(o.workspaces,t);return r?(no(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(C(`No workspace matches "${t}". Available: ${o.workspaces.map(i=>i.name??i.id).join(", ")}`)),1)}async function Ht(e,t){let n;try{n=await mn(e,t)}catch(k){console.log(C(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:i,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?O("\u25CF"):" "} ${Zs(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Fd({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${Zs(k)}${k.id===l?" (current)":""}`,value:k.id}))}),m=o.find(k=>k.id===p);no(e,i,r,p,m?.name),console.log(j(`\u2713 Workspace set to "${m?.name??p}" for profile "${i}".`))}W();import{select as Gd}from"@inquirer/prompts";import{resolveActiveProfile as Yd,setProfileProject as zd,listProjects as Kd}from"document360-engine";async function Xe(e,t){let n=Yd(e,t),o={profile:n.name,connection:n.connection};return{projects:await Kd(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ta=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Sr(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 oo(e,t,n,o){zd(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function na(e,t,n){let o;try{o=await Xe(e,n)}catch(i){return console.log(C(`Could not list projects: ${i.message}`)),1}let r=Sr(o.projects,t);return r?(oo(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(C(`No project matches "${t}". Available: ${o.projects.map(i=>i.name??i.id).join(", ")}`)),1)}async function ro(e,t){let n;try{n=await Xe(e,t)}catch(m){console.log(C(`Could not list projects: ${m.message}`));return}let{projects:o,profile:r,current:i}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let m of o)console.log(` ${m.id===i?O("\u25CF"):" "} ${ta(m)} ${f(m.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let l=await Gd({message:"Select the Document360 project for this repo:",choices:o.map(m=>({name:`${ta(m)}${m.id===i?" (current)":""}`,value:m.id}))}),p=o.find(m=>m.id===l);oo(e,r,l,p?.name),console.log(j(`\u2713 Project set to "${p?.name??l}" for profile "${r}". Next: pick a workspace.`))}W();import Xd from"picocolors";function Qd(e=process.env){return e.FORCE_HYPERLINK==="0"||!Xd.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 Jd(e,t=e,n){return Qd(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Zd=/https?:\/\/[^\s\x1b]+/g;function gn(e,t){return e.replace(Zd,n=>Jd(n,n,t))}function sa(e){return{...oa(e.idToken)??{},...oa(e.accessToken)??{}}}function so(e){let t=sa(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 ao(e){let t=io(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 tu(n,{manual:e.manual,promptForRedirect:i=>eu({message:i})},i=>console.log(gn(i))),r=ra(t.name,o);if(ia(r),await Dr(r,t.name,i=>console.log(f(i))),console.log(""),console.log(j(`\u2713 Logged in to "${t.name}" as ${so(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{au(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Ht(process.cwd(),t.name))}catch{}}async function Dr(e,t,n){let r=sa(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(io(process.cwd(),t).project.projectId)return;let l;try{let{projects:p}=await Xe(process.cwd(),t);l=p.find(m=>m.id===r)?.name}catch{}su(process.cwd(),t,{projectId:r,projectName:l}),n(` Project "${l??r}" written to profile "${t}".`)}catch{}}async function aa(e){let t=io(process.cwd(),e.profile),n=t.connection,o=iu(t.name);if(!o){console.log(C(`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 ${O(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${so(o)}`),ru(o))if(o.refreshToken)try{let r=ra(t.name,await nu(n,o.refreshToken));ia(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 la(e){let t=io(process.cwd(),e.profile);ou(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 ca,writeProjectConfig as lu,resolveActiveProfile as cu,loadTokens as du,isExpired as uu}from"document360-engine";function lo(e){let t=ca(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(C("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?O("\u25CF "):" ",i=o.production?L(" \u26A0 PRODUCTION"):"",l=o.connection.environment??"(inline)",p=du(n),m=p?uu(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${O(n)} \u2192 ${l}${i} [${m}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function co(e,t){let n=ca(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(C(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,lu(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(j(`\u2713 Default profile is now "${t}"${o}`))}function uo(e,t){try{let n=cu(e,t);console.log(""),console.log(`Profile ${O(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(C(n.message)),process.exitCode=1}}W();import{existsSync as pu,readdirSync as fu,statSync as da}from"node:fs";import{join as ua}from"node:path";import{apiLogDir as hu}from"document360-engine";function pa(){let e=hu();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!pu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=fu(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let i=(da(ua(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${i} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let i=(da(ua(e,r)).size/1024).toFixed(1);console.log(` ${C(r)} ${f(`${i} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as mu,resolveAuth as gu,findByName as wu,slugify as yu,touchSession as ku,upsertSession as bu,resolveActiveProfile as vu}from"document360-engine";async function fa(e,t,n,o,r,i){let l=gu(n);l.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2)),l.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=vu(e,r)}catch(v){console.error(C(`Document360 profile error: ${v.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),i||(console.error(C("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let m;if(o){let v=wu(e,o);v||(console.error(C(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),m=v.uuid,console.error(f(`Resuming "${v.name}"`))}let k=mu({cwd:e,resume:m,profileName:r,allowProdWrites:i===!0}),g=m??null,T=1;for await(let v of k.send(t))switch(v.type){case"session":if(!g){g=v.sessionId;let _=new Date().toISOString();bu({uuid:g,name:yu(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:_,updatedAt:_})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(ae(` \u2699 ${v.name}`));break;case"result":T=v.ok?0:1,console.error(f(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(C("agent finished with an error result"));break;case"error":console.error(""),console.error(C(`agent error: ${v.message}`)),process.exit(1)}g&&ku(g),process.stdout.write(`
230
- `),process.exit(T)}import{createInterface as wm}from"node:readline/promises";import{createSession as ls,resolveAuth as ym,getSession as km,setTitle as bm,slugify as vm,touchSession as xc,upsertSession as $m,generateTitle as xm,resolveActiveProfile as Cc,resolveModelSetting as Cm,readProjectConfig as Rm,resolveAndPersistAppType as Pm,decodeJwtClaims as $c,isExpired as Tm,loadTokens as Sm,isDirectiveMention as Dm,stripDirectiveMention as jm,appendDirective as Am,reconcileUpgradeActions as Em,stampArticles as Nm,listArticleFiles as Im,CONTENT_CAP_VERSION as _m}from"document360-engine";import{ENGINE_VERSION as xu}from"document360-engine";var Se=[{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:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/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:"/roadmap",s:"The docs campaign: progress + the next step."},{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:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"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:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function $u(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 ha(e){let n=[e?`document360-writer \u2014 help \xB7 v${e.version} \xB7 engine v${e.engineVersion}`:"document360-writer \u2014 help",""];for(let o of Se){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push($u(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function jr(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:xu}:void 0;for(let o of ha(n))console.log(o);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}W();import{getSession as Cu}from"document360-engine";async function ma(e,t){let n=t.currentUuid(),o=n?Cu(n):void 0;return console.log(o?f(`
223
+ `}function Vt(e){po(ga(e)),po(va(e)),po(Er(e));for(let n of[ga(e),Er(e)]){let o=Su(n,".gitkeep");qt(o)||mt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
224
+ `)}qt(wa(e))||mt(wa(e),Nu()),qt(ya(e))||mt(ya(e),Du),qt(ka(e))||mt(ka(e),ju),mt(fo(e),xa());let t=je(e);return Ra(e,new Date().toISOString()),t}async function Ca(e,t){for(let n of Gt(Vt(t.cwd)))console.log(n);return{kind:"continue"}}function gt(){return[`This is document360-writer's dev hand-off setup (v${ce}).`,'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\u20136). 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 \u2014 and SURFACE each hint drop in"," your reply (name the file + the one-line surface), never silently; NEVER write or publish the"," user-facing articles yourself (that is the docs agent's job \u2014 you only hand off); each session,"," check `.d360-writer/messages/` for open questions from the docs agent and answer them promptly and"," in full \u2014 an open docs question BLOCKS the documentation, and `[discovery]` questions define the"," whole product brief, so answer those in depth; AND when the"," human types `@d360-writer <directive>` in your session, append it as an `## [open] <directive>` block"," to `.d360-writer/directives.md` (create if absent) and commit \u2014 do NOT action it yourself (the docs"," agent picks it up on its next /catch-up) \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 IN FULL \u2014 an open docs question blocks the documentation,"," and `[discovery]`-tagged questions (what the product is, who it's for, its core mental model,"," misconceptions, positioning, terminology) define the whole product brief, so answer those in depth."," Fold durable facts into the architecture brief and 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": ${ce},`,' "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(`
225
+ `)}function Nr(e){try{let t=Pu($a(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Ra(e,t){let o={...Nr(e)??{},emittedVersion:ce,emittedAt:t};mt($a(e),`${JSON.stringify(o,null,2)}
226
+ `)}function He(e){try{return Tu(va(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function je(e){let n=Nr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ce?"stale":"current",completedVersion:n}}function ho(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ce};try{if(!qt(fo(e)))return n;let o=Nr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let i=o?.completedVersion??0;ce>r&&(po(Er(e)),mt(fo(e),xa()),Ra(e,t),n.guideRefreshed=!0),ce>i&&(Eu(e).some(p=>p.kind==="request"&&p.subject.startsWith(ba))||(Au(e,{id:`onb${ce}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${ba}${ce})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${ce}${i?` (you last completed v${i})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",gt()].join(`
227
+ `)}),n.notifiedBuilder=!0))}catch{}return n}function mo(e){if(!qt(fo(e)))return[];let t=je(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${ce}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Bt,gt(),Bt,"(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, checking"," `.d360-writer/messages/`, and relaying `@d360-writer` directives to `.d360-writer/directives.md`)."," Leave everything else in that file untouched.","2. The `.d360-writer/` folder is already deleted on disk. If it was committed, remove it from version"," control too \u2014 `git rm -r --cached .d360-writer` (if it still resolves) \u2014 and commit the deletions.","3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
228
+ `)}function go(){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):",Bt,Ir(),Bt]}function Gt(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${ce}.`," 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):",Bt,gt(),Bt,"","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 Bt,ce,ba,Qe=to(()=>{"use strict";Bt="-".repeat(64),ce=8;ba="Re-run dev\u2194docs onboarding (protocol v"});var _a={};Qs(_a,{initCommand:()=>Or,scaffoldInit:()=>_r});import{input as wn,confirm as Iu}from"@inquirer/prompts";import{basename as Pa,join as wo}from"node:path";import{existsSync as Yt,readFileSync as _u,readdirSync as Ou,writeFileSync as Lu}from"node:fs";import{writeProjectConfig as Ta,readProjectConfig as Mu,projectConfigPath as Sa,writerDir as Uu,DEFAULT_DOCS_DIR as Da,DEFAULT_CAPTURE_DIR as ja,DEFAULT_OUTPUT_DIR as Aa}from"document360-engine";function _r(e,t="berlin"){let n=Sa(e);if(Yt(n))return{created:!1,path:n,profileName:""};let o={projectId:Na(e)??Pa(e),docsDir:Da,captureDir:ja,outputDir:Aa,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Ia(e)};return Ta(o,e),Ea(e),{created:!0,path:n,profileName:t}}function Ea(e){let t=wo(Uu(e),".gitignore");Yt(t)||Lu(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
229
+ `),"utf8")}async function Or(){let e=process.cwd(),t=Sa(e);if(Yt(t)&&!await Iu({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Na(e)??Pa(e),o=await wn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await wn({message:"Capture directory (where document360-capture .spec.ts files live):",default:ja}),i=await wn({message:"Screenshot output directory:",default:Aa}),l=await wn({message:"Default connection profile name:",default:"berlin"}),p=await wn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),m={projectId:o,docsDir:Da,captureDir:r,outputDir:i,profiles:{[l]:{connection:{environment:p},production:!1}},defaultProfile:l,authoritativeSourceFiles:Ia(e)},k=Mu(e);k?.terminologyGlossary&&(m.terminologyGlossary=k.terminologyGlossary),Ta(m,e),Ea(e);let g=Vt(e);console.log(""),console.log(j(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${O(`d360-writer login --profile ${l}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let T of Gt(g))console.log(T);return console.log(""),console.log(`${f("Then ask:")} ${O('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Na(e){let t=wo(e,"package.json");if(!Yt(t))return null;try{return JSON.parse(_u(t,"utf8")).name??null}catch{return null}}function Ia(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Yt(wo(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=wo(e,n);Yt(o)&&!Wu(o)&&t.push(n)}return t}function Wu(e){try{return Ou(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var yo=to(()=>{"use strict";W();Qe()});var Ol={};Qs(Ol,{doctorCommand:()=>Cn,renderDoctorChecks:()=>_l,runDoctorChecks:()=>Il});import{existsSync as Af}from"node:fs";import{d360GetAll as Ef,getAccessToken as Nf,isExpired as ji,loadProfileMap as If,loadTokens as _f,packageSkillsDir as El,ENGINE_VERSION as Of,projectConfigPath as Lf,readProjectConfig as Mf,DEFAULT_DOCS_DIR as Uf,fetchManifestSummary as Wf,resolveActiveProfile as Ff,classifyClaudeAuth as Hf,CLAUDE_CODE_SETUP_HINT as Nl,resolveModelSetting as qf,probeModel as Bf,detectAppType as Vf,playbookSkillName as Gf,D360AuthError as Yf}from"document360-engine";async function Il(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Of}`});let o=Number(process.versions.node.split(".")[0]);n.push(o>=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 r=Hf();r.state==="ready"?n.push({level:"ok",label:`Claude auth: ${r.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):r.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${Nl}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Nl});let i=qf(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),r.state==="ready"){let P=await Bf(e,i.model??void 0);P.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(P.latencyMs/1e3).toFixed(1)}s`}):P.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${P.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 l=Mf(e);if(!l)return n.push({level:"fail",label:`No ${Lf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${l.projectId}`});let p=(l.docsDir??Uf).replace(/\/+$/,"");n.push(l.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 ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let m=l.authoritativeSourceFiles??[];n.push(m.length>0?{level:"ok",label:`Sources: docs grounded in ${m.length} path(s) (${m.slice(0,3).join(", ")}${m.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 k=l.appType??Vf(e);if(k){let P=l.appType?"from config":"auto-detected",N=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${P})${N?` \u2192 ${Gf(k)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let g;try{g=Ff(e),n.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(P){return n.push({level:"fail",label:`Profile config: ${P.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let T=_f(g.name);T?ji(T)&&!T.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):ji(T)?n.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(T.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${g.name})`}),n.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let v=If(e,g.name);v?v.projectId&&g.project.projectId&&v.projectId!==g.project.projectId?n.push({level:"fail",label:`Category map projectId (${v.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(v.articles).length} articles, ${Object.keys(v.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),n.push(Af(El())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${El()}`,fix:"Reinstall document360-writer (broken install)"});let _=je(e);if(_.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ce})`}):_.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${_.completedVersion}, current is v${ce}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),T&&(!ji(T)||T.refreshToken)){let P={profile:g.name,connection:g.connection};try{await Nf(P);let D=await Ef(P,"/v3/projects");n.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${D.length} project(s) visible`})}catch(D){n.push({level:"fail",label:`API call failed: ${D.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=v?.projectId??g.project.projectId;if(N&&g.project.workspaceId)try{let D=await Wf(P,N,g.project.workspaceId);if(D){let M=(D.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${g.connection.name} (${D.languages?.length??0} language${(D.languages?.length??0)===1?"":"s"}) \xB7 hash ${M||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${g.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(D){D instanceof Yf||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(D.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??N})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${D.message.slice(0,80)})`})}}return n}function _l(e){let t=[""];for(let r of e){let i=r.level==="ok"?j("\u2713"):r.level==="warn"?L("\u26A0"):C("\u2717");t.push(` ${i} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${O(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?j(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):C(`\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 _l(await Il(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Eo=to(()=>{"use strict";Qe();W()});import{Command as uw}from"commander";import{createRequire as pw}from"node:module";import{AUTH_MODES as fw}from"document360-engine";import{input as tu}from"@inquirer/prompts";import{loginPkce as nu,refreshTokens as ou,toStoredTokens as ra,clearTokens as ru,decodeJwtClaims as oa,isExpired as iu,loadTokens as su,saveTokens as ia,resolveActiveProfile as io,setProfileProject as au,readProjectConfig as lu}from"document360-engine";W();import{select as Hd}from"@inquirer/prompts";import{resolveActiveProfile as qd,setProfileProject as Bd,resolveProjectId as Vd,listWorkspaces as Gd}from"document360-engine";async function mn(e,t){let n=qd(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Vd(o);return{workspaces:await Gd(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Zs=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Tr(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 no(e,t,n,o,r){Bd(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ea(e,t,n){let o;try{o=await mn(e,n)}catch(i){return console.log(C(`Could not list workspaces: ${i.message}`)),1}let r=Tr(o.workspaces,t);return r?(no(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(C(`No workspace matches "${t}". Available: ${o.workspaces.map(i=>i.name??i.id).join(", ")}`)),1)}async function Ht(e,t){let n;try{n=await mn(e,t)}catch(k){console.log(C(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:i,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?O("\u25CF"):" "} ${Zs(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Hd({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${Zs(k)}${k.id===l?" (current)":""}`,value:k.id}))}),m=o.find(k=>k.id===p);no(e,i,r,p,m?.name),console.log(j(`\u2713 Workspace set to "${m?.name??p}" for profile "${i}".`))}W();import{select as Yd}from"@inquirer/prompts";import{resolveActiveProfile as zd,setProfileProject as Kd,listProjects as Xd}from"document360-engine";async function Xe(e,t){let n=zd(e,t),o={profile:n.name,connection:n.connection};return{projects:await Xd(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ta=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Sr(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 oo(e,t,n,o){Kd(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function na(e,t,n){let o;try{o=await Xe(e,n)}catch(i){return console.log(C(`Could not list projects: ${i.message}`)),1}let r=Sr(o.projects,t);return r?(oo(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(C(`No project matches "${t}". Available: ${o.projects.map(i=>i.name??i.id).join(", ")}`)),1)}async function ro(e,t){let n;try{n=await Xe(e,t)}catch(m){console.log(C(`Could not list projects: ${m.message}`));return}let{projects:o,profile:r,current:i}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let m of o)console.log(` ${m.id===i?O("\u25CF"):" "} ${ta(m)} ${f(m.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let l=await Yd({message:"Select the Document360 project for this repo:",choices:o.map(m=>({name:`${ta(m)}${m.id===i?" (current)":""}`,value:m.id}))}),p=o.find(m=>m.id===l);oo(e,r,l,p?.name),console.log(j(`\u2713 Project set to "${p?.name??l}" for profile "${r}". Next: pick a workspace.`))}W();import Qd from"picocolors";function Jd(e=process.env){return e.FORCE_HYPERLINK==="0"||!Qd.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 Zd(e,t=e,n){return Jd(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var eu=/https?:\/\/[^\s\x1b]+/g;function gn(e,t){return e.replace(eu,n=>Zd(n,n,t))}function sa(e){return{...oa(e.idToken)??{},...oa(e.accessToken)??{}}}function so(e){let t=sa(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 ao(e){let t=io(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 nu(n,{manual:e.manual,promptForRedirect:i=>tu({message:i})},i=>console.log(gn(i))),r=ra(t.name,o);if(ia(r),await Dr(r,t.name,i=>console.log(f(i))),console.log(""),console.log(j(`\u2713 Logged in to "${t.name}" as ${so(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{lu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Ht(process.cwd(),t.name))}catch{}}async function Dr(e,t,n){let r=sa(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(io(process.cwd(),t).project.projectId)return;let l;try{let{projects:p}=await Xe(process.cwd(),t);l=p.find(m=>m.id===r)?.name}catch{}au(process.cwd(),t,{projectId:r,projectName:l}),n(` Project "${l??r}" written to profile "${t}".`)}catch{}}async function aa(e){let t=io(process.cwd(),e.profile),n=t.connection,o=su(t.name);if(!o){console.log(C(`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 ${O(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${so(o)}`),iu(o))if(o.refreshToken)try{let r=ra(t.name,await ou(n,o.refreshToken));ia(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 la(e){let t=io(process.cwd(),e.profile);ru(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 ca,writeProjectConfig as cu,resolveActiveProfile as du,loadTokens as uu,isExpired as pu}from"document360-engine";function lo(e){let t=ca(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(C("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?O("\u25CF "):" ",i=o.production?L(" \u26A0 PRODUCTION"):"",l=o.connection.environment??"(inline)",p=uu(n),m=p?pu(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${O(n)} \u2192 ${l}${i} [${m}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function co(e,t){let n=ca(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(C(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,cu(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(j(`\u2713 Default profile is now "${t}"${o}`))}function uo(e,t){try{let n=du(e,t);console.log(""),console.log(`Profile ${O(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(C(n.message)),process.exitCode=1}}W();import{existsSync as fu,readdirSync as hu,statSync as da}from"node:fs";import{join as ua}from"node:path";import{apiLogDir as mu}from"document360-engine";function pa(){let e=mu();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!fu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=hu(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let i=(da(ua(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${i} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let i=(da(ua(e,r)).size/1024).toFixed(1);console.log(` ${C(r)} ${f(`${i} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as gu,resolveAuth as wu,findByName as yu,slugify as ku,touchSession as bu,upsertSession as vu,resolveActiveProfile as $u}from"document360-engine";async function fa(e,t,n,o,r,i){let l=wu(n);l.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2)),l.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=$u(e,r)}catch(v){console.error(C(`Document360 profile error: ${v.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),i||(console.error(C("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let m;if(o){let v=yu(e,o);v||(console.error(C(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),m=v.uuid,console.error(f(`Resuming "${v.name}"`))}let k=gu({cwd:e,resume:m,profileName:r,allowProdWrites:i===!0}),g=m??null,T=1;for await(let v of k.send(t))switch(v.type){case"session":if(!g){g=v.sessionId;let _=new Date().toISOString();vu({uuid:g,name:ku(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:_,updatedAt:_})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(ae(` \u2699 ${v.name}`));break;case"result":T=v.ok?0:1,console.error(f(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(C("agent finished with an error result"));break;case"error":console.error(""),console.error(C(`agent error: ${v.message}`)),process.exit(1)}g&&bu(g),process.stdout.write(`
230
+ `),process.exit(T)}import{createInterface as km}from"node:readline/promises";import{createSession as ls,resolveAuth as bm,getSession as vm,setTitle as $m,slugify as xm,touchSession as Cc,upsertSession as Cm,generateTitle as Rm,resolveActiveProfile as Rc,resolveModelSetting as Pm,readProjectConfig as Tm,resolveAndPersistAppType as Sm,decodeJwtClaims as xc,isExpired as Dm,loadTokens as jm,isDirectiveMention as Am,stripDirectiveMention as Em,appendDirective as Nm,reconcileUpgradeActions as Im,stampArticles as _m,listArticleFiles as Om,CONTENT_CAP_VERSION as Lm}from"document360-engine";import{ENGINE_VERSION as Cu}from"document360-engine";var De=[{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:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/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:"/roadmap",s:"The docs campaign: progress + the next step."},{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:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"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:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function xu(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 ha(e){let n=[e?`document360-writer \u2014 help \xB7 v${e.version} \xB7 engine v${e.engineVersion}`:"document360-writer \u2014 help",""];for(let o of De){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(xu(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function jr(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:Cu}:void 0;for(let o of ha(n))console.log(o);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}W();import{getSession as Ru}from"document360-engine";async function ma(e,t){let n=t.currentUuid(),o=n?Ru(n):void 0;return console.log(o?f(`
231
231
  (conversation reset \u2014 "${o.name}" is still available via /resume)
232
232
  `):f(`
233
233
  (conversation reset \u2014 agent will start fresh on the next prompt)
234
- `)),{kind:"clear"}}async function Ar(){return{kind:"exit"}}yo();W();import{readMcpConfig as Lr,writeMcpConfig as Oa}from"document360-engine";async function ko(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Wu(),{kind:"continue"}):t==="add"?(Fu(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Hu(e.slice(1)),{kind:"continue"}):(console.log(C(`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 Wu(){let e=Lr(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
234
+ `)),{kind:"clear"}}async function Ar(){return{kind:"exit"}}yo();W();import{readMcpConfig as Lr,writeMcpConfig as Oa}from"document360-engine";async function ko(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Fu(),{kind:"continue"}):t==="add"?(Hu(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(qu(e.slice(1)),{kind:"continue"}):(console.log(C(`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 Fu(){let e=Lr(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
235
235
  No MCP servers registered. Add one with /mcp add <name> <type> <ref>
236
- `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${O(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),i=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${O(n)} ${f(`(${o.type})`)} ${o.url}${i}`)}}console.log("")}function Fu(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(C("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(C(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Lr(),i;if(n==="stdio")i={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 m=o[++p],k=m?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(C(`-H expects key:value (no spaces). Got: ${m??"(nothing)"}`));return}l[k[1].trim()]=k[2].trim()}else{console.log(C(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}i={type:n,url:o[0],headers:Object.keys(l).length>0?l:void 0}}r.servers[t]=i,Oa(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 Hu(e){let t=e[0];if(!t){console.log(C("Usage: /mcp remove <name>"));return}let n=Lr();if(!n.servers[t]){console.log(C(`No server named "${t}".`));return}delete n.servers[t],Oa(n),console.log(j(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as op}from"node:fs";import{join as rp}from"node:path";import{select as ip}from"@inquirer/prompts";import{computeSyncStatus as bo,planPartitions as sp,relatedArticlePaths as ap,resolveModelForOperation as lp,runPartitioned as cp,loadProfileMap as dp,resolveActiveProfile as up,resolveCrossLinks as pp,applyStructureOrder as Ga,orderSyncLine as Ya,applyRelatedArticles as za,relatedSyncLine as Ka}from"document360-engine";import Q from"picocolors";import Ha from"wrap-ansi";import qr from"string-width";W();import Je from"picocolors";import Mr from"wrap-ansi";import Ur from"string-width";var La=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Ma=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Ua=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function qu(e){let t=e.replace(/\r/g,"").split(`
237
- `),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(La(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Ma(t[o+1])){let p=Ua(r);o+=2;let m=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)m.push(Ua(t[o++]));n.push({kind:"table",header:p,rows:m});continue}let i=r.match(/^(#{1,6})\s+(.*)$/);if(i){n.push({kind:"heading",level:i[1].length,text:i[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let m=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(m),text:m.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])&&!La(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Ma(t[o+1]));)l.push(t[o++]);n.push({kind:"para",text:l.join(" ")})}return n}function Wr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Je.bold(t.slice(2,-2)):t.startsWith("`")?O(t.slice(1,-1)):Je.italic(t.slice(1,-1)))}var Bu=(e,t)=>e+" ".repeat(Math.max(0,t-Ur(e)));function Vu(e,t,n){let o=e.length,r=e.map((P,N)=>Math.max(Ur(P),...t.map(D=>Ur(D[N]??"")))),i=Math.max(24,n),l=3*o+1,p=[...r],m=()=>p.reduce((P,N)=>P+N,0)+l,k=0;for(;m()>i&&k++<1e4;){let P=-1,N=6;for(let D=0;D<o;D++)p[D]>N&&(N=p[D],P=D);if(P===-1)break;p[P]-=1}let g=(P,N,D)=>Je.gray(P+p.map(M=>"\u2500".repeat(M+2)).join(N)+D),T=Je.gray("\u2502"),v=(P,N)=>{let D=p.map((ee,X)=>{let ne=P[X]??"",Be=N?Je.bold(ne):Wr(ne);return Mr(Be,ee,{hard:!0}).split(`
238
- `)}),M=Math.max(...D.map(ee=>ee.length)),B=[];for(let ee=0;ee<M;ee++)B.push(p.map((X,ne)=>`${T} ${Bu(D[ne][ee]??"",X)} `).join("")+T);return B.join(`
236
+ `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${O(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),i=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${O(n)} ${f(`(${o.type})`)} ${o.url}${i}`)}}console.log("")}function Hu(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(C("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(C(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Lr(),i;if(n==="stdio")i={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 m=o[++p],k=m?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(C(`-H expects key:value (no spaces). Got: ${m??"(nothing)"}`));return}l[k[1].trim()]=k[2].trim()}else{console.log(C(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}i={type:n,url:o[0],headers:Object.keys(l).length>0?l:void 0}}r.servers[t]=i,Oa(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 qu(e){let t=e[0];if(!t){console.log(C("Usage: /mcp remove <name>"));return}let n=Lr();if(!n.servers[t]){console.log(C(`No server named "${t}".`));return}delete n.servers[t],Oa(n),console.log(j(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as rp}from"node:fs";import{join as ip}from"node:path";import{select as sp}from"@inquirer/prompts";import{computeSyncStatus as bo,planPartitions as ap,relatedArticlePaths as lp,resolveModelForOperation as cp,runPartitioned as dp,loadProfileMap as up,resolveActiveProfile as pp,resolveCrossLinks as fp,applyStructureOrder as Ga,orderSyncLine as Ya,applyRelatedArticles as za,relatedSyncLine as Ka}from"document360-engine";import Q from"picocolors";import Ha from"wrap-ansi";import qr from"string-width";W();import Je from"picocolors";import Mr from"wrap-ansi";import Ur from"string-width";var La=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Ma=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Ua=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Bu(e){let t=e.replace(/\r/g,"").split(`
237
+ `),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(La(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Ma(t[o+1])){let p=Ua(r);o+=2;let m=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)m.push(Ua(t[o++]));n.push({kind:"table",header:p,rows:m});continue}let i=r.match(/^(#{1,6})\s+(.*)$/);if(i){n.push({kind:"heading",level:i[1].length,text:i[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let m=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(m),text:m.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])&&!La(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Ma(t[o+1]));)l.push(t[o++]);n.push({kind:"para",text:l.join(" ")})}return n}function Wr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Je.bold(t.slice(2,-2)):t.startsWith("`")?O(t.slice(1,-1)):Je.italic(t.slice(1,-1)))}var Vu=(e,t)=>e+" ".repeat(Math.max(0,t-Ur(e)));function Gu(e,t,n){let o=e.length,r=e.map((P,N)=>Math.max(Ur(P),...t.map(D=>Ur(D[N]??"")))),i=Math.max(24,n),l=3*o+1,p=[...r],m=()=>p.reduce((P,N)=>P+N,0)+l,k=0;for(;m()>i&&k++<1e4;){let P=-1,N=6;for(let D=0;D<o;D++)p[D]>N&&(N=p[D],P=D);if(P===-1)break;p[P]-=1}let g=(P,N,D)=>Je.gray(P+p.map(M=>"\u2500".repeat(M+2)).join(N)+D),T=Je.gray("\u2502"),v=(P,N)=>{let D=p.map((ee,X)=>{let te=P[X]??"",Pe=N?Je.bold(te):Wr(te);return Mr(Pe,ee,{hard:!0}).split(`
238
+ `)}),M=Math.max(...D.map(ee=>ee.length)),B=[];for(let ee=0;ee<M;ee++)B.push(p.map((X,te)=>`${T} ${Vu(D[te][ee]??"",X)} `).join("")+T);return B.join(`
239
239
  `)},_=[g("\u250C","\u252C","\u2510"),v(e,!0)];return _.push(t.length===0?g("\u2514","\u2534","\u2518"):g("\u251C","\u253C","\u2524")),t.forEach((P,N)=>{_.push(v(P,!1)),_.push(N===t.length-1?g("\u2514","\u2534","\u2518"):g("\u251C","\u253C","\u2524"))}),_.join(`
240
- `)}function Gu(e,t){switch(e.kind){case"heading":return Je.bold(e.text);case"hr":return Je.gray("\u2500".repeat(t));case"para":return Mr(Wr(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",i=" ".repeat(2+r.length+1),[l="",...p]=Mr(Wr(o.text),Math.max(10,t-i.length)).split(`
240
+ `)}function Yu(e,t){switch(e.kind){case"heading":return Je.bold(e.text);case"hr":return Je.gray("\u2500".repeat(t));case"para":return Mr(Wr(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",i=" ".repeat(2+r.length+1),[l="",...p]=Mr(Wr(o.text),Math.max(10,t-i.length)).split(`
241
241
  `);return` ${r} ${l}`+p.map(m=>`
242
242
  ${i}${m}`).join("")}).join(`
243
243
  `)}case"code":return e.lines.map(n=>Je.gray(" "+n)).join(`
244
- `);case"table":return Vu(e.header,e.rows,t)}}function Fr(e,t){let n=Math.max(20,t);return qu(e).map(o=>Gu(o,n)).join(`
244
+ `);case"table":return Gu(e.header,e.rows,t)}}function Fr(e,t){let n=Math.max(20,t);return Bu(e).map(o=>Yu(o,n)).join(`
245
245
 
246
- `)}W();import Yu from"picocolors";var zu=[127,86,217],Ku=[22,38,43],Wa={T:zu,E:Ku},yn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Hr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Xu=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Fa(){if(!Yu.isColorSupported)return[];let e=yn[0].length,t=[];for(let n=0;n<yn.length;n+=2){let o="";for(let r=0;r<e;r++){let i=Wa[yn[n][r]],l=n+1<yn.length?Wa[yn[n+1][r]]:void 0;i&&l?o+=`${Hr(i)}${Xu(l)}\u2580\x1B[49m\x1B[39m`:i?o+=`${Hr(i)}\u2580\x1B[39m`:l?o+=`${Hr(l)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function kn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function we(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Ze(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var zt=(e,t)=>` ${e.padEnd(13)}${t}`;function Qu(e,t){let n=[hn("\u270E document360-writer")+Q.gray(` v${e.version} \xB7 engine v${e.engineVersion}`),Q.gray(" Reads your code, writes your docs."),"",zt("Claude:",`${e.claude}${Q.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),zt("Document360:",e.configured?e.loggedOut?Q.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?Q.gray(` (${e.sessionHint})`):""}`:Q.yellow("not set up \u2014 run /init")),zt("Profile:",e.configured?`${e.profile}${Q.gray(` (${e.apiUrl})`)}${e.prod?Q.bold(Q.yellow(" \u26A0 PRODUCTION")):""}`:Q.gray("\u2014 (run /init)")),zt("Project:",e.project),zt("Mode:",Q.gray(e.mode)),zt("cwd:",Q.gray(e.cwd))],o=Fa();if(o.length===0)return n.join(`
246
+ `)}W();import zu from"picocolors";var Ku=[127,86,217],Xu=[22,38,43],Wa={T:Ku,E:Xu},yn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Hr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Qu=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Fa(){if(!zu.isColorSupported)return[];let e=yn[0].length,t=[];for(let n=0;n<yn.length;n+=2){let o="";for(let r=0;r<e;r++){let i=Wa[yn[n][r]],l=n+1<yn.length?Wa[yn[n+1][r]]:void 0;i&&l?o+=`${Hr(i)}${Qu(l)}\u2580\x1B[49m\x1B[39m`:i?o+=`${Hr(i)}\u2580\x1B[39m`:l?o+=`${Hr(l)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function kn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function we(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Ze(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var zt=(e,t)=>` ${e.padEnd(13)}${t}`;function Ju(e,t){let n=[hn("\u270E document360-writer")+Q.gray(` v${e.version} \xB7 engine v${e.engineVersion}`),Q.gray(" Reads your code, writes your docs."),"",zt("Claude:",`${e.claude}${Q.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),zt("Document360:",e.configured?e.loggedOut?Q.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?Q.gray(` (${e.sessionHint})`):""}`:Q.yellow("not set up \u2014 run /init")),zt("Profile:",e.configured?`${e.profile}${Q.gray(` (${e.apiUrl})`)}${e.prod?Q.bold(Q.yellow(" \u26A0 PRODUCTION")):""}`:Q.gray("\u2014 (run /init)")),zt("Project:",e.project),zt("Mode:",Q.gray(e.mode)),zt("cwd:",Q.gray(e.cwd))],o=Fa();if(o.length===0)return n.join(`
247
247
  `);let r=2,i=3,l=qr(o[0]);if(!(t>=r+l+i+Math.max(...n.map(g=>qr(g)))))return[...o.map(g=>" "+g),...n].join(`
248
248
  `);let m=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let g=0;g<Math.max(o.length+m,n.length);g++){let T=o[g-m]??" ".repeat(l);k.push((" ".repeat(r)+T+" ".repeat(i)+(n[g]??"")).trimEnd())}return k.join(`
249
- `)}var Ju={error:Q.red,warn:Q.yellow,ok:Q.green,info:Q.gray};function Br(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Qu(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",i=Math.max(10,n-4),l=50,p=e.text.split(`
249
+ `)}var Zu={error:Q.red,warn:Q.yellow,ok:Q.green,info:Q.gray};function Br(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Ju(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",i=Math.max(10,n-4),l=50,p=e.text.split(`
250
250
  `).flatMap(k=>Ha(k,i,{hard:!0}).split(`
251
251
  `)),m=Math.max(0,p.length-l);return m>0&&(p=[...p.slice(0,l),Q.dim(`\u2026 +${m} more lines`)]),`
252
252
  `+p.map((k,g)=>o+(g===0?O(" \u276F "):" ")+k+" ".repeat(Math.max(0,i-qr(k))+1)+r).join(`
@@ -259,22 +259,22 @@ ${i}${m}`).join("")}).join(`
259
259
  `+hn(`\u25A3 Preview \u2014 ${e.name}`)+`
260
260
 
261
261
  `+Fr(e.text,n);case"note":return`
262
- `+Ju[e.tone](gn(e.text));case"done":return`
262
+ `+Zu[e.tone](gn(e.text));case"done":return`
263
263
  `+(e.ok?Q.magenta("\u2736 "):Q.red("\u2736 "))+Q.gray(`Cooked for ${kn(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${we(e.costUsd)}`:""))}}function qa(e,t){return e.map(n=>Br(n,t)).join(`
264
- `)}import{resolveActiveProfile as Zu,loadTokens as ep,isExpired as tp,decodeJwtClaims as Ba}from"document360-engine";function np(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function je(e,t){try{let n=Zu(e,t),o=ep(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(tp(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={...Ba(o.idToken)??{},...Ba(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 ${np(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var bn=3;function Vr(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(`
265
- `)}var Va={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Gr(e){return e.filter(t=>t.path!==null&&t.status in Va&&!t.link).map(t=>({path:t.path,label:Va[t.status]}))}function vo(e){let t=Gr(e),n=new Set(e.filter(o=>o.status==="conflict"&&o.path).map(o=>o.path));return{clean:t.filter(o=>!n.has(o.path)),conflicts:t.filter(o=>n.has(o.path))}}function $o(e){return`\u26A0 ${e} conflict${e===1?"":"s"} skipped \u2014 edited both here and on the portal, so publishing would overwrite the portal edit. Resolve them: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's).`}function xo(e){return e.filter(t=>t.link).length}function Yr(e,t){try{let n=dp(e,up(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=pp(op(rp(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 fp(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 Xa(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let i=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),l=o.get(i);l?l.push(r):o.set(i,[r])}for(let r of[...o.keys()].sort()){let i=o.get(r).sort((l,p)=>l.path.localeCompare(p.path));n.push({kind:"category",label:`${fp(r)} (${i.length})`,paths:i.map(l=>l.path),indent:!1});for(let l of i){let p=l.path.replace(/\\/g,"/").split("/").pop()??l.path;n.push({kind:"article",label:p,paths:[l.path],indent:!0,note:l.label})}}for(let r of[...t].sort((i,l)=>i.path.localeCompare(l.path))){let i=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:i,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function Co(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(`
266
- `)}function zr(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),i=e.filter(v=>!v.ok),l=e.reduce((v,_)=>v+o(_),0),p=r.reduce((v,_)=>v+o(_),0),m=n==="api"?`${we(e.reduce((v,_)=>v+_.costUsd,0))} total`:Ze(e.reduce((v,_)=>v+_.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,g=v=>`${v} article${v===1?"":"s"}`,T=[];if(i.length===0)T.push(`Published ${g(l)} (${k}) successfully \xB7 ${m}.`),T.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{T.push(`Published ${p}/${g(l)} (${k}) \xB7 ${m}.`),T.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let v of i)T.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return T}async function wt(e,t){let{model:n}=lp(e.cwd,"standard"),o=async(r,i)=>{let l=sp(r);console.log(f(i?`Resolving cross-links in ${r.length} article${r.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${r.length} article${r.length===1?"":"s"} across ${l.length} partition${l.length===1?"":"s"} (\u2264${bn} agents at once) on ${n}\u2026`)),i||console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let p=!1;for await(let m of cp({cwd:e.cwd,partitions:l,promptFor:k=>Co(k.paths),concurrency:bn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(m.type==="partition_status")m.status==="running"?console.log(f(` \u25B8 ${m.label} \u2014 publishing\u2026`)):m.status==="done"?console.log(j(` \u2713 ${m.label}`)):console.log(C(` \u2717 ${m.label}`));else if(m.type==="run_done"){p=m.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let T of zr(m.results,l,k))console.log(m.ok?j(T):L(T));let g=Yr(e.cwd,e.profileName);g&&console.log(f(g));try{let T=Ya(await Ga({cwd:e.cwd,profileName:e.profileName}));T&&console.log(f(T))}catch{}try{let T=Ka(await za({cwd:e.cwd,profileName:e.profileName}));T&&console.log(f(T))}catch{}}return p};try{if(!await o(t,!1)){let i=await Kr(e.cwd,e.profileName,t);i.length>0&&await o(i,!0)}}catch(r){console.log(C(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Ro(e,t,n){let o=ap(e,n);if(o.length===0)return[];let r=new Set(Gr((await bo({cwd:e,profileName:t})).entries).map(i=>i.path));return o.filter(i=>r.has(i))}async function Kr(e,t,n){try{let o=new Set(n),r=await bo({cwd:e,profileName:t});return Gr(r.entries).map(i=>i.path).filter(i=>o.has(i))}catch{return[]}}async function Qa(e,t){let n=je(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Ro(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 wt(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await bo({cwd:t?.cwd??process.cwd()}),{clean:i,conflicts:l}=vo(r.entries),p=xo(r.entries),m=e.includes("--force")&&l.length>0;p>0&&console.log(L(`\u26A0 ${p} 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.`)),l.length>0&&!m&&console.log(L($o(l.length)));let k=m?[...i,...l]:i;if(k.length===0){if(l.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(j(p>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let g=Ya(await Ga({cwd:t.cwd,profileName:t.profileName}));g&&console.log(f(g));let T=Ka(await za({cwd:t.cwd,profileName:t.profileName}));T&&console.log(f(T))}catch{}return{kind:"continue"}}return t?await wt(t,k.map(g=>g.path)):{kind:"forward-to-agent",prompt:Co(k.map(g=>g.path)),display:"/publish --all"}}catch(r){return console.log(C(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let i=await bo({cwd:t?.cwd??process.cwd()}),{clean:l,conflicts:p}=vo(i.entries);r=l;let m=xo(i.entries);if(m>0&&console.log(L(`\u26A0 ${m} 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.`)),p.length>0&&console.log(L($o(p.length))),r.length===0&&p.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(i){return console.log(C(`Could not compute sync status: ${i.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 i of r)console.log(` ${i.path} ${f(`(${i.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>ip({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(i=>({name:i.path,value:i.path,description:i.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await wt(t,r.map(i=>i.path))}return{kind:"forward-to-agent",prompt:Vr(o),display:`/publish ${o}`}}async function vn(){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(`
267
- `),display:"/audit"}}W();import{readProjectConfig as hp}from"document360-engine";function Xr(){return["Run the discover-product skill against this repo.","","Build (or continue refining) the product brief at `.d360-writer/product-brief.md` by interviewing the","source repo's coding agent (the builder):","1. Gather all grounding \u2014 the code surface (analyze-codebase pass), `.d360-writer/architecture/`"," (+ CREATOR-NOTES), any specs under `.d360-writer/input/`, existing docs, git log, and the current"," product brief if one exists.","2. Self-assess against the 8-point readiness rubric (identity, audience, core mental model,"," misconceptions, positioning, key concepts & terminology, critical journeys, boundaries/non-goals).","3. Write/update the brief \u2014 every claim cited to its grounding \u2014 and keep its frontmatter current"," (status, rounds, open_questions, last_updated).","4. For the dimensions you cannot yet ground confidently, ask the builder a focused batch (\u22646) of pointed",' questions via d360_ask_builder, with the subject prefixed "[discovery] ". Then END the turn \u2014 the'," builder answers async; /catch-up will ingest the answers and continue the loop.","","Set status: confident and hand off to propose-structure ONLY when every rubric dimension passes. If the","builder stays silent across a few rounds, degrade gracefully per the skill (best-effort brief, flagged","open questions) rather than blocking the docs. Do NOT write or publish any articles in this turn."].join(`
268
- `)}async function Ja(e,t){let n=t?.cwd??process.cwd();return hp(n)?{kind:"forward-to-agent",prompt:Xr(),display:"/discover"}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{checkbox as mp}from"@inquirer/prompts";import{inventoryRepo as gp,readProjectConfig as Za,writeProjectConfig as wp}from"document360-engine";function Qr(e,t){let n=Za(e);n&&(n.authoritativeSourceFiles=t,wp(n,e))}function Po(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 el(e,t){let n=t?.cwd??process.cwd();if(!Za(n))return console.log(C("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=gp(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(O("Recommended documentation scope (run /scope in the REPL to choose):"));for(let i of o)console.log(` ${i.recommended?"\u25C9":"\u25CB"} ${i.path} ${f(Po(i))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>mp({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(i=>({name:`${i.path} (${Po(i)})`,value:i.path,checked:i.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"};Qr(n,r),console.log(j(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let i of r)console.log(` ${i}`);return console.log(""),{kind:"continue"}}W();import{confirm as Tp}from"@inquirer/prompts";import{applyPull as ei,computeSyncStatus as al,compareRemoteSources as Sp,planPull as ll,planImport as Dp,applyImport as jp,establishBaselines as Ap,rebaselineServerMeta as Ep,D360AuthError as Np}from"document360-engine";W();var tl=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:C,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:O,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:C,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:C,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ae,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:ae,mark:"\xB7"}];function yp(e){return e.path?e.path:`${e.title??"(untitled)"} ${ae(`[${e.articleId}]`)}`}function kp(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(g=>g.link);if(o.length>0){n.push(""),n.push(ge("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let g of o)n.push(` ${L("~")} ${L(g.path??"")} ${ae(`\u2192 "${g.link.title}"`)}`)}for(let g of tl){let T=e.entries.filter(v=>v.status===g.status&&!(g.status==="untracked-local"&&v.link));if(T.length!==0){n.push(""),n.push(ge(g.header));for(let v of T)n.push(` ${g.paint(g.mark)} ${g.paint(yp(v))}${v.detail?ae(` (${v.detail})`):""}`)}}let r=e.counts["in-sync"]??0,i=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,m=i===r?j("\u2713 everything up to date"):[r>0?j(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...tl.map(g=>{let T=(e.counts[g.status]??0)-(g.status==="untracked-local"?p:0);return T>0?`${T} ${l[g.status]}`:null})].filter(Boolean).join(ae(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${kp(t)}`:"";return n.push(m+ae(` \xB7 ${i} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as bp}from"diff";import nl from"picocolors";var ol=80,vp="\x1B[48;2;74;28;28m",$p="\x1B[48;2;24;66;24m",rl="\x1B[49m",Jr=e=>String(e).padStart(5);function He(e,t,n){let o=v=>{let _=v.replace(/\r\n/g,`
264
+ `)}import{resolveActiveProfile as ep,loadTokens as tp,isExpired as np,decodeJwtClaims as Ba}from"document360-engine";function op(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ae(e,t){try{let n=ep(e,t),o=tp(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(np(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={...Ba(o.idToken)??{},...Ba(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 ${op(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var bn=3;function Vr(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(`
265
+ `)}var Va={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Gr(e){return e.filter(t=>t.path!==null&&t.status in Va&&!t.link).map(t=>({path:t.path,label:Va[t.status]}))}function vo(e){let t=Gr(e),n=new Set(e.filter(o=>o.status==="conflict"&&o.path).map(o=>o.path));return{clean:t.filter(o=>!n.has(o.path)),conflicts:t.filter(o=>n.has(o.path))}}function $o(e){return`\u26A0 ${e} conflict${e===1?"":"s"} skipped \u2014 edited both here and on the portal, so publishing would overwrite the portal edit. Resolve them: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's).`}function xo(e){return e.filter(t=>t.link).length}function Yr(e,t){try{let n=up(e,pp(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=fp(rp(ip(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 hp(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 Xa(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let i=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),l=o.get(i);l?l.push(r):o.set(i,[r])}for(let r of[...o.keys()].sort()){let i=o.get(r).sort((l,p)=>l.path.localeCompare(p.path));n.push({kind:"category",label:`${hp(r)} (${i.length})`,paths:i.map(l=>l.path),indent:!1});for(let l of i){let p=l.path.replace(/\\/g,"/").split("/").pop()??l.path;n.push({kind:"article",label:p,paths:[l.path],indent:!0,note:l.label})}}for(let r of[...t].sort((i,l)=>i.path.localeCompare(l.path))){let i=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:i,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function Co(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(`
266
+ `)}function zr(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),i=e.filter(v=>!v.ok),l=e.reduce((v,_)=>v+o(_),0),p=r.reduce((v,_)=>v+o(_),0),m=n==="api"?`${we(e.reduce((v,_)=>v+_.costUsd,0))} total`:Ze(e.reduce((v,_)=>v+_.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,g=v=>`${v} article${v===1?"":"s"}`,T=[];if(i.length===0)T.push(`Published ${g(l)} (${k}) successfully \xB7 ${m}.`),T.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{T.push(`Published ${p}/${g(l)} (${k}) \xB7 ${m}.`),T.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let v of i)T.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return T}async function wt(e,t){let{model:n}=cp(e.cwd,"standard"),o=async(r,i)=>{let l=ap(r);console.log(f(i?`Resolving cross-links in ${r.length} article${r.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${r.length} article${r.length===1?"":"s"} across ${l.length} partition${l.length===1?"":"s"} (\u2264${bn} agents at once) on ${n}\u2026`)),i||console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let p=!1;for await(let m of dp({cwd:e.cwd,partitions:l,promptFor:k=>Co(k.paths),concurrency:bn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(m.type==="partition_status")m.status==="running"?console.log(f(` \u25B8 ${m.label} \u2014 publishing\u2026`)):m.status==="done"?console.log(j(` \u2713 ${m.label}`)):console.log(C(` \u2717 ${m.label}`));else if(m.type==="run_done"){p=m.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let T of zr(m.results,l,k))console.log(m.ok?j(T):L(T));let g=Yr(e.cwd,e.profileName);g&&console.log(f(g));try{let T=Ya(await Ga({cwd:e.cwd,profileName:e.profileName}));T&&console.log(f(T))}catch{}try{let T=Ka(await za({cwd:e.cwd,profileName:e.profileName}));T&&console.log(f(T))}catch{}}return p};try{if(!await o(t,!1)){let i=await Kr(e.cwd,e.profileName,t);i.length>0&&await o(i,!0)}}catch(r){console.log(C(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Ro(e,t,n){let o=lp(e,n);if(o.length===0)return[];let r=new Set(Gr((await bo({cwd:e,profileName:t})).entries).map(i=>i.path));return o.filter(i=>r.has(i))}async function Kr(e,t,n){try{let o=new Set(n),r=await bo({cwd:e,profileName:t});return Gr(r.entries).map(i=>i.path).filter(i=>o.has(i))}catch{return[]}}async function Qa(e,t){let n=Ae(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Ro(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 wt(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await bo({cwd:t?.cwd??process.cwd()}),{clean:i,conflicts:l}=vo(r.entries),p=xo(r.entries),m=e.includes("--force")&&l.length>0;p>0&&console.log(L(`\u26A0 ${p} 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.`)),l.length>0&&!m&&console.log(L($o(l.length)));let k=m?[...i,...l]:i;if(k.length===0){if(l.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(j(p>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let g=Ya(await Ga({cwd:t.cwd,profileName:t.profileName}));g&&console.log(f(g));let T=Ka(await za({cwd:t.cwd,profileName:t.profileName}));T&&console.log(f(T))}catch{}return{kind:"continue"}}return t?await wt(t,k.map(g=>g.path)):{kind:"forward-to-agent",prompt:Co(k.map(g=>g.path)),display:"/publish --all"}}catch(r){return console.log(C(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let i=await bo({cwd:t?.cwd??process.cwd()}),{clean:l,conflicts:p}=vo(i.entries);r=l;let m=xo(i.entries);if(m>0&&console.log(L(`\u26A0 ${m} 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.`)),p.length>0&&console.log(L($o(p.length))),r.length===0&&p.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(i){return console.log(C(`Could not compute sync status: ${i.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 i of r)console.log(` ${i.path} ${f(`(${i.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>sp({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(i=>({name:i.path,value:i.path,description:i.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await wt(t,r.map(i=>i.path))}return{kind:"forward-to-agent",prompt:Vr(o),display:`/publish ${o}`}}async function vn(){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(`
267
+ `),display:"/audit"}}W();import{readProjectConfig as mp}from"document360-engine";function Xr(){return["Run the discover-product skill against this repo.","","Build (or continue refining) the product brief at `.d360-writer/product-brief.md` by interviewing the","source repo's coding agent (the builder):","1. Gather all grounding \u2014 the code surface (analyze-codebase pass), `.d360-writer/architecture/`"," (+ CREATOR-NOTES), any specs under `.d360-writer/input/`, existing docs, git log, and the current"," product brief if one exists.","2. Self-assess against the 8-point readiness rubric (identity, audience, core mental model,"," misconceptions, positioning, key concepts & terminology, critical journeys, boundaries/non-goals).","3. Write/update the brief \u2014 every claim cited to its grounding \u2014 and keep its frontmatter current"," (status, rounds, open_questions, last_updated).","4. For the dimensions you cannot yet ground confidently, ask the builder a focused batch (\u22646) of pointed",' questions via d360_ask_builder, with the subject prefixed "[discovery] ". Then END the turn \u2014 the'," builder answers async; /catch-up will ingest the answers and continue the loop.","","Set status: confident and hand off to propose-structure ONLY when every rubric dimension passes. If the","builder stays silent across a few rounds, degrade gracefully per the skill (best-effort brief, flagged","open questions) rather than blocking the docs. Do NOT write or publish any articles in this turn."].join(`
268
+ `)}async function Ja(e,t){let n=t?.cwd??process.cwd();return mp(n)?{kind:"forward-to-agent",prompt:Xr(),display:"/discover"}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{checkbox as gp}from"@inquirer/prompts";import{inventoryRepo as wp,readProjectConfig as Za,writeProjectConfig as yp}from"document360-engine";function Qr(e,t){let n=Za(e);n&&(n.authoritativeSourceFiles=t,yp(n,e))}function Po(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 el(e,t){let n=t?.cwd??process.cwd();if(!Za(n))return console.log(C("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=wp(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(O("Recommended documentation scope (run /scope in the REPL to choose):"));for(let i of o)console.log(` ${i.recommended?"\u25C9":"\u25CB"} ${i.path} ${f(Po(i))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>gp({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(i=>({name:`${i.path} (${Po(i)})`,value:i.path,checked:i.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"};Qr(n,r),console.log(j(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let i of r)console.log(` ${i}`);return console.log(""),{kind:"continue"}}W();import{confirm as Sp}from"@inquirer/prompts";import{applyPull as ei,computeSyncStatus as al,compareRemoteSources as Dp,planPull as ll,planImport as jp,applyImport as Ap,establishBaselines as Ep,rebaselineServerMeta as Np,D360AuthError as Ip}from"document360-engine";W();var tl=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:C,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:O,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:C,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:C,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ae,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:ae,mark:"\xB7"}];function kp(e){return e.path?e.path:`${e.title??"(untitled)"} ${ae(`[${e.articleId}]`)}`}function bp(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(g=>g.link);if(o.length>0){n.push(""),n.push(ge("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let g of o)n.push(` ${L("~")} ${L(g.path??"")} ${ae(`\u2192 "${g.link.title}"`)}`)}for(let g of tl){let T=e.entries.filter(v=>v.status===g.status&&!(g.status==="untracked-local"&&v.link));if(T.length!==0){n.push(""),n.push(ge(g.header));for(let v of T)n.push(` ${g.paint(g.mark)} ${g.paint(kp(v))}${v.detail?ae(` (${v.detail})`):""}`)}}let r=e.counts["in-sync"]??0,i=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,m=i===r?j("\u2713 everything up to date"):[r>0?j(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...tl.map(g=>{let T=(e.counts[g.status]??0)-(g.status==="untracked-local"?p:0);return T>0?`${T} ${l[g.status]}`:null})].filter(Boolean).join(ae(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${bp(t)}`:"";return n.push(m+ae(` \xB7 ${i} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as vp}from"diff";import nl from"picocolors";var ol=80,$p="\x1B[48;2;74;28;28m",xp="\x1B[48;2;24;66;24m",rl="\x1B[49m",Jr=e=>String(e).padStart(5);function qe(e,t,n){let o=v=>{let _=v.replace(/\r\n/g,`
269
269
  `);return _.endsWith(`
270
270
  `)||_===""?_:_+`
271
- `},r=o(e),i=o(t);if(r===i)return null;let l=Math.max(20,n-10),p=bp("a","b",r,i,"","",{context:3}),m=0,k=0,g=[];p.hunks.forEach((v,_)=>{_>0&&g.push(nl.gray(" \u2026"));let P=v.oldStart,N=v.newStart;for(let D of v.lines){let M=D[0],B=D.slice(1).slice(0,l);M==="-"?(k++,g.push(`${vp}${Jr(P++)} - ${B}${rl}`)):M==="+"?(m++,g.push(`${$p}${Jr(N++)} + ${B}${rl}`)):(g.push(nl.gray(Jr(N))+" "+B),P++,N++)}});let T=g.slice(0,ol);return{added:m,removed:k,lines:T,hidden:Math.max(0,g.length-ol)}}W();import{select as xp}from"@inquirer/prompts";import{applyPull as Cp,computeSyncStatus as Rp,planPull as Pp}from"document360-engine";var il=e=>e===1?"":"s";async function Zr(e,t){console.log(""),console.log(`${O("\u25CF")} ${ge(t.title)} ${ae(`(${t.path})`)}`);for(let r of t.notes)console.log(L(` \u26A0 ${r}`));let n=He(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(ae(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${il(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(f(` \u2026 +${n.hidden} more diff lines`))}else console.log(f(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>xp({message:`Conflict \u2014 ${t.path}`,choices:[{name:"Keep local (publish \u2014 overwrites the portal edit)",value:"local"},{name:"Take portal (overwrites your local edits)",value:"portal"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip");return o==="portal"?(Cp({cwd:e.cwd,profileName:e.profileName},t),console.log(j(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(f(" Skipped \u2014 still a conflict.")),"skipped")}async function sl(e,t){let n=je(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let i=(await Rp({cwd:t.cwd,profileName:t.profileName})).entries.filter(p=>p.status==="conflict"&&p.path).map(p=>p.path);if(o){if(!i.includes(o))return console.log(j(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};i=[o]}if(i.length===0)return console.log(j("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let l=[];for(let p of i){let m=await Pp({cwd:t.cwd,profileName:t.profileName,relPath:p});await Zr(t,m)==="keep-local"&&l.push(p)}if(l.length>0)return console.log(f(`Publishing ${l.length} kept-local article${il(l.length)} over the portal\u2026`)),await wt(t,l)}catch(r){console.log(C(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function cl(e,t){let n=je(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Ip(t),{kind:"continue"};if(o==="--baseline")return await _p(t,e.filter(l=>l!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Op(t),{kind:"continue"};if(o)return console.log(C(`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 Lp(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let i=await ti({cwd:t.cwd,profileName:t.profileName});for(let l of ni(i))console.log(l.tone==="ok"?j(l.text):l.tone==="warn"?L(l.text):f(l.text));console.log("")}catch(r){r instanceof Np?console.log(C(r.message)):console.log(C(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function ti(e){let t=await al({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 ll({cwd:e.cwd,profileName:e.profileName,relPath:o.path});ei({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 Dp({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});jp({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 So=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,yt=e=>e===1?"":"s";function ni(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${yt(e.pulled.length)} into local: ${So(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${yt(e.imported.length)}: ${So(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${yt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${yt(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's). (${So(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${yt(e.failed.length)} failed: ${So(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 Ip(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await al({cwd:e.cwd,profileName:e.profileName});for(let o of To(n,Date.now()-t))console.log(o);console.log("")}async function _p(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 Ap({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Ep({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 i of o.skipped)console.log(f(` - ${i.path} (${i.reason})`))}}async function Op(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Sp({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${ge(String(t.legacyCount))} \xB7 Manifest: ${ge(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(C(`\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 Lp(e,t){let n=t.replace(/\\/g,"/"),o=await ll({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Zr(e,o)==="keep-local"&&(console.log(f(`Publishing ${o.path} over the portal\u2026`)),await wt(e,[o.path]));return}console.log(""),console.log(`${O("\u25CF")} ${ge(o.title)} ${ae(`(${o.path})`)}`);for(let l of o.notes)console.log(L(` \u26A0 ${l}`));let r=He(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.")),ei({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ae(` \u23BF Added ${r.added} line${yt(r.added)}, removed ${r.removed} line${yt(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(()=>Tp({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}ei({cwd:e.cwd,profileName:e.profileName},o),console.log(j(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as Mp}from"node:fs";import{resolve as Up}from"node:path";import{estimateBulkCost as Wp,planPartitions as Fp,readProjectConfig as Hp,resolveModelForOperation as qp,runPartitioned as Bp,trackedArticlePaths as Vp}from"document360-engine";var oi=3;function ri(e){let t,n=!1;for(let r=0;r<e.length;r++){let i=e[r];i==="--run"||i==="--yes"?n=!0:i==="--scope"?t=e[++r]:i?.startsWith("--scope=")&&(t=i.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function ii(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function si(e,t){return t.map(n=>{let o=0;try{o=Mp(Up(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ai(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:
271
+ `},r=o(e),i=o(t);if(r===i)return null;let l=Math.max(20,n-10),p=vp("a","b",r,i,"","",{context:3}),m=0,k=0,g=[];p.hunks.forEach((v,_)=>{_>0&&g.push(nl.gray(" \u2026"));let P=v.oldStart,N=v.newStart;for(let D of v.lines){let M=D[0],B=D.slice(1).slice(0,l);M==="-"?(k++,g.push(`${$p}${Jr(P++)} - ${B}${rl}`)):M==="+"?(m++,g.push(`${xp}${Jr(N++)} + ${B}${rl}`)):(g.push(nl.gray(Jr(N))+" "+B),P++,N++)}});let T=g.slice(0,ol);return{added:m,removed:k,lines:T,hidden:Math.max(0,g.length-ol)}}W();import{select as Cp}from"@inquirer/prompts";import{applyPull as Rp,computeSyncStatus as Pp,planPull as Tp}from"document360-engine";var il=e=>e===1?"":"s";async function Zr(e,t){console.log(""),console.log(`${O("\u25CF")} ${ge(t.title)} ${ae(`(${t.path})`)}`);for(let r of t.notes)console.log(L(` \u26A0 ${r}`));let n=qe(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(ae(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${il(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(f(` \u2026 +${n.hidden} more diff lines`))}else console.log(f(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>Cp({message:`Conflict \u2014 ${t.path}`,choices:[{name:"Keep local (publish \u2014 overwrites the portal edit)",value:"local"},{name:"Take portal (overwrites your local edits)",value:"portal"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip");return o==="portal"?(Rp({cwd:e.cwd,profileName:e.profileName},t),console.log(j(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(f(" Skipped \u2014 still a conflict.")),"skipped")}async function sl(e,t){let n=Ae(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let i=(await Pp({cwd:t.cwd,profileName:t.profileName})).entries.filter(p=>p.status==="conflict"&&p.path).map(p=>p.path);if(o){if(!i.includes(o))return console.log(j(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};i=[o]}if(i.length===0)return console.log(j("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let l=[];for(let p of i){let m=await Tp({cwd:t.cwd,profileName:t.profileName,relPath:p});await Zr(t,m)==="keep-local"&&l.push(p)}if(l.length>0)return console.log(f(`Publishing ${l.length} kept-local article${il(l.length)} over the portal\u2026`)),await wt(t,l)}catch(r){console.log(C(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function cl(e,t){let n=Ae(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await _p(t),{kind:"continue"};if(o==="--baseline")return await Op(t,e.filter(l=>l!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Lp(t),{kind:"continue"};if(o)return console.log(C(`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 Mp(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let i=await ti({cwd:t.cwd,profileName:t.profileName});for(let l of ni(i))console.log(l.tone==="ok"?j(l.text):l.tone==="warn"?L(l.text):f(l.text));console.log("")}catch(r){r instanceof Ip?console.log(C(r.message)):console.log(C(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function ti(e){let t=await al({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 ll({cwd:e.cwd,profileName:e.profileName,relPath:o.path});ei({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 jp({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Ap({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 So=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,yt=e=>e===1?"":"s";function ni(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${yt(e.pulled.length)} into local: ${So(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${yt(e.imported.length)}: ${So(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${yt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${yt(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's). (${So(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${yt(e.failed.length)} failed: ${So(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 _p(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await al({cwd:e.cwd,profileName:e.profileName});for(let o of To(n,Date.now()-t))console.log(o);console.log("")}async function Op(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 Ep({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Np({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 i of o.skipped)console.log(f(` - ${i.path} (${i.reason})`))}}async function Lp(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Dp({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${ge(String(t.legacyCount))} \xB7 Manifest: ${ge(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(C(`\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 Mp(e,t){let n=t.replace(/\\/g,"/"),o=await ll({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Zr(e,o)==="keep-local"&&(console.log(f(`Publishing ${o.path} over the portal\u2026`)),await wt(e,[o.path]));return}console.log(""),console.log(`${O("\u25CF")} ${ge(o.title)} ${ae(`(${o.path})`)}`);for(let l of o.notes)console.log(L(` \u26A0 ${l}`));let r=qe(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.")),ei({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ae(` \u23BF Added ${r.added} line${yt(r.added)}, removed ${r.removed} line${yt(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(()=>Sp({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}ei({cwd:e.cwd,profileName:e.profileName},o),console.log(j(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as Up}from"node:fs";import{resolve as Wp}from"node:path";import{estimateBulkCost as Fp,planPartitions as Hp,readProjectConfig as qp,resolveModelForOperation as Bp,runPartitioned as Vp,trackedArticlePaths as Gp}from"document360-engine";var oi=3;function ri(e){let t,n=!1;for(let r=0;r<e.length;r++){let i=e[r];i==="--run"||i==="--yes"?n=!0:i==="--scope"?t=e[++r]:i?.startsWith("--scope=")&&(t=i.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function ii(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function si(e,t){return t.map(n=>{let o=0;try{o=Up(Wp(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ai(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:
272
272
  - 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.
273
273
  - 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.
274
274
  - 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.
275
275
  - Work only on these files:
276
276
  `+e.paths.map(t=>`- ${t}`).join(`
277
- `)}function li(e,t,n){let o=e.reduce((p,m)=>p+m.paths.length,0),[r,i]=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: ${we(r)}\u2013${we(i)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function ci(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),i=e.filter(P=>!P.ok),l=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),m=e.reduce((P,N)=>P+N.costUsd,0),k=e.reduce((P,N)=>P+N.outputTokens,0),g=n==="api"?`${we(m)} total`:Ze(k),T=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=P=>`${P} article${P===1?"":"s"}`,_=[];if(i.length===0)_.push(`Converted ${v(l)} (${T}) successfully \xB7 ${g}.`);else{_.push(`Converted ${p}/${v(l)} (${T}) \xB7 ${g}.`),_.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let P of i)_.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return _}async function dl(e,t){if(!Hp(t.cwd))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=ri(e),r=Vp(t.cwd,t.profileName);if(r.length===0)return console.log(C("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let i=ii(r,n);if(i.length===0)return console.log(C(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let l=Fp(i),p=`/convert${n?` --scope ${n}`:""} --run`,{model:m,forced:k}=qp(t.cwd,"light");if(!o){let g=Wp({files:si(t.cwd,i),op:"convert",model:m});n&&console.log(f(`Scope: ${n} (${i.length} of ${r.length} tracked articles).`));for(let T of li(l,g,oi))console.log(T);return console.log(f(`Model: ${m}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${i.length} articles across ${l.length} partitions (\u2264${oi} agents at once) on ${m}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let g of Bp({cwd:t.cwd,partitions:l,promptFor:ai,concurrency:oi,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:m}))if(g.type==="partition_status")g.status==="running"?console.log(f(` \u25B8 ${g.label} \u2014 converting\u2026`)):g.status==="done"?console.log(j(` \u2713 ${g.label}`)):console.log(C(` \u2717 ${g.label}`));else if(g.type==="run_done"){console.log("");let T=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let v of ci(g.results,l,T))console.log(g.ok?j(v):L(v))}}catch(g){console.log(C(`Convert run failed: ${g.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as fl}from"node:fs";import{resolve as hl}from"node:path";import{estimateBulkCost as ef,lintDocs as tf,planPartitions as nf,readDocsPlan as of,readProjectConfig as ml,DEFAULT_DOCS_DIR as rf,resolveModelForOperation as sf,runPartitioned as af,stampArticles as lf,CONTENT_CAP_VERSION as cf}from"document360-engine";import{readProjectConfig as Gp,loadProfileMap as Yp,resolveActiveProfile as zp,desiredCategoryOrder as Kp,desiredArticleOrder as Xp,DEFAULT_DOCS_DIR as Qp}from"document360-engine";var di=e=>e.replace(/\\/g,"/"),Jp=e=>di(e).split("/").pop()??e;function Zp(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function $n(e,t){try{let n=Gp(e);if(!n)return[];let o=zp(e,t),r=Yp(e,o.name);if(!r)return[];let i=di(n.docsDir??Qp).replace(/\/+$/,""),l=new Map;for(let m of Xp(r))l.set(m.categoryPath,(l.get(m.categoryPath)??0)+1);let p=[];for(let m of Kp(r)){let k=di(m.path),g=k.startsWith(`${i}/`)?k.slice(i.length+1):k===i?"":k;g&&p.push({token:g,label:Zp(Jp(k)),count:l.get(m.path)??0})}return p}catch{return[]}}function ul(e,t){let n=$n(e,t);return n.length===0?["No categories yet \u2014 author some articles first, then scope to one."]:["Which category? Re-run with one of:",...n.map(o=>` --scope ${o.token} (${o.label} \xB7 ${o.count} article${o.count===1?"":"s"})`)]}function et(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function Kt(e,t,n,o){let r=$n(e,o);if(r.length<=1)return[];let i=n.filter(k=>k.startsWith("--")).join(" "),l=i?` ${i}`:"",p=`/${t}${l} --all`.replace(/\s+/g," "),m=k=>t==="write"?`/write --scope ${k}${l}`:`/${t} ${k}${l}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((k,g)=>k+g.count,0)} articles). Pick a target:`,` ${p} (everything)`,...r.map(k=>` ${m(k.token)} (${k.label} \xB7 ${k.count} article${k.count===1?"":"s"})`)]}function Do(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function pl(e,t){let n=e.indexOf("--scope");if(n===-1)return["--scope",t,...e];let o=e[n+1],r=[...e];return o===void 0||o.startsWith("-")?r.splice(n+1,0,t):r[n+1]=t,r}var df=3,uf=8;function ui(e){return e===void 0||!Number.isFinite(e)?df:Math.max(1,Math.min(Math.floor(e),uf))}function pi(e){let t,n,o=!1,r=!1,i,l=m=>{let k=Number(m);return m!==void 0&&Number.isFinite(k)?k:void 0};for(let m=0;m<e.length;m++){let k=e[m];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[++m]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?i=l(e[++m]):k?.startsWith("--concurrency=")?i=l(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=m=>m?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:i,rewrite:r}}function pf(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function ff(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function fi(e,t,n){return n.filter(o=>{try{return fl(hl(e,t,o)).size===0}catch{return!0}})}function hi(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let i=1;for(let l of o.get(r)?.sources??[])try{i+=fl(hl(e,l)).size}catch{}return{path:r,bytes:i}})}function mi(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.
277
+ `)}function li(e,t,n){let o=e.reduce((p,m)=>p+m.paths.length,0),[r,i]=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: ${we(r)}\u2013${we(i)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function ci(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),i=e.filter(P=>!P.ok),l=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),m=e.reduce((P,N)=>P+N.costUsd,0),k=e.reduce((P,N)=>P+N.outputTokens,0),g=n==="api"?`${we(m)} total`:Ze(k),T=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=P=>`${P} article${P===1?"":"s"}`,_=[];if(i.length===0)_.push(`Converted ${v(l)} (${T}) successfully \xB7 ${g}.`);else{_.push(`Converted ${p}/${v(l)} (${T}) \xB7 ${g}.`),_.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let P of i)_.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return _}async function dl(e,t){if(!qp(t.cwd))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=ri(e),r=Gp(t.cwd,t.profileName);if(r.length===0)return console.log(C("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let i=ii(r,n);if(i.length===0)return console.log(C(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let l=Hp(i),p=`/convert${n?` --scope ${n}`:""} --run`,{model:m,forced:k}=Bp(t.cwd,"light");if(!o){let g=Fp({files:si(t.cwd,i),op:"convert",model:m});n&&console.log(f(`Scope: ${n} (${i.length} of ${r.length} tracked articles).`));for(let T of li(l,g,oi))console.log(T);return console.log(f(`Model: ${m}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${i.length} articles across ${l.length} partitions (\u2264${oi} agents at once) on ${m}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let g of Vp({cwd:t.cwd,partitions:l,promptFor:ai,concurrency:oi,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:m}))if(g.type==="partition_status")g.status==="running"?console.log(f(` \u25B8 ${g.label} \u2014 converting\u2026`)):g.status==="done"?console.log(j(` \u2713 ${g.label}`)):console.log(C(` \u2717 ${g.label}`));else if(g.type==="run_done"){console.log("");let T=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let v of ci(g.results,l,T))console.log(g.ok?j(v):L(v))}}catch(g){console.log(C(`Convert run failed: ${g.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as fl}from"node:fs";import{resolve as hl}from"node:path";import{estimateBulkCost as tf,lintDocs as nf,planPartitions as of,readDocsPlan as rf,readProjectConfig as ml,DEFAULT_DOCS_DIR as sf,resolveModelForOperation as af,runPartitioned as lf,stampArticles as cf,CONTENT_CAP_VERSION as df}from"document360-engine";import{readProjectConfig as Yp,loadProfileMap as zp,resolveActiveProfile as Kp,desiredCategoryOrder as Xp,desiredArticleOrder as Qp,DEFAULT_DOCS_DIR as Jp}from"document360-engine";var di=e=>e.replace(/\\/g,"/"),Zp=e=>di(e).split("/").pop()??e;function ef(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function $n(e,t){try{let n=Yp(e);if(!n)return[];let o=Kp(e,t),r=zp(e,o.name);if(!r)return[];let i=di(n.docsDir??Jp).replace(/\/+$/,""),l=new Map;for(let m of Qp(r))l.set(m.categoryPath,(l.get(m.categoryPath)??0)+1);let p=[];for(let m of Xp(r)){let k=di(m.path),g=k.startsWith(`${i}/`)?k.slice(i.length+1):k===i?"":k;g&&p.push({token:g,label:ef(Zp(k)),count:l.get(m.path)??0})}return p}catch{return[]}}function ul(e,t){let n=$n(e,t);return n.length===0?["No categories yet \u2014 author some articles first, then scope to one."]:["Which category? Re-run with one of:",...n.map(o=>` --scope ${o.token} (${o.label} \xB7 ${o.count} article${o.count===1?"":"s"})`)]}function et(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function Kt(e,t,n,o){let r=$n(e,o);if(r.length<=1)return[];let i=n.filter(k=>k.startsWith("--")).join(" "),l=i?` ${i}`:"",p=`/${t}${l} --all`.replace(/\s+/g," "),m=k=>t==="write"?`/write --scope ${k}${l}`:`/${t} ${k}${l}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((k,g)=>k+g.count,0)} articles). Pick a target:`,` ${p} (everything)`,...r.map(k=>` ${m(k.token)} (${k.label} \xB7 ${k.count} article${k.count===1?"":"s"})`)]}function Do(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function pl(e,t){let n=e.indexOf("--scope");if(n===-1)return["--scope",t,...e];let o=e[n+1],r=[...e];return o===void 0||o.startsWith("-")?r.splice(n+1,0,t):r[n+1]=t,r}var uf=3,pf=8;function ui(e){return e===void 0||!Number.isFinite(e)?uf:Math.max(1,Math.min(Math.floor(e),pf))}function pi(e){let t,n,o=!1,r=!1,i,l=m=>{let k=Number(m);return m!==void 0&&Number.isFinite(k)?k:void 0};for(let m=0;m<e.length;m++){let k=e[m];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[++m]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?i=l(e[++m]):k?.startsWith("--concurrency=")?i=l(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=m=>m?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:i,rewrite:r}}function ff(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function hf(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function fi(e,t,n){return n.filter(o=>{try{return fl(hl(e,t,o)).size===0}catch{return!0}})}function hi(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let i=1;for(let l of o.get(r)?.sources??[])try{i+=fl(hl(e,l)).size}catch{}return{path:r,bytes:i}})}function mi(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.
278
278
  `:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
279
279
  - It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose, its \`type\` (concept | task | reference | faq; missing \u21D2 task), and the source files it draws from (AGENT-PLAN.md has the same table).
280
280
  - Use the skeleton for that \`type\` (see write-article): a \`concept\`/overview page opens with what the product IS + its mental model and takes NO Prerequisites/Steps; only a \`task\` page gets Steps.
@@ -284,79 +284,79 @@ ${i}${m}`).join("")}).join(`
284
284
  - 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.
285
285
  Articles:
286
286
  `+e.paths.map(r=>`- ${r}`).join(`
287
- `)}function gi(e,t,n){let o=e.reduce((l,p)=>l+p.paths.length,0),[r,i]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(l=>` \u2022 ${l.label} \u2014 ${l.paths.length} article${l.paths.length===1?"":"s"}`),"",`Estimated cost: ${we(r)}\u2013${we(i)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function wi(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),i=e.filter(P=>!P.ok),l=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),m=e.reduce((P,N)=>P+N.costUsd,0),k=e.reduce((P,N)=>P+N.outputTokens,0),g=n==="api"?`${we(m)} total`:Ze(k),T=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=P=>`${P} article${P===1?"":"s"}`,_=[];if(i.length===0)_.push(`Wrote ${v(l)} (${T}) successfully \xB7 ${g}.`),_.push("Next \u2014 push them to Document360:"),_.push("/publish --all"),_.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{_.push(`Wrote ${p}/${v(l)} (${T}) \xB7 ${g}.`),_.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let P of i)_.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return _}function yi(e,t,n){try{let o=tf({cwd:e,paths:n.map(i=>`${t}/${i}`)});if(o.length===0)return null;let r=new Set(o.map(i=>i.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 /check --fix corrects them.`}catch{return null}}function ki(e,t,n){let o=(ml(e)?.docsDir??rf).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=pf(n.path,o);return r.includes(p)?{docsDir:o,targets:[p],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${p}" isn't in the docs plan (.d360-writer/plan.json).`}}let i=ff(r,n.scope);if(n.scope&&i.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:i,planCount:r.length,rewriting:!0};let l=fi(e,o,i);if(l.length===0){let p=n.scope?` under "${n.scope}"`:"",m=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${m} --rewrite to regenerate them all.`}}return{docsDir:o,targets:l,planCount:r.length}}async function gl(e,t){if(!ml(t.cwd))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Do(e)){for(let M of ul(t.cwd,t.profileName))console.log(f(M));return{kind:"continue"}}if(et("write",e)){let M=Kt(t.cwd,"write",e,t.profileName);if(M.length>0){for(let B of M)console.log(f(B));return{kind:"continue"}}}let n=of(t.cwd);if(n.length===0)return console.log(C("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:i,concurrency:l,rewrite:p}=pi(e),{docsDir:m,targets:k,reason:g,rewriting:T}=ki(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(g?L(g):L("Nothing to write.")),{kind:"continue"};T&&console.log(L(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let v=nf(k),_=ui(l),{model:P,forced:N}=sf(t.cwd,"standard"),D=!!r;if(i&&!D){let M=ef({files:hi(t.cwd,n,k),op:"write",model:P});o&&console.log(f(`Scope: ${o} (${k.length} pending).`));for(let B of gi(v,M,_))console.log(B);return console.log(f(`Model: ${P}${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 ${v.length} partition${v.length===1?"":"s"} (\u2264${_} agents at once) on ${P}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let M of af({cwd:t.cwd,partitions:v,promptFor:B=>mi(B,m,{rewrite:T||D}),concurrency:_,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:P}))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(C(` \u2717 ${M.label}`));else if(M.type==="run_done"){console.log("");let B=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let X of wi(M.results,v,B))console.log(M.ok?j(X):L(X));if(M.ok)try{lf(t.cwd,k.map(X=>`${m}/${X}`),{writtenCap:cf})}catch{}let ee=yi(t.cwd,m,k);ee&&console.log(L(ee))}}catch(M){console.log(C(`Write run failed: ${M.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as hf,readdirSync as wl,statSync as yl}from"node:fs";import{join as kl}from"node:path";import{inputDir as mf,readProjectConfig as gf}from"document360-engine";var bl=/\.(md|markdown|pdf|txt)$/i;function bi(e){let t=mf(e);if(!hf(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of wl(t)){let i=kl(t,r),l=!1;try{l=yl(i).isDirectory()}catch{continue}if(l){if(r.startsWith("."))continue;let p=wf(i);p>0&&n.push({name:r,docCount:p})}else bl.test(r)&&o++}return n.sort((r,i)=>r.name.localeCompare(i.name)),{features:n,looseDocs:o}}function wf(e){let t=0;for(let n of wl(e))try{yl(kl(e,n)).isFile()&&bl.test(n)&&t++}catch{}return t}function vi(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 jo(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(`
288
- `)}var $i="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function vl(e,t){let n=t?.cwd??process.cwd();if(!gf(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=bi(n);if(o.length===0&&r===0)return console.log(f($i)),{kind:"continue"};let i=e.join(" ").trim();if(!i){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let m of o)console.log(` ${m.name} ${f(`(${m.docCount} doc${m.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:jo(p),display:p?`/draft ${p}`:"/draft"}}let l=vi(o,i);return{kind:"forward-to-agent",prompt:jo(l??"",l?void 0:i),display:`/draft ${i}`}}W();import{listOpenForDocs as yf,readProjectConfig as kf}from"document360-engine";function xi(e){try{return yf(e).filter(t=>t.kind==="request").length}catch{return 0}}function Ci(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Ri(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(`
289
- `)}var Pi="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 $l(e,t){let n=t?.cwd??process.cwd();if(!kf(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Ci(e);if(!r&&xi(n)===0)return console.log(f(Pi)),{kind:"continue"};let i=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Ri(r,o),display:i}}W();import{search as bf}from"@inquirer/prompts";import{findByName as vf,getSession as $f,listSessions as xf,relativeTime as Cl}from"document360-engine";async function Rl(e,t){let n=xf(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=vf(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(C(`No session matches "${o}".`)),xl(n),{kind:"continue"})}if(!process.stdin.isTTY)return xl(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>bf({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async i=>{let l=(i??"").toLowerCase();return n.filter(p=>!l||p.name.toLowerCase().includes(l)||p.firstPrompt.toLowerCase().includes(l)).map(p=>({name:`${p.name} ${Cl(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=$f(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function xl(e){console.log("");for(let t of e.slice(0,15))console.log(` ${O(t.name)} ${f(Cl(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Cf}from"document360-engine";function Ti(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 Pl(e,t){let n=Ti(e.join(" "));if(!n)return console.log(C("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Cf(o,n)?console.log(j(`\u2713 Session renamed to "${n}"`)):console.log(C("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 Tl,readProjectConfig as Rf,writeProjectConfig as Pf}from"document360-engine";W();function Si(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Rf(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 Tl().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Pf(o,e),null):`Unknown environment "${r}". Known: ${Tl().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function Sl(e,t){let n=e[0];if(!n)return lo(t.cwd),{kind:"continue"};if(n==="add"){let o=Si(t.cwd,e[1],e[2]);return o?(console.log(C(o)),{kind:"continue"}):(console.log(j(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${O(`/profile ${e[1]}`)} then ${O("/login")}`),{kind:"continue"})}return co(t.cwd,n),uo(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Tf}from"@inquirer/prompts";import{readProjectConfig as Sf,readUserConfig as Dl,resolveModelSetting as Di,writeUserConfig as jl}from"document360-engine";var _e=[{value:null,label:"Auto",desc:"Sonnet (latest) \u2014 right-sized for docs work (recommended); heavier models only when you pin them"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus (latest) \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet (latest) \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku (latest) \xB7 fastest for quick answers"}];function Ao(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=_e.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Df(e){switch(e.source){case"project":return".d360-writer/config.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"auto":return"auto \u2014 the docs-right default (newest Sonnet); /model to pin another"}}function xn(e,t){let n=()=>Di(e).model;if(t==="default"){let i=Dl();return i.defaultModel?(delete i.defaultModel,jl(i),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Di(e).model} (auto; applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}jl({...Dl(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Sf(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer/config.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function Al(e,t){let n=e[0]?.trim();if(!n){let l=Di(t.cwd);if(!process.stdin.isTTY)return console.log(`${ge("Model:")} ${O(l.model)}${l.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${Df(l)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Ao(l),m;try{m=await t.withPausedInput(()=>Tf({message:`Select model (current: ${l.model}${l.source==="auto"?" \xB7 auto":""})`,default:_e[p].value,choices:_e.map((v,_)=>({name:`${v.label}${_===p?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:g,effective:T}=xn(t.cwd,m??"default");for(let v of k)console.log(v.startsWith("\u26A0")?L(v):v.startsWith("\u2713")?j(v):f(v));return g&&await t.setModel(T),{kind:"continue"}}let{lines:o,changed:r,effective:i}=xn(t.cwd,n);for(let l of o)console.log(l.startsWith("\u26A0")?L(l):l.startsWith("\u2713")?j(l):f(l));return r&&await t.setModel(i),{kind:"continue"}}Eo();async function Ll(e,t){return await t.withPausedInput(()=>Ht(t.cwd)),{kind:"clear"}}async function Ml(e,t){return await t.withPausedInput(()=>ro(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as Yf}from"document360-engine";async function Ul(e,t){let n=!1;try{n=Yf(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 Wl=async(e,t)=>{try{await t.withPausedInput(()=>ao({}))}catch(n){console.log(C(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as zf,clearTokens as Kf,clearProfileProject as Xf}from"document360-engine";async function Fl(e,t){let n;try{n=zf(t.cwd,t.profileName).name}catch(r){return console.log(C(r.message)),{kind:"continue"}}let o=Kf(n);return Xf(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 Hl}from"node:fs";import{isAbsolute as Qf,join as Jf,resolve as Zf}from"node:path";import{readProjectConfig as eh,screenshotPlaceholderIds as th,DEFAULT_CAPTURE_DIR as nh,DEFAULT_OUTPUT_DIR as oh}from"document360-engine";var ql=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ai(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?ql(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:ql(o),setup:t}:{mode:"single",id:o}}function Ei(e,t){let n=eh(e),o=n?.captureDir??nh,r=n?.outputDir??oh,i=(l,p)=>Qf(l)?Jf(l,p):Zf(e,l,p);return th(e,{scope:t}).map(({id:l,file:p})=>{let m=Hl(i(r,`${l}.png`))?"captured":Hl(i(o,`${l}.spec.ts`))?"spec":"placeholder";return{id:l,file:p,state:m}})}var rh={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},ih={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Ni(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(i=>i.file))].sort(),o=e.filter(i=>i.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let i of n){r.push(i);for(let l of e.filter(p=>p.file===i))r.push(` ${rh[l.state]} ${l.id.padEnd(34)} ${ih[l.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Bl(e){return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(t=>`- ${t}`).join(`
287
+ `)}function gi(e,t,n){let o=e.reduce((l,p)=>l+p.paths.length,0),[r,i]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(l=>` \u2022 ${l.label} \u2014 ${l.paths.length} article${l.paths.length===1?"":"s"}`),"",`Estimated cost: ${we(r)}\u2013${we(i)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function wi(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),i=e.filter(P=>!P.ok),l=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),m=e.reduce((P,N)=>P+N.costUsd,0),k=e.reduce((P,N)=>P+N.outputTokens,0),g=n==="api"?`${we(m)} total`:Ze(k),T=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=P=>`${P} article${P===1?"":"s"}`,_=[];if(i.length===0)_.push(`Wrote ${v(l)} (${T}) successfully \xB7 ${g}.`),_.push("Next \u2014 push them to Document360:"),_.push("/publish --all"),_.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{_.push(`Wrote ${p}/${v(l)} (${T}) \xB7 ${g}.`),_.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let P of i)_.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return _}function yi(e,t,n){try{let o=nf({cwd:e,paths:n.map(i=>`${t}/${i}`)});if(o.length===0)return null;let r=new Set(o.map(i=>i.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 /check --fix corrects them.`}catch{return null}}function ki(e,t,n){let o=(ml(e)?.docsDir??sf).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=ff(n.path,o);return r.includes(p)?{docsDir:o,targets:[p],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${p}" isn't in the docs plan (.d360-writer/plan.json).`}}let i=hf(r,n.scope);if(n.scope&&i.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:i,planCount:r.length,rewriting:!0};let l=fi(e,o,i);if(l.length===0){let p=n.scope?` under "${n.scope}"`:"",m=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${m} --rewrite to regenerate them all.`}}return{docsDir:o,targets:l,planCount:r.length}}async function gl(e,t){if(!ml(t.cwd))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Do(e)){for(let M of ul(t.cwd,t.profileName))console.log(f(M));return{kind:"continue"}}if(et("write",e)){let M=Kt(t.cwd,"write",e,t.profileName);if(M.length>0){for(let B of M)console.log(f(B));return{kind:"continue"}}}let n=rf(t.cwd);if(n.length===0)return console.log(C("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:i,concurrency:l,rewrite:p}=pi(e),{docsDir:m,targets:k,reason:g,rewriting:T}=ki(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(g?L(g):L("Nothing to write.")),{kind:"continue"};T&&console.log(L(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let v=of(k),_=ui(l),{model:P,forced:N}=af(t.cwd,"standard"),D=!!r;if(i&&!D){let M=tf({files:hi(t.cwd,n,k),op:"write",model:P});o&&console.log(f(`Scope: ${o} (${k.length} pending).`));for(let B of gi(v,M,_))console.log(B);return console.log(f(`Model: ${P}${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 ${v.length} partition${v.length===1?"":"s"} (\u2264${_} agents at once) on ${P}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let M of lf({cwd:t.cwd,partitions:v,promptFor:B=>mi(B,m,{rewrite:T||D}),concurrency:_,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:P}))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(C(` \u2717 ${M.label}`));else if(M.type==="run_done"){console.log("");let B=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let X of wi(M.results,v,B))console.log(M.ok?j(X):L(X));if(M.ok)try{cf(t.cwd,k.map(X=>`${m}/${X}`),{writtenCap:df})}catch{}let ee=yi(t.cwd,m,k);ee&&console.log(L(ee))}}catch(M){console.log(C(`Write run failed: ${M.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as mf,readdirSync as wl,statSync as yl}from"node:fs";import{join as kl}from"node:path";import{inputDir as gf,readProjectConfig as wf}from"document360-engine";var bl=/\.(md|markdown|pdf|txt)$/i;function bi(e){let t=gf(e);if(!mf(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of wl(t)){let i=kl(t,r),l=!1;try{l=yl(i).isDirectory()}catch{continue}if(l){if(r.startsWith("."))continue;let p=yf(i);p>0&&n.push({name:r,docCount:p})}else bl.test(r)&&o++}return n.sort((r,i)=>r.name.localeCompare(i.name)),{features:n,looseDocs:o}}function yf(e){let t=0;for(let n of wl(e))try{yl(kl(e,n)).isFile()&&bl.test(n)&&t++}catch{}return t}function vi(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 jo(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(`
288
+ `)}var $i="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function vl(e,t){let n=t?.cwd??process.cwd();if(!wf(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=bi(n);if(o.length===0&&r===0)return console.log(f($i)),{kind:"continue"};let i=e.join(" ").trim();if(!i){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let m of o)console.log(` ${m.name} ${f(`(${m.docCount} doc${m.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:jo(p),display:p?`/draft ${p}`:"/draft"}}let l=vi(o,i);return{kind:"forward-to-agent",prompt:jo(l??"",l?void 0:i),display:`/draft ${i}`}}W();import{listOpenForDocs as kf,readProjectConfig as bf}from"document360-engine";function xi(e){try{return kf(e).filter(t=>t.kind==="request").length}catch{return 0}}function Ci(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Ri(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(`
289
+ `)}var Pi="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 $l(e,t){let n=t?.cwd??process.cwd();if(!bf(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Ci(e);if(!r&&xi(n)===0)return console.log(f(Pi)),{kind:"continue"};let i=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Ri(r,o),display:i}}W();import{search as vf}from"@inquirer/prompts";import{findByName as $f,getSession as xf,listSessions as Cf,relativeTime as Cl}from"document360-engine";async function Rl(e,t){let n=Cf(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=$f(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(C(`No session matches "${o}".`)),xl(n),{kind:"continue"})}if(!process.stdin.isTTY)return xl(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>vf({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async i=>{let l=(i??"").toLowerCase();return n.filter(p=>!l||p.name.toLowerCase().includes(l)||p.firstPrompt.toLowerCase().includes(l)).map(p=>({name:`${p.name} ${Cl(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=xf(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function xl(e){console.log("");for(let t of e.slice(0,15))console.log(` ${O(t.name)} ${f(Cl(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Rf}from"document360-engine";function Ti(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 Pl(e,t){let n=Ti(e.join(" "));if(!n)return console.log(C("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Rf(o,n)?console.log(j(`\u2713 Session renamed to "${n}"`)):console.log(C("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 Tl,readProjectConfig as Pf,writeProjectConfig as Tf}from"document360-engine";W();function Si(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Pf(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 Tl().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Tf(o,e),null):`Unknown environment "${r}". Known: ${Tl().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function Sl(e,t){let n=e[0];if(!n)return lo(t.cwd),{kind:"continue"};if(n==="add"){let o=Si(t.cwd,e[1],e[2]);return o?(console.log(C(o)),{kind:"continue"}):(console.log(j(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${O(`/profile ${e[1]}`)} then ${O("/login")}`),{kind:"continue"})}return co(t.cwd,n),uo(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Sf}from"@inquirer/prompts";import{readProjectConfig as Df,readUserConfig as Dl,resolveModelSetting as Di,writeUserConfig as jl}from"document360-engine";var Oe=[{value:null,label:"Auto",desc:"Sonnet (latest) \u2014 right-sized for docs work (recommended); heavier models only when you pin them"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus (latest) \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet (latest) \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku (latest) \xB7 fastest for quick answers"}];function Ao(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Oe.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function jf(e){switch(e.source){case"project":return".d360-writer/config.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"auto":return"auto \u2014 the docs-right default (newest Sonnet); /model to pin another"}}function xn(e,t){let n=()=>Di(e).model;if(t==="default"){let i=Dl();return i.defaultModel?(delete i.defaultModel,jl(i),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Di(e).model} (auto; applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}jl({...Dl(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Df(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer/config.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function Al(e,t){let n=e[0]?.trim();if(!n){let l=Di(t.cwd);if(!process.stdin.isTTY)return console.log(`${ge("Model:")} ${O(l.model)}${l.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${jf(l)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Ao(l),m;try{m=await t.withPausedInput(()=>Sf({message:`Select model (current: ${l.model}${l.source==="auto"?" \xB7 auto":""})`,default:Oe[p].value,choices:Oe.map((v,_)=>({name:`${v.label}${_===p?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:g,effective:T}=xn(t.cwd,m??"default");for(let v of k)console.log(v.startsWith("\u26A0")?L(v):v.startsWith("\u2713")?j(v):f(v));return g&&await t.setModel(T),{kind:"continue"}}let{lines:o,changed:r,effective:i}=xn(t.cwd,n);for(let l of o)console.log(l.startsWith("\u26A0")?L(l):l.startsWith("\u2713")?j(l):f(l));return r&&await t.setModel(i),{kind:"continue"}}Eo();async function Ll(e,t){return await t.withPausedInput(()=>Ht(t.cwd)),{kind:"clear"}}async function Ml(e,t){return await t.withPausedInput(()=>ro(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as zf}from"document360-engine";async function Ul(e,t){let n=!1;try{n=zf(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 Wl=async(e,t)=>{try{await t.withPausedInput(()=>ao({}))}catch(n){console.log(C(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as Kf,clearTokens as Xf,clearProfileProject as Qf}from"document360-engine";async function Fl(e,t){let n;try{n=Kf(t.cwd,t.profileName).name}catch(r){return console.log(C(r.message)),{kind:"continue"}}let o=Xf(n);return Qf(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 Hl}from"node:fs";import{isAbsolute as Jf,join as Zf,resolve as eh}from"node:path";import{readProjectConfig as th,screenshotPlaceholderIds as nh,DEFAULT_CAPTURE_DIR as oh,DEFAULT_OUTPUT_DIR as rh}from"document360-engine";var ql=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ai(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?ql(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:ql(o),setup:t}:{mode:"single",id:o}}function Ei(e,t){let n=th(e),o=n?.captureDir??oh,r=n?.outputDir??rh,i=(l,p)=>Jf(l)?Zf(l,p):eh(e,l,p);return nh(e,{scope:t}).map(({id:l,file:p})=>{let m=Hl(i(r,`${l}.png`))?"captured":Hl(i(o,`${l}.spec.ts`))?"spec":"placeholder";return{id:l,file:p,state:m}})}var ih={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},sh={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Ni(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(i=>i.file))].sort(),o=e.filter(i=>i.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let i of n){r.push(i);for(let l of e.filter(p=>p.file===i))r.push(` ${ih[l.state]} ${l.id.padEnd(34)} ${sh[l.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Bl(e){return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(t=>`- ${t}`).join(`
290
290
  `),"","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(`
291
291
  `)}async function No(e,t){let n=Ai(e);if(n.mode==="list"){let l=t?.cwd??process.cwd();for(let p of Ni(Ei(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(`
292
292
  `),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(`
293
- `),i=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:i}}import{existsSync as sh,readFileSync as ah}from"node:fs";import{isAbsolute as lh,join as ch,resolve as dh}from"node:path";import{readProjectConfig as uh,DEFAULT_CAPTURE_DIR as ph}from"document360-engine";async function Rn(){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(`
294
- `),display:"/capture-setup"}}var Vl="-".repeat(64);function Ii(e){let t=ph;try{let g=uh(e);g?.captureDir&&(t=g.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=lh(t)?ch(t,"CAPTURE-TESTID-REQUESTS.json"):dh(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!sh(n))return null;let o;try{let g=JSON.parse(ah(n,"utf8").replace(/^/,""));o=Array.isArray(g?.requests)?g.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(g=>g.file).filter(Boolean)).size,i=o.length,l=`${i} data-testid attribute${i===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,m=`${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.","",Vl,`Read ${m} 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.",Vl]}Qe();W();import{listOpenForDocs as fh,readProjectConfig as hh}from"document360-engine";function _i(e){try{return fh(e).length}catch{return 0}}function Oi(){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 to a [discovery]-tagged question (subject starts "[discovery] ") \u2192 this is product-discovery,'," not an article edit: fold the fact into `.d360-writer/product-brief.md` (updating the cited grounding,"," clearing the matching OPEN marker), then RE-RUN the discover-product readiness assessment \u2014 set the"," brief's frontmatter status to `confident` and offer propose-structure if every rubric dimension now"," passes, else ask the next focused batch via d360_ask_builder. Do not touch articles for these."," \u2022 answer (a reply to any other 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(`
295
- `)}async function Gl(e,t){let n=t?.cwd??process.cwd();return hh(n)?_i(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:Oi(),display:"/inbox"}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as mh,listOpenForDocs as gh,listOpenDirectives as wh,readProjectConfig as yh,computeSyncStatus as kh,planPull as bh,applyPull as vh,planImport as $h,applyImport as xh}from"document360-engine";function Pn(e){let t=0,n=0,o=0,r=0;try{t=mh(e).length}catch{}try{let i=gh(e);n=i.filter(l=>l.kind==="request").length,o=i.filter(l=>l.kind==="answer").length}catch{}try{r=wh(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function Tn(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),t.length?t.join(", "):null}function Mi(e){return{publish:e.includes("--publish")}}function Ui({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 brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. 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), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page" \u2014 .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback once (idempotent \u2014 it creates the hidden feedback category + seed articles if this workspace has none, else no-ops), then d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY \u2014 triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.",'4. 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), fold any answers into the affected article(s) + the architecture brief \u2014 EXCEPT an answer to a [discovery]-tagged question (subject starts "[discovery] "), which is product discovery: fold it into `.d360-writer/product-brief.md`, then re-run the discover-product readiness assessment (flip the brief to `confident` if every rubric dimension now passes and offer propose-structure, else leave a follow-up [discovery] question) \u2014 address each feedback item (improve the doc it points at \u2014 as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts \u2014 following the active doc-type playbook).',"5. 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.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the loop:"," \u2022 stamp consumed hints, and mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done), and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed \u2014 never delete existing steps;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article \u2014 `**d360-writer response:** \u2713 actioned in <article> \u2014 <date>` (or `declined \u2014 <reason>`) \u2014 NEVER overwriting the person's own text \u2014 then call d360_feedback_done(article_id, resulting_articles);"," \u2022 EXCEPT the Creator-notes item (is_creator_notes:true): do NOT reply in it \u2014 instead fold its content into `.d360-writer/architecture/CREATOR-NOTES.md` as an appended, dated `## From portal Creator notes (<date>)` section (preserve every existing note + human edit), then call d360_feedback_done for it.","8. Push the drafts to Document360.","9. 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?"10. 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(`
296
- `)}var Ch={status:kh,plan:bh,apply:vh,planImport:$h,applyImport:xh};async function Wi(e,t=Ch){let n={pulled:[],imported:[],conflicts:[],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"&&r.articleId)try{let i=await t.planImport({cwd:e.cwd,profileName:e.profileName,articleId:r.articleId});t.applyImport({cwd:e.cwd,profileName:e.profileName},i),n.imported.push(i.path)}catch(i){n.failed.push({path:r.title??r.articleId,error:i.message})}else if(r.status==="remote-ahead"&&r.path)try{let i=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},i),n.pulled.push(r.path)}catch(i){n.failed.push({path:r.path,error:i.message})}return n}var Li=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Io=e=>e===1?"":"s";function Fi(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${Io(e.pulled.length)} into local: ${Li(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Io(e.imported.length)} into local drafts: ${Li(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Io(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Li(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${Io(e.failed.length)} failed \u2014 left for /pull.`),t}async function Yl(e,t){let n=t?.cwd??process.cwd();if(!yh(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=je(n,t?.profileName);if(!o.ok)return console.log(C(o.reason)),{kind:"continue"};let{publish:r}=Mi(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let i=await Wi({cwd:n,profileName:t?.profileName});for(let p of Fi(i))console.log(p.startsWith("\u2713")?j(p):p.startsWith("\u2139")?f(p):L(p));let l=Tn(Pn(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:Ui({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as Rh}from"node:child_process";var kt="document360-writer",_o=`npm i -g ${kt}@latest`;async function Oo(){let e=process.platform==="win32";return new Promise(t=>{try{let n=Rh(`npm i -g ${kt}@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 zl(){return console.log(f(`Updating ${kt}\u2026`)),(await Oo()).ok?console.log(j("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(C(`Update failed \u2014 run manually: ${_o}`)),{kind:"continue"}}W();Qe();import{existsSync as Hi,rmSync as Ph}from"node:fs";import{basename as Kl,resolve as qi}from"node:path";import{execFileSync as Th}from"node:child_process";import{input as Sh}from"@inquirer/prompts";import{readProjectConfig as Dh,devHintsGuidePath as jh}from"document360-engine";var Ah=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Eh=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Lo=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Xl=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Ql(e){let t=Lo(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Xl(t)?!0:Eh.has(t)}function Bi(e){let t=null;try{t=Dh(e)}catch{t=null}let n=new Set(Ah);for(let o of[Lo(t?.docsDir),Lo(t?.captureDir),Lo(t?.outputDir)])o&&Xl(o)&&n.add(o);return[...n].filter(o=>Ql(o)&&Hi(qi(e,o)))}function Vi(e,t){let n=[],o=[];for(let r of t){if(!Ql(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Ph(qi(e,r),{recursive:!0,force:!0}),n.push(r)}catch(i){o.push({path:r,error:i.message})}}return{removed:n,failed:o}}function Jl(e,t){try{return Th("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
297
- `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Nh(e){return Jl(e,".d360-writer/hints")}function Ih(e){return Jl(e,".d360-writer/messages")}function Gi(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Nh(e),o=Ih(e),r=Hi(qi(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(i=>` \u2022 ${i}`),"",...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: ${Kl(e)}`]}async function Zl(e,t){let n=Bi(t.cwd);for(let m of Gi(t.cwd,n))console.log(n.length===0?f(m):m);if(n.length===0)return{kind:"continue"};let o=Kl(t.cwd);if((await t.withPausedInput(()=>Sh({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let i=Hi(jh(t.cwd)),{removed:l,failed:p}=Vi(t.cwd,n);console.log(j(`\u2713 Reset complete \u2014 removed ${l.length} item${l.length===1?"":"s"}. The repo is back to its original state.`));for(let m of p)console.log(C(` \u2717 ${m.path}: ${m.error}`));if(i){for(let m of go())console.log(m);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 _h}from"document360-engine";function Mo(e){if(e.length===0)return["\u2713 No issues found \u2014 no leaked internals, unknown commands, stale version facts, or AI-tells 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 / AI-tells):`];for(let[o,r]of t){n.push(` ${o}`);for(let i of r)n.push(` L${i.line}: "${i.term}" \u2014 ${i.message}`)}return n}function Yi(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.","- ai-tell: a machine-sounding buzzword (e.g. delve, leverage, furthermore, robust). Rewrite the phrase in"," plain, direct developer language; preserve the meaning; do NOT swap one buzzword for another.","","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(i=>` - L${i.line} [${i.kind}]: "${i.term}" \u2014 ${i.message}`)].join(`
293
+ `),i=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:i}}import{existsSync as ah,readFileSync as lh}from"node:fs";import{isAbsolute as ch,join as dh,resolve as uh}from"node:path";import{readProjectConfig as ph,DEFAULT_CAPTURE_DIR as fh}from"document360-engine";async function Rn(){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(`
294
+ `),display:"/capture-setup"}}var Vl="-".repeat(64);function Ii(e){let t=fh;try{let g=ph(e);g?.captureDir&&(t=g.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=ch(t)?dh(t,"CAPTURE-TESTID-REQUESTS.json"):uh(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!ah(n))return null;let o;try{let g=JSON.parse(lh(n,"utf8").replace(/^/,""));o=Array.isArray(g?.requests)?g.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(g=>g.file).filter(Boolean)).size,i=o.length,l=`${i} data-testid attribute${i===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,m=`${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.","",Vl,`Read ${m} 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.",Vl]}Qe();W();import{listOpenForDocs as hh,readProjectConfig as mh}from"document360-engine";function _i(e){try{return hh(e).length}catch{return 0}}function Oi(){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 to a [discovery]-tagged question (subject starts "[discovery] ") \u2192 this is product-discovery,'," not an article edit: fold the fact into `.d360-writer/product-brief.md` (updating the cited grounding,"," clearing the matching OPEN marker), then RE-RUN the discover-product readiness assessment \u2014 set the"," brief's frontmatter status to `confident` and offer propose-structure if every rubric dimension now"," passes, else ask the next focused batch via d360_ask_builder. Do not touch articles for these."," \u2022 answer (a reply to any other 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(`
295
+ `)}async function Gl(e,t){let n=t?.cwd??process.cwd();return mh(n)?_i(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:Oi(),display:"/inbox"}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as gh,listOpenForDocs as wh,listOpenDirectives as yh,readProjectConfig as kh,computeSyncStatus as bh,planPull as vh,applyPull as $h,planImport as xh,applyImport as Ch}from"document360-engine";function Pn(e){let t=0,n=0,o=0,r=0;try{t=gh(e).length}catch{}try{let i=wh(e);n=i.filter(l=>l.kind==="request").length,o=i.filter(l=>l.kind==="answer").length}catch{}try{r=yh(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function Tn(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),t.length?t.join(", "):null}function Mi(e){return{publish:e.includes("--publish")}}function Ui({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 brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. 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), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page" \u2014 .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback once (idempotent \u2014 it creates the hidden feedback category + seed articles if this workspace has none, else no-ops), then d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY \u2014 triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.",'4. 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), fold any answers into the affected article(s) + the architecture brief \u2014 EXCEPT an answer to a [discovery]-tagged question (subject starts "[discovery] "), which is product discovery: fold it into `.d360-writer/product-brief.md`, then re-run the discover-product readiness assessment (flip the brief to `confident` if every rubric dimension now passes and offer propose-structure, else leave a follow-up [discovery] question) \u2014 address each feedback item (improve the doc it points at \u2014 as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts \u2014 following the active doc-type playbook).',"5. 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.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the loop:"," \u2022 stamp consumed hints, and mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done), and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed \u2014 never delete existing steps;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article \u2014 `**d360-writer response:** \u2713 actioned in <article> \u2014 <date>` (or `declined \u2014 <reason>`) \u2014 NEVER overwriting the person's own text \u2014 then call d360_feedback_done(article_id, resulting_articles);"," \u2022 EXCEPT the Creator-notes item (is_creator_notes:true): do NOT reply in it \u2014 instead fold its content into `.d360-writer/architecture/CREATOR-NOTES.md` as an appended, dated `## From portal Creator notes (<date>)` section (preserve every existing note + human edit), then call d360_feedback_done for it.","8. Push the drafts to Document360.","9. 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?"10. 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(`
296
+ `)}var Rh={status:bh,plan:vh,apply:$h,planImport:xh,applyImport:Ch};async function Wi(e,t=Rh){let n={pulled:[],imported:[],conflicts:[],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"&&r.articleId)try{let i=await t.planImport({cwd:e.cwd,profileName:e.profileName,articleId:r.articleId});t.applyImport({cwd:e.cwd,profileName:e.profileName},i),n.imported.push(i.path)}catch(i){n.failed.push({path:r.title??r.articleId,error:i.message})}else if(r.status==="remote-ahead"&&r.path)try{let i=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},i),n.pulled.push(r.path)}catch(i){n.failed.push({path:r.path,error:i.message})}return n}var Li=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Io=e=>e===1?"":"s";function Fi(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${Io(e.pulled.length)} into local: ${Li(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Io(e.imported.length)} into local drafts: ${Li(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Io(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Li(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${Io(e.failed.length)} failed \u2014 left for /pull.`),t}async function Yl(e,t){let n=t?.cwd??process.cwd();if(!kh(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ae(n,t?.profileName);if(!o.ok)return console.log(C(o.reason)),{kind:"continue"};let{publish:r}=Mi(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let i=await Wi({cwd:n,profileName:t?.profileName});for(let p of Fi(i))console.log(p.startsWith("\u2713")?j(p):p.startsWith("\u2139")?f(p):L(p));let l=Tn(Pn(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:Ui({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as Ph}from"node:child_process";var kt="document360-writer",_o=`npm i -g ${kt}@latest`;async function Oo(){let e=process.platform==="win32";return new Promise(t=>{try{let n=Ph(`npm i -g ${kt}@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 zl(){return console.log(f(`Updating ${kt}\u2026`)),(await Oo()).ok?console.log(j("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(C(`Update failed \u2014 run manually: ${_o}`)),{kind:"continue"}}W();Qe();import{existsSync as Hi,rmSync as Th}from"node:fs";import{basename as Kl,resolve as qi}from"node:path";import{execFileSync as Sh}from"node:child_process";import{input as Dh}from"@inquirer/prompts";import{readProjectConfig as jh,devHintsGuidePath as Ah}from"document360-engine";var Eh=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Nh=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Lo=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Xl=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Ql(e){let t=Lo(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Xl(t)?!0:Nh.has(t)}function Bi(e){let t=null;try{t=jh(e)}catch{t=null}let n=new Set(Eh);for(let o of[Lo(t?.docsDir),Lo(t?.captureDir),Lo(t?.outputDir)])o&&Xl(o)&&n.add(o);return[...n].filter(o=>Ql(o)&&Hi(qi(e,o)))}function Vi(e,t){let n=[],o=[];for(let r of t){if(!Ql(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Th(qi(e,r),{recursive:!0,force:!0}),n.push(r)}catch(i){o.push({path:r,error:i.message})}}return{removed:n,failed:o}}function Jl(e,t){try{return Sh("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
297
+ `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Ih(e){return Jl(e,".d360-writer/hints")}function _h(e){return Jl(e,".d360-writer/messages")}function Gi(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Ih(e),o=_h(e),r=Hi(qi(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(i=>` \u2022 ${i}`),"",...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: ${Kl(e)}`]}async function Zl(e,t){let n=Bi(t.cwd);for(let m of Gi(t.cwd,n))console.log(n.length===0?f(m):m);if(n.length===0)return{kind:"continue"};let o=Kl(t.cwd);if((await t.withPausedInput(()=>Dh({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let i=Hi(Ah(t.cwd)),{removed:l,failed:p}=Vi(t.cwd,n);console.log(j(`\u2713 Reset complete \u2014 removed ${l.length} item${l.length===1?"":"s"}. The repo is back to its original state.`));for(let m of p)console.log(C(` \u2717 ${m.path}: ${m.error}`));if(i){for(let m of go())console.log(m);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 Oh}from"document360-engine";function Mo(e){if(e.length===0)return["\u2713 No issues found \u2014 no leaked internals, unknown commands, stale version facts, or AI-tells 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 / AI-tells):`];for(let[o,r]of t){n.push(` ${o}`);for(let i of r)n.push(` L${i.line}: "${i.term}" \u2014 ${i.message}`)}return n}function Yi(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.","- ai-tell: a machine-sounding buzzword (e.g. delve, leverage, furthermore, robust). Rewrite the phrase in"," plain, direct developer language; preserve the meaning; do NOT swap one buzzword for another.","","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(i=>` - L${i.line} [${i.kind}]: "${i.term}" \u2014 ${i.message}`)].join(`
298
298
  `)).join(`
299
299
  `)].join(`
300
- `)}async function ec(e,t){let n=e.includes("--fix"),o=e.find(l=>!l.startsWith("--")),r=o?` ${o}`:"",i=_h({cwd:t.cwd,scope:o});if(n)return i.length===0?(console.log(j("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${i.length} doc issue${i.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:Yi(i),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let l of Mo(i))console.log(i.length===0?j(l):L(l));return i.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}W();import{lintDocs as Fh,loadStyleGuide as Hh,buildReviewPrompt as qh,readProjectConfig as Bh,DEFAULT_DOCS_DIR as Vh}from"document360-engine";W();import{readProjectConfig as Oh,loadProfileMap as Lh,resolveActiveProfile as Mh,desiredCategoryOrder as Uh,desiredArticleOrder as Wh}from"document360-engine";function tc(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var nc=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Sn(e,t){try{if(!Oh(e))return[];let n=Mh(e,t),o=Lh(e,n.name);if(!o)return[];let r=new Map;for(let l of Wh(o)){let p=r.get(l.categoryPath);p?p.push(l):r.set(l.categoryPath,[l])}let i=[];for(let l of Uh(o)){i.push(tc(nc(l.path)));for(let p of(r.get(l.path)??[]).sort((m,k)=>m.order-k.order))i.push(` ${tc(nc(p.path))}`)}return i}catch{return[]}}async function oc(e,t){let n=Sn(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(O("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function zi(e,t){let n=Bh(e);if(!n)return null;let o=(n.docsDir??Vh).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),i=t.find(g=>!g.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),l=Fh({cwd:e}),p=i?l.filter(g=>g.path===`${o}/${i}`||g.path.startsWith(`${o}/${i}/`)):l,m=i?"":Sn(e).join(`
301
- `);return{prompt:qh({docsRoot:o,scope:i,styleGuide:Hh(e),deterministicFindings:p,fix:r,structure:m||void 0}),display:`/review${i?` ${i}`:""}${r?" --fix":""}`}}async function rc(e,t){if(et("review",e)){let o=Kt(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=zi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as Gh}from"document360-engine";function Ki(e,t){if(!Gh(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(`
302
- `),display:`/reorder${n?` ${n}`:""}`}}async function ic(e,t){if(et("reorder",e)){let o=Kt(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=Ki(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as Yh,writeProjectConfig as sc,isAppType as zh,playbookSkillName as Kh,detectAppType as ac}from"document360-engine";var lc=["web","cli","service","library"],Xh=new Set(["web","cli"]);function Xi(e){return Xh.has(e)?`${Kh(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Uo(e,t){let n=t.cwd,o=Yh(n);if(!o)return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let i=o.appType??ac(n);if(i){let l=o.appType?"set in config":"auto-detected";console.log(`${O("Genre:")} ${i} (${l}) \u2014 ${Xi(i)}`)}else console.log(L("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${lc.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(f("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:i,...l}=o;sc(l,n);let p=ac(n);return console.log(j(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${Xi(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return zh(r)?(sc({...o,appType:r},n),console.log(j(`\u2713 Genre set to ${r} \u2014 ${Xi(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(C(`Unknown genre "${r}". Choose one of: ${lc.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}W();import{listRoadmap as cc,roadmapProgress as dc,stampRoadmapDone as Qh}from"document360-engine";function Qi(e){let t=cc(e);if(t.length===0)return["No docs roadmap yet \u2014 the docs agent seeds .d360-writer/roadmap.md when it pins a structure,","and adds steps as the app changes. You can also write steps by hand (## [open] <step>), or ask:",'"propose the docs roadmap for this repo".'];let n=dc(e),o=[`Docs roadmap \u2014 ${n.done} of ${n.total} step${n.total===1?"":"s"} done:`,""];for(let r of t)o.push(` ${r.status==="done"?"\u2713":"\u25CB"} ${r.title}${r.run?` \xB7 ${r.run}`:""}`);return o.push(""),o.push(n.next?`Next: ${n.next.title}${n.next.run?` \u2014 ${n.next.run}`:""}`:"Campaign complete \u2014 the docs agent adds new steps as the app changes."),o.push("(Edit .d360-writer/roadmap.md freely \xB7 /roadmap done <step> marks one you finished yourself.)"),o}function Ji(e,t){if(!t.trim())return{ok:!1,line:"Usage: /roadmap done <step title>"};if(!Qh(e,t,{doneAt:new Date().toISOString()})){let r=cc(e).filter(i=>i.status==="open");return{ok:!1,line:r.length?`No open step titled "${t}". Open steps: ${r.map(i=>`"${i.title}"`).join(", ")}`:`No open step titled "${t}" \u2014 the roadmap has no open steps.`}}let o=dc(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${t}${o?` \u2014 next up: ${o.title}${o.run?` (${o.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}async function uc(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Ji(n,e.slice(1).join(" ").trim());return console.log(r.ok?j(r.line):L(r.line)),{kind:"continue"}}let o=Qi(n);console.log(O(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?f(r):r);return{kind:"continue"}}var pc={help:jr,"?":jr,clear:ma,exit:Ar,quit:Ar,init:Or,mcp:ko,publish:Qa,audit:vn,discover:Ja,scope:el,pull:cl,resolve:sl,convert:dl,write:gl,draft:vl,document:$l,resume:Rl,rename:Pl,profile:Sl,model:Al,doctor:Cn,workspace:Ll,project:Ml,"allow-prod":Ul,login:Wl,logout:Fl,screenshot:No,"capture-setup":Rn,devhints:Ca,inbox:Gl,"catch-up":Yl,update:zl,reset:Zl,check:ec,review:rc,reorder:ic,structure:oc,genre:Uo,roadmap:uc};function fc(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}Qe();var Jh="Or just tell me what to write or update.",Zh='\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 ye(e){return e===1?"":"s"}function Wo(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Zi(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var em={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",options:[{cmd:"/genre web",desc:"web app / SaaS UI"},{cmd:"/genre cli",desc:"command-line tool"},{cmd:"/genre service",desc:"API / backend service"},{cmd:"/genre library",desc:"SDK / library"}]};function tm(e){let t=[];if(e.devhints!=="current"&&e.builderStarted){let n=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",o=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";t.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${n}${o} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${n}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&t.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:em,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.discovery&&e.discovery.status==="in-progress"){let n=e.discovery.openQuestions;t.push(n>0?{key:"discovery",bullet:`product discovery is waiting on ${n} answer${ye(n)} from your builder`,lead:{kind:"cmd",cmd:"/catch-up",reason:"it folds in your builder\u2019s answers and continues discovery"},picker:null,follow:"Then /catch-up ingests your builder\u2019s answers and continues discovery."}:{key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${ye(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${ye(n)}.`})}if(e.directives>0||e.pendingText){let n=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",o=[];e.directives>0&&o.push(`${e.directives} owner directive${ye(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
303
- \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ye(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${ye(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${ye(n)} up.`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${ye(n.total)} done \u2014 next: ${o.title}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${ye(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${ye(n)}.`})}return t}function hc(e,t){let n=t.filter(i=>i.bullet).map(i=>` \u2022 ${i.bullet}`),o=t[0],r=[];o.lead?r.push(Zi(o.lead)):o.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let i of t.slice(1,3))i.follow&&r.push(i.follow);return[e,...n,r.join(" "),Jh].join(`
304
- `)}function Dn(e){if(!e.ready)return{kind:"idle"};let t=tm(e);if(!e.hasDocs){let r=t[0];return r&&(r.lead?.kind==="cmd"||r.picker)?{kind:"recommend",rec:{note:hc("\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",t),tone:r.tone??"info",lead:r.lead,picker:r.picker}}:{kind:"recommend",rec:{note:Zh,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null}}}if(t.length===0){let r=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${ye(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${ye(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${r}`,tone:"info",lead:null,picker:null}}}let n=t[0];return(n.key==="audit"||n.key==="roadmap"&&t[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${ye(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:hc("Welcome back \u2014 where your docs stand:",t),tone:n.tone??"info",lead:n.lead,picker:n.picker}}}import{existsSync as es,readdirSync as ns}from"node:fs";import{spawnSync as nm}from"node:child_process";import{join as Fo}from"node:path";import{readProjectConfig as gc,resolveActiveProfile as wc,loadTokens as om,isExpired as rm,loadProfileMap as yc,countLocalAhead as im,readDocsPlan as sm,devHintsGuidePath as am,DEFAULT_DOCS_DIR as ts,roadmapProgress as lm,readProductBriefState as cm}from"document360-engine";Qe();function mc(e){try{return ns(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function os(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>mc(Fo(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&mc(Fo(e,o)))}function rs(e,t){try{let n=gc(e);if(!n)return!1;let o=wc(e,t),r=yc(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let i=Fo(e,(n.docsDir??ts).replace(/\/+$/,""));return!!(es(i)&&ns(i).length>0||es(am(e)))}catch{return!1}}function jn(e,t,n){try{let o=gc(e);if(!o)return null;let r=wc(e,t),i=om(r.name),l=!!i&&(!rm(i)||!!i.refreshToken),p=rs(e,t)||!os(e,o.authoritativeSourceFiles),m=yc(e,r.name),k=m?Object.keys(m.articles).length:0,g=Fo(e,(o.docsDir??ts).replace(/\/+$/,"")),T=!1;try{T=es(g)&&ns(g).length>0}catch{}let v=0;if(m?.lastAnalyzedCommit)try{let ne=nm("git",["rev-list","--count",`${m.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});ne.status===0&&(v=parseInt((ne.stdout||"").trim(),10)||0)}catch{}let _=0;try{let ne=sm(e);if(ne.length>0){let Be=(o.docsDir??ts).replace(/\/+$/,"");_=fi(e,Be,ne.map(ot=>ot.path)).length}}catch{}let P=Pn(e),N=Tn({...P,directives:0}),D=im(e,t),M=De(e),B=lm(e),ee=cm(e),X=ee?{status:ee.status,openQuestions:ee.openQuestions}:null;return{ready:l&&p&&!n.claudeMissing,hasDocs:T,tracked:k,pendingText:N,directives:P.directives,behind:v,pendingWrites:_,localAhead:D,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:M.status,devhintsCompletedVersion:M.completedVersion,devhintsToVersion:ce,builderStarted:Fe(e),genreUnknown:n.genreUnknown,roadmap:B,discovery:X}}catch{return null}}function is(e,t){let n=[],o="";for(let r of e.split(/\s+/).filter(Boolean))for(o.length?o.length+1+r.length<=t?o+=` ${r}`:(n.push(o),o=r):o=r;o.length>t;)n.push(o.slice(0,t)),o=o.slice(t);return o&&n.push(o),n}function Ho(e){if(e.length===0)return[];let t=(r,i)=>`${r}${"\u2500".repeat(78)}${i}`,n=(r="")=>`\u2502 ${r.padEnd(76)} \u2502`,o=[`\u2B06 d360-writer upgraded \u2014 ${e.length===1?"one improvement affects":`${e.length} improvements affect`} the docs you've already written:`,"",t("\u250C","\u2510")];return e.forEach((r,i)=>{i>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let l of is(`${i+1}. ${r.feature}`,76))o.push(n(l));o.push(n());for(let l of is(r.why,73))o.push(n(` ${l}`));o.push(n());for(let l of is(`\u2192 What to do: ${r.how}`,73))o.push(n(` ${l}`));o.push(n())}),o.push(t("\u2514","\u2518")),o.push(""),o.push("\u2713 These are on your docs roadmap \u2014 each launch walks you to the next step (/roadmap shows them all)."),o}W();var dm={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"},bc=160,as=200,vc=40;function xe(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function kc(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}: ${xe(typeof r=="string"?r:JSON.stringify(r),vc)}`);return t.length>4&&n.push("\u2026"),xe(n.join(", "),bc)}var tt=e=>typeof e=="string"&&e?e:null,ss=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function um(e){let t=tt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ")}function pm(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=tt(t.title);if(!o)return null;let r=um(t.local_path);return n("Create article",`"${xe(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=tt(t.title),r=ss(t.article_id);return n("Update article",o?`"${xe(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",ss(t.article_id)?`id ${ss(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",tt(t.name)?`"${xe(tt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=tt(t.file_path);return n("Upload image",o?xe(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function qo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...i]=e.split("__"),l=i.join("__");if(r==="document360"){let k=pm(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:kc(t)}}let n=dm[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:xe(o,bc)}:{title:e,sep:"",arg:kc(t)}}function fm(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 hm(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(fm).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>xe(r,as))]}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}: ${xe(String(r),vc)}`);return n.length>0?[xe(n.join(" \xB7 "),as)]:null}return null}function mm(e){let t=tt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function gm(e,t,n){switch(e){case"d360_create_article":{let o=mm(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=tt(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 ${xe(o[0],120)}`:""}`]}default:return null}}function Bo(e,t=4,n,o){let r=e.replace(/\r\n/g,`
305
- `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let l=gm(n.slice(18),o,r);if(l)return{lines:l,hidden:0}}let i=hm(r)??r.split(`
306
- `);return{lines:i.slice(0,t).map(l=>xe(l,as)),hidden:Math.max(0,i.length-t)}}function Vo(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 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 Om=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Lm(e,t,n,o){if(Om.test(e))try{let r=Cc(o),i=typeof t.project_id=="string"&&t.project_id||r.project.projectId,l=Go(t,n),p=Yo(n);e.endsWith("publish_article")&&p&&console.log(O(` \u2B95 Live: ${p}`)),l&&i&&console.log(O(` \u2B95 Preview: ${Vo(r.connection.portalUrl,i,l,r.project.languageCode??"en")}`))}catch{}}async function Rc(e=process.cwd(),t="auto",n,o){let r=ym(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${O("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${O('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Mm(e,n),r.kind==="subscription"&&(r.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 i=!1,l=ls({cwd:e,profileName:n,allowProdWrites:i}),p={uuid:null,firstPrompt:null,titleFired:!1},m=wm({input:process.stdin,output:process.stdout}),k=[],g=null,T=!1;m.on("line",P=>{if(g){let N=g;g=null,N(P)}else k.push(P)}),m.on("close",()=>{if(T=!0,g){let P=g;g=null,P(null)}});function v(){return k.length>0?Promise.resolve(k.shift()):T?Promise.resolve(null):(process.stdout.write(O("> ")),new Promise(P=>{g=P}))}let _={cwd:e,version:o,profileName:n,allowProdWrites:()=>i,restartAgent:()=>{l.close(),l=ls({cwd:e,profileName:n,allowProdWrites:i}),p={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>p.uuid,setPendingName:P=>{p.pendingName=P},setModel:async P=>l.setModel(P),withPausedInput:async P=>{m.pause();try{return await P()}finally{m.resume()}}};try{for(;;){let P=await v();if(P===null)break;let N=P.trim();if(N){if(N.startsWith("/")){let D=fc(N);if(!D)continue;let M=pc[D.name];if(!M){console.log(C(`Unknown command: /${D.name}`)),console.log(f("Type /help for the list."));continue}let B=await M(D.args,_);if(B.kind==="exit")break;if(B.kind==="clear"){_.restartAgent();continue}if(B.kind==="allow-prod"){i=!0,_.restartAgent(),console.log(j("\u2713 Production writes authorized for this session.")),console.log("");continue}if(B.kind==="resume"){l.close(),l=ls({cwd:e,resume:B.uuid,profileName:n,allowProdWrites:i});let ee=km(B.uuid);p={uuid:B.uuid,firstPrompt:ee?.firstPrompt??null,titleFired:!0},xc(B.uuid),console.log(j(`\u2713 Resumed "${B.name}"`)),console.log("");continue}if(B.kind==="forward-to-agent"){p.firstPrompt||(p.firstPrompt=B.display??B.prompt);let ee=(B.display??"").trim().split(/\s+/),X=(ee[0]==="/check"||ee[0]==="/review")&&ee.includes("--fix"),ne=ee.slice(1).find(ot=>!ot.startsWith("--")),Be=X?Im(e,ne):[];if(await cs(l,B.prompt,r,p,e),X)try{Nm(e,Be,{reviewedCap:_m})}catch{}}else Um(e,n);continue}if(Dm(N)){let D=jm(N);if(D){try{Am(e,{title:D,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}p.firstPrompt||(p.firstPrompt=N),await cs(l,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${D}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${D}" and the article path(s) you wrote.`,r,p,e);continue}}p.firstPrompt||(p.firstPrompt=N),await cs(l,N,r,p,e)}}}finally{l.close(),m.close()}}function Mm(e,t){console.log(""),console.log(hn("document360-writer")),console.log(f(` cwd: ${e}`));let n=Cm(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Wm(e,t)),!Rm(e))console.log(L(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{let o=!1;try{if(ho(e),!Fe(e))for(let r of mo(e))console.log(L(` ${r}`))}catch{}try{let r=Pm(e);r.persisted&&r.appType?console.log(f(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=Em(e);for(let i of Ho(r.applied))console.log(L(` ${i}`))}catch{}try{let r=jn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),i=r?Dn(r):null;if(i?.kind==="recommend"&&i.rec.note){let l=i.rec.tone==="warn"?L:f;for(let p of i.rec.note.split(`
307
- `))console.log(l(` ${p}`));i.rec.picker&&console.log(O(` Pick one: ${i.rec.picker.options.map(p=>p.cmd).join(" \xB7 ")}`))}}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Um(e,t){try{let n=jn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Dn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(f(` Next: ${Zi(o.rec.lead)}`))}catch{}}function Wm(e,t){try{let n=Cc(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=Sm(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let i={...$c(r.idToken)??{},...$c(r.accessToken)??{}},l=i.email??i.preferred_username??"signed in";return Tm(r)&&!r.refreshToken?L(` 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 Fm(){console.error(""),console.error(`Sign in with your Claude subscription: run ${O("claude")} once, then retry.`),console.error(` (No Claude Code? ${O("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${O("https://console.anthropic.com/settings/keys")}`)}function Hm(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;$m({uuid:t,name:r??vm(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function qm(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||xm(o,t).then(r=>{r&&bm(n,r)}).catch(()=>{})}async function cs(e,t,n,o,r){let i=new Map;for await(let l of e.send(t))Bm(l,o,r,n,i)}function Bm(e,t,n,o,r){switch(e.type){case"session":t.uuid||Hm(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=qo(e.name,e.input);i&&(process.stdout.write(`
308
-
309
- `),console.log(`${j("\u25CF")} ${ge(i.title)}${i.arg!==null?ae(`${i.sep}(${i.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=He(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let l=p=>p===1?"":"s";console.log(ae(` \u23BF Added ${i.added} line${l(i.added)}, removed ${i.removed} line${l(i.removed)}`));for(let p of i.lines)console.log(p);i.hidden>0&&console.log(f(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let l=Bo(e.output,4,e.isError?void 0:i.name,i.input),p=e.isError?C:ae;l.lines.forEach((m,k)=>console.log(p((k===0?" \u23BF ":" ")+m))),l.hidden>0&&console.log(f(` \u2026 +${l.hidden} lines`)),e.isError||Lm(i.name,i.input,e.output,n);break}case"result":process.stdout.write(`
310
- `),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&&(xc(t.uuid),t.titleFired||qm(t,n));break;case"error":console.error(""),console.error(C(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Fm();break}}import{render as iw}from"ink";import{resolveAuth as sw}from"document360-engine";import{useCallback as G,useEffect as Re,useMemo as ms,useRef as J,useState as F}from"react";import{Box as oe,Text as A,useApp as ig,useInput as sg,useStdout as ag}from"ink";import{existsSync as Qt,readFileSync as nr,readdirSync as lg}from"node:fs";import{basename as En,isAbsolute as cg,join as gs}from"node:path";import{createSession as ed,classifyClaudeAuth as $s,CLAUDE_CODE_SETUP_HINT as dg,loginPkce as ug,toStoredTokens as pg,saveTokens as fg,getAccessToken as hg,resolveActiveProfile as Ce,resolveProjectId as mg,getArticle as gg,decodeJwtClaims as Zt,isExpired as nt,loadTokens as vt,clearTokens as wg,clearProfileProject as yg,setTitle as kg,slugify as bg,touchSession as ws,upsertSession as vg,generateTitle as td,findByName as $g,listSessions as xg,renameSession as Cg,suggestNextAction as Rg,readProjectConfig as te,writeProjectConfig as nd,resolveAndPersistAppType as Pg,detectAppType as Tg,resolveModelSetting as xs,loadProfileMap as od,applyPull as rd,computeSyncStatus as ys,lintDocs as id,compareRemoteSources as Sg,planPull as sd,establishBaselines as Dg,rebaselineServerMeta as jg,inventoryRepo as Ag,knownEnvironments as Eg,resolveEnvironment as Ng,planPartitions as ks,partitionEvenly as Ig,screenshotPlaceholderIds as _g,trackedArticlePaths as Og,runPartitioned as or,estimateBulkCost as ad,resolveModelForOperation as rr,readDocsPlan as Lg,checkForUpdate as Mg,detectInstallKind as Ug,isSelfUpdatable as Wg,devHintsGuidePath as ld,toolFeedbackPath as cd,reconcileToolFeedback as Fg,reconcileUpgradeActions as Hg,stampArticles as bs,listArticleFiles as dd,CONTENT_CAP_VERSION as vs,ENGINE_VERSION as yd,DEFAULT_DOCS_DIR as kd,setProfileProject as qg,writeCrashLog as Bg,applyStructureOrder as ud,orderSyncLine as pd,applyRelatedArticles as fd,relatedSyncLine as hd}from"document360-engine";Qe();import{spawn as Pc}from"node:child_process";function Vm(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Gm(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?Pc([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Pc(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 i=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(i)}catch{o(!1)}})}async function ds(e){for(let[t,n]of Vm())if(await Gm(t,n,e))return!0;return!1}var Ym=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function us(e,t){if(t.closed)return e;let n=e.split(`
311
- `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let i=n[r];if(!t.cueSeen){Ym.test(i)&&(t.cueSeen=!0);continue}let l=/^(\s{0,3})[-*•]\s+(.*)$/.exec(i);l?(n[r]=`${l[1]}${++t.num}. ${l[2]}`,o=!0):o&&i.trim()!==""&&/^\S/.test(i)&&(t.closed=!0)}return n.join(`
312
- `)}import{existsSync as zm,mkdirSync as Km,readFileSync as Xm,writeFileSync as Qm}from"node:fs";import{join as Tc}from"node:path";import{writerDir as Jm}from"document360-engine";function Sc(e){return Tc(Jm(e),".sessions")}function Dc(e,t){return Tc(Sc(e),`${t}.json`)}function jc(e,t,n){try{Km(Sc(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Qm(Dc(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function ps(e,t){try{let n=Dc(e,t);if(!zm(n))return[];let o=JSON.parse(Xm(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Zm=e=>`\x1B]0;${e}\x07`,eg=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Ac(e){process.stdout.isTTY&&process.stdout.write(e)}function Xt(e){Ac(Zm(e))}function zo(e){Ac(eg(e))}var Ko=["\xB7 "," \xB7"],Xo="\u{1F7E3}";Eo();yo();var Qo=[{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:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{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> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; 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:"roadmap",usage:"/roadmap [done <step>]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done <step>` marks one you finished yourself",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:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (publish), take portal (pull), or skip \u2014 for each. Bare: walk them all",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:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",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:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],Ec={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/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","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function Nc(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Ec[n])return Ec[n];let o=Qo.find(r=>r.name===t);return o?o.desc:""}function Ic(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Qo.filter(n=>n.name.startsWith(t))}function _c(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as Oc,Text as de}from"ink";import{jsx as ue,jsxs as Jo}from"react/jsx-runtime";function tg({row:e}){switch(e.t){case"head":return ue(de,{color:q,bold:!0,children:e.s});case"text":return ue(de,{children:e.s});case"dim":return ue(de,{dimColor:!0,children:e.s});case"sub":return ue(de,{bold:!0,dimColor:!0,children:e.s});case"good":return ue(de,{color:"green",children:e.s});case"step":return Jo(de,{children:[ue(de,{color:q,children:`${e.n}. `}),e.s]});case"cmd":return Jo(de,{children:[" ",ue(de,{color:q,children:e.name.padEnd(20)}),ue(de,{dimColor:!0,children:e.s})]});case"gap":return ue(de,{children:" "})}}function Lc({tab:e,width:t,version:n,engineVersion:o}){let r=Se[e]??Se[0],i=6+Se.reduce((p,m)=>p+m.label.length+4,0),l="\u2500".repeat(Math.min(i,Math.max(t-1,20)));return Jo(Oc,{flexDirection:"column",paddingX:1,children:[Jo(de,{children:[ue(de,{color:q,bold:!0,children:"Help "}),Se.map((p,m)=>m===e?ue(de,{color:"white",backgroundColor:q,bold:!0,children:` ${p.label} `},p.key):ue(de,{dimColor:!0,children:` ${p.label} `},p.key))]}),ue(de,{color:q,children:l}),ue(Oc,{flexDirection:"column",marginTop:1,children:r.rows.map((p,m)=>ue(tg,{row:p},m))}),ue(de,{dimColor:!0,children:`
313
- \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var ng=/^(?:\d+[.)]|[-*•])\s+/;function Mc(e,t,n=4){let o=new Set(t.map(i=>i.toLowerCase())),r=[];for(let i of e.split(`
314
- `)){let l=i.trim().replace(ng,""),p=l.match(/^`([^`]+)`$/);p&&(l=p[1].trim());let m=l.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!m||!o.has(m[1].toLowerCase()))continue;let k=`/${m[1].toLowerCase()}${m[2]?` ${m[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}W();function An(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function qe(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Uc(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var og=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Wc(e,t,n){if(!og.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(i=>{let l=i.replace(/\\/g,"/");return r===l||r.endsWith(`/${l}`)})??null}function fs(e){return e.replace(/^[\w.-]+\//,"")}var Zo=16,Fc={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function bt(e){return typeof e=="string"?e:e.cmd}function Hc(e){return typeof e=="string"?void 0:e.desc}function hs(e){return e.trim().split(/\s+/).slice(1).join(" ")}function qc(e,t){let n=hs(t);return e.some(r=>bt(r).trim()===t.trim()||!!n&&hs(bt(r))===n)?e.filter(r=>bt(r).trim()!==t.trim()&&!(n&&hs(bt(r))===n)):[]}import{isDirectiveMention as Vg,stripDirectiveMention as Gg,appendDirective as Yg}from"document360-engine";var rg=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Bc(e){return e.replace(/\r\n?/g,`
315
- `)}function Vc(e){return e.includes(`
316
- `)||e.length>200}function Gc(e,t){let n=t.split(`
317
- `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Yc(e,t){return e.replace(rg,n=>t.get(n)??n)}function zc(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function er(e,t){let n=Math.max(1,t),o=[],r=0;for(let i of e.split(`
318
- `)){if(i.length===0)o.push({start:r,end:r});else for(let l=0;l<i.length;l+=n)o.push({start:r+l,end:r+Math.min(l+n,i.length)});r+=i.length+1}return o.length>0?o:[{start:0,end:0}]}function tr(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Kc(e,t,n){let o=tr(e,t),r=o+n;if(r<0||r>=e.length)return t;let i=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+i,e[r].end)}function Xc(e,t,n){let o=e[tr(e,t)];return n==="start"?o.start:o.end}function Qc(e,t,n){let o=Math.max(1,n),r=e.split(`
300
+ `)}async function ec(e,t){let n=e.includes("--fix"),o=e.find(l=>!l.startsWith("--")),r=o?` ${o}`:"",i=Oh({cwd:t.cwd,scope:o});if(n)return i.length===0?(console.log(j("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${i.length} doc issue${i.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:Yi(i),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let l of Mo(i))console.log(i.length===0?j(l):L(l));return i.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}W();import{lintDocs as Hh,loadStyleGuide as qh,buildReviewPrompt as Bh,readProjectConfig as Vh,DEFAULT_DOCS_DIR as Gh}from"document360-engine";W();import{readProjectConfig as Lh,loadProfileMap as Mh,resolveActiveProfile as Uh,desiredCategoryOrder as Wh,desiredArticleOrder as Fh}from"document360-engine";function tc(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var nc=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Sn(e,t){try{if(!Lh(e))return[];let n=Uh(e,t),o=Mh(e,n.name);if(!o)return[];let r=new Map;for(let l of Fh(o)){let p=r.get(l.categoryPath);p?p.push(l):r.set(l.categoryPath,[l])}let i=[];for(let l of Wh(o)){i.push(tc(nc(l.path)));for(let p of(r.get(l.path)??[]).sort((m,k)=>m.order-k.order))i.push(` ${tc(nc(p.path))}`)}return i}catch{return[]}}async function oc(e,t){let n=Sn(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(O("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function zi(e,t){let n=Vh(e);if(!n)return null;let o=(n.docsDir??Gh).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),i=t.find(g=>!g.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),l=Hh({cwd:e}),p=i?l.filter(g=>g.path===`${o}/${i}`||g.path.startsWith(`${o}/${i}/`)):l,m=i?"":Sn(e).join(`
301
+ `);return{prompt:Bh({docsRoot:o,scope:i,styleGuide:qh(e),deterministicFindings:p,fix:r,structure:m||void 0}),display:`/review${i?` ${i}`:""}${r?" --fix":""}`}}async function rc(e,t){if(et("review",e)){let o=Kt(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=zi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as Yh}from"document360-engine";function Ki(e,t){if(!Yh(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(`
302
+ `),display:`/reorder${n?` ${n}`:""}`}}async function ic(e,t){if(et("reorder",e)){let o=Kt(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=Ki(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as zh,writeProjectConfig as sc,isAppType as Kh,playbookSkillName as Xh,detectAppType as ac}from"document360-engine";var lc=["web","cli","service","library"],Qh=new Set(["web","cli"]);function Xi(e){return Qh.has(e)?`${Xh(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Uo(e,t){let n=t.cwd,o=zh(n);if(!o)return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let i=o.appType??ac(n);if(i){let l=o.appType?"set in config":"auto-detected";console.log(`${O("Genre:")} ${i} (${l}) \u2014 ${Xi(i)}`)}else console.log(L("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${lc.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(f("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:i,...l}=o;sc(l,n);let p=ac(n);return console.log(j(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${Xi(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return Kh(r)?(sc({...o,appType:r},n),console.log(j(`\u2713 Genre set to ${r} \u2014 ${Xi(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(C(`Unknown genre "${r}". Choose one of: ${lc.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}W();import{listRoadmap as cc,roadmapProgress as dc,stampRoadmapDone as Jh}from"document360-engine";function Qi(e){let t=cc(e);if(t.length===0)return["No docs roadmap yet \u2014 the docs agent seeds .d360-writer/roadmap.md when it pins a structure,","and adds steps as the app changes. You can also write steps by hand (## [open] <step>), or ask:",'"propose the docs roadmap for this repo".'];let n=dc(e),o=[`Docs roadmap \u2014 ${n.done} of ${n.total} step${n.total===1?"":"s"} done:`,""];for(let r of t)o.push(` ${r.status==="done"?"\u2713":"\u25CB"} ${r.title}${r.run?` \xB7 ${r.run}`:""}`);return o.push(""),o.push(n.next?`Next: ${n.next.title}${n.next.run?` \u2014 ${n.next.run}`:""}`:"Campaign complete \u2014 the docs agent adds new steps as the app changes."),o.push("(Edit .d360-writer/roadmap.md freely \xB7 /roadmap done <step> marks one you finished yourself.)"),o}function Ji(e,t){if(!t.trim())return{ok:!1,line:"Usage: /roadmap done <step title>"};if(!Jh(e,t,{doneAt:new Date().toISOString()})){let r=cc(e).filter(i=>i.status==="open");return{ok:!1,line:r.length?`No open step titled "${t}". Open steps: ${r.map(i=>`"${i.title}"`).join(", ")}`:`No open step titled "${t}" \u2014 the roadmap has no open steps.`}}let o=dc(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${t}${o?` \u2014 next up: ${o.title}${o.run?` (${o.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}async function uc(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Ji(n,e.slice(1).join(" ").trim());return console.log(r.ok?j(r.line):L(r.line)),{kind:"continue"}}let o=Qi(n);console.log(O(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?f(r):r);return{kind:"continue"}}var pc={help:jr,"?":jr,clear:ma,exit:Ar,quit:Ar,init:Or,mcp:ko,publish:Qa,audit:vn,discover:Ja,scope:el,pull:cl,resolve:sl,convert:dl,write:gl,draft:vl,document:$l,resume:Rl,rename:Pl,profile:Sl,model:Al,doctor:Cn,workspace:Ll,project:Ml,"allow-prod":Ul,login:Wl,logout:Fl,screenshot:No,"capture-setup":Rn,devhints:Ca,inbox:Gl,"catch-up":Yl,update:zl,reset:Zl,check:ec,review:rc,reorder:ic,structure:oc,genre:Uo,roadmap:uc};function fc(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}Qe();var Zh="Or just tell me what to write or update.",em='\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 ye(e){return e===1?"":"s"}function Wo(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function es(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var tm={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",options:[{cmd:"/genre web",desc:"web app / SaaS UI"},{cmd:"/genre cli",desc:"command-line tool"},{cmd:"/genre service",desc:"API / backend service"},{cmd:"/genre library",desc:"SDK / library"}]};function nm(e){let t=[];if(e.devhints!=="current"&&e.builderStarted){let n=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",o=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";t.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${n}${o} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${n}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&t.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:tm,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.discovery&&e.discovery.status!=="confident"){let n=e.discovery.openQuestions;t.push(e.discovery.status==="pending"?{key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/publish steps)."}:n>0?{key:"discovery",bullet:`product discovery is waiting on ${n} answer${ye(n)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}:{key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${ye(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${ye(n)}.`})}if(e.directives>0||e.pendingText){let n=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",o=[];e.directives>0&&o.push(`${e.directives} owner directive${ye(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
303
+ \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ye(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${ye(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${ye(n)} up.`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${ye(n.total)} done \u2014 next: ${o.title}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${ye(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${ye(n)}.`})}return t}function hc(e){return e.find(t=>t.lead||t.picker)??null}function Zi(e,t){let n=t.filter(l=>l.bullet).map(l=>` \u2022 ${l.bullet}`),o=hc(t),r=[];o?.lead?r.push(es(o.lead)):o?.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let l of t.filter(p=>p!==o).slice(0,2))l.follow&&r.push(l.follow);let i=[e,...n];return r.length&&i.push(r.join(" ")),i.push(Zh),i.join(`
304
+ `)}function Dn(e){if(!e.ready)return{kind:"idle"};let t=nm(e);if(!e.hasDocs){let i=hc(t);return i&&(i.lead?.kind==="cmd"||i.picker)?{kind:"recommend",rec:{note:Zi("\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",t),tone:i.tone??"info",lead:i.lead,picker:i.picker}}:{kind:"recommend",rec:{note:em,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null}}}if(t.length===0){let i=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${ye(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${ye(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${i}`,tone:"info",lead:null,picker:null}}}let n=t.filter(i=>i.lead||i.picker),o=n[0]??null;return o?(o.key==="audit"||o.key==="roadmap"&&n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${ye(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:Zi("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:Zi("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as ts,readdirSync as os}from"node:fs";import{spawnSync as om}from"node:child_process";import{join as Fo}from"node:path";import{readProjectConfig as gc,resolveActiveProfile as wc,loadTokens as rm,isExpired as im,loadProfileMap as yc,countLocalAhead as sm,readDocsPlan as am,devHintsGuidePath as lm,DEFAULT_DOCS_DIR as ns,roadmapProgress as cm,listRoadmap as dm,readProductBriefState as um}from"document360-engine";Qe();function mc(e){try{return os(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function rs(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>mc(Fo(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&mc(Fo(e,o)))}function is(e,t){try{let n=gc(e);if(!n)return!1;let o=wc(e,t),r=yc(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let i=Fo(e,(n.docsDir??ns).replace(/\/+$/,""));return!!(ts(i)&&os(i).length>0||ts(lm(e)))}catch{return!1}}function jn(e,t,n){try{let o=gc(e);if(!o)return null;let r=wc(e,t),i=rm(r.name),l=!!i&&(!im(i)||!!i.refreshToken),p=is(e,t)||!rs(e,o.authoritativeSourceFiles),m=yc(e,r.name),k=m?Object.keys(m.articles).length:0,g=Fo(e,(o.docsDir??ns).replace(/\/+$/,"")),T=!1;try{T=ts(g)&&os(g).length>0}catch{}let v=0;if(m?.lastAnalyzedCommit)try{let te=om("git",["rev-list","--count",`${m.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});te.status===0&&(v=parseInt((te.stdout||"").trim(),10)||0)}catch{}let _=0;try{let te=am(e);if(te.length>0){let Pe=(o.docsDir??ns).replace(/\/+$/,"");_=fi(e,Pe,te.map(ot=>ot.path)).length}}catch{}let P=Pn(e),N=Tn({...P,directives:0}),D=sm(e,t),M=je(e),B=cm(e),ee=um(e),X=ee?{status:ee.status,openQuestions:ee.openQuestions}:null;return!X&&T&&dm(e).some(Pe=>Pe.status==="open"&&(Pe.run??"").trim()==="/discover")&&(X={status:"pending",openQuestions:0}),{ready:l&&p&&!n.claudeMissing,hasDocs:T,tracked:k,pendingText:N,directives:P.directives,behind:v,pendingWrites:_,localAhead:D,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:M.status,devhintsCompletedVersion:M.completedVersion,devhintsToVersion:ce,builderStarted:He(e),genreUnknown:n.genreUnknown,roadmap:B,discovery:X}}catch{return null}}function kc(e,t){let n=[],o="";for(let r of e.split(/\s+/).filter(Boolean))for(o.length?o.length+1+r.length<=t?o+=` ${r}`:(n.push(o),o=r):o=r;o.length>t;)n.push(o.slice(0,t)),o=o.slice(t);return o&&n.push(o),n}function Ho(e){if(e.length===0)return[];let t=(i,l)=>`${i}${"\u2500".repeat(78)}${l}`,n=(i="")=>`\u2502 ${i.padEnd(76)} \u2502`,o=[`\u2B06 d360-writer upgraded \u2014 ${e.length===1?"one improvement affects":`${e.length} improvements affect`} the docs you've already written:`,"",t("\u250C","\u2510")];e.forEach((i,l)=>{l>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let p of kc(`${l+1}. ${i.feature}`,76))o.push(n(p));o.push(n());for(let p of kc(i.why,73))o.push(n(` ${p}`));o.push(n())}),o.push(t("\u2514","\u2518")),o.push("");let r=e.length>1;return o.push(`\u2713 ${r?"These are":"This is"} now on your docs roadmap \u2014 each launch shows your next step below (/roadmap shows the full campaign).`),o}W();var pm={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"},vc=160,as=200,$c=40;function xe(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function bc(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}: ${xe(typeof r=="string"?r:JSON.stringify(r),$c)}`);return t.length>4&&n.push("\u2026"),xe(n.join(", "),vc)}var tt=e=>typeof e=="string"&&e?e:null,ss=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function fm(e){let t=tt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ")}function hm(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=tt(t.title);if(!o)return null;let r=fm(t.local_path);return n("Create article",`"${xe(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=tt(t.title),r=ss(t.article_id);return n("Update article",o?`"${xe(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",ss(t.article_id)?`id ${ss(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",tt(t.name)?`"${xe(tt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=tt(t.file_path);return n("Upload image",o?xe(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function qo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...i]=e.split("__"),l=i.join("__");if(r==="document360"){let k=hm(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:bc(t)}}let n=pm[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:xe(o,vc)}:{title:e,sep:"",arg:bc(t)}}function mm(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 gm(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(mm).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>xe(r,as))]}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}: ${xe(String(r),$c)}`);return n.length>0?[xe(n.join(" \xB7 "),as)]:null}return null}function wm(e){let t=tt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function ym(e,t,n){switch(e){case"d360_create_article":{let o=wm(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=tt(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 ${xe(o[0],120)}`:""}`]}default:return null}}function Bo(e,t=4,n,o){let r=e.replace(/\r\n/g,`
305
+ `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let l=ym(n.slice(18),o,r);if(l)return{lines:l,hidden:0}}let i=gm(r)??r.split(`
306
+ `);return{lines:i.slice(0,t).map(l=>xe(l,as)),hidden:Math.max(0,i.length-t)}}function Vo(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 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 Mm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Um(e,t,n,o){if(Mm.test(e))try{let r=Rc(o),i=typeof t.project_id=="string"&&t.project_id||r.project.projectId,l=Go(t,n),p=Yo(n);e.endsWith("publish_article")&&p&&console.log(O(` \u2B95 Live: ${p}`)),l&&i&&console.log(O(` \u2B95 Preview: ${Vo(r.connection.portalUrl,i,l,r.project.languageCode??"en")}`))}catch{}}async function Pc(e=process.cwd(),t="auto",n,o){let r=bm(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${O("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${O('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Wm(e,n),r.kind==="subscription"&&(r.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 i=!1,l=ls({cwd:e,profileName:n,allowProdWrites:i}),p={uuid:null,firstPrompt:null,titleFired:!1},m=km({input:process.stdin,output:process.stdout}),k=[],g=null,T=!1;m.on("line",P=>{if(g){let N=g;g=null,N(P)}else k.push(P)}),m.on("close",()=>{if(T=!0,g){let P=g;g=null,P(null)}});function v(){return k.length>0?Promise.resolve(k.shift()):T?Promise.resolve(null):(process.stdout.write(O("> ")),new Promise(P=>{g=P}))}let _={cwd:e,version:o,profileName:n,allowProdWrites:()=>i,restartAgent:()=>{l.close(),l=ls({cwd:e,profileName:n,allowProdWrites:i}),p={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>p.uuid,setPendingName:P=>{p.pendingName=P},setModel:async P=>l.setModel(P),withPausedInput:async P=>{m.pause();try{return await P()}finally{m.resume()}}};try{for(;;){let P=await v();if(P===null)break;let N=P.trim();if(N){if(N.startsWith("/")){let D=fc(N);if(!D)continue;let M=pc[D.name];if(!M){console.log(C(`Unknown command: /${D.name}`)),console.log(f("Type /help for the list."));continue}let B=await M(D.args,_);if(B.kind==="exit")break;if(B.kind==="clear"){_.restartAgent();continue}if(B.kind==="allow-prod"){i=!0,_.restartAgent(),console.log(j("\u2713 Production writes authorized for this session.")),console.log("");continue}if(B.kind==="resume"){l.close(),l=ls({cwd:e,resume:B.uuid,profileName:n,allowProdWrites:i});let ee=vm(B.uuid);p={uuid:B.uuid,firstPrompt:ee?.firstPrompt??null,titleFired:!0},Cc(B.uuid),console.log(j(`\u2713 Resumed "${B.name}"`)),console.log("");continue}if(B.kind==="forward-to-agent"){p.firstPrompt||(p.firstPrompt=B.display??B.prompt);let ee=(B.display??"").trim().split(/\s+/),X=(ee[0]==="/check"||ee[0]==="/review")&&ee.includes("--fix"),te=ee.slice(1).find(ot=>!ot.startsWith("--")),Pe=X?Om(e,te):[];if(await cs(l,B.prompt,r,p,e),X)try{_m(e,Pe,{reviewedCap:Lm})}catch{}}else Fm(e,n);continue}if(Am(N)){let D=Em(N);if(D){try{Nm(e,{title:D,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}p.firstPrompt||(p.firstPrompt=N),await cs(l,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${D}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${D}" and the article path(s) you wrote.`,r,p,e);continue}}p.firstPrompt||(p.firstPrompt=N),await cs(l,N,r,p,e)}}}finally{l.close(),m.close()}}function Wm(e,t){console.log(""),console.log(hn("document360-writer")),console.log(f(` cwd: ${e}`));let n=Pm(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Hm(e,t)),!Tm(e))console.log(L(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{let o=!1;try{if(ho(e),!He(e))for(let r of mo(e))console.log(L(` ${r}`))}catch{}try{let r=Sm(e);r.persisted&&r.appType?console.log(f(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=Im(e);for(let i of Ho(r.applied))console.log(L(` ${i}`))}catch{}try{let r=jn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),i=r?Dn(r):null;if(i?.kind==="recommend"&&i.rec.note){let l=i.rec.tone==="warn"?L:f;for(let p of i.rec.note.split(`
307
+ `))console.log(l(` ${p}`));i.rec.picker&&console.log(O(` Pick one: ${i.rec.picker.options.map(p=>p.cmd).join(" \xB7 ")}`))}}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Fm(e,t){try{let n=jn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Dn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(f(` Next: ${es(o.rec.lead)}`))}catch{}}function Hm(e,t){try{let n=Rc(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=jm(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let i={...xc(r.idToken)??{},...xc(r.accessToken)??{}},l=i.email??i.preferred_username??"signed in";return Dm(r)&&!r.refreshToken?L(` 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 qm(){console.error(""),console.error(`Sign in with your Claude subscription: run ${O("claude")} once, then retry.`),console.error(` (No Claude Code? ${O("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${O("https://console.anthropic.com/settings/keys")}`)}function Bm(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Cm({uuid:t,name:r??xm(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Vm(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Rm(o,t).then(r=>{r&&$m(n,r)}).catch(()=>{})}async function cs(e,t,n,o,r){let i=new Map;for await(let l of e.send(t))Gm(l,o,r,n,i)}function Gm(e,t,n,o,r){switch(e.type){case"session":t.uuid||Bm(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=qo(e.name,e.input);i&&(process.stdout.write(`
308
+
309
+ `),console.log(`${j("\u25CF")} ${ge(i.title)}${i.arg!==null?ae(`${i.sep}(${i.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=qe(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let l=p=>p===1?"":"s";console.log(ae(` \u23BF Added ${i.added} line${l(i.added)}, removed ${i.removed} line${l(i.removed)}`));for(let p of i.lines)console.log(p);i.hidden>0&&console.log(f(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let l=Bo(e.output,4,e.isError?void 0:i.name,i.input),p=e.isError?C:ae;l.lines.forEach((m,k)=>console.log(p((k===0?" \u23BF ":" ")+m))),l.hidden>0&&console.log(f(` \u2026 +${l.hidden} lines`)),e.isError||Um(i.name,i.input,e.output,n);break}case"result":process.stdout.write(`
310
+ `),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&&(Cc(t.uuid),t.titleFired||Vm(t,n));break;case"error":console.error(""),console.error(C(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&qm();break}}import{render as aw}from"ink";import{resolveAuth as lw}from"document360-engine";import{useCallback as G,useEffect as Re,useMemo as ms,useRef as J,useState as F}from"react";import{Box as oe,Text as A,useApp as ag,useInput as lg,useStdout as cg}from"ink";import{existsSync as Qt,readFileSync as nr,readdirSync as dg}from"node:fs";import{basename as En,isAbsolute as ug,join as gs}from"node:path";import{createSession as td,classifyClaudeAuth as $s,CLAUDE_CODE_SETUP_HINT as pg,loginPkce as fg,toStoredTokens as hg,saveTokens as mg,getAccessToken as gg,resolveActiveProfile as Ce,resolveProjectId as wg,getArticle as yg,decodeJwtClaims as Zt,isExpired as nt,loadTokens as vt,clearTokens as kg,clearProfileProject as bg,setTitle as vg,slugify as $g,touchSession as ws,upsertSession as xg,generateTitle as nd,findByName as Cg,listSessions as Rg,renameSession as Pg,suggestNextAction as Tg,readProjectConfig as ne,writeProjectConfig as od,resolveAndPersistAppType as Sg,detectAppType as Dg,resolveModelSetting as xs,loadProfileMap as rd,applyPull as id,computeSyncStatus as ys,lintDocs as sd,compareRemoteSources as jg,planPull as ad,establishBaselines as Ag,rebaselineServerMeta as Eg,inventoryRepo as Ng,knownEnvironments as Ig,resolveEnvironment as _g,planPartitions as ks,partitionEvenly as Og,screenshotPlaceholderIds as Lg,trackedArticlePaths as Mg,runPartitioned as or,estimateBulkCost as ld,resolveModelForOperation as rr,readDocsPlan as Ug,checkForUpdate as Wg,detectInstallKind as Fg,isSelfUpdatable as Hg,devHintsGuidePath as cd,toolFeedbackPath as dd,reconcileToolFeedback as qg,reconcileUpgradeActions as Bg,stampArticles as bs,listArticleFiles as ud,CONTENT_CAP_VERSION as vs,ENGINE_VERSION as kd,DEFAULT_DOCS_DIR as bd,setProfileProject as Vg,writeCrashLog as Gg,applyStructureOrder as pd,orderSyncLine as fd,applyRelatedArticles as hd,relatedSyncLine as md}from"document360-engine";Qe();import{spawn as Tc}from"node:child_process";function Ym(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function zm(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?Tc([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Tc(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 i=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(i)}catch{o(!1)}})}async function ds(e){for(let[t,n]of Ym())if(await zm(t,n,e))return!0;return!1}var Km=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function us(e,t){if(t.closed)return e;let n=e.split(`
311
+ `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let i=n[r];if(!t.cueSeen){Km.test(i)&&(t.cueSeen=!0);continue}let l=/^(\s{0,3})[-*•]\s+(.*)$/.exec(i);l?(n[r]=`${l[1]}${++t.num}. ${l[2]}`,o=!0):o&&i.trim()!==""&&/^\S/.test(i)&&(t.closed=!0)}return n.join(`
312
+ `)}import{existsSync as Xm,mkdirSync as Qm,readFileSync as Jm,writeFileSync as Zm}from"node:fs";import{join as Sc}from"node:path";import{writerDir as eg}from"document360-engine";function Dc(e){return Sc(eg(e),".sessions")}function jc(e,t){return Sc(Dc(e),`${t}.json`)}function Ac(e,t,n){try{Qm(Dc(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Zm(jc(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function ps(e,t){try{let n=jc(e,t);if(!Xm(n))return[];let o=JSON.parse(Jm(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var tg=e=>`\x1B]0;${e}\x07`,ng=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Ec(e){process.stdout.isTTY&&process.stdout.write(e)}function Xt(e){Ec(tg(e))}function zo(e){Ec(ng(e))}var Ko=["\xB7 "," \xB7"],Xo="\u{1F7E3}";Eo();yo();var Qo=[{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:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{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> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; 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:"roadmap",usage:"/roadmap [done <step>]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done <step>` marks one you finished yourself",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:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (publish), take portal (pull), or skip \u2014 for each. Bare: walk them all",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:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",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:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],Nc={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/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","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function Ic(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Nc[n])return Nc[n];let o=Qo.find(r=>r.name===t);return o?o.desc:""}function _c(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Qo.filter(n=>n.name.startsWith(t))}function Oc(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as Lc,Text as de}from"ink";import{jsx as ue,jsxs as Jo}from"react/jsx-runtime";function og({row:e}){switch(e.t){case"head":return ue(de,{color:q,bold:!0,children:e.s});case"text":return ue(de,{children:e.s});case"dim":return ue(de,{dimColor:!0,children:e.s});case"sub":return ue(de,{bold:!0,dimColor:!0,children:e.s});case"good":return ue(de,{color:"green",children:e.s});case"step":return Jo(de,{children:[ue(de,{color:q,children:`${e.n}. `}),e.s]});case"cmd":return Jo(de,{children:[" ",ue(de,{color:q,children:e.name.padEnd(20)}),ue(de,{dimColor:!0,children:e.s})]});case"gap":return ue(de,{children:" "})}}function Mc({tab:e,width:t,version:n,engineVersion:o}){let r=De[e]??De[0],i=6+De.reduce((p,m)=>p+m.label.length+4,0),l="\u2500".repeat(Math.min(i,Math.max(t-1,20)));return Jo(Lc,{flexDirection:"column",paddingX:1,children:[Jo(de,{children:[ue(de,{color:q,bold:!0,children:"Help "}),De.map((p,m)=>m===e?ue(de,{color:"white",backgroundColor:q,bold:!0,children:` ${p.label} `},p.key):ue(de,{dimColor:!0,children:` ${p.label} `},p.key))]}),ue(de,{color:q,children:l}),ue(Lc,{flexDirection:"column",marginTop:1,children:r.rows.map((p,m)=>ue(og,{row:p},m))}),ue(de,{dimColor:!0,children:`
313
+ \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var rg=/^(?:\d+[.)]|[-*•])\s+/;function Uc(e,t,n=4){let o=new Set(t.map(i=>i.toLowerCase())),r=[];for(let i of e.split(`
314
+ `)){let l=i.trim().replace(rg,""),p=l.match(/^`([^`]+)`$/);p&&(l=p[1].trim());let m=l.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!m||!o.has(m[1].toLowerCase()))continue;let k=`/${m[1].toLowerCase()}${m[2]?` ${m[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}W();function An(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Be(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Wc(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var ig=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Fc(e,t,n){if(!ig.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(i=>{let l=i.replace(/\\/g,"/");return r===l||r.endsWith(`/${l}`)})??null}function fs(e){return e.replace(/^[\w.-]+\//,"")}var Zo=16,Hc={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function bt(e){return typeof e=="string"?e:e.cmd}function qc(e){return typeof e=="string"?void 0:e.desc}function hs(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Bc(e,t){let n=hs(t);return e.some(r=>bt(r).trim()===t.trim()||!!n&&hs(bt(r))===n)?e.filter(r=>bt(r).trim()!==t.trim()&&!(n&&hs(bt(r))===n)):[]}import{isDirectiveMention as Yg,stripDirectiveMention as zg,appendDirective as Kg}from"document360-engine";var sg=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Vc(e){return e.replace(/\r\n?/g,`
315
+ `)}function Gc(e){return e.includes(`
316
+ `)||e.length>200}function Yc(e,t){let n=t.split(`
317
+ `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function zc(e,t){return e.replace(sg,n=>t.get(n)??n)}function Kc(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function er(e,t){let n=Math.max(1,t),o=[],r=0;for(let i of e.split(`
318
+ `)){if(i.length===0)o.push({start:r,end:r});else for(let l=0;l<i.length;l+=n)o.push({start:r+l,end:r+Math.min(l+n,i.length)});r+=i.length+1}return o.length>0?o:[{start:0,end:0}]}function tr(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Xc(e,t,n){let o=tr(e,t),r=o+n;if(r<0||r>=e.length)return t;let i=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+i,e[r].end)}function Qc(e,t,n){let o=e[tr(e,t)];return n==="start"?o.start:o.end}function Jc(e,t,n){let o=Math.max(1,n),r=e.split(`
319
319
  `),i=0;for(let l=r.length-1;l>=0;l--){let p=r[l];if(i+=Math.max(1,Math.ceil(p.length/o)),i>=t){let m=i-t;return{text:[m>0?p.slice(m*o):p,...r.slice(l+1)].join(`
320
- `),truncated:l>0||m>0}}}return{text:e,truncated:!1}}function Jc(e,t){if(t||e.length===0||/\s$/.test(e))return{head:e,keep:""};let n=e.search(/\s\S*$/);return n<0?{head:"",keep:e}:{head:e.slice(0,n),keep:e.slice(n)}}function Zc(e){let t=!1,n=0,o=0;for(let r of e.split(`
321
- `)){let i=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&i<e.length&&(n=i+1),o=i+1}return n}import{Fragment as ir,jsx as E,jsxs as Y}from"react/jsx-runtime";var zg={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},md=` 1. /init \u2014 pick your Document360 environment & scaffold config
320
+ `),truncated:l>0||m>0}}}return{text:e,truncated:!1}}function Zc(e,t){if(t||e.length===0||/\s$/.test(e))return{head:e,keep:""};let n=e.search(/\s\S*$/);return n<0?{head:"",keep:e}:{head:e.slice(0,n),keep:e.slice(n)}}function ed(e){let t=!1,n=0,o=0;for(let r of e.split(`
321
+ `)){let i=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&i<e.length&&(n=i+1),o=i+1}return n}import{Fragment as ir,jsx as E,jsxs as Y}from"react/jsx-runtime";var Xg={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},gd=` 1. /init \u2014 pick your Document360 environment & scaffold config
322
322
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
323
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Kg(e,t,n,o){let r=$s(n),i=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",l=xs(e),p=te(e),m=(p?.docsDir??kd).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${m}/ + config`,g={version:t,engineVersion:yd,claude:i,model:l.model,modelSource:zg[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 g;try{let T=Ce(e,o);g.profile=T.name,g.apiUrl=T.connection.apiUrl,g.prod=T.production,g.project=T.project.projectName??T.project.projectId??"(chosen at login)";let v=vt(T.name);if(v){let _={...Zt(v.idToken)??{},...Zt(v.accessToken)??{}},P=_.email??_.preferred_username??"signed in";nt(v)?v.refreshToken&&(g.who=P,g.loggedOut=!1,g.sessionHint="session expired \u2014 refreshing\u2026"):(g.who=P,g.loggedOut=!1,g.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return g}function Xg(e,t){try{let n=Ce(e,t),o=vt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Zt(o.idToken)??{},...Zt(o.accessToken)??{}},i=r.email??r.preferred_username??"signed in";return nt(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${i} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var gd=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],en=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Qg="Ask me to write or update an article\u2026";function Jt({ch:e,dim:t}){let[n,o]=F(!0);return Re(()=>{let r=setInterval(()=>o(i=>!i),530);return()=>clearInterval(r)},[]),E(A,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Jg=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function wd(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Zg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ew({startTime:e,chars:t}){let[n,o]=F(0);Re(()=>{let m=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(m)},[]);let r=en[n%en.length],i=gd[Math.floor(n/16)%gd.length],l=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return Y(oe,{children:[E(A,{color:q,children:` ${r} ${i}\u2026 `}),E(A,{color:"gray",children:`(${kn(l)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function tw({text:e}){let[t,n]=F(0);return Re(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),E(oe,{paddingX:1,children:E(A,{color:q,children:`${en[t%en.length]} ${e}`})})}var nw=12e4;function ow({p:e}){let[t,n]=F(0);Re(()=>{let D=setInterval(()=>n(M=>M+1),150);return()=>clearInterval(D)},[]);let o=en[t%en.length],r=Math.floor((Date.now()-e.startedAt)/1e3),i=Math.floor((Date.now()-e.lastAt)/1e3),l=Math.round(e.chars/4),p=Date.now()-e.lastAt>=nw,m=e.verb??"Converting",k=e.unit??"article",g=e.rows.reduce((D,M)=>D+M.items,0),T=m.toLowerCase(),v=e.rows,_=0;if(v.length>Zo){let D=v.findIndex(B=>B.status==="active"||B.status==="pending"),M=Math.max(0,Math.min(D-2,v.length-Zo));_=v.slice(0,M).filter(B=>B.status==="done").length,v=v.slice(M,M+Zo)}let P=Math.min(40,Math.max(...v.map(D=>fs(D.label).length),0)),N=D=>D==="failed"?"red":D==="active"?q:void 0;return Y(oe,{flexDirection:"column",children:[Y(oe,{children:[E(A,{color:q,children:` ${o} ${m} ${g} ${k}${g===1?"":"s"} `}),E(A,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${l} tokens \xB7 ${kn(r)} \xB7 esc to stop`})]}),_>0&&E(A,{dimColor:!0,children:` \u2714 +${_} done`}),v.map(D=>Y(A,{color:N(D.status),dimColor:D.status==="done"||D.status==="pending",children:[` ${Fc[D.status]} ${fs(D.label).padEnd(P)}`,D.status==="active"&&D.itemsDone!==void 0?` (${D.itemsDone}/${D.items} ${k}${D.items===1?"":"s"})`:D.status!=="pending"?` (${D.items} ${k}${D.items===1?"":"s"})`:"",D.status==="active"?` \u2190 ${T}\u2026`:""]},D.label)),p&&E(A,{color:"yellow",children:` \u26A0 no activity for ${kn(i)} \u2014 press esc to stop if it's wedged`})]})}var rw=10800*1e3;function bd({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=ig(),[i,l]=F(n),[p,m]=F(null),[k,g]=F({text:"",pos:0}),T=k.text,v=G(c=>{g(a=>{let s=typeof c=="function"?c(a.text):c;return{text:s,pos:s.length}})},[]),_=G(c=>{g(a=>({text:a.text.slice(0,a.pos)+c+a.text.slice(a.pos),pos:a.pos+c.length}))},[]),P=G(()=>{g(c=>{if(c.pos===0)return c;let a=c.text.slice(0,c.pos),s=zc(a)??a.slice(0,-1);return{text:s+c.text.slice(c.pos),pos:s.length}})},[]),[N,D]=F(!1),[M,B]=F(!1),[ee,X]=F(0),[ne,Be]=F(null),[ot,Ts]=F(null),[rt,it]=F([]),Nn=J(!1),ar=J(!1),[lr,Ss]=F(!1),In=J(0),[Td,_n]=F(!1),[Sd,On]=F(!1),[cr,Ds]=F(null),[Dd,$t]=F(0),st=J(0),[tn,xt]=F(0),[Ct,Ln]=F(null),js=J(new Map),jd=J(0),Rt=J([]),Pe=J(null);Pe.current===null&&(Pe.current=ed({cwd:e,profileName:i,allowProdWrites:!1}));let Oe=J({uuid:null,firstPrompt:null,titleFired:!1}),Mn=J(new Map),Pt=J(!1),dr=J([]),le=J([]),Tt=J([]),Un=J(null),[As,at]=F(null),ur=J(null),[lt,ct]=F(null),[Le,St]=F(null),[Me,Dt]=F(null),[fe,jt]=F(null),[ke,dt]=F(null),[Ve,At]=F(null),[Ue,ut]=F(null),[Es,nn]=F(null),[be,pt]=F(null),[he,Et]=F(null),[Ns,pr]=F([]),ft=J([]),on=J(!1),Te=J(null),[Wn,re]=F(null),[Is,_s]=F(null),Fn=J(!1),Hn=J(null),rn=J(null),[ve,ht]=F(null),[qn,sn]=F(null),fr=!!(Me||fe||ke||Ve||Ue||be||he||ve||qn),[Os,Nt]=F(0),[Ls,It]=F(0),[Ad,Ms]=F(0),hr=ms(()=>{try{let c=xs(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,Ad]),{stdout:Ee}=ag(),[,Ed]=F(0),Us=J(`${Ee.columns??80}x${Ee.rows??24}`),Ge=G(()=>Math.max(20,(Ee.columns??80)-1),[Ee]),d=G(c=>{Rt.current.push(c),console.log(Br(c,Ge()))},[Ge]),me=G((c,a)=>{In.current++,Be(c),Ts(a??null)},[]),Ye=G(()=>{In.current++,Be(null),Ts(null)},[]),K=G(c=>me(c,Wo({kind:"cmd",cmd:c,reason:""})),[me]),Ws=G((c,a)=>{!a?.silent&&c.note&&d({kind:"note",tone:c.tone,text:c.note}),c.picker&&(it(c.picker.options.map(s=>({cmd:s.cmd,desc:s.desc}))),nn(c.picker.title)),c.lead&&me(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,Wo(c.lead))},[d,me]),_t=G((c,a,s="info")=>{c&&d({kind:"note",tone:s,text:c}),a&&me(a.kind==="cmd"?a.cmd:a.text,Wo(a))},[d,me]),[an,mr]=F(null),[Nd,Fs]=F(!1),Ot=G(c=>{mr(c),Fs(!1),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),gr=J(!1),wr=G(async()=>{try{if(gr.current||!Wg(Ug())||te(e)?.mode==="engineer")return;let c=await Mg({pkg:kt,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;gr.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${kt} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),On(!0),(await Oo().finally(()=>On(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),K("/exit"),Ds(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${_o}`})}catch{}},[e,o,d,K]),Bn=G(c=>{let a=je(e,i);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),rn.current=c,K("/login"),!1)},[e,i,d,K]),[Vn,yr]=F(null),ln=J(!0),Gn=J(0),cn=J(0);Re(()=>{let c=setInterval(()=>{if(ln.current){Gn.current=0,cn.current=0;return}if(!N)try{if(!Qt(ld(e)))return;if(De(e).status==="current"){ln.current=!0,Gn.current=0,cn.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."}),mr(null),me("write the docs for this repo");return}Gn.current+=1;let a=Gn.current;if((a===4||a%15===0)&&cn.current<3){cn.current+=1;let s=cn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Fe(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${s}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${s}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,N,d]),Re(()=>{let c=As??En(e);if(!N){zo(0),Xt(`${Xo} ${c}`);return}zo(3);let a=0;Xt(`${Ko[0]} ${c}`);let s=setInterval(()=>{a=(a+1)%Ko.length,Xt(`${Ko[a]} ${c}`)},400);return()=>clearInterval(s)},[N,e,As]),Re(()=>()=>zo(0),[]);let dn=G(c=>{let a=jn(e,i,{claudeMissing:$s(t).state==="missing",allowAutoAudit:c,genreUnknown:ar.current});return a?Dn(a):{kind:"idle"}},[e,i,t]);Re(()=>{let c=performance.now(),a=[],s=(w,x)=>{let $=performance.now();try{return x()}finally{let V=Math.round(performance.now()-$);V>=80&&a.push(`${w}: ${V}ms`)}};d({kind:"banner",info:s("banner",()=>Kg(e,o,t,i))});let h=$s(t).state==="missing";if(h&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
324
- ${dg}
325
- Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!te(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:
326
- ${md}`}),K(h?"/doctor":"/init");return}h&&K("/doctor");try{let w=Ce(e,i),x=vt(w.name);x&&nt(x)&&x.refreshToken?hg({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),X($=>$+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),K("/login")}):(!x||nt(x))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 sign in with /login.`}),K("/login"))}catch{}try{let w=te(e),x=Ce(e,i),$=vt(x.name);w&&$&&!nt($)&&os(e,w.authoritativeSourceFiles)&&!rs(e,i)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),K("/scope"))}catch{}try{let w=s("resolve-genre",()=>Pg(e));w.persisted&&w.appType?d({kind:"note",tone:"ok",text:`\u2713 Detected a ${w.appType} app \u2014 enabled the ${w.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):w.source==="unknown"&&te(e)&&(ar.current=!0)}catch{}let u=De(e);try{if(s("reconcile-devhints",()=>ho(e)),u.status!=="current"&&!Fe(e)){let w=mo(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
327
- `)}),Ot(gt()),ln.current=!1)}}catch{}try{let w=s("reconcile-feedback",()=>Fg(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{}try{let w=s("upgrade-actions",()=>Hg(e));w.applied.length>0&&d({kind:"note",tone:"warn",text:Ho(w.applied).join(`
328
- `)})}catch{}let y=s("ready-decision",()=>dn(!0));y.kind==="autoAudit"?(d({kind:"note",tone:"info",text:y.note}),vn().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&ie(w.prompt,{display:w.display,quietUser:!0})})):y.kind==="recommend"&&Ws(y.rec);let b=Math.round(performance.now()-c);b>=800&&Bg({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${b}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${a.length?a.join(`
323
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Qg(e,t,n,o){let r=$s(n),i=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",l=xs(e),p=ne(e),m=(p?.docsDir??bd).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${m}/ + config`,g={version:t,engineVersion:kd,claude:i,model:l.model,modelSource:Xg[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 g;try{let T=Ce(e,o);g.profile=T.name,g.apiUrl=T.connection.apiUrl,g.prod=T.production,g.project=T.project.projectName??T.project.projectId??"(chosen at login)";let v=vt(T.name);if(v){let _={...Zt(v.idToken)??{},...Zt(v.accessToken)??{}},P=_.email??_.preferred_username??"signed in";nt(v)?v.refreshToken&&(g.who=P,g.loggedOut=!1,g.sessionHint="session expired \u2014 refreshing\u2026"):(g.who=P,g.loggedOut=!1,g.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return g}function Jg(e,t){try{let n=Ce(e,t),o=vt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Zt(o.idToken)??{},...Zt(o.accessToken)??{}},i=r.email??r.preferred_username??"signed in";return nt(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${i} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var wd=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],en=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Zg="Ask me to write or update an article\u2026";function Jt({ch:e,dim:t}){let[n,o]=F(!0);return Re(()=>{let r=setInterval(()=>o(i=>!i),530);return()=>clearInterval(r)},[]),E(A,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var ew=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function yd(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var tw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function nw({startTime:e,chars:t}){let[n,o]=F(0);Re(()=>{let m=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(m)},[]);let r=en[n%en.length],i=wd[Math.floor(n/16)%wd.length],l=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return Y(oe,{children:[E(A,{color:q,children:` ${r} ${i}\u2026 `}),E(A,{color:"gray",children:`(${kn(l)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function ow({text:e}){let[t,n]=F(0);return Re(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),E(oe,{paddingX:1,children:E(A,{color:q,children:`${en[t%en.length]} ${e}`})})}var rw=12e4;function iw({p:e}){let[t,n]=F(0);Re(()=>{let D=setInterval(()=>n(M=>M+1),150);return()=>clearInterval(D)},[]);let o=en[t%en.length],r=Math.floor((Date.now()-e.startedAt)/1e3),i=Math.floor((Date.now()-e.lastAt)/1e3),l=Math.round(e.chars/4),p=Date.now()-e.lastAt>=rw,m=e.verb??"Converting",k=e.unit??"article",g=e.rows.reduce((D,M)=>D+M.items,0),T=m.toLowerCase(),v=e.rows,_=0;if(v.length>Zo){let D=v.findIndex(B=>B.status==="active"||B.status==="pending"),M=Math.max(0,Math.min(D-2,v.length-Zo));_=v.slice(0,M).filter(B=>B.status==="done").length,v=v.slice(M,M+Zo)}let P=Math.min(40,Math.max(...v.map(D=>fs(D.label).length),0)),N=D=>D==="failed"?"red":D==="active"?q:void 0;return Y(oe,{flexDirection:"column",children:[Y(oe,{children:[E(A,{color:q,children:` ${o} ${m} ${g} ${k}${g===1?"":"s"} `}),E(A,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${l} tokens \xB7 ${kn(r)} \xB7 esc to stop`})]}),_>0&&E(A,{dimColor:!0,children:` \u2714 +${_} done`}),v.map(D=>Y(A,{color:N(D.status),dimColor:D.status==="done"||D.status==="pending",children:[` ${Hc[D.status]} ${fs(D.label).padEnd(P)}`,D.status==="active"&&D.itemsDone!==void 0?` (${D.itemsDone}/${D.items} ${k}${D.items===1?"":"s"})`:D.status!=="pending"?` (${D.items} ${k}${D.items===1?"":"s"})`:"",D.status==="active"?` \u2190 ${T}\u2026`:""]},D.label)),p&&E(A,{color:"yellow",children:` \u26A0 no activity for ${kn(i)} \u2014 press esc to stop if it's wedged`})]})}var sw=10800*1e3;function vd({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=ag(),[i,l]=F(n),[p,m]=F(null),[k,g]=F({text:"",pos:0}),T=k.text,v=G(c=>{g(a=>{let s=typeof c=="function"?c(a.text):c;return{text:s,pos:s.length}})},[]),_=G(c=>{g(a=>({text:a.text.slice(0,a.pos)+c+a.text.slice(a.pos),pos:a.pos+c.length}))},[]),P=G(()=>{g(c=>{if(c.pos===0)return c;let a=c.text.slice(0,c.pos),s=Kc(a)??a.slice(0,-1);return{text:s+c.text.slice(c.pos),pos:s.length}})},[]),[N,D]=F(!1),[M,B]=F(!1),[ee,X]=F(0),[te,Pe]=F(null),[ot,Ts]=F(null),[rt,it]=F([]),Nn=J(!1),ar=J(!1),[lr,Ss]=F(!1),In=J(0),[Sd,_n]=F(!1),[Dd,On]=F(!1),[cr,Ds]=F(null),[jd,$t]=F(0),st=J(0),[tn,xt]=F(0),[Ct,Ln]=F(null),js=J(new Map),Ad=J(0),Rt=J([]),Te=J(null);Te.current===null&&(Te.current=td({cwd:e,profileName:i,allowProdWrites:!1}));let Le=J({uuid:null,firstPrompt:null,titleFired:!1}),Mn=J(new Map),Pt=J(!1),dr=J([]),le=J([]),Tt=J([]),Un=J(null),[As,at]=F(null),ur=J(null),[lt,ct]=F(null),[Me,St]=F(null),[Ue,Dt]=F(null),[fe,jt]=F(null),[ke,dt]=F(null),[Ve,At]=F(null),[We,ut]=F(null),[Es,nn]=F(null),[be,pt]=F(null),[he,Et]=F(null),[Ns,pr]=F([]),ft=J([]),on=J(!1),Se=J(null),[Wn,re]=F(null),[Is,_s]=F(null),Fn=J(!1),Hn=J(null),rn=J(null),[ve,ht]=F(null),[qn,sn]=F(null),fr=!!(Ue||fe||ke||Ve||We||be||he||ve||qn),[Os,Nt]=F(0),[Ls,It]=F(0),[Ed,Ms]=F(0),hr=ms(()=>{try{let c=xs(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,Ed]),{stdout:Ne}=cg(),[,Nd]=F(0),Us=J(`${Ne.columns??80}x${Ne.rows??24}`),Ge=G(()=>Math.max(20,(Ne.columns??80)-1),[Ne]),d=G(c=>{Rt.current.push(c),console.log(Br(c,Ge()))},[Ge]),me=G((c,a)=>{In.current++,Pe(c),Ts(a??null)},[]),Ye=G(()=>{In.current++,Pe(null),Ts(null)},[]),K=G(c=>me(c,Wo({kind:"cmd",cmd:c,reason:""})),[me]),Ws=G((c,a)=>{!a?.silent&&c.note&&d({kind:"note",tone:c.tone,text:c.note}),c.picker&&(it(c.picker.options.map(s=>({cmd:s.cmd,desc:s.desc}))),nn(c.picker.title)),c.lead&&me(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,Wo(c.lead))},[d,me]),_t=G((c,a,s="info")=>{c&&d({kind:"note",tone:s,text:c}),a&&me(a.kind==="cmd"?a.cmd:a.text,Wo(a))},[d,me]),[an,mr]=F(null),[Id,Fs]=F(!1),Ot=G(c=>{mr(c),Fs(!1),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),gr=J(!1),wr=G(async()=>{try{if(gr.current||!Hg(Fg())||ne(e)?.mode==="engineer")return;let c=await Wg({pkg:kt,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;gr.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${kt} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),On(!0),(await Oo().finally(()=>On(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),K("/exit"),Ds(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${_o}`})}catch{}},[e,o,d,K]),Bn=G(c=>{let a=Ae(e,i);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),rn.current=c,K("/login"),!1)},[e,i,d,K]),[Vn,yr]=F(null),ln=J(!0),Gn=J(0),cn=J(0);Re(()=>{let c=setInterval(()=>{if(ln.current){Gn.current=0,cn.current=0;return}if(!N)try{if(!Qt(cd(e)))return;if(je(e).status==="current"){ln.current=!0,Gn.current=0,cn.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."}),mr(null),me("write the docs for this repo");return}Gn.current+=1;let a=Gn.current;if((a===4||a%15===0)&&cn.current<3){cn.current+=1;let s=cn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:He(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${s}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${s}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,N,d]),Re(()=>{let c=As??En(e);if(!N){zo(0),Xt(`${Xo} ${c}`);return}zo(3);let a=0;Xt(`${Ko[0]} ${c}`);let s=setInterval(()=>{a=(a+1)%Ko.length,Xt(`${Ko[a]} ${c}`)},400);return()=>clearInterval(s)},[N,e,As]),Re(()=>()=>zo(0),[]);let dn=G(c=>{let a=jn(e,i,{claudeMissing:$s(t).state==="missing",allowAutoAudit:c,genreUnknown:ar.current});return a?Dn(a):{kind:"idle"}},[e,i,t]);Re(()=>{let c=performance.now(),a=[],s=(w,x)=>{let $=performance.now();try{return x()}finally{let V=Math.round(performance.now()-$);V>=80&&a.push(`${w}: ${V}ms`)}};d({kind:"banner",info:s("banner",()=>Qg(e,o,t,i))});let h=$s(t).state==="missing";if(h&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
324
+ ${pg}
325
+ Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!ne(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:
326
+ ${gd}`}),K(h?"/doctor":"/init");return}h&&K("/doctor");try{let w=Ce(e,i),x=vt(w.name);x&&nt(x)&&x.refreshToken?gg({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),X($=>$+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),K("/login")}):(!x||nt(x))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 sign in with /login.`}),K("/login"))}catch{}try{let w=ne(e),x=Ce(e,i),$=vt(x.name);w&&$&&!nt($)&&rs(e,w.authoritativeSourceFiles)&&!is(e,i)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),K("/scope"))}catch{}try{let w=s("resolve-genre",()=>Sg(e));w.persisted&&w.appType?d({kind:"note",tone:"ok",text:`\u2713 Detected a ${w.appType} app \u2014 enabled the ${w.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):w.source==="unknown"&&ne(e)&&(ar.current=!0)}catch{}let u=je(e);try{if(s("reconcile-devhints",()=>ho(e)),u.status!=="current"&&!He(e)){let w=mo(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
327
+ `)}),Ot(gt()),ln.current=!1)}}catch{}try{let w=s("reconcile-feedback",()=>qg(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{}try{let w=s("upgrade-actions",()=>Bg(e));w.applied.length>0&&d({kind:"note",tone:"warn",text:Ho(w.applied).join(`
328
+ `)})}catch{}let y=s("ready-decision",()=>dn(!0));y.kind==="autoAudit"?(d({kind:"note",tone:"info",text:y.note}),vn().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&ie(w.prompt,{display:w.display,quietUser:!0})})):y.kind==="recommend"&&Ws(y.rec);let b=Math.round(performance.now()-c);b>=800&&Gg({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${b}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${a.length?a.join(`
329
329
  `):"no single phase \u226580ms"}
330
- cwd: ${e}`}),wr()},[]),Re(()=>{let c=setInterval(()=>{wr()},rw);return()=>clearInterval(c)},[wr]),Re(()=>{if(N||lr||Nn.current||ne!==null||rt.length>0||T!==""||an!==null||le.current.length>0||Un.current||fr)return;let c=dn(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&Ws(c.rec,{silent:!0})},[N,ne,rt,T,an,fr,ee,dn,lr]),Re(()=>{let c=null,a=null,s=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let h=`${Ee.columns??80}x${Ee.rows??24}`;h!==Us.current&&(Us.current=h,Ed(u=>u+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+qa(Rt.current,Ge())+"\x1B[?2026l")},80))},400)};return Ee.on("resize",s),()=>{c&&clearTimeout(c),a&&clearTimeout(a),Ee.off("resize",s)}},[Ee,Ge]);let Ne=Math.max(20,(Ee.columns??80)-1),Hs=ms(()=>Xg(e,i),[e,i,ee]),kr=(()=>{if(Sd)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(cr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${cr?` v${cr}`:""}\u2026`,isSetup:!0};if(Vn)return{text:"\u{1F6E0} press c to copy the d360-writer feedback \u2014 then send it to the team (Teams / Slack / email)\u2026",isSetup:!0};if(an)return Nd?{text:"\u2713 copied \u2014 paste it into your coding agent \xB7 I\u2019ll pick up automatically when it finishes\u2026",isSetup:!0}:{text:"\u2328 press c to copy the prompt above \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(le.current.length>0)return le.current[0].mode==="conflict"?{text:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let c=te(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let a=gs(e,(c.docsDir??kd).replace(/\/+$/,"")),s=(()=>{try{return Qt(a)&&lg(a).length>0}catch{return!1}})();try{let h=Ce(e,i),u=vt(h.name);if(!(!!u&&!(nt(u)&&!u.refreshToken)))return{text:`Sign in with /login (profile "${h.name}")\u2026`,isSetup:!0};if(!h.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!h.project.workspaceId&&!s)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return s?{text:Qg,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),un=Ic(T),qs=un.length>0&&!N,br=p!==null?Qc(p,8,Ne):null,Yn=be?be.paths.filter(c=>!be.query||c.toLowerCase().includes(be.query.toLowerCase())).slice(0,8):[],zn=ve?ve.sessions.filter(c=>{let a=ve.query.toLowerCase();return!a||c.name.toLowerCase().includes(a)||c.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],$e=G((c,a)=>{Pe.current?.close(),Pe.current=ed({cwd:e,resume:c,profileName:a??i,allowProdWrites:Pt.current}),c||(Oe.current={uuid:null,firstPrompt:null,titleFired:!1},at(null)),Nt(0),It(0)},[e,i]),Bs=G((c,a,s)=>{if(Jg.test(c))try{let h=Ce(e,i),u=typeof a.project_id=="string"&&a.project_id||h.project.projectId,y=Go(a,s),b=[],w=Yo(s);c.endsWith("publish_article")&&w&&b.push(`Live: ${w}`),y&&u&&b.push(`Preview: ${Vo(h.connection.portalUrl,u,y,h.project.languageCode??"en")}`),b.length>0&&d({kind:"link",lines:b})}catch{}},[e,i,d]),ie=G(async(c,a)=>{_n(!0),Nn.current=!1,Ye(),it([]),nn(null),mr(null);let s=In.current;a?.quietUser||d({kind:"user",text:a?.echoDisplay&&a.display?a.display:c});let h=Oe.current;h.firstPrompt||(h.firstPrompt=a?.display??c),st.current=Date.now(),$t(0),D(!0),Mn.current.clear();let u="",y=!1,b=!1,w="",x={num:0,closed:!1,cueSeen:!1},$=null,V=()=>{$||($=setTimeout(()=>{$=null,m(w.length>0?w:null)},60))},H=()=>{$&&clearTimeout($),$=null,m(null)},I=(R=!1)=>{let{head:S,keep:U}=Jc(w,R);S.trim()&&d({kind:"assistant",text:us(S.trimEnd(),x)}),w=U,H()};try{for await(let R of Pe.current.send(c))if(R.type==="session"){if(!h.uuid){h.uuid=R.sessionId;let S=new Date().toISOString(),U=ur.current,Z=U??bg(h.firstPrompt??"session");vg({uuid:R.sessionId,name:Z,renamed:!!U,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:S,updatedAt:S}),at(Z),ur.current=null}}else if(R.type==="text"){w+=R.delta,u+=R.delta;let S=Zc(w);if(S>0){let U=w.slice(0,S).trimEnd();U&&d({kind:"assistant",text:us(U,x)}),w=w.slice(S)}V(),$t(U=>U+R.delta.length)}else if(R.type==="tool"){y=!0;let S=qo(R.name,R.input);S&&(I(),d({kind:"tool",title:S.title,sep:S.sep,arg:S.arg}),Mn.current.set(R.id,{name:R.name,input:R.input}))}else if(R.type==="article_diff"){let S=He(R.oldContent,R.newContent,Ge());S&&(I(),d({kind:"diff",added:S.added,removed:S.removed,lines:S.lines,hidden:S.hidden}))}else if(R.type==="tool_result"){R.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(R.output)&&(Fn.current=!0);let S=Mn.current.get(R.id);if(S){Mn.current.delete(R.id),I();let U=Bo(R.output,4,R.isError?void 0:S.name,S.input);d({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:R.isError}),R.isError||Bs(S.name,S.input,R.output)}}else if(R.type==="result"){if(I(!0),Nt(S=>S+R.outputTokens),It(S=>S+R.costUsd),d({kind:"done",seconds:Math.round((Date.now()-st.current)/1e3),tokens:R.outputTokens,costUsd:R.costUsd,ok:R.ok}),!b&&!y&&!u.trim()&&!on.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)."}),R.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let S=cd(e);if(Qt(S)){let U=nr(S,"utf8").trim();U&&(yr(U),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{}if(R.ok&&x.cueSeen)Ss(!0),it([]);else{let S=R.ok?Mc(u,Qo.map(U=>U.name)):[];if(S.length>0)K(S[0]);else if(R.ok&&u.trim()){let U=dn(!1);U.kind==="recommend"&&(U.rec.lead||U.rec.picker)||Rg(c,u,e).then(Z=>{Z&&In.current===s&&me(Z)}).catch(()=>{})}}if(h.uuid&&(ws(h.uuid),!h.titleFired)){h.titleFired=!0;let S=h.uuid,U=h.firstPrompt;U&&td(U,e).then(Z=>{Z&&(kg(S,Z),at(Z))}).catch(()=>{})}}else R.type==="error"&&(I(!0),b=!0,R.kind==="auth"&&(Fn.current=!0),d({kind:"note",text:`agent error: ${R.message}`,tone:"error"}))}finally{D(!1),H(),X(R=>R+1),Oe.current.uuid&&jc(e,Oe.current.uuid,Rt.current),Fn.current&&(Fn.current=!1,Hn.current=a?.display??c,me("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")),on.current&&(on.current=!1,ft.current.length>0&&(d({kind:"note",tone:"info",text:`(${ft.current.length} queued message(s) discarded)`}),ft.current=[],pr([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Bs,Ge,me,K,Ye,dn]),Lt=G(async c=>{let a=rr(e,"standard");st.current=Date.now(),$t(0),D(!0);let s=new AbortController;Te.current=s;let h=async(u,y)=>{let b=ks(u);re({verb:"Publishing",total:b.length,done:0,active:[],rows:An(b),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:y?`Resolving cross-links in ${u.length} article${u.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${u.length} article${u.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${bn} agents at once) on ${a.model}\u2026 (esc to stop)`});let w=!1;for await(let x of or({cwd:e,partitions:b,promptFor:$=>Co($.paths),concurrency:bn,profileName:i,allowProdWrites:Pt.current,model:a.model,signal:s.signal}))if(x.type==="partition_status")x.status==="running"?re($=>$&&{...$,active:[...$.active,x.label],rows:qe($.rows,x.label,"active"),lastAt:Date.now()}):re($=>$&&{...$,active:$.active.filter(V=>V!==x.label),done:$.done+1,rows:qe($.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_event")re($=>{if(!$)return $;let V={...$,lastAt:Date.now()};return x.event.type==="tool"?V.tools=$.tools+1:x.event.type==="text"&&(V.chars=$.chars+x.event.delta.length),V});else if(x.type==="run_done"){w=x.aborted,It(I=>I+x.totalCostUsd),Nt(I=>I+x.results.reduce((R,S)=>R+S.outputTokens,0));let $=x.aborted?"Stopped. ":"",V=t.kind==="api"?"api":"subscription";d({kind:"note",tone:x.aborted?"warn":x.ok?"ok":"warn",text:$+zr(x.results,b,V).join(`
331
- `)});let H=Yr(e,i);if(H&&d({kind:"note",tone:"info",text:H}),!x.aborted){try{let I=await ud({cwd:e,profileName:i}),R=pd(I);R?d({kind:"note",tone:"info",text:R}):I.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${I.skipped}`})}catch(I){d({kind:"note",tone:"warn",text:`Order sync failed: ${I.message}`})}try{let I=hd(await fd({cwd:e,profileName:i}));I&&d({kind:"note",tone:"info",text:I})}catch(I){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${I.message}`})}}}return w};try{if(!await h(c,!1)){let y=await Kr(e,i,c);y.length>0&&await h(y,!0)}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{Te.current=null,re(null),D(!1),X(u=>u+1)}},[e,i,d,t]),vr=G(async c=>{await ie(Vr(c),{display:`/publish ${c}`,quietUser:!0});try{let a=await Ro(e,i,c.replace(/\\/g,"/"));a.length>0&&(nn(`Related articles not yet published (${a.length}):`),it([`/publish --related ${c}`,...a.map(s=>`/publish ${s}`)]))}catch{}},[e,i,ie]),$r=G(c=>{let a=vt(c);if(!a||nt(a)&&!a.refreshToken)return null;let s={...Zt(a.idToken)??{},...Zt(a.accessToken)??{}};return s.email??s.preferred_username??"signed in"},[]),xr=G((c,a)=>{if(a){let s=te(e);s&&(s.defaultProfile=c,nd(s,e))}l(c),$e(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),$r(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),K("/login")),X(s=>s+1)},[e,d,$e,$r,K]),Kn=G((c,a,s)=>{no(e,c,a,s.id,s.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${s.name??s.id}" (agent restarted).`}),$e(),od(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:Gt(Vt(e)).join(`
332
- `)}),Ot(gt()),ln.current=De(e).status==="current"||Fe(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,$e,Ot]),Xn=G(async c=>{let a;try{a=await mn(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),K("/workspace");return}if(a.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let s=a.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),h=s.length>0?s:a.workspaces;if(h.length===1){let u=h[0],y=a.workspaces.length-h.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${y>0?" (skipped the API-documentation workspace)":""}.`}),Kn(a.profile,a.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),K("/workspace")},[e,d,Kn,K]),Qn=G((c,a)=>{oo(e,c,a.id,a.name),d({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),$e(),Xn(c)},[e,d,$e,Xn]),Vs=G(async c=>{let a;try{a=Ce(e,c)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:s}=await Xe(e,a.name),h=s.find(u=>u.id===a.project.projectId);h?.name&&qg(e,a.name,{projectName:h.name})}catch{}await Xn(a.name);return}try{let{projects:s}=await Xe(e,a.name);if(s.length===1){let h=s[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${h.name??h.id}".`}),Qn(a.name,{id:h.id,name:h.name});return}if(s.length>1){let h=s.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?"}),dt({cursor:0,current:-1,rows:h,profile:a.name,environment:a.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),K("/project")}},[e,d,Xn,Qn,K]),Mt=G(()=>{let c=le.current[0];if(!c)return;let{plan:a,mode:s}=c;d({kind:"note",tone:"info",text:`\u25CF ${a.title} (${a.path})`});for(let u of a.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${u}`});a.overwritesLocalChanges&&s==="pull"&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let h=He(a.oldContent,a.newContent,Ge());d(h?{kind:"diff",added:h.added,removed:h.removed,lines:h.lines,hidden:h.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),s==="conflict"?(d({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),d({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):d({kind:"note",tone:"info",text:`Write ${a.path}? (y/n \u2014 anything else cancels)`})},[d,Ge]),Cr=G(()=>{if(le.current.length>0){Mt();return}let c=Tt.current;Tt.current=[],c.length>0?(d({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),Lt(c)):K("/pull")},[Mt,d,Lt,K]),Gs=G(c=>{if(le.current.length===0)return!1;let a=c.trim().toLowerCase(),s=le.current[0];if(s.mode==="conflict"){if(a==="l"||a==="local")le.current.shift(),Tt.current.push(s.plan.path),d({kind:"note",tone:"info",text:`Keeping local ${s.plan.path} \u2014 will publish over the portal.`});else if(a==="p"||a==="portal"){le.current.shift();try{rd({cwd:e,profileName:i},s.plan),d({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${s.plan.path} (local overwritten, sync base advanced).`})}catch(h){d({kind:"note",tone:"error",text:`Take-portal failed: ${h.message}`})}}else if(a==="s"||a==="skip"||a==="n")le.current.shift(),d({kind:"note",tone:"info",text:`Skipped ${s.plan.path} \u2014 still a conflict.`});else{let h=le.current.length;return le.current=[],Tt.current=[],d({kind:"note",tone:"info",text:`Resolve cancelled (${h} conflict${h===1?"":"s"} left untouched).`}),!0}return Cr(),!0}if(a==="y"||a==="yes"){let h=le.current.shift().plan;try{rd({cwd:e,profileName:i},h),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${h.path} (sync base advanced).`})}catch(u){d({kind:"note",tone:"error",text:`Pull failed: ${u.message}`})}}else if(a==="n"||a==="no"){let h=le.current.shift().plan;d({kind:"note",tone:"info",text:`Skipped ${h.path}.`})}else{let h=le.current.length;return le.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${h} article(s) left untouched).`}),!0}return Cr(),!0},[e,i,Cr,d]),Rr=G(async c=>{d({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let a=await ys({cwd:e,profileName:i}),s=c?.replace(/\\/g,"/"),h=a.entries.filter(y=>y.status==="conflict"&&y.path).map(y=>y.path);if(s){if(!h.includes(s)){d({kind:"note",tone:"ok",text:`${s} isn\u2019t in conflict \u2014 nothing to resolve.`});return}h=[s]}if(h.length===0){d({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let u=[];for(let y of h)try{u.push({plan:await sd({cwd:e,profileName:i,relPath:y}),mode:"conflict"})}catch(b){d({kind:"note",tone:"error",text:`Could not load ${y} from Document360: ${b.message}`})}if(u.length===0)return;d({kind:"note",tone:"info",text:`Resolving ${u.length} conflict${u.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),le.current=u,Tt.current=[],Mt()}catch(a){d({kind:"note",tone:"error",text:`Could not compute sync status: ${a.message}`})}},[e,i,d,Mt]),Ys=G(c=>{let a=Un.current;if(!a)return!1;if(Un.current=null,Ye(),c.trim()!==a.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:s,failed:h}=Vi(e,a.targets);d({kind:"note",tone:h.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${s.length} item${s.length===1?"":"s"}. The repo is back to its original state.`});for(let u of h)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return a.hadDevhints&&(d({kind:"note",tone:"warn",text:go().join(`
330
+ cwd: ${e}`}),wr()},[]),Re(()=>{let c=setInterval(()=>{wr()},sw);return()=>clearInterval(c)},[wr]),Re(()=>{if(N||lr||Nn.current||te!==null||rt.length>0||T!==""||an!==null||le.current.length>0||Un.current||fr)return;let c=dn(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&Ws(c.rec,{silent:!0})},[N,te,rt,T,an,fr,ee,dn,lr]),Re(()=>{let c=null,a=null,s=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let h=`${Ne.columns??80}x${Ne.rows??24}`;h!==Us.current&&(Us.current=h,Nd(u=>u+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+qa(Rt.current,Ge())+"\x1B[?2026l")},80))},400)};return Ne.on("resize",s),()=>{c&&clearTimeout(c),a&&clearTimeout(a),Ne.off("resize",s)}},[Ne,Ge]);let Ie=Math.max(20,(Ne.columns??80)-1),Hs=ms(()=>Jg(e,i),[e,i,ee]),kr=(()=>{if(Dd)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(cr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${cr?` v${cr}`:""}\u2026`,isSetup:!0};if(Vn)return{text:"\u{1F6E0} press c to copy the d360-writer feedback \u2014 then send it to the team (Teams / Slack / email)\u2026",isSetup:!0};if(an)return Id?{text:"\u2713 copied \u2014 paste it into your coding agent \xB7 I\u2019ll pick up automatically when it finishes\u2026",isSetup:!0}:{text:"\u2328 press c to copy the prompt above \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(le.current.length>0)return le.current[0].mode==="conflict"?{text:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let c=ne(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let a=gs(e,(c.docsDir??bd).replace(/\/+$/,"")),s=(()=>{try{return Qt(a)&&dg(a).length>0}catch{return!1}})();try{let h=Ce(e,i),u=vt(h.name);if(!(!!u&&!(nt(u)&&!u.refreshToken)))return{text:`Sign in with /login (profile "${h.name}")\u2026`,isSetup:!0};if(!h.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!h.project.workspaceId&&!s)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return s?{text:Zg,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),un=_c(T),qs=un.length>0&&!N,br=p!==null?Jc(p,8,Ie):null,Yn=be?be.paths.filter(c=>!be.query||c.toLowerCase().includes(be.query.toLowerCase())).slice(0,8):[],zn=ve?ve.sessions.filter(c=>{let a=ve.query.toLowerCase();return!a||c.name.toLowerCase().includes(a)||c.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],$e=G((c,a)=>{Te.current?.close(),Te.current=td({cwd:e,resume:c,profileName:a??i,allowProdWrites:Pt.current}),c||(Le.current={uuid:null,firstPrompt:null,titleFired:!1},at(null)),Nt(0),It(0)},[e,i]),Bs=G((c,a,s)=>{if(ew.test(c))try{let h=Ce(e,i),u=typeof a.project_id=="string"&&a.project_id||h.project.projectId,y=Go(a,s),b=[],w=Yo(s);c.endsWith("publish_article")&&w&&b.push(`Live: ${w}`),y&&u&&b.push(`Preview: ${Vo(h.connection.portalUrl,u,y,h.project.languageCode??"en")}`),b.length>0&&d({kind:"link",lines:b})}catch{}},[e,i,d]),ie=G(async(c,a)=>{_n(!0),Nn.current=!1,Ye(),it([]),nn(null),mr(null);let s=In.current;a?.quietUser||d({kind:"user",text:a?.echoDisplay&&a.display?a.display:c});let h=Le.current;h.firstPrompt||(h.firstPrompt=a?.display??c),st.current=Date.now(),$t(0),D(!0),Mn.current.clear();let u="",y=!1,b=!1,w="",x={num:0,closed:!1,cueSeen:!1},$=null,V=()=>{$||($=setTimeout(()=>{$=null,m(w.length>0?w:null)},60))},H=()=>{$&&clearTimeout($),$=null,m(null)},I=(R=!1)=>{let{head:S,keep:U}=Zc(w,R);S.trim()&&d({kind:"assistant",text:us(S.trimEnd(),x)}),w=U,H()};try{for await(let R of Te.current.send(c))if(R.type==="session"){if(!h.uuid){h.uuid=R.sessionId;let S=new Date().toISOString(),U=ur.current,Z=U??$g(h.firstPrompt??"session");xg({uuid:R.sessionId,name:Z,renamed:!!U,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:S,updatedAt:S}),at(Z),ur.current=null}}else if(R.type==="text"){w+=R.delta,u+=R.delta;let S=ed(w);if(S>0){let U=w.slice(0,S).trimEnd();U&&d({kind:"assistant",text:us(U,x)}),w=w.slice(S)}V(),$t(U=>U+R.delta.length)}else if(R.type==="tool"){y=!0;let S=qo(R.name,R.input);S&&(I(),d({kind:"tool",title:S.title,sep:S.sep,arg:S.arg}),Mn.current.set(R.id,{name:R.name,input:R.input}))}else if(R.type==="article_diff"){let S=qe(R.oldContent,R.newContent,Ge());S&&(I(),d({kind:"diff",added:S.added,removed:S.removed,lines:S.lines,hidden:S.hidden}))}else if(R.type==="tool_result"){R.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(R.output)&&(Fn.current=!0);let S=Mn.current.get(R.id);if(S){Mn.current.delete(R.id),I();let U=Bo(R.output,4,R.isError?void 0:S.name,S.input);d({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:R.isError}),R.isError||Bs(S.name,S.input,R.output)}}else if(R.type==="result"){if(I(!0),Nt(S=>S+R.outputTokens),It(S=>S+R.costUsd),d({kind:"done",seconds:Math.round((Date.now()-st.current)/1e3),tokens:R.outputTokens,costUsd:R.costUsd,ok:R.ok}),!b&&!y&&!u.trim()&&!on.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)."}),R.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let S=dd(e);if(Qt(S)){let U=nr(S,"utf8").trim();U&&(yr(U),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{}if(R.ok&&x.cueSeen)Ss(!0),it([]);else{let S=R.ok?Uc(u,Qo.map(U=>U.name)):[];if(S.length>0)K(S[0]);else if(R.ok&&u.trim()){let U=dn(!1);U.kind==="recommend"&&(U.rec.lead||U.rec.picker)||Tg(c,u,e).then(Z=>{Z&&In.current===s&&me(Z)}).catch(()=>{})}}if(h.uuid&&(ws(h.uuid),!h.titleFired)){h.titleFired=!0;let S=h.uuid,U=h.firstPrompt;U&&nd(U,e).then(Z=>{Z&&(vg(S,Z),at(Z))}).catch(()=>{})}}else R.type==="error"&&(I(!0),b=!0,R.kind==="auth"&&(Fn.current=!0),d({kind:"note",text:`agent error: ${R.message}`,tone:"error"}))}finally{D(!1),H(),X(R=>R+1),Le.current.uuid&&Ac(e,Le.current.uuid,Rt.current),Fn.current&&(Fn.current=!1,Hn.current=a?.display??c,me("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")),on.current&&(on.current=!1,ft.current.length>0&&(d({kind:"note",tone:"info",text:`(${ft.current.length} queued message(s) discarded)`}),ft.current=[],pr([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Bs,Ge,me,K,Ye,dn]),Lt=G(async c=>{let a=rr(e,"standard");st.current=Date.now(),$t(0),D(!0);let s=new AbortController;Se.current=s;let h=async(u,y)=>{let b=ks(u);re({verb:"Publishing",total:b.length,done:0,active:[],rows:An(b),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:y?`Resolving cross-links in ${u.length} article${u.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${u.length} article${u.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${bn} agents at once) on ${a.model}\u2026 (esc to stop)`});let w=!1;for await(let x of or({cwd:e,partitions:b,promptFor:$=>Co($.paths),concurrency:bn,profileName:i,allowProdWrites:Pt.current,model:a.model,signal:s.signal}))if(x.type==="partition_status")x.status==="running"?re($=>$&&{...$,active:[...$.active,x.label],rows:Be($.rows,x.label,"active"),lastAt:Date.now()}):re($=>$&&{...$,active:$.active.filter(V=>V!==x.label),done:$.done+1,rows:Be($.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_event")re($=>{if(!$)return $;let V={...$,lastAt:Date.now()};return x.event.type==="tool"?V.tools=$.tools+1:x.event.type==="text"&&(V.chars=$.chars+x.event.delta.length),V});else if(x.type==="run_done"){w=x.aborted,It(I=>I+x.totalCostUsd),Nt(I=>I+x.results.reduce((R,S)=>R+S.outputTokens,0));let $=x.aborted?"Stopped. ":"",V=t.kind==="api"?"api":"subscription";d({kind:"note",tone:x.aborted?"warn":x.ok?"ok":"warn",text:$+zr(x.results,b,V).join(`
331
+ `)});let H=Yr(e,i);if(H&&d({kind:"note",tone:"info",text:H}),!x.aborted){try{let I=await pd({cwd:e,profileName:i}),R=fd(I);R?d({kind:"note",tone:"info",text:R}):I.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${I.skipped}`})}catch(I){d({kind:"note",tone:"warn",text:`Order sync failed: ${I.message}`})}try{let I=md(await hd({cwd:e,profileName:i}));I&&d({kind:"note",tone:"info",text:I})}catch(I){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${I.message}`})}}}return w};try{if(!await h(c,!1)){let y=await Kr(e,i,c);y.length>0&&await h(y,!0)}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{Se.current=null,re(null),D(!1),X(u=>u+1)}},[e,i,d,t]),vr=G(async c=>{await ie(Vr(c),{display:`/publish ${c}`,quietUser:!0});try{let a=await Ro(e,i,c.replace(/\\/g,"/"));a.length>0&&(nn(`Related articles not yet published (${a.length}):`),it([`/publish --related ${c}`,...a.map(s=>`/publish ${s}`)]))}catch{}},[e,i,ie]),$r=G(c=>{let a=vt(c);if(!a||nt(a)&&!a.refreshToken)return null;let s={...Zt(a.idToken)??{},...Zt(a.accessToken)??{}};return s.email??s.preferred_username??"signed in"},[]),xr=G((c,a)=>{if(a){let s=ne(e);s&&(s.defaultProfile=c,od(s,e))}l(c),$e(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),$r(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),K("/login")),X(s=>s+1)},[e,d,$e,$r,K]),Kn=G((c,a,s)=>{no(e,c,a,s.id,s.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${s.name??s.id}" (agent restarted).`}),$e(),rd(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:Gt(Vt(e)).join(`
332
+ `)}),Ot(gt()),ln.current=je(e).status==="current"||He(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,$e,Ot]),Xn=G(async c=>{let a;try{a=await mn(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),K("/workspace");return}if(a.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let s=a.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),h=s.length>0?s:a.workspaces;if(h.length===1){let u=h[0],y=a.workspaces.length-h.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${y>0?" (skipped the API-documentation workspace)":""}.`}),Kn(a.profile,a.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),K("/workspace")},[e,d,Kn,K]),Qn=G((c,a)=>{oo(e,c,a.id,a.name),d({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),$e(),Xn(c)},[e,d,$e,Xn]),Vs=G(async c=>{let a;try{a=Ce(e,c)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:s}=await Xe(e,a.name),h=s.find(u=>u.id===a.project.projectId);h?.name&&Vg(e,a.name,{projectName:h.name})}catch{}await Xn(a.name);return}try{let{projects:s}=await Xe(e,a.name);if(s.length===1){let h=s[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${h.name??h.id}".`}),Qn(a.name,{id:h.id,name:h.name});return}if(s.length>1){let h=s.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?"}),dt({cursor:0,current:-1,rows:h,profile:a.name,environment:a.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),K("/project")}},[e,d,Xn,Qn,K]),Mt=G(()=>{let c=le.current[0];if(!c)return;let{plan:a,mode:s}=c;d({kind:"note",tone:"info",text:`\u25CF ${a.title} (${a.path})`});for(let u of a.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${u}`});a.overwritesLocalChanges&&s==="pull"&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let h=qe(a.oldContent,a.newContent,Ge());d(h?{kind:"diff",added:h.added,removed:h.removed,lines:h.lines,hidden:h.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),s==="conflict"?(d({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),d({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):d({kind:"note",tone:"info",text:`Write ${a.path}? (y/n \u2014 anything else cancels)`})},[d,Ge]),Cr=G(()=>{if(le.current.length>0){Mt();return}let c=Tt.current;Tt.current=[],c.length>0?(d({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),Lt(c)):K("/pull")},[Mt,d,Lt,K]),Gs=G(c=>{if(le.current.length===0)return!1;let a=c.trim().toLowerCase(),s=le.current[0];if(s.mode==="conflict"){if(a==="l"||a==="local")le.current.shift(),Tt.current.push(s.plan.path),d({kind:"note",tone:"info",text:`Keeping local ${s.plan.path} \u2014 will publish over the portal.`});else if(a==="p"||a==="portal"){le.current.shift();try{id({cwd:e,profileName:i},s.plan),d({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${s.plan.path} (local overwritten, sync base advanced).`})}catch(h){d({kind:"note",tone:"error",text:`Take-portal failed: ${h.message}`})}}else if(a==="s"||a==="skip"||a==="n")le.current.shift(),d({kind:"note",tone:"info",text:`Skipped ${s.plan.path} \u2014 still a conflict.`});else{let h=le.current.length;return le.current=[],Tt.current=[],d({kind:"note",tone:"info",text:`Resolve cancelled (${h} conflict${h===1?"":"s"} left untouched).`}),!0}return Cr(),!0}if(a==="y"||a==="yes"){let h=le.current.shift().plan;try{id({cwd:e,profileName:i},h),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${h.path} (sync base advanced).`})}catch(u){d({kind:"note",tone:"error",text:`Pull failed: ${u.message}`})}}else if(a==="n"||a==="no"){let h=le.current.shift().plan;d({kind:"note",tone:"info",text:`Skipped ${h.path}.`})}else{let h=le.current.length;return le.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${h} article(s) left untouched).`}),!0}return Cr(),!0},[e,i,Cr,d]),Rr=G(async c=>{d({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let a=await ys({cwd:e,profileName:i}),s=c?.replace(/\\/g,"/"),h=a.entries.filter(y=>y.status==="conflict"&&y.path).map(y=>y.path);if(s){if(!h.includes(s)){d({kind:"note",tone:"ok",text:`${s} isn\u2019t in conflict \u2014 nothing to resolve.`});return}h=[s]}if(h.length===0){d({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let u=[];for(let y of h)try{u.push({plan:await ad({cwd:e,profileName:i,relPath:y}),mode:"conflict"})}catch(b){d({kind:"note",tone:"error",text:`Could not load ${y} from Document360: ${b.message}`})}if(u.length===0)return;d({kind:"note",tone:"info",text:`Resolving ${u.length} conflict${u.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),le.current=u,Tt.current=[],Mt()}catch(a){d({kind:"note",tone:"error",text:`Could not compute sync status: ${a.message}`})}},[e,i,d,Mt]),Ys=G(c=>{let a=Un.current;if(!a)return!1;if(Un.current=null,Ye(),c.trim()!==a.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:s,failed:h}=Vi(e,a.targets);d({kind:"note",tone:h.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${s.length} item${s.length===1?"":"s"}. The repo is back to its original state.`});for(let u of h)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return a.hadDevhints&&(d({kind:"note",tone:"warn",text:go().join(`
333
333
  `)}),Ot(Ir())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
334
- ${md}`}),K("/init"),_n(!1),!0},[e,d,Ot,Ye,K]),pn=G(async c=>{let a=c.slice(1).trim().split(/\s+/),s=(a[0]??"").toLowerCase(),h=a.slice(1);if(_n(!0),Do(h)&&["write","check","review","reorder"].includes(s)){let u=$n(e,i);if(u.length===0){d({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let y=b=>s==="write"?`/write ${pl(h,b).join(" ")}`.trim():`/${s} ${[b,...h.filter(w=>w!=="--scope")].join(" ")}`.trim();if(u.length===1){pn(y(u[0].token));return}ut({cursor:0,rows:u,run:b=>{pn(y(b))}});return}if(et(s,h)){let u=$n(e,i);if(u.length>1){let y=h.filter($=>$.startsWith("--")).join(" "),b=$=>`/${s}${$?` ${s==="write"?`--scope ${$}`:$}`:""}${y?` ${y}`:""} ${$?"":"--all"}`.replace(/\s+/g," ").trim(),w=u.reduce(($,V)=>$+V.count,0),x={token:"",label:s==="review"?`Everything \u2014 all ${w} articles + structure (IA) review`:s==="reorder"?`Everything \u2014 reorder all ${u.length} categories`:`Everything \u2014 rewrite all ${w} planned articles`,count:w};ut({cursor:0,rows:[x,...u],run:$=>{pn(b($))}});return}}switch(s){case"help":sn({tab:0});return;case"exit":case"quit":Pe.current?.close(),r();return;case"clear":$e(),Rt.current=[],_n(!1),Ye(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=Ce(e,i)}catch(y){d({kind:"note",tone:"error",text:y.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),B(!0);try{let y=await ug(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},w=>d({kind:"note",tone:"info",text:w})),b=pg(u.name,y);if(fg(b),await Dr(b,u.name,w=>d({kind:"note",tone:"info",text:w})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${so(b)}`}),await Vs(i),rn.current){let w=rn.current;rn.current=null;let x=je(e,i);x.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${w}.`}),K(w)):(d({kind:"note",tone:"warn",text:`${x.reason} (then ${w}.)`}),K("/login"),rn.current=w)}else Hn.current&&(me(Hn.current,"\u21E5 tab to re-send your last prompt\u2026"),Hn.current=null)}catch(y){d({kind:"note",tone:"error",text:`Login failed: ${y.message}`})}finally{B(!1),X(y=>y+1)}return}case"allow-prod":{let u=!1;try{u=Ce(e,i).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Pt.current=!0,$e(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Ti(h.join(" ")),y=Oe.current.uuid;if(!y){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}ur.current=u,at(u),Xt(`${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 b=Oe.current.firstPrompt??"";td(b,e).then(w=>{w?(me(`/rename ${w}`),d({kind:"note",tone:"info",text:`Suggestion: "${w}" \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}Cg(y,u),at(u),Xt(`${Xo} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=h[0],y=te(e);if(!u){let b=Object.entries(y?.profiles??{});if(b.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let w=b.map(([V,H])=>({name:V,env:H.connection?.environment??"custom",prod:H.production===!0,who:$r(V)})),x=i??y?.defaultProfile,$=Math.max(0,w.findIndex(V=>V.name===x));St({cursor:$,current:$,rows:w});return}if(u==="add"){let b=Si(e,h[1],h[2]);if(b){d({kind:"note",tone:"error",text:b});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),xr(h[1],!1);return}if(!y?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}xr(u,!0);return}case"doctor":await Cn(h,{cwd:e,version:o});return;case"genre":{await Uo(h,{cwd:e});try{ar.current=!(te(e)?.appType??Tg(e))}catch{}X(u=>u+1);return}case"roadmap":{if(h[0]?.toLowerCase()==="done"){let u=Ji(e,h.slice(1).join(" ").trim());d({kind:"note",tone:u.ok?"ok":"warn",text:u.line}),X(y=>y+1);return}d({kind:"note",tone:"info",text:Qi(e).join(`
335
- `)});return}case"mcp":await ko(h);return;case"init":{if(te(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=Eg().map(y=>({name:y,apiUrl:Ng(y).apiUrl}));Dt({cursor:0,rows:u});return}case"resume":{let u=h.join(" ").trim(),y=xg(e).filter(x=>x.uuid!==Oe.current.uuid);if(!u){if(!y.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}ht({query:"",cursor:0,sessions:y});return}let b=$g(e,u);if(!b){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}$e(b.uuid),Oe.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},at(b.name),ws(b.uuid),Rt.current=[];let w=ps(e,b.uuid);for(let x of w)d(x);d({kind:"note",tone:"ok",text:w.length?`Resumed "${b.name}" \u2014 restored ${w.length} message(s); continue where you left off.`:`Resumed "${b.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=h.join(" ").trim(),y;try{y=await mn(e,i)}catch(w){d({kind:"note",tone:"error",text:`Could not list workspaces: ${w.message}`});return}if(!u){let w=y.workspaces.map($=>({id:$.id,name:$.name??$.id,type:$.workspace_type}));if(w.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let x=Math.max(0,w.findIndex($=>$.id===y.current));jt({cursor:x,current:x,rows:w,profile:y.profile,projectId:y.projectId,projectName:y.projectName,environment:y.environment});return}let b=Tr(y.workspaces,u);if(!b){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}Kn(y.profile,y.projectId,b);return}case"project":{let u=h.join(" ").trim(),y;try{y=await Xe(e,i)}catch(w){d({kind:"note",tone:"error",text:`Could not list projects: ${w.message} (signed in? try /login)`});return}if(!u){let w=y.projects.map($=>({id:$.id,name:$.name??$.id,sub:$.sub_domain}));if(w.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let x=w.findIndex($=>$.id===y.current);dt({cursor:Math.max(0,x),current:x,rows:w,profile:y.profile,environment:y.environment});return}let b=Sr(y.projects,u);if(!b){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${y.projects.map(w=>w.name??w.id).join(", ")}`});return}Qn(y.profile,b);return}case"logout":{let u;try{u=Ce(e,i).name}catch(b){d({kind:"note",tone:"error",text:b.message});return}let y=wg(u);yg(e,u),$e(),X(b=>b+1),d({kind:"note",tone:y?"ok":"info",text:y?`\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."}),K("/login");return}case"publish":{if(!Bn(c.trim()))return;if(h[0]==="--related"&&h[1]){let w=await Ro(e,i,h[1].replace(/\\/g,"/"));if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Lt(w);return}let u=h.filter(w=>!w.startsWith("--"));if(u[0]){await vr(u[0]);return}let y=h.includes("--all"),b=h.includes("--force");d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let w=await ys({cwd:e,profileName:i}),{clean:x,conflicts:$}=vo(w.entries),V=y&&b&&$.length>0,H=xo(w.entries);if(H>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${H} article${H===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.`}),$.length>0&&!V&&d({kind:"note",tone:"warn",text:$o($.length)}),x.length===0&&!V){if($.length>0){K("/resolve");return}d({kind:"note",tone:"ok",text:H>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let I=w.counts["unknown-base"]??0;I>0&&d({kind:"note",tone:"info",text:`(${I} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),_s("Reconciling structure on Document360 (order + related articles)\u2026");try{let R=await ud({cwd:e,profileName:i}),S=hd(await fd({cwd:e,profileName:i})),U=pd(R);U?d({kind:"note",tone:"info",text:U}):R.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${R.skipped}`}),S&&d({kind:"note",tone:"info",text:S}),d({kind:"note",tone:"ok",text:U||S?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(U||S)&&K("/structure")}catch(R){d({kind:"note",tone:"warn",text:`Structure sync failed: ${R.message}`})}finally{_s(null)}return}if(y){let I=(V?[...x,...$]:x).map(R=>R.path);await Lt(I),$.length>0&&!V&&K("/resolve");return}At({cursor:0,rows:Xa(x,$)})}catch(w){d({kind:"note",tone:"error",text:`Could not compute sync status: ${w.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!Bn(c.trim()))return;await Rr(h.find(u=>!u.startsWith("--")));return}case"preview":{let u=h.join(" ").trim();if(!u){let b=[];try{b=Object.keys(od(e,Ce(e,i).name)?.articles??{})}catch{}if(b.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}pt({query:"",cursor:0,paths:b});return}let y=cg(u)?u:gs(e,u);if(Qt(y)){try{d({kind:"preview",name:En(y),text:wd(nr(y,"utf8"))})}catch(b){d({kind:"note",tone:"error",text:`Could not read ${y}: ${b.message}`})}return}if(Zg.test(u)){try{let b=Ce(e,i),w={profile:b.name,connection:b.connection},x=b.project.projectId??mg(w),$=await gg(w,x,u);d({kind:"preview",name:$.title??u,text:$.content??"*(article has no content)*"})}catch(b){d({kind:"note",tone:"error",text:`Could not fetch article: ${b.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=h[0]?.trim();if(!u){let x=Ao(xs(e));ct({cursor:x,current:x});return}let{lines:y,changed:b,effective:w}=xn(e,u);for(let x of y)d({kind:"note",tone:x.startsWith("\u26A0")?"warn":x.startsWith("\u2713")?"ok":"info",text:x});b&&(Ms(x=>x+1),Pe.current?.setModel(w));return}case"convert":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:y}=ri(h),b=Og(e,i);if(b.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let w=ii(b,u);if(w.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${b.length} are tracked overall.)`});return}let x=ks(w),$=3,V=`/convert${u?` --scope ${u}`:""} --run`,H=rr(e,"light");if(!y){let R=ad({files:si(e,w),op:"convert",model:H.model}),S=u?`Scope: ${u} (${w.length} of ${b.length} tracked)
334
+ ${gd}`}),K("/init"),_n(!1),!0},[e,d,Ot,Ye,K]),pn=G(async c=>{let a=c.slice(1).trim().split(/\s+/),s=(a[0]??"").toLowerCase(),h=a.slice(1);if(_n(!0),Do(h)&&["write","check","review","reorder"].includes(s)){let u=$n(e,i);if(u.length===0){d({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let y=b=>s==="write"?`/write ${pl(h,b).join(" ")}`.trim():`/${s} ${[b,...h.filter(w=>w!=="--scope")].join(" ")}`.trim();if(u.length===1){pn(y(u[0].token));return}ut({cursor:0,rows:u,run:b=>{pn(y(b))}});return}if(et(s,h)){let u=$n(e,i);if(u.length>1){let y=h.filter($=>$.startsWith("--")).join(" "),b=$=>`/${s}${$?` ${s==="write"?`--scope ${$}`:$}`:""}${y?` ${y}`:""} ${$?"":"--all"}`.replace(/\s+/g," ").trim(),w=u.reduce(($,V)=>$+V.count,0),x={token:"",label:s==="review"?`Everything \u2014 all ${w} articles + structure (IA) review`:s==="reorder"?`Everything \u2014 reorder all ${u.length} categories`:`Everything \u2014 rewrite all ${w} planned articles`,count:w};ut({cursor:0,rows:[x,...u],run:$=>{pn(b($))}});return}}switch(s){case"help":sn({tab:0});return;case"exit":case"quit":Te.current?.close(),r();return;case"clear":$e(),Rt.current=[],_n(!1),Ye(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=Ce(e,i)}catch(y){d({kind:"note",tone:"error",text:y.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),B(!0);try{let y=await fg(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},w=>d({kind:"note",tone:"info",text:w})),b=hg(u.name,y);if(mg(b),await Dr(b,u.name,w=>d({kind:"note",tone:"info",text:w})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${so(b)}`}),await Vs(i),rn.current){let w=rn.current;rn.current=null;let x=Ae(e,i);x.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${w}.`}),K(w)):(d({kind:"note",tone:"warn",text:`${x.reason} (then ${w}.)`}),K("/login"),rn.current=w)}else Hn.current&&(me(Hn.current,"\u21E5 tab to re-send your last prompt\u2026"),Hn.current=null)}catch(y){d({kind:"note",tone:"error",text:`Login failed: ${y.message}`})}finally{B(!1),X(y=>y+1)}return}case"allow-prod":{let u=!1;try{u=Ce(e,i).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Pt.current=!0,$e(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Ti(h.join(" ")),y=Le.current.uuid;if(!y){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}ur.current=u,at(u),Xt(`${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 b=Le.current.firstPrompt??"";nd(b,e).then(w=>{w?(me(`/rename ${w}`),d({kind:"note",tone:"info",text:`Suggestion: "${w}" \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}Pg(y,u),at(u),Xt(`${Xo} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=h[0],y=ne(e);if(!u){let b=Object.entries(y?.profiles??{});if(b.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let w=b.map(([V,H])=>({name:V,env:H.connection?.environment??"custom",prod:H.production===!0,who:$r(V)})),x=i??y?.defaultProfile,$=Math.max(0,w.findIndex(V=>V.name===x));St({cursor:$,current:$,rows:w});return}if(u==="add"){let b=Si(e,h[1],h[2]);if(b){d({kind:"note",tone:"error",text:b});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),xr(h[1],!1);return}if(!y?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}xr(u,!0);return}case"doctor":await Cn(h,{cwd:e,version:o});return;case"genre":{await Uo(h,{cwd:e});try{ar.current=!(ne(e)?.appType??Dg(e))}catch{}X(u=>u+1);return}case"roadmap":{if(h[0]?.toLowerCase()==="done"){let u=Ji(e,h.slice(1).join(" ").trim());d({kind:"note",tone:u.ok?"ok":"warn",text:u.line}),X(y=>y+1);return}d({kind:"note",tone:"info",text:Qi(e).join(`
335
+ `)});return}case"mcp":await ko(h);return;case"init":{if(ne(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=Ig().map(y=>({name:y,apiUrl:_g(y).apiUrl}));Dt({cursor:0,rows:u});return}case"resume":{let u=h.join(" ").trim(),y=Rg(e).filter(x=>x.uuid!==Le.current.uuid);if(!u){if(!y.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}ht({query:"",cursor:0,sessions:y});return}let b=Cg(e,u);if(!b){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}$e(b.uuid),Le.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},at(b.name),ws(b.uuid),Rt.current=[];let w=ps(e,b.uuid);for(let x of w)d(x);d({kind:"note",tone:"ok",text:w.length?`Resumed "${b.name}" \u2014 restored ${w.length} message(s); continue where you left off.`:`Resumed "${b.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=h.join(" ").trim(),y;try{y=await mn(e,i)}catch(w){d({kind:"note",tone:"error",text:`Could not list workspaces: ${w.message}`});return}if(!u){let w=y.workspaces.map($=>({id:$.id,name:$.name??$.id,type:$.workspace_type}));if(w.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let x=Math.max(0,w.findIndex($=>$.id===y.current));jt({cursor:x,current:x,rows:w,profile:y.profile,projectId:y.projectId,projectName:y.projectName,environment:y.environment});return}let b=Tr(y.workspaces,u);if(!b){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}Kn(y.profile,y.projectId,b);return}case"project":{let u=h.join(" ").trim(),y;try{y=await Xe(e,i)}catch(w){d({kind:"note",tone:"error",text:`Could not list projects: ${w.message} (signed in? try /login)`});return}if(!u){let w=y.projects.map($=>({id:$.id,name:$.name??$.id,sub:$.sub_domain}));if(w.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let x=w.findIndex($=>$.id===y.current);dt({cursor:Math.max(0,x),current:x,rows:w,profile:y.profile,environment:y.environment});return}let b=Sr(y.projects,u);if(!b){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${y.projects.map(w=>w.name??w.id).join(", ")}`});return}Qn(y.profile,b);return}case"logout":{let u;try{u=Ce(e,i).name}catch(b){d({kind:"note",tone:"error",text:b.message});return}let y=kg(u);bg(e,u),$e(),X(b=>b+1),d({kind:"note",tone:y?"ok":"info",text:y?`\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."}),K("/login");return}case"publish":{if(!Bn(c.trim()))return;if(h[0]==="--related"&&h[1]){let w=await Ro(e,i,h[1].replace(/\\/g,"/"));if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Lt(w);return}let u=h.filter(w=>!w.startsWith("--"));if(u[0]){await vr(u[0]);return}let y=h.includes("--all"),b=h.includes("--force");d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let w=await ys({cwd:e,profileName:i}),{clean:x,conflicts:$}=vo(w.entries),V=y&&b&&$.length>0,H=xo(w.entries);if(H>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${H} article${H===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.`}),$.length>0&&!V&&d({kind:"note",tone:"warn",text:$o($.length)}),x.length===0&&!V){if($.length>0){K("/resolve");return}d({kind:"note",tone:"ok",text:H>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let I=w.counts["unknown-base"]??0;I>0&&d({kind:"note",tone:"info",text:`(${I} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),_s("Reconciling structure on Document360 (order + related articles)\u2026");try{let R=await pd({cwd:e,profileName:i}),S=md(await hd({cwd:e,profileName:i})),U=fd(R);U?d({kind:"note",tone:"info",text:U}):R.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${R.skipped}`}),S&&d({kind:"note",tone:"info",text:S}),d({kind:"note",tone:"ok",text:U||S?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(U||S)&&K("/structure")}catch(R){d({kind:"note",tone:"warn",text:`Structure sync failed: ${R.message}`})}finally{_s(null)}return}if(y){let I=(V?[...x,...$]:x).map(R=>R.path);await Lt(I),$.length>0&&!V&&K("/resolve");return}At({cursor:0,rows:Xa(x,$)})}catch(w){d({kind:"note",tone:"error",text:`Could not compute sync status: ${w.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!Bn(c.trim()))return;await Rr(h.find(u=>!u.startsWith("--")));return}case"preview":{let u=h.join(" ").trim();if(!u){let b=[];try{b=Object.keys(rd(e,Ce(e,i).name)?.articles??{})}catch{}if(b.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}pt({query:"",cursor:0,paths:b});return}let y=ug(u)?u:gs(e,u);if(Qt(y)){try{d({kind:"preview",name:En(y),text:yd(nr(y,"utf8"))})}catch(b){d({kind:"note",tone:"error",text:`Could not read ${y}: ${b.message}`})}return}if(tw.test(u)){try{let b=Ce(e,i),w={profile:b.name,connection:b.connection},x=b.project.projectId??wg(w),$=await yg(w,x,u);d({kind:"preview",name:$.title??u,text:$.content??"*(article has no content)*"})}catch(b){d({kind:"note",tone:"error",text:`Could not fetch article: ${b.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=h[0]?.trim();if(!u){let x=Ao(xs(e));ct({cursor:x,current:x});return}let{lines:y,changed:b,effective:w}=xn(e,u);for(let x of y)d({kind:"note",tone:x.startsWith("\u26A0")?"warn":x.startsWith("\u2713")?"ok":"info",text:x});b&&(Ms(x=>x+1),Te.current?.setModel(w));return}case"convert":{if(!ne(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:y}=ri(h),b=Mg(e,i);if(b.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let w=ii(b,u);if(w.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${b.length} are tracked overall.)`});return}let x=ks(w),$=3,V=`/convert${u?` --scope ${u}`:""} --run`,H=rr(e,"light");if(!y){let R=ld({files:si(e,w),op:"convert",model:H.model}),S=u?`Scope: ${u} (${w.length} of ${b.length} tracked)
336
336
  `:"",U=`
337
337
  Model: ${H.model}${H.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:S+li(x,R,$).join(`
338
- `)+U}),K(V);return}st.current=Date.now(),$t(0),D(!0);let I=new AbortController;Te.current=I,re({verb:"Converting",total:x.length,done:0,active:[],rows:An(x),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${w.length} articles across ${x.length} partitions (\u2264${$} agents at once) on ${H.model}\u2026 (esc to stop)`});try{for await(let R of or({cwd:e,partitions:x,promptFor:ai,concurrency:$,profileName:i,allowProdWrites:Pt.current,model:H.model,signal:I.signal}))if(R.type==="partition_status")R.status==="running"?re(S=>S&&{...S,active:[...S.active,R.label],rows:qe(S.rows,R.label,"active"),lastAt:Date.now()}):re(S=>S&&{...S,active:S.active.filter(U=>U!==R.label),done:S.done+1,rows:qe(S.rows,R.label,R.status==="done"?"done":"failed"),lastAt:Date.now()});else if(R.type==="partition_event")re(S=>{if(!S)return S;let U={...S,lastAt:Date.now()};return R.event.type==="tool"?U.tools=S.tools+1:R.event.type==="text"&&(U.chars=S.chars+R.event.delta.length),U});else if(R.type==="run_done"){It(Z=>Z+R.totalCostUsd),Nt(Z=>Z+R.results.reduce((Wt,Ft)=>Wt+Ft.outputTokens,0));let S=R.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";d({kind:"note",tone:R.aborted?"warn":R.ok?"ok":"warn",text:S+ci(R.results,x,U).join(`
339
- `)})}}catch(R){d({kind:"note",tone:"error",text:`Convert run failed: ${R.message}`})}finally{Te.current=null,re(null),D(!1),X(R=>R+1)}return}case"write":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Lg(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:y,path:b,preview:w,concurrency:x,rewrite:$}=pi(h),{docsDir:V,targets:H,reason:I,rewriting:R}=ki(e,u,{scope:y,path:b,rewrite:$});if(H.length===0){d({kind:"note",tone:"warn",text:I??"Nothing to write."});return}R&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${H.length} already-written article${H.length===1?"":"s"} (overwrites them; git has your baseline).`});let S=ks(H),U=ui(x),Z=rr(e,"standard"),Wt=!!b;if(w&&!Wt){let z=ad({files:hi(e,u,H),op:"write",model:Z.model}),se=y?`Scope: ${y} (${H.length} pending)
338
+ `)+U}),K(V);return}st.current=Date.now(),$t(0),D(!0);let I=new AbortController;Se.current=I,re({verb:"Converting",total:x.length,done:0,active:[],rows:An(x),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${w.length} articles across ${x.length} partitions (\u2264${$} agents at once) on ${H.model}\u2026 (esc to stop)`});try{for await(let R of or({cwd:e,partitions:x,promptFor:ai,concurrency:$,profileName:i,allowProdWrites:Pt.current,model:H.model,signal:I.signal}))if(R.type==="partition_status")R.status==="running"?re(S=>S&&{...S,active:[...S.active,R.label],rows:Be(S.rows,R.label,"active"),lastAt:Date.now()}):re(S=>S&&{...S,active:S.active.filter(U=>U!==R.label),done:S.done+1,rows:Be(S.rows,R.label,R.status==="done"?"done":"failed"),lastAt:Date.now()});else if(R.type==="partition_event")re(S=>{if(!S)return S;let U={...S,lastAt:Date.now()};return R.event.type==="tool"?U.tools=S.tools+1:R.event.type==="text"&&(U.chars=S.chars+R.event.delta.length),U});else if(R.type==="run_done"){It(Z=>Z+R.totalCostUsd),Nt(Z=>Z+R.results.reduce((Wt,Ft)=>Wt+Ft.outputTokens,0));let S=R.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";d({kind:"note",tone:R.aborted?"warn":R.ok?"ok":"warn",text:S+ci(R.results,x,U).join(`
339
+ `)})}}catch(R){d({kind:"note",tone:"error",text:`Convert run failed: ${R.message}`})}finally{Se.current=null,re(null),D(!1),X(R=>R+1)}return}case"write":{if(!ne(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Ug(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:y,path:b,preview:w,concurrency:x,rewrite:$}=pi(h),{docsDir:V,targets:H,reason:I,rewriting:R}=ki(e,u,{scope:y,path:b,rewrite:$});if(H.length===0){d({kind:"note",tone:"warn",text:I??"Nothing to write."});return}R&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${H.length} already-written article${H.length===1?"":"s"} (overwrites them; git has your baseline).`});let S=ks(H),U=ui(x),Z=rr(e,"standard"),Wt=!!b;if(w&&!Wt){let z=ld({files:hi(e,u,H),op:"write",model:Z.model}),se=y?`Scope: ${y} (${H.length} pending)
340
340
  `:"",pe=`
341
341
  Model: ${Z.model}${Z.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:se+gi(S,z,U).join(`
342
- `)+pe}),K(`/write${y?` --scope ${y}`:""}`);return}st.current=Date.now(),$t(0),D(!0);let Ft=new AbortController;Te.current=Ft,re({verb:"Writing",total:S.length,done:0,active:[],rows:An(S),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${H.length} article${H.length===1?"":"s"} across ${S.length} partition${S.length===1?"":"s"} (\u2264${U} agents at once) on ${Z.model}${Z.forced?" (forced)":""}\u2026 (esc to stop)`});let eo=new Set;try{for await(let z of or({cwd:e,partitions:S,promptFor:se=>mi(se,V,{rewrite:R||Wt}),concurrency:U,profileName:i,allowProdWrites:Pt.current,model:Z.model,signal:Ft.signal}))if(z.type==="partition_status")z.status==="running"?re(se=>se&&{...se,active:[...se.active,z.label],rows:qe(se.rows,z.label,"active"),lastAt:Date.now()}):re(se=>se&&{...se,active:se.active.filter(pe=>pe!==z.label),done:se.done+1,rows:qe(se.rows,z.label,z.status==="done"?"done":"failed"),lastAt:Date.now()});else if(z.type==="partition_event"){let se=null;if(z.event.type==="tool"){let pe=Wc(z.event.name,z.event.input,S[z.index]?.paths??[]);pe&&!eo.has(pe)&&(eo.add(pe),se=z.label)}re(pe=>{if(!pe)return pe;let Ie={...pe,lastAt:Date.now()};return z.event.type==="tool"?Ie.tools=pe.tools+1:z.event.type==="text"&&(Ie.chars=pe.chars+z.event.delta.length),se&&(Ie.rows=Uc(Ie.rows,se)),Ie})}else if(z.type==="run_done"){It(ze=>ze+z.totalCostUsd),Nt(ze=>ze+z.results.reduce((We,Od)=>We+Od.outputTokens,0));let se=z.aborted?"Stopped. ":"",pe=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:z.aborted?"warn":z.ok?"ok":"warn",text:se+wi(z.results,S,pe).join(`
343
- `)}),!z.aborted&&z.ok)try{let ze=(eo.size>0?[...eo]:H).map(We=>`${V}/${We}`);bs(e,ze,{writtenCap:vs})}catch{}let Ie=z.aborted?null:yi(e,V,H);if(Ie&&d({kind:"note",tone:"warn",text:Ie}),!z.aborted&&z.ok){let ze=y??b??"",We=ze?` ${ze}`:"";_t(Ie?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${We} --fix, then /review${We} --fix for editorial quality, then /publish --all (add /screenshot --all first if you want images).`:`Written. I\u2019d run /review${We} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot --all first if you want images).`,{kind:"cmd",cmd:Ie?`/check${We} --fix`:`/review${We} --fix`,reason:""})}}}catch(z){d({kind:"note",tone:"error",text:`Write run failed: ${z.message}`})}finally{Te.current=null,re(null),D(!1),X(z=>z+1)}return}case"draft":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:y}=bi(e);if(u.length===0&&y===0){d({kind:"note",tone:"info",text:$i});return}let b=h.join(" ").trim();if(!b&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
342
+ `)+pe}),K(`/write${y?` --scope ${y}`:""}`);return}st.current=Date.now(),$t(0),D(!0);let Ft=new AbortController;Se.current=Ft,re({verb:"Writing",total:S.length,done:0,active:[],rows:An(S),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${H.length} article${H.length===1?"":"s"} across ${S.length} partition${S.length===1?"":"s"} (\u2264${U} agents at once) on ${Z.model}${Z.forced?" (forced)":""}\u2026 (esc to stop)`});let eo=new Set;try{for await(let z of or({cwd:e,partitions:S,promptFor:se=>mi(se,V,{rewrite:R||Wt}),concurrency:U,profileName:i,allowProdWrites:Pt.current,model:Z.model,signal:Ft.signal}))if(z.type==="partition_status")z.status==="running"?re(se=>se&&{...se,active:[...se.active,z.label],rows:Be(se.rows,z.label,"active"),lastAt:Date.now()}):re(se=>se&&{...se,active:se.active.filter(pe=>pe!==z.label),done:se.done+1,rows:Be(se.rows,z.label,z.status==="done"?"done":"failed"),lastAt:Date.now()});else if(z.type==="partition_event"){let se=null;if(z.event.type==="tool"){let pe=Fc(z.event.name,z.event.input,S[z.index]?.paths??[]);pe&&!eo.has(pe)&&(eo.add(pe),se=z.label)}re(pe=>{if(!pe)return pe;let _e={...pe,lastAt:Date.now()};return z.event.type==="tool"?_e.tools=pe.tools+1:z.event.type==="text"&&(_e.chars=pe.chars+z.event.delta.length),se&&(_e.rows=Wc(_e.rows,se)),_e})}else if(z.type==="run_done"){It(ze=>ze+z.totalCostUsd),Nt(ze=>ze+z.results.reduce((Fe,Ld)=>Fe+Ld.outputTokens,0));let se=z.aborted?"Stopped. ":"",pe=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:z.aborted?"warn":z.ok?"ok":"warn",text:se+wi(z.results,S,pe).join(`
343
+ `)}),!z.aborted&&z.ok)try{let ze=(eo.size>0?[...eo]:H).map(Fe=>`${V}/${Fe}`);bs(e,ze,{writtenCap:vs})}catch{}let _e=z.aborted?null:yi(e,V,H);if(_e&&d({kind:"note",tone:"warn",text:_e}),!z.aborted&&z.ok){let ze=y??b??"",Fe=ze?` ${ze}`:"";_t(_e?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${Fe} --fix, then /review${Fe} --fix for editorial quality, then /publish --all (add /screenshot --all first if you want images).`:`Written. I\u2019d run /review${Fe} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot --all first if you want images).`,{kind:"cmd",cmd:_e?`/check${Fe} --fix`:`/review${Fe} --fix`,reason:""})}}}catch(z){d({kind:"note",tone:"error",text:`Write run failed: ${z.message}`})}finally{Se.current=null,re(null),D(!1),X(z=>z+1)}return}case"draft":{if(!ne(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:y}=bi(e);if(u.length===0&&y===0){d({kind:"note",tone:"info",text:$i});return}let b=h.join(" ").trim();if(!b&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
344
344
  ${u.map($=>` \u2022 ${$.name} (${$.docCount} doc${$.docCount===1?"":"s"})`).join(`
345
345
  `)}`}),it(u.map($=>`/draft ${$.name}`));return}let w="",x;if(b){let $=vi(u,b);$?w=$:x=b}else w=u[0]?.name??"";await ie(jo(w,x),{display:b?`/draft ${b}`:"/draft",quietUser:!0});return}case"pull":{if(!Bn(c.trim()))return;let u=h.find(y=>y.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let w=Date.now(),x=await ys({cwd:e,profileName:i});d({kind:"note",tone:"info",text:To(x,Date.now()-w).join(`
346
- `)});return}if(u==="--baseline"){let w=h.find(H=>!H.startsWith("--")),x=w?w.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:x?`Setting the sync baseline for ${x}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let $=await Dg({cwd:e,profileName:i,relPaths:x?[x]:void 0}),V=x?{rebaselined:[],skipped:[]}:await jg({cwd:e,profileName:i});if($.baselined.length===0&&$.skipped.length===0&&V.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}$.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${$.baselined.length} article${$.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),V.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${V.rebaselined.length} article${V.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),$.skipped.length>0&&d({kind:"note",tone:"warn",text:`${$.skipped.length} skipped:
346
+ `)});return}if(u==="--baseline"){let w=h.find(H=>!H.startsWith("--")),x=w?w.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:x?`Setting the sync baseline for ${x}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let $=await Ag({cwd:e,profileName:i,relPaths:x?[x]:void 0}),V=x?{rebaselined:[],skipped:[]}:await Eg({cwd:e,profileName:i});if($.baselined.length===0&&$.skipped.length===0&&V.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}$.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${$.baselined.length} article${$.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),V.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${V.rebaselined.length} article${V.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),$.skipped.length>0&&d({kind:"note",tone:"warn",text:`${$.skipped.length} skipped:
347
347
  ${$.skipped.map(H=>` - ${H.path} (${H.reason})`).join(`
348
- `)}`}),X(H=>H+1);return}if(u==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let w=await Sg({cwd:e,profileName:i}),x=w.onlyInLegacy.length===0&&w.onlyInManifest.length===0&&w.mappedMissingFromManifest.length===0,$=[`Legacy listing: ${w.legacyCount} \xB7 Manifest: ${w.manifestCount} \xB7 in both: ${w.inBoth}`];x?$.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(w.mappedMissingFromManifest.length&&$.push(`\u2717 ${w.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${w.mappedMissingFromManifest.slice(0,5).join(", ")}`),w.onlyInLegacy.length&&$.push(`\u26A0 ${w.onlyInLegacy.length} only in the legacy listing: ${w.onlyInLegacy.slice(0,5).join(", ")}`),w.onlyInManifest.length&&$.push(`\u26A0 ${w.onlyInManifest.length} only in the manifest: ${w.onlyInManifest.slice(0,5).join(", ")}`),$.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:x?"ok":"warn",text:$.join(`
349
- `)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=h[0];if(y){let w=await sd({cwd:e,profileName:i,relPath:y.replace(/\\/g,"/")});le.current=[{plan:w,mode:w.overwritesLocalChanges?"conflict":"pull"}],Tt.current=[],Mt();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let b=await ti({cwd:e,profileName:i});for(let w of ni(b))d({kind:"note",tone:w.tone,text:w.text});X(w=>w+1)}catch(y){d({kind:"note",tone:"error",text:`Pull failed: ${y.message}`})}return}case"scope":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Ag(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}Et({cursor:0,rows:u.map(y=>({...y,checked:y.recommended}))});return}case"audit":{if(h[0]==="--auto"){let y=te(e);if(!y){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=h[1]!=="off";nd({...y,autoAudit:b},e),d({kind:"note",tone:"ok",text:b?"\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 vn();u.kind==="forward-to-agent"&&u.prompt&&await ie(u.prompt,{display:u.display,quietUser:!0});return}case"check":{let u=h.find(w=>!w.startsWith("--")),y=u?` ${u}`:"",b=id({cwd:e,scope:u});if(h.includes("--fix")){if(b.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 ${b.length} doc issue${b.length===1?"":"s"}\u2026`});let w=dd(e,u);await ie(Yi(b),{display:`/check${y} --fix`,quietUser:!0});try{bs(e,w,{reviewedCap:vs})}catch{}let x=id({cwd:e,scope:u});d({kind:"note",tone:x.length===0?"ok":"warn",text:x.length===0?"\u2713 Doc-checker: all issues resolved.":Mo(x).join(`
348
+ `)}`}),X(H=>H+1);return}if(u==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let w=await jg({cwd:e,profileName:i}),x=w.onlyInLegacy.length===0&&w.onlyInManifest.length===0&&w.mappedMissingFromManifest.length===0,$=[`Legacy listing: ${w.legacyCount} \xB7 Manifest: ${w.manifestCount} \xB7 in both: ${w.inBoth}`];x?$.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(w.mappedMissingFromManifest.length&&$.push(`\u2717 ${w.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${w.mappedMissingFromManifest.slice(0,5).join(", ")}`),w.onlyInLegacy.length&&$.push(`\u26A0 ${w.onlyInLegacy.length} only in the legacy listing: ${w.onlyInLegacy.slice(0,5).join(", ")}`),w.onlyInManifest.length&&$.push(`\u26A0 ${w.onlyInManifest.length} only in the manifest: ${w.onlyInManifest.slice(0,5).join(", ")}`),$.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:x?"ok":"warn",text:$.join(`
349
+ `)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=h[0];if(y){let w=await ad({cwd:e,profileName:i,relPath:y.replace(/\\/g,"/")});le.current=[{plan:w,mode:w.overwritesLocalChanges?"conflict":"pull"}],Tt.current=[],Mt();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let b=await ti({cwd:e,profileName:i});for(let w of ni(b))d({kind:"note",tone:w.tone,text:w.text});X(w=>w+1)}catch(y){d({kind:"note",tone:"error",text:`Pull failed: ${y.message}`})}return}case"scope":{if(!ne(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Ng(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}Et({cursor:0,rows:u.map(y=>({...y,checked:y.recommended}))});return}case"audit":{if(h[0]==="--auto"){let y=ne(e);if(!y){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=h[1]!=="off";od({...y,autoAudit:b},e),d({kind:"note",tone:"ok",text:b?"\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 vn();u.kind==="forward-to-agent"&&u.prompt&&await ie(u.prompt,{display:u.display,quietUser:!0});return}case"check":{let u=h.find(w=>!w.startsWith("--")),y=u?` ${u}`:"",b=sd({cwd:e,scope:u});if(h.includes("--fix")){if(b.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 ${b.length} doc issue${b.length===1?"":"s"}\u2026`});let w=ud(e,u);await ie(Yi(b),{display:`/check${y} --fix`,quietUser:!0});try{bs(e,w,{reviewedCap:vs})}catch{}let x=sd({cwd:e,scope:u});d({kind:"note",tone:x.length===0?"ok":"warn",text:x.length===0?"\u2713 Doc-checker: all issues resolved.":Mo(x).join(`
350
350
  `)}),_t(x.length===0?`Deterministic issues fixed. Next: /review${y} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${y} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${y} --fix`,reason:""});return}d({kind:"note",tone:b.length===0?"ok":"warn",text:Mo(b).join(`
351
351
  `)}),b.length>0&&_t(`Found ${b.length} doc issue${b.length===1?"":"s"} above. /check${y} --fix has the agent fix them in place (or /review${y} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${y} --fix`,reason:""});return}case"structure":{let u=Sn(e,i);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(`
352
- `)});return}case"reorder":{let u=Ki(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ie(u.prompt,{display:u.display,quietUser:!0}),_t("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let u=zi(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=h.includes("--fix"),b=h.find(x=>!x.startsWith("--")),w=y?dd(e,b):[];if(await ie(u.prompt,{display:u.display,quietUser:!0}),y)try{bs(e,w,{reviewedCap:vs})}catch{}if(y)_t("\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let x=h.filter($=>$!=="--fix").join(" ");_t(`The review listed issues above. /review${x?` ${x}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${x?` ${x}`:""} --fix`,reason:""})}return}case"capture-setup":{let u=await Rn();u.kind==="forward-to-agent"&&u.prompt&&await ie(u.prompt,{display:u.display,quietUser:!0});let y=Ii(e);y&&d({kind:"note",tone:"info",text:y.join(`
353
- `)});return}case"devhints":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Gt(Vt(e)).join(`
354
- `)}),Ot(gt()),ln.current=De(e).status==="current"||Fe(e);return}case"discover":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ie(Xr(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(_i(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 ie(Oi(),{display:"/inbox",quietUser:!0});return}case"feedback":{let u=cd(e),y="";try{y=Qt(u)?nr(u,"utf8"):""}catch{y=""}if(!/^## /m.test(y)){d({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let b=await ds(y.trim());d({kind:"note",tone:b?"ok":"warn",text:b?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${u} and copy it manually.`}),b&&yr(null);return}case"document":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:y}=Ci(h);if(!y&&xi(e)===0){d({kind:"note",tone:"info",text:Pi});return}let b=`/document${y?` ${y}`:""}${u?" --publish":""}`;await ie(Ri(y,u),{display:b,quietUser:!0});return}case"catch-up":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Bn(c.trim()))return;let{publish:u}=Mi(h);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let y=await Wi({cwd:e,profileName:i});for(let w of Fi(y))d({kind:"note",tone:w.startsWith("\u2713")?"ok":w.startsWith("\u2139")?"info":"warn",text:w});let b=Tn(Pn(e));d({kind:"note",tone:"info",text:b?`Catching up on ${b}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ie(Ui({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{gr.current=!0,d({kind:"note",tone:"info",text:`Updating ${kt}\u2026 (don\u2019t close this window)`}),On(!0),(await Oo().finally(()=>On(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),K("/exit"),Ds("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${_o}`});return}case"screenshot":{let u=Ai(h);if(u.mode==="list"){if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Ni(Ei(e,u.scope),u.scope).join(`
355
- `)});return}if(u.mode==="single"){let I=await No(h);I.kind==="forward-to-agent"&&I.prompt&&await ie(I.prompt,{display:I.display,quietUser:!0});return}if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=u.mode==="scope"?u.scope:void 0,b=_g(e,{scope:y}).map(I=>I.id);if(b.length===0){d({kind:"note",tone:"info",text:y?`No screenshot placeholders under ${y}.`:"No screenshot placeholders found in the docs."});return}let w=6,x=Ig(b,3),$=rr(e,"standard");st.current=Date.now(),$t(0),D(!0);let V=new AbortController;Te.current=V,re({verb:"Authoring",unit:"spec",total:x.length,done:0,active:[],rows:An(x),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${b.length} screenshot spec${b.length===1?"":"s"} across ${x.length} partition${x.length===1?"":"s"} (\u2264${w} agents at once) on ${$.model}${$.forced?" (forced)":""}\u2026 (esc to stop)`});let H=!1;try{for await(let I of or({cwd:e,partitions:x,promptFor:Bl,concurrency:w,profileName:i,allowProdWrites:Pt.current,model:$.model,signal:V.signal}))if(I.type==="partition_status")I.status==="running"?re(R=>R&&{...R,active:[...R.active,I.label],rows:qe(R.rows,I.label,"active"),lastAt:Date.now()}):re(R=>R&&{...R,active:R.active.filter(S=>S!==I.label),done:R.done+1,rows:qe(R.rows,I.label,I.status==="done"?"done":"failed"),lastAt:Date.now()});else if(I.type==="partition_event")re(R=>{if(!R)return R;let S={...R,lastAt:Date.now()};return I.event.type==="tool"?S.tools=R.tools+1:I.event.type==="text"&&(S.chars=R.chars+I.event.delta.length),S});else if(I.type==="run_done"){It(Z=>Z+I.totalCostUsd),Nt(Z=>Z+I.results.reduce((Wt,Ft)=>Wt+Ft.outputTokens,0));let R=I.results.filter(Z=>Z.ok).length,S=I.aborted?"Stopped. ":"";H=!I.aborted&&u.setup;let U=I.aborted?"":H?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:I.aborted?"warn":I.ok?"ok":"warn",text:`${S}Authored specs \u2014 ${R}/${I.results.length} batches ok.${U}`})}}catch(I){d({kind:"note",tone:"error",text:`Spec authoring failed: ${I.message}`})}finally{Te.current=null,re(null),D(!1),X(I=>I+1)}if(H){let I=await Rn();I.kind==="forward-to-agent"&&I.prompt&&await ie(I.prompt,{display:I.display,quietUser:!0});let R=Ii(e);R&&d({kind:"note",tone:"info",text:R.join(`
356
- `)})}return}case"reset":{let u=Bi(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Un.current={repoName:En(e),targets:u,hadDevhints:Qt(ld(e))},d({kind:"note",tone:"warn",text:Gi(e,u).join(`
357
- `)}),me(En(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${s} \u2014 type /help.`})}},[e,r,i,Mt,Rr,d,$e,ie,Lt,vr,Vs]),Jn=G(c=>{let a=(c??T).trim();if(v(""),Ln(null),xt(0),a.startsWith("/")&&(Nn.current=!1,Ye(),nn(null),it(h=>qc(h,a))),!a||(Ss(!1),Ys(a))||Gs(a))return;dr.current.push(a);let s=Yc(a,js.current);if(a.startsWith("/"))d({kind:"user",text:a}),pn(s);else if(Vg(s)){d({kind:"user",text:a});let h=Gg(s);if(!h)ie(s,{display:a,quietUser:!0});else{try{Yg(e,{title:h,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ie(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${h}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${h}" and the article path(s) you wrote.`,{display:a,quietUser:!0})}}else ie(s,{display:a})},[T,Ys,Gs,pn,ie]),zs=G(c=>{if(c.length>1){if(c.includes("\x1B"))return;let a=Bc(c);if(Vc(a)){let s=Gc(++jd.current,a);js.current.set(s,a),_(s)}else _(a);return}_(c)},[_]),Ut=Math.max(10,Ne-6),Ks=ms(()=>er(k.text,Ut),[k.text,Ut]),Pr=G(c=>g(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+c))})),[]),Zn=G(c=>g(a=>({...a,pos:Kc(er(a.text,Ut),a.pos,c)})),[Ut]),fn=G(c=>g(a=>({...a,pos:Xc(er(a.text,Ut),a.pos,c)})),[Ut]),Id=["\x1B[H","\x1B[1~","\x1BOH"],_d=["\x1B[F","\x1B[4~","\x1BOF"],Xs=G((c,a)=>a.leftArrow?(Pr(-1),!0):a.rightArrow?(Pr(1),!0):c&&Id.includes(c)?(fn("start"),!0):c&&_d.includes(c)?(fn("end"),!0):a.ctrl&&c==="a"?(fn("start"),!0):a.ctrl&&c==="e"?(fn("end"),!0):!1,[Pr,fn]);return sg((c,a)=>{if(a.ctrl&&c==="c"){Pe.current?.close(),r();return}if(!M){if(N){if(a.escape){if(Te.current){if(!Te.current.signal.aborted){let s=(Wn?.verb??"work").toLowerCase(),h=Wn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${s} run (finishing in-flight ${h}s)\u2026`}),Te.current.abort()}return}on.current||(on.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Pe.current?.interrupt());return}if(a.return){let s=T.trim();if(!s)return;ft.current.push(s),pr([...ft.current]),v("");return}if(Xs(c,a))return;if(a.upArrow){Zn(-1);return}if(a.downArrow){Zn(1);return}if(a.backspace||a.delete){P();return}c&&!a.ctrl&&!a.meta&&zs(c);return}if(lt){if(a.upArrow){ct(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){ct(s=>s&&{...s,cursor:Math.min(_e.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=_e.length){ct(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=_e[lt.cursor];ct(null);let{lines:h,changed:u,effective:y}=xn(e,s.value??"default");for(let b of h)d({kind:"note",tone:b.startsWith("\u26A0")?"warn":b.startsWith("\u2713")?"ok":"info",text:b});u&&(Ms(b=>b+1),Pe.current?.setModel(y));return}if(c==="s"){let s=_e[lt.cursor];ct(null),Pe.current?.setModel(s.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${s.label} for this session only (your saved default is unchanged).`});return}if(a.escape){ct(null);return}return}if(Le){if(a.upArrow){St(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){St(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Le.rows.length){St(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return||c==="s"){let s=Le.rows[Le.cursor];St(null),xr(s.name,a.return===!0);return}if(a.escape){St(null);return}return}if(qn){if(a.escape){sn(null);return}if(a.leftArrow||a.tab&&a.shift){sn(s=>s&&{tab:(s.tab-1+Se.length)%Se.length});return}if(a.rightArrow||a.tab){sn(s=>s&&{tab:(s.tab+1)%Se.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Se.length){sn({tab:Number(c)-1});return}return}if(Me){if(a.upArrow){Dt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Dt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Me.rows.length){Dt(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=Me.rows[Me.cursor].name;if(Dt(null),!_r(e,s).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 "${s}").`});let u=!1;try{let y=vt(s);u=!!y&&!(nt(y)&&!y.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${s} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${s}) and pick your project.`}),K("/login"),X(y=>y+1);return}if(a.escape){Dt(null);return}return}if(fe){if(a.upArrow){jt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){jt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=fe.rows.length){jt(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=fe.rows[fe.cursor],{profile:h,projectId:u}=fe;jt(null),Kn(h,u,s);return}if(a.escape){jt(null);return}return}if(ke){if(a.upArrow){dt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){dt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ke.rows.length){dt(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=ke.rows[ke.cursor],{profile:h}=ke;dt(null),Qn(h,s);return}if(a.escape){dt(null);return}return}if(he){if(a.upArrow){Et(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Et(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c===" "){Et(s=>s&&{...s,rows:s.rows.map((h,u)=>u===s.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let s=he.rows.filter(h=>h.checked).map(h=>h.path);if(Et(null),s.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Qr(e,s),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${s.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of s)d({kind:"note",tone:"info",text:` ${h}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){Et(null);return}return}if(Ue){if(a.upArrow){ut(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){ut(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ue.rows.length){ut(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=Ue.rows[Ue.cursor],h=Ue.run;ut(null),h(s.token);return}if(a.escape){ut(null);return}return}if(Ve){if(a.upArrow){At(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){At(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ve.rows.length){At(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=Ve.rows[Ve.cursor];At(null),s.conflict?Rr(s.paths[0]):s.kind==="article"?vr(s.paths[0]):Lt(s.paths);return}if(a.escape){At(null);return}return}if(be){if(a.escape){pt(null);return}if(a.upArrow){pt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){pt(s=>s&&{...s,cursor:Math.min(Math.max(0,Yn.length-1),s.cursor+1)});return}if(a.return){let s=Yn[be.cursor];if(s){pt(null);try{d({kind:"preview",name:En(s),text:wd(nr(gs(e,s),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${s}: ${h.message}`})}}return}if(a.backspace||a.delete){pt(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){pt(s=>s&&{...s,query:s.query+c,cursor:0});return}return}if(ve){if(a.escape){ht(null);return}if(a.upArrow){ht(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){ht(s=>s&&{...s,cursor:Math.min(Math.max(0,zn.length-1),s.cursor+1)});return}if(a.return){let s=zn[ve.cursor];if(s){ht(null),$e(s.uuid),Oe.current={uuid:s.uuid,firstPrompt:s.firstPrompt,titleFired:!0},at(s.name),ws(s.uuid),Rt.current=[];let h=ps(e,s.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${s.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${s.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){ht(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){ht(s=>s&&{...s,query:s.query+c,cursor:0});return}return}if(a.tab&&!T&&ne){v(ne),Ye();return}if(!T&&rt.length>0&&!lr&&c&&/^[1-9]$/.test(c)){let s=rt[Number(c)-1];if(s){v(bt(s));return}}if(!T&&(Vn||an)&&c==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let s=Vn!=null;ds(Vn??an).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?s?"\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.":s?"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&&s&&yr(null),u&&!s&&Fs(!0)});return}if(!Xs(c,a)){if(qs){if(a.upArrow){xt(s=>Math.max(0,s-1));return}if(a.downArrow){xt(s=>Math.min(un.length-1,s+1));return}if(a.tab){v("/"+(un[tn]?.name??"")+" "),xt(0);return}if(a.return){let s=un[tn];if(s){let h=T.trim().slice(1).split(/\s+/).slice(1).join(" ");if(_c(s.usage)&&!h){v("/"+s.name+" "),xt(0);return}Jn("/"+s.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(T!==""&&Ct===null){Zn(-1);return}let s=dr.current;if(!s.length)return;let h=Ct===null?s.length-1:Math.max(0,Ct-1);Ln(h),v(s[h]??"");return}if(a.downArrow){if(T!==""&&Ct===null){Zn(1);return}let s=dr.current;if(Ct===null)return;let h=Ct+1;h>=s.length?(Ln(null),v("")):(Ln(h),v(s[h]??""));return}}if(a.return){Jn();return}if(a.backspace||a.delete){P();return}if(a.escape){v(""),xt(0),Ye(),it([]),nn(null),Nn.current=!0;return}c&&!a.ctrl&&!a.meta&&zs(c)}}}),Re(()=>{if(N||M)return;let c=ft.current.shift();c!==void 0&&(pr([...ft.current]),Jn(c))},[N,M,Jn]),Y(oe,{flexDirection:"column",width:Ne,children:[br!==null&&Y(oe,{marginTop:1,flexDirection:"column",children:[br.truncated&&E(A,{dimColor:!0,children:"\u2026"}),E(A,{children:br.text})]}),N&&(Wn?E(ow,{p:Wn}):E(ew,{startTime:st.current,chars:Dd})),!N&&Is?E(tw,{text:Is}):null,E(oe,{borderStyle:"round",borderColor:Hs.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:T?Ks.map((c,a)=>{let s=k.text.slice(c.start,c.end),h=a===tr(Ks,k.pos),u=Math.min(k.pos,c.end)-c.start;return Y(A,{children:[E(A,{color:q,children:a===0?"> ":" "}),h?Y(ir,{children:[s.slice(0,u),E(Jt,{ch:s[u]??" "}),s.slice(u+1)]}):s||" "]},`${a}-${c.start}`)}):Y(A,{children:[E(A,{color:q,children:"> "}),fr?E(Jt,{ch:" "}):ne&&!N&&ot?Y(ir,{children:[E(Jt,{ch:ot[0],dim:!0}),E(A,{color:"gray",children:ot.slice(1)})]}):ne&&!N?Y(ir,{children:[E(Jt,{ch:ne[0],dim:!0}),E(A,{color:"gray",children:ne.slice(1)}),E(A,{dimColor:!0,children:" (tab)"})]}):(kr.isSetup||!Td)&&!N?Y(ir,{children:[E(Jt,{ch:kr.text[0],dim:!0}),E(A,{color:"gray",children:kr.text.slice(1)})]}):E(Jt,{ch:" "})]})}),Ns.length>0&&E(oe,{flexDirection:"column",paddingX:1,children:Ns.map((c,a)=>E(A,{color:"gray",children:`\u29D7 queued: ${c}`},`${a}-${c.slice(0,24)}`))}),qn?E(Lc,{tab:qn.tab,width:Ne,version:o,engineVersion:yd}):lt?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Select model"}),E(A,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),_e.map((c,a)=>Y(A,{color:a===lt.cursor?q:void 0,children:[a===lt.cursor?"\u276F ":" ",`${a+1}. ${c.label}${a===lt.current?" \u2714":""}`.padEnd(16),E(A,{color:"gray",children:c.desc})]},c.label)),E(A,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Le?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Switch connection profile"}),Le.rows.map((c,a)=>Y(A,{color:a===Le.cursor?q:void 0,children:[a===Le.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===Le.current?" \u2714":""}`.padEnd(20),E(A,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?E(A,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),E(A,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Me?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Pick your Document360 environment"}),Me.rows.map((c,a)=>Y(A,{color:a===Me.cursor?q:void 0,children:[a===Me.cursor?"\u276F ":" ",`${a+1}. ${c.name}`.padEnd(16),E(A,{color:"gray",children:c.apiUrl})]},c.name)),E(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Switch workspace"}),E(A,{dimColor:!0,children:`environment ${fe.environment} \xB7 project ${fe.projectName??`${fe.projectId.slice(0,8)}\u2026`}`}),fe.rows.map((c,a)=>Y(A,{color:a===fe.cursor?q:void 0,children:[a===fe.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===fe.current?" \u2714":""}`.padEnd(30),E(A,{color:"gray",children:c.type??""})]},c.id)),E(A,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ke?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Choose project"}),E(A,{dimColor:!0,children:`environment ${ke.environment}`}),ke.rows.map((c,a)=>Y(A,{color:a===ke.cursor?q:void 0,children:[a===ke.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===ke.current?" \u2714":""}`.padEnd(30),E(A,{color:"gray",children:c.sub??""})]},c.id)),E(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):he?(()=>{let a=Math.min(Math.max(0,he.cursor-Math.floor(7)),Math.max(0,he.rows.length-14)),s=he.rows.slice(a,a+14),h=he.rows.filter(u=>u.checked).length;return Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:`Which folders back the user docs? (${h} selected of ${he.rows.length})`}),a>0?E(A,{dimColor:!0,children:` \u2191 ${a} more`}):null,s.map((u,y)=>{let b=a+y;return Y(A,{color:b===he.cursor?q:void 0,children:[b===he.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Ne-34)),E(A,{color:"gray",children:Po(u)})]},u.path)}),a+14<he.rows.length?E(A,{dimColor:!0,children:` \u2193 ${he.rows.length-a-14} more`}):null,E(A,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Ue?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Which category? (pick one to scope to)"}),Ue.rows.map((c,a)=>{let s=a===Ue.cursor,h=`${a+1}.`.padEnd(3);return Y(A,{color:s?q:void 0,children:[s?"\u276F ":" ",`${h} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Ne-24))),E(A,{color:"gray",children:` ${c.token}`})]},c.token)}),E(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Ve?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Ve.rows.map((c,a)=>{let s=a===Ve.cursor,h=c.indent?" ":" ",u=`${a+1}.`.padEnd(3);return Y(A,{color:s?q:void 0,bold:c.kind==="category"&&!s,children:[s?"\u276F ":" ",`${h}${u} ${c.label}`.padEnd(Math.min(56,Ne-24)),c.note?E(A,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),E(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):be?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:`Preview article${be.query?` \u2014 filter: ${be.query}`:" (type to filter)"}`}),Yn.length===0?E(A,{color:"gray",children:"no articles match"}):Yn.map((c,a)=>Y(A,{color:a===be.cursor?q:void 0,children:[a===be.cursor?"\u276F ":" ",c]},c)),E(A,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):ve?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:`Resume session${ve.query?` \u2014 filter: ${ve.query}`:" (type to filter)"}`}),zn.length===0?E(A,{color:"gray",children:"no sessions match"}):zn.map((c,a)=>Y(A,{color:a===ve.cursor?q:void 0,children:[a===ve.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),E(A,{color:a===ve.cursor?q:"gray",children:c.firstPrompt.slice(0,Math.max(10,Ne-40))})]},c.uuid)),E(A,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):qs?Y(oe,{flexDirection:"column",children:[un.map((c,a)=>Y(A,{color:a===tn?q:void 0,children:[a===tn?"\u276F ":" ",c.usage.padEnd(22)," ",E(A,{color:a===tn?q:"gray",children:c.name==="model"&&hr?`${c.desc} (currently ${hr})`:c.desc})]},c.name)),E(A,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!T&&rt.length>0?Y(oe,{flexDirection:"column",paddingX:1,children:[Es?E(A,{color:q,children:Es}):null,rt.map((c,a)=>{let s=bt(c),h=s.slice(0,Math.max(20,Ne-5)),u=Ne-h.length-7,y=u>=12?(Hc(c)??Nc(s)).slice(0,u):"";return Y(A,{children:[E(A,{color:q,children:a+1})," ",h,y?E(A,{dimColor:!0,children:` \u2014 ${y}`}):null]},s)}),E(A,{dimColor:!0,children:`press 1-${rt.length} to fill \xB7 esc cancel`})]}):E(oe,{paddingX:1,children:Y(A,{color:"gray",children:[Hs.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${hr??"model n/a"}${t.kind==="api"?Ls>0?` \xB7 ${we(Ls)}`:"":Os>0?` \xB7 ${Ze(Os)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as aw}from"react/jsx-runtime";async function vd(e=process.cwd(),t="auto",n,o="0.0.0"){let r=sw(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:i}=iw(aw(bd,{cwd:e,auth:r,profileName:n,version:o}));await i(),process.stdout.write(`
358
- `),process.exit(0)}W();import{writeCrashLog as $d,isBenignTransportError as lw}from"document360-engine";var xd=!1;function Cs(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Cd(e){if(xd)return;xd=!0;let t=(n,o)=>{if(lw(o)){$d({kind:n,level:"transport",message:Cs(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=$d({kind:n,level:"fatal",message:Cs(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
352
+ `)});return}case"reorder":{let u=Ki(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ie(u.prompt,{display:u.display,quietUser:!0}),_t("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let u=zi(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=h.includes("--fix"),b=h.find(x=>!x.startsWith("--")),w=y?ud(e,b):[];if(await ie(u.prompt,{display:u.display,quietUser:!0}),y)try{bs(e,w,{reviewedCap:vs})}catch{}if(y)_t("\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let x=h.filter($=>$!=="--fix").join(" ");_t(`The review listed issues above. /review${x?` ${x}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${x?` ${x}`:""} --fix`,reason:""})}return}case"capture-setup":{let u=await Rn();u.kind==="forward-to-agent"&&u.prompt&&await ie(u.prompt,{display:u.display,quietUser:!0});let y=Ii(e);y&&d({kind:"note",tone:"info",text:y.join(`
353
+ `)});return}case"devhints":{if(!ne(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Gt(Vt(e)).join(`
354
+ `)}),Ot(gt()),ln.current=je(e).status==="current"||He(e);return}case"discover":{if(!ne(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ie(Xr(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!ne(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(_i(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 ie(Oi(),{display:"/inbox",quietUser:!0});return}case"feedback":{let u=dd(e),y="";try{y=Qt(u)?nr(u,"utf8"):""}catch{y=""}if(!/^## /m.test(y)){d({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let b=await ds(y.trim());d({kind:"note",tone:b?"ok":"warn",text:b?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${u} and copy it manually.`}),b&&yr(null);return}case"document":{if(!ne(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:y}=Ci(h);if(!y&&xi(e)===0){d({kind:"note",tone:"info",text:Pi});return}let b=`/document${y?` ${y}`:""}${u?" --publish":""}`;await ie(Ri(y,u),{display:b,quietUser:!0});return}case"catch-up":{if(!ne(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Bn(c.trim()))return;let{publish:u}=Mi(h);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let y=await Wi({cwd:e,profileName:i});for(let w of Fi(y))d({kind:"note",tone:w.startsWith("\u2713")?"ok":w.startsWith("\u2139")?"info":"warn",text:w});let b=Tn(Pn(e));d({kind:"note",tone:"info",text:b?`Catching up on ${b}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ie(Ui({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{gr.current=!0,d({kind:"note",tone:"info",text:`Updating ${kt}\u2026 (don\u2019t close this window)`}),On(!0),(await Oo().finally(()=>On(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),K("/exit"),Ds("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${_o}`});return}case"screenshot":{let u=Ai(h);if(u.mode==="list"){if(!ne(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Ni(Ei(e,u.scope),u.scope).join(`
355
+ `)});return}if(u.mode==="single"){let I=await No(h);I.kind==="forward-to-agent"&&I.prompt&&await ie(I.prompt,{display:I.display,quietUser:!0});return}if(!ne(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=u.mode==="scope"?u.scope:void 0,b=Lg(e,{scope:y}).map(I=>I.id);if(b.length===0){d({kind:"note",tone:"info",text:y?`No screenshot placeholders under ${y}.`:"No screenshot placeholders found in the docs."});return}let w=6,x=Og(b,3),$=rr(e,"standard");st.current=Date.now(),$t(0),D(!0);let V=new AbortController;Se.current=V,re({verb:"Authoring",unit:"spec",total:x.length,done:0,active:[],rows:An(x),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${b.length} screenshot spec${b.length===1?"":"s"} across ${x.length} partition${x.length===1?"":"s"} (\u2264${w} agents at once) on ${$.model}${$.forced?" (forced)":""}\u2026 (esc to stop)`});let H=!1;try{for await(let I of or({cwd:e,partitions:x,promptFor:Bl,concurrency:w,profileName:i,allowProdWrites:Pt.current,model:$.model,signal:V.signal}))if(I.type==="partition_status")I.status==="running"?re(R=>R&&{...R,active:[...R.active,I.label],rows:Be(R.rows,I.label,"active"),lastAt:Date.now()}):re(R=>R&&{...R,active:R.active.filter(S=>S!==I.label),done:R.done+1,rows:Be(R.rows,I.label,I.status==="done"?"done":"failed"),lastAt:Date.now()});else if(I.type==="partition_event")re(R=>{if(!R)return R;let S={...R,lastAt:Date.now()};return I.event.type==="tool"?S.tools=R.tools+1:I.event.type==="text"&&(S.chars=R.chars+I.event.delta.length),S});else if(I.type==="run_done"){It(Z=>Z+I.totalCostUsd),Nt(Z=>Z+I.results.reduce((Wt,Ft)=>Wt+Ft.outputTokens,0));let R=I.results.filter(Z=>Z.ok).length,S=I.aborted?"Stopped. ":"";H=!I.aborted&&u.setup;let U=I.aborted?"":H?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:I.aborted?"warn":I.ok?"ok":"warn",text:`${S}Authored specs \u2014 ${R}/${I.results.length} batches ok.${U}`})}}catch(I){d({kind:"note",tone:"error",text:`Spec authoring failed: ${I.message}`})}finally{Se.current=null,re(null),D(!1),X(I=>I+1)}if(H){let I=await Rn();I.kind==="forward-to-agent"&&I.prompt&&await ie(I.prompt,{display:I.display,quietUser:!0});let R=Ii(e);R&&d({kind:"note",tone:"info",text:R.join(`
356
+ `)})}return}case"reset":{let u=Bi(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Un.current={repoName:En(e),targets:u,hadDevhints:Qt(cd(e))},d({kind:"note",tone:"warn",text:Gi(e,u).join(`
357
+ `)}),me(En(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${s} \u2014 type /help.`})}},[e,r,i,Mt,Rr,d,$e,ie,Lt,vr,Vs]),Jn=G(c=>{let a=(c??T).trim();if(v(""),Ln(null),xt(0),a.startsWith("/")&&(Nn.current=!1,Ye(),nn(null),it(h=>Bc(h,a))),!a||(Ss(!1),Ys(a))||Gs(a))return;dr.current.push(a);let s=zc(a,js.current);if(a.startsWith("/"))d({kind:"user",text:a}),pn(s);else if(Yg(s)){d({kind:"user",text:a});let h=zg(s);if(!h)ie(s,{display:a,quietUser:!0});else{try{Kg(e,{title:h,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ie(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${h}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${h}" and the article path(s) you wrote.`,{display:a,quietUser:!0})}}else ie(s,{display:a})},[T,Ys,Gs,pn,ie]),zs=G(c=>{if(c.length>1){if(c.includes("\x1B"))return;let a=Vc(c);if(Gc(a)){let s=Yc(++Ad.current,a);js.current.set(s,a),_(s)}else _(a);return}_(c)},[_]),Ut=Math.max(10,Ie-6),Ks=ms(()=>er(k.text,Ut),[k.text,Ut]),Pr=G(c=>g(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+c))})),[]),Zn=G(c=>g(a=>({...a,pos:Xc(er(a.text,Ut),a.pos,c)})),[Ut]),fn=G(c=>g(a=>({...a,pos:Qc(er(a.text,Ut),a.pos,c)})),[Ut]),_d=["\x1B[H","\x1B[1~","\x1BOH"],Od=["\x1B[F","\x1B[4~","\x1BOF"],Xs=G((c,a)=>a.leftArrow?(Pr(-1),!0):a.rightArrow?(Pr(1),!0):c&&_d.includes(c)?(fn("start"),!0):c&&Od.includes(c)?(fn("end"),!0):a.ctrl&&c==="a"?(fn("start"),!0):a.ctrl&&c==="e"?(fn("end"),!0):!1,[Pr,fn]);return lg((c,a)=>{if(a.ctrl&&c==="c"){Te.current?.close(),r();return}if(!M){if(N){if(a.escape){if(Se.current){if(!Se.current.signal.aborted){let s=(Wn?.verb??"work").toLowerCase(),h=Wn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${s} run (finishing in-flight ${h}s)\u2026`}),Se.current.abort()}return}on.current||(on.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Te.current?.interrupt());return}if(a.return){let s=T.trim();if(!s)return;ft.current.push(s),pr([...ft.current]),v("");return}if(Xs(c,a))return;if(a.upArrow){Zn(-1);return}if(a.downArrow){Zn(1);return}if(a.backspace||a.delete){P();return}c&&!a.ctrl&&!a.meta&&zs(c);return}if(lt){if(a.upArrow){ct(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){ct(s=>s&&{...s,cursor:Math.min(Oe.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Oe.length){ct(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=Oe[lt.cursor];ct(null);let{lines:h,changed:u,effective:y}=xn(e,s.value??"default");for(let b of h)d({kind:"note",tone:b.startsWith("\u26A0")?"warn":b.startsWith("\u2713")?"ok":"info",text:b});u&&(Ms(b=>b+1),Te.current?.setModel(y));return}if(c==="s"){let s=Oe[lt.cursor];ct(null),Te.current?.setModel(s.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${s.label} for this session only (your saved default is unchanged).`});return}if(a.escape){ct(null);return}return}if(Me){if(a.upArrow){St(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){St(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Me.rows.length){St(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return||c==="s"){let s=Me.rows[Me.cursor];St(null),xr(s.name,a.return===!0);return}if(a.escape){St(null);return}return}if(qn){if(a.escape){sn(null);return}if(a.leftArrow||a.tab&&a.shift){sn(s=>s&&{tab:(s.tab-1+De.length)%De.length});return}if(a.rightArrow||a.tab){sn(s=>s&&{tab:(s.tab+1)%De.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=De.length){sn({tab:Number(c)-1});return}return}if(Ue){if(a.upArrow){Dt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Dt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ue.rows.length){Dt(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=Ue.rows[Ue.cursor].name;if(Dt(null),!_r(e,s).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 "${s}").`});let u=!1;try{let y=vt(s);u=!!y&&!(nt(y)&&!y.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${s} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${s}) and pick your project.`}),K("/login"),X(y=>y+1);return}if(a.escape){Dt(null);return}return}if(fe){if(a.upArrow){jt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){jt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=fe.rows.length){jt(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=fe.rows[fe.cursor],{profile:h,projectId:u}=fe;jt(null),Kn(h,u,s);return}if(a.escape){jt(null);return}return}if(ke){if(a.upArrow){dt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){dt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ke.rows.length){dt(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=ke.rows[ke.cursor],{profile:h}=ke;dt(null),Qn(h,s);return}if(a.escape){dt(null);return}return}if(he){if(a.upArrow){Et(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Et(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c===" "){Et(s=>s&&{...s,rows:s.rows.map((h,u)=>u===s.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let s=he.rows.filter(h=>h.checked).map(h=>h.path);if(Et(null),s.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Qr(e,s),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${s.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of s)d({kind:"note",tone:"info",text:` ${h}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){Et(null);return}return}if(We){if(a.upArrow){ut(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){ut(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=We.rows.length){ut(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=We.rows[We.cursor],h=We.run;ut(null),h(s.token);return}if(a.escape){ut(null);return}return}if(Ve){if(a.upArrow){At(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){At(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ve.rows.length){At(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=Ve.rows[Ve.cursor];At(null),s.conflict?Rr(s.paths[0]):s.kind==="article"?vr(s.paths[0]):Lt(s.paths);return}if(a.escape){At(null);return}return}if(be){if(a.escape){pt(null);return}if(a.upArrow){pt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){pt(s=>s&&{...s,cursor:Math.min(Math.max(0,Yn.length-1),s.cursor+1)});return}if(a.return){let s=Yn[be.cursor];if(s){pt(null);try{d({kind:"preview",name:En(s),text:yd(nr(gs(e,s),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${s}: ${h.message}`})}}return}if(a.backspace||a.delete){pt(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){pt(s=>s&&{...s,query:s.query+c,cursor:0});return}return}if(ve){if(a.escape){ht(null);return}if(a.upArrow){ht(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){ht(s=>s&&{...s,cursor:Math.min(Math.max(0,zn.length-1),s.cursor+1)});return}if(a.return){let s=zn[ve.cursor];if(s){ht(null),$e(s.uuid),Le.current={uuid:s.uuid,firstPrompt:s.firstPrompt,titleFired:!0},at(s.name),ws(s.uuid),Rt.current=[];let h=ps(e,s.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${s.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${s.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){ht(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){ht(s=>s&&{...s,query:s.query+c,cursor:0});return}return}if(a.tab&&!T&&te){v(te),Ye();return}if(!T&&rt.length>0&&!lr&&c&&/^[1-9]$/.test(c)){let s=rt[Number(c)-1];if(s){v(bt(s));return}}if(!T&&(Vn||an)&&c==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let s=Vn!=null;ds(Vn??an).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?s?"\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.":s?"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&&s&&yr(null),u&&!s&&Fs(!0)});return}if(!Xs(c,a)){if(qs){if(a.upArrow){xt(s=>Math.max(0,s-1));return}if(a.downArrow){xt(s=>Math.min(un.length-1,s+1));return}if(a.tab){v("/"+(un[tn]?.name??"")+" "),xt(0);return}if(a.return){let s=un[tn];if(s){let h=T.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Oc(s.usage)&&!h){v("/"+s.name+" "),xt(0);return}Jn("/"+s.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(T!==""&&Ct===null){Zn(-1);return}let s=dr.current;if(!s.length)return;let h=Ct===null?s.length-1:Math.max(0,Ct-1);Ln(h),v(s[h]??"");return}if(a.downArrow){if(T!==""&&Ct===null){Zn(1);return}let s=dr.current;if(Ct===null)return;let h=Ct+1;h>=s.length?(Ln(null),v("")):(Ln(h),v(s[h]??""));return}}if(a.return){Jn();return}if(a.backspace||a.delete){P();return}if(a.escape){v(""),xt(0),Ye(),it([]),nn(null),Nn.current=!0;return}c&&!a.ctrl&&!a.meta&&zs(c)}}}),Re(()=>{if(N||M)return;let c=ft.current.shift();c!==void 0&&(pr([...ft.current]),Jn(c))},[N,M,Jn]),Y(oe,{flexDirection:"column",width:Ie,children:[br!==null&&Y(oe,{marginTop:1,flexDirection:"column",children:[br.truncated&&E(A,{dimColor:!0,children:"\u2026"}),E(A,{children:br.text})]}),N&&(Wn?E(iw,{p:Wn}):E(nw,{startTime:st.current,chars:jd})),!N&&Is?E(ow,{text:Is}):null,E(oe,{borderStyle:"round",borderColor:Hs.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:T?Ks.map((c,a)=>{let s=k.text.slice(c.start,c.end),h=a===tr(Ks,k.pos),u=Math.min(k.pos,c.end)-c.start;return Y(A,{children:[E(A,{color:q,children:a===0?"> ":" "}),h?Y(ir,{children:[s.slice(0,u),E(Jt,{ch:s[u]??" "}),s.slice(u+1)]}):s||" "]},`${a}-${c.start}`)}):Y(A,{children:[E(A,{color:q,children:"> "}),fr?E(Jt,{ch:" "}):te&&!N&&ot?Y(ir,{children:[E(Jt,{ch:ot[0],dim:!0}),E(A,{color:"gray",children:ot.slice(1)})]}):te&&!N?Y(ir,{children:[E(Jt,{ch:te[0],dim:!0}),E(A,{color:"gray",children:te.slice(1)}),E(A,{dimColor:!0,children:" (tab)"})]}):(kr.isSetup||!Sd)&&!N?Y(ir,{children:[E(Jt,{ch:kr.text[0],dim:!0}),E(A,{color:"gray",children:kr.text.slice(1)})]}):E(Jt,{ch:" "})]})}),Ns.length>0&&E(oe,{flexDirection:"column",paddingX:1,children:Ns.map((c,a)=>E(A,{color:"gray",children:`\u29D7 queued: ${c}`},`${a}-${c.slice(0,24)}`))}),qn?E(Mc,{tab:qn.tab,width:Ie,version:o,engineVersion:kd}):lt?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Select model"}),E(A,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Oe.map((c,a)=>Y(A,{color:a===lt.cursor?q:void 0,children:[a===lt.cursor?"\u276F ":" ",`${a+1}. ${c.label}${a===lt.current?" \u2714":""}`.padEnd(16),E(A,{color:"gray",children:c.desc})]},c.label)),E(A,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Me?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Switch connection profile"}),Me.rows.map((c,a)=>Y(A,{color:a===Me.cursor?q:void 0,children:[a===Me.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===Me.current?" \u2714":""}`.padEnd(20),E(A,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?E(A,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),E(A,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ue?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Pick your Document360 environment"}),Ue.rows.map((c,a)=>Y(A,{color:a===Ue.cursor?q:void 0,children:[a===Ue.cursor?"\u276F ":" ",`${a+1}. ${c.name}`.padEnd(16),E(A,{color:"gray",children:c.apiUrl})]},c.name)),E(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Switch workspace"}),E(A,{dimColor:!0,children:`environment ${fe.environment} \xB7 project ${fe.projectName??`${fe.projectId.slice(0,8)}\u2026`}`}),fe.rows.map((c,a)=>Y(A,{color:a===fe.cursor?q:void 0,children:[a===fe.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===fe.current?" \u2714":""}`.padEnd(30),E(A,{color:"gray",children:c.type??""})]},c.id)),E(A,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ke?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Choose project"}),E(A,{dimColor:!0,children:`environment ${ke.environment}`}),ke.rows.map((c,a)=>Y(A,{color:a===ke.cursor?q:void 0,children:[a===ke.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===ke.current?" \u2714":""}`.padEnd(30),E(A,{color:"gray",children:c.sub??""})]},c.id)),E(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):he?(()=>{let a=Math.min(Math.max(0,he.cursor-Math.floor(7)),Math.max(0,he.rows.length-14)),s=he.rows.slice(a,a+14),h=he.rows.filter(u=>u.checked).length;return Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:`Which folders back the user docs? (${h} selected of ${he.rows.length})`}),a>0?E(A,{dimColor:!0,children:` \u2191 ${a} more`}):null,s.map((u,y)=>{let b=a+y;return Y(A,{color:b===he.cursor?q:void 0,children:[b===he.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Ie-34)),E(A,{color:"gray",children:Po(u)})]},u.path)}),a+14<he.rows.length?E(A,{dimColor:!0,children:` \u2193 ${he.rows.length-a-14} more`}):null,E(A,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():We?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Which category? (pick one to scope to)"}),We.rows.map((c,a)=>{let s=a===We.cursor,h=`${a+1}.`.padEnd(3);return Y(A,{color:s?q:void 0,children:[s?"\u276F ":" ",`${h} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Ie-24))),E(A,{color:"gray",children:` ${c.token}`})]},c.token)}),E(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Ve?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Ve.rows.map((c,a)=>{let s=a===Ve.cursor,h=c.indent?" ":" ",u=`${a+1}.`.padEnd(3);return Y(A,{color:s?q:void 0,bold:c.kind==="category"&&!s,children:[s?"\u276F ":" ",`${h}${u} ${c.label}`.padEnd(Math.min(56,Ie-24)),c.note?E(A,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),E(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):be?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:`Preview article${be.query?` \u2014 filter: ${be.query}`:" (type to filter)"}`}),Yn.length===0?E(A,{color:"gray",children:"no articles match"}):Yn.map((c,a)=>Y(A,{color:a===be.cursor?q:void 0,children:[a===be.cursor?"\u276F ":" ",c]},c)),E(A,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):ve?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:`Resume session${ve.query?` \u2014 filter: ${ve.query}`:" (type to filter)"}`}),zn.length===0?E(A,{color:"gray",children:"no sessions match"}):zn.map((c,a)=>Y(A,{color:a===ve.cursor?q:void 0,children:[a===ve.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),E(A,{color:a===ve.cursor?q:"gray",children:c.firstPrompt.slice(0,Math.max(10,Ie-40))})]},c.uuid)),E(A,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):qs?Y(oe,{flexDirection:"column",children:[un.map((c,a)=>Y(A,{color:a===tn?q:void 0,children:[a===tn?"\u276F ":" ",c.usage.padEnd(22)," ",E(A,{color:a===tn?q:"gray",children:c.name==="model"&&hr?`${c.desc} (currently ${hr})`:c.desc})]},c.name)),E(A,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!T&&rt.length>0?Y(oe,{flexDirection:"column",paddingX:1,children:[Es?E(A,{color:q,children:Es}):null,rt.map((c,a)=>{let s=bt(c),h=s.slice(0,Math.max(20,Ie-5)),u=Ie-h.length-7,y=u>=12?(qc(c)??Ic(s)).slice(0,u):"";return Y(A,{children:[E(A,{color:q,children:a+1})," ",h,y?E(A,{dimColor:!0,children:` \u2014 ${y}`}):null]},s)}),E(A,{dimColor:!0,children:`press 1-${rt.length} to fill \xB7 esc cancel`})]}):E(oe,{paddingX:1,children:Y(A,{color:"gray",children:[Hs.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${hr??"model n/a"}${t.kind==="api"?Ls>0?` \xB7 ${we(Ls)}`:"":Os>0?` \xB7 ${Ze(Os)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as cw}from"react/jsx-runtime";async function $d(e=process.cwd(),t="auto",n,o="0.0.0"){let r=lw(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:i}=aw(cw(vd,{cwd:e,auth:r,profileName:n,version:o}));await i(),process.stdout.write(`
358
+ `),process.exit(0)}W();import{writeCrashLog as xd,isBenignTransportError as dw}from"document360-engine";var Cd=!1;function Cs(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Rd(e){if(Cd)return;Cd=!0;let t=(n,o)=>{if(dw(o)){xd({kind:n,level:"transport",message:Cs(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=xd({kind:n,level:"fatal",message:Cs(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
359
359
  `+C(`\u2717 d360-writer crashed: ${Cs(o)}`)+`
360
360
  `),r&&process.stderr.write(f(` Crash details: ${r}`)+`
361
361
  `+f(" Run: d360-writer logs")+`
362
- `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var pw=dw(import.meta.url),sr=pw("../package.json");Cd("d360-writer");var Ae=new cw;function Rs(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Ae.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=>{Rs(e),await ao({profile:e.profile,manual:e.manual})});Ae.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Rs(e),await la({profile:e.profile})});Ae.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Rs(e),await aa({profile:e.profile})});var Ps=Ae.command("profile").description("Manage connection profiles for the current repo");Ps.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>lo(process.cwd()));Ps.command("use <name>").description("Set the default profile for this repo").action(e=>co(process.cwd(),e));Ps.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>uo(process.cwd(),e));var Rd=Ae.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Rd.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Ht(process.cwd(),e.profile));Rd.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await ea(process.cwd(),e,t.profile)});var Pd=Ae.command("project").description("Choose the Document360 project for this repo (active profile's identity)");Pd.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>ro(process.cwd(),e.profile));Pd.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await na(process.cwd(),e,t.profile)});Ae.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(yo(),_a));await e()});Ae.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>pa());Ae.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(()=>(Eo(),Ol)),n=await t(process.cwd(),sr.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Ae.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(sr.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(uw.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 fa(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 Rc(e.cwd,e.auth,e.profile,sr.version):await vd(e.cwd,e.auth,e.profile,sr.version)});Ae.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
362
+ `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var hw=pw(import.meta.url),sr=hw("../package.json");Rd("d360-writer");var Ee=new uw;function Rs(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Ee.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=>{Rs(e),await ao({profile:e.profile,manual:e.manual})});Ee.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Rs(e),await la({profile:e.profile})});Ee.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Rs(e),await aa({profile:e.profile})});var Ps=Ee.command("profile").description("Manage connection profiles for the current repo");Ps.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>lo(process.cwd()));Ps.command("use <name>").description("Set the default profile for this repo").action(e=>co(process.cwd(),e));Ps.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>uo(process.cwd(),e));var Pd=Ee.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Pd.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Ht(process.cwd(),e.profile));Pd.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await ea(process.cwd(),e,t.profile)});var Td=Ee.command("project").description("Choose the Document360 project for this repo (active profile's identity)");Td.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>ro(process.cwd(),e.profile));Td.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await na(process.cwd(),e,t.profile)});Ee.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(yo(),_a));await e()});Ee.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>pa());Ee.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(()=>(Eo(),Ol)),n=await t(process.cwd(),sr.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Ee.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(sr.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(fw.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 fa(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 Pc(e.cwd,e.auth,e.profile,sr.version):await $d(e.cwd,e.auth,e.profile,sr.version)});Ee.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});