document360-writer 0.5.85 → 0.5.87

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 (78) hide show
  1. package/dist/cli.js +108 -108
  2. package/package.json +3 -3
  3. package/dist/cli.d.ts +0 -2
  4. package/dist/commands/allowProd.d.ts +0 -3
  5. package/dist/commands/audit.d.ts +0 -2
  6. package/dist/commands/capture-setup.d.ts +0 -12
  7. package/dist/commands/catchup.d.ts +0 -63
  8. package/dist/commands/clear.d.ts +0 -3
  9. package/dist/commands/convert.d.ts +0 -35
  10. package/dist/commands/devhints.d.ts +0 -125
  11. package/dist/commands/doctor.d.ts +0 -13
  12. package/dist/commands/document.d.ts +0 -19
  13. package/dist/commands/draft.d.ts +0 -27
  14. package/dist/commands/exit.d.ts +0 -2
  15. package/dist/commands/genre.d.ts +0 -3
  16. package/dist/commands/help.d.ts +0 -2
  17. package/dist/commands/inbox.d.ts +0 -11
  18. package/dist/commands/index.d.ts +0 -28
  19. package/dist/commands/init.d.ts +0 -9
  20. package/dist/commands/lint.d.ts +0 -8
  21. package/dist/commands/login.d.ts +0 -4
  22. package/dist/commands/logout.d.ts +0 -5
  23. package/dist/commands/logsCli.d.ts +0 -2
  24. package/dist/commands/mcp.d.ts +0 -2
  25. package/dist/commands/model.d.ts +0 -17
  26. package/dist/commands/profile.d.ts +0 -6
  27. package/dist/commands/project.d.ts +0 -3
  28. package/dist/commands/publish.d.ts +0 -57
  29. package/dist/commands/pull.d.ts +0 -45
  30. package/dist/commands/rename.d.ts +0 -5
  31. package/dist/commands/reorder.d.ts +0 -8
  32. package/dist/commands/reset.d.ts +0 -31
  33. package/dist/commands/resume.d.ts +0 -3
  34. package/dist/commands/review.d.ts +0 -9
  35. package/dist/commands/roadmap.d.ts +0 -10
  36. package/dist/commands/scope.d.ts +0 -9
  37. package/dist/commands/screenshot.d.ts +0 -44
  38. package/dist/commands/structure.d.ts +0 -6
  39. package/dist/commands/update.d.ts +0 -18
  40. package/dist/commands/workspace.d.ts +0 -3
  41. package/dist/commands/write.d.ts +0 -73
  42. package/dist/d360/authCli.d.ts +0 -13
  43. package/dist/d360/portalLink.d.ts +0 -18
  44. package/dist/d360/profileCli.d.ts +0 -3
  45. package/dist/d360/projectCli.d.ts +0 -17
  46. package/dist/d360/workspaceCli.d.ts +0 -17
  47. package/dist/lib/authPreflight.d.ts +0 -14
  48. package/dist/lib/categoryChoices.d.ts +0 -23
  49. package/dist/lib/checklist.d.ts +0 -30
  50. package/dist/lib/clipboard.d.ts +0 -1
  51. package/dist/lib/colors.d.ts +0 -10
  52. package/dist/lib/commandSuggest.d.ts +0 -7
  53. package/dist/lib/crashHandler.d.ts +0 -2
  54. package/dist/lib/diffRender.d.ts +0 -8
  55. package/dist/lib/hyperlink.d.ts +0 -5
  56. package/dist/lib/inputLayout.d.ts +0 -19
  57. package/dist/lib/mascot.d.ts +0 -5
  58. package/dist/lib/mdRender.d.ts +0 -7
  59. package/dist/lib/modelChoices.d.ts +0 -14
  60. package/dist/lib/nextActions.d.ts +0 -104
  61. package/dist/lib/paste.d.ts +0 -19
  62. package/dist/lib/pickOptions.d.ts +0 -18
  63. package/dist/lib/quickOptions.d.ts +0 -24
  64. package/dist/lib/readyState.d.ts +0 -19
  65. package/dist/lib/streaming.d.ts +0 -23
  66. package/dist/lib/syncRender.d.ts +0 -10
  67. package/dist/lib/toolFormat.d.ts +0 -30
  68. package/dist/lib/upgradeTable.d.ts +0 -5
  69. package/dist/oneShot.d.ts +0 -7
  70. package/dist/repl.d.ts +0 -18
  71. package/dist/tui/App.d.ts +0 -9
  72. package/dist/tui/HelpModal.d.ts +0 -7
  73. package/dist/tui/catalog.d.ts +0 -17
  74. package/dist/tui/helpContent.d.ts +0 -35
  75. package/dist/tui/index.d.ts +0 -3
  76. package/dist/tui/itemRender.d.ts +0 -79
  77. package/dist/tui/termTitle.d.ts +0 -28
  78. package/dist/tui/transcriptStore.d.ts +0 -5
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var ku=Object.defineProperty;var zn=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Ms=(e,t)=>{for(var n in t)ku(e,n,{get:t[n],enumerable:!0})};import Ye from"picocolors";var F,bu,xu,$u,Us,on,f,$,O,N,_,ae,Pe,U=zn(()=>{"use strict";F="#7f56d9",[bu,xu,$u]=[127,86,217],Us=e=>Ye.isColorSupported?`\x1B[38;2;${bu};${xu};${$u}m${e}\x1B[39m`:e,on=e=>Ye.bold(Us(e)),f=e=>Ye.dim(e),$=e=>Ye.red(e),O=e=>Ye.yellow(e),N=e=>Ye.green(e),_=Us,ae=e=>Ye.gray(e),Pe=e=>Ye.bold(e)});import{existsSync as Ot,writeFileSync as ut,readFileSync as sd,readdirSync as ad}from"node:fs";import{join as ld}from"node:path";import{devHintsGuidePath as io,hintsDir as oa,architectureDir as la,messagesDir as xr,creatorNotesPath as ra,devhintsStatePath as ca,directivesPath as ia,DIRECTIVES_HEADER as cd,roadmapPath as sa,ROADMAP_HEADER as ud,ensureDir as ro,writeMessage as dd,listOpenForDev as pd}from"document360-engine";function ua(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var $u=Object.defineProperty;var Qn=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Ws=(e,t)=>{for(var n in t)$u(e,n,{get:t[n],enumerable:!0})};import Ye from"picocolors";var F,xu,vu,Cu,Fs,ln,f,x,L,N,_,le,Pe,U=Qn(()=>{"use strict";F="#7f56d9",[xu,vu,Cu]=[127,86,217],Fs=e=>Ye.isColorSupported?`\x1B[38;2;${xu};${vu};${Cu}m${e}\x1B[39m`:e,ln=e=>Ye.bold(Fs(e)),f=e=>Ye.dim(e),x=e=>Ye.red(e),L=e=>Ye.yellow(e),N=e=>Ye.green(e),_=Fs,le=e=>Ye.gray(e),Pe=e=>Ye.bold(e)});import{existsSync as Mt,writeFileSync as pt,readFileSync as ld,readdirSync as cd}from"node:fs";import{join as ud}from"node:path";import{devHintsGuidePath as lo,hintsDir as ia,architectureDir as ua,messagesDir as Cr,creatorNotesPath as sa,devhintsStatePath as da,directivesPath as aa,DIRECTIVES_HEADER as dd,roadmapPath as la,ROADMAP_HEADER as pd,ensureDir as ao,writeMessage as fd,listOpenForDev as md}from"document360-engine";function pa(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
3
3
 
4
4
  <!-- devhints script v${se} \xB7 maintained by document360-writer (/devhints). -->
5
5
 
@@ -193,7 +193,7 @@ do it**:
193
193
  **Do NOT write or action the documentation yourself** \u2014 same boundary as Part 2. Writing the article is the
194
194
  docs agent's job; it actions open directives on its next \`/catch-up\` (as drafts) and flips each to \`[done]\`
195
195
  with the article it wrote. You are only the relay so the ask is captured durably and travels via git.
196
- `}function fd(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
196
+ `}function hd(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
197
197
 
198
198
  <!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
199
199
  The builder agent reads this FIRST and treats it as authoritative when writing the architecture
@@ -207,60 +207,60 @@ Anything only a human knows that would help document this product. For example:
207
207
  - Gotchas or non-obvious behavior.
208
208
 
209
209
  (Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
210
- `}function Mt(e){ro(oa(e)),ro(la(e)),ro(xr(e));for(let n of[oa(e),xr(e)]){let o=ld(n,".gitkeep");Ot(o)||ut(o,`# Keeps this document360-writer inbox tracked in git even when empty.
211
- `)}Ot(ra(e))||ut(ra(e),fd()),Ot(ia(e))||ut(ia(e),cd),Ot(sa(e))||ut(sa(e),ud),ut(io(e),ua());let t=Se(e);return pa(e,new Date().toISOString()),t}async function da(e,t){for(let n of Ut(Mt(t.cwd)))console.log(n);return{kind:"continue"}}function dt(){return[`This is document360-writer's dev hand-off setup (v${se}).`,'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; 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 \u2014 fold durable facts into the architecture brief and/or drop"," a reply (`from: dev`, `kind: answer`, `re: <id>`) \u2014 then set the question's frontmatter `status: done`."," If there are none, continue.","5. Then STOP and ask me for tribal knowledge \u2014 present it as a clearly-marked, standalone prompt on its"," own line (NOT buried in prose) and WAIT for my reply before doing anything else. Use this shape:",' "\u23F8 YOUR INPUT NEEDED \u2014 Any tribal knowledge that would help document this product? (folder map,',` terminology, what to prioritize or skip, gotchas.) Type it below, or reply 'none' / 'carry on' to skip."`," If I give you anything, phrase it clearly and append it to `.d360-writer/architecture/CREATOR-NOTES.md`"," (keep the existing header comment and every note already there; only add). If I say 'none'/'carry on', continue.",`6. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${se},`,' "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(`
212
- `)}function $r(e){try{let t=sd(ca(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function pa(e,t){let o={...$r(e)??{},emittedVersion:se,emittedAt:t};ut(ca(e),`${JSON.stringify(o,null,2)}
213
- `)}function We(e){try{return ad(la(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Se(e){let n=$r(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<se?"stale":"current",completedVersion:n}}function so(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:se};try{if(!Ot(io(e)))return n;let o=$r(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let i=o?.completedVersion??0;se>r&&(ro(xr(e)),ut(io(e),ua()),pa(e,t),n.guideRefreshed=!0),se>i&&(pd(e).some(p=>p.kind==="request"&&p.subject.startsWith(aa))||(dd(e,{id:`onb${se}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${aa}${se})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${se}${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:","",dt()].join(`
214
- `)}),n.notifiedBuilder=!0))}catch{}return n}function ao(e){if(!Ot(io(e)))return[];let t=Se(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${se}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Lt,dt(),Lt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function vr(){return['document360-writer (its "docs agent") has been removed from this repository. Please undo its dev\u2192docs',"hand-off setup and restore this repo to how it was before \u2014 in order:","","1. In this repo's agent-memory file (CLAUDE.md, or AGENTS.md \u2014 whichever it edited), REMOVE the",' "Documentation hand-off" section that was added (the rule about dropping hint files in'," `.d360-writer/hints/`, keeping `.d360-writer/architecture/` current, checking"," `.d360-writer/messages/`, and relaying `@d360-writer` directives to `.d360-writer/directives.md`)."," Leave everything else in that file untouched.","2. The `.d360-writer/` folder is already deleted on disk. If it was committed, remove it from version"," control too \u2014 `git rm -r --cached .d360-writer` (if it still resolves) \u2014 and commit the deletions.","3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
215
- `)}function lo(){return['\u{1F9F9} One leftover: your builder still has the "Documentation hand-off" rule in its CLAUDE.md / AGENTS.md'," (reset only clears d360-writer's own .d360-writer/ folder \u2014 never your repo's files)."," To restore it, paste this prompt into your repo's coding agent (Claude Code / Codex / Cursor):",Lt,vr(),Lt]}function Ut(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${se}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",Lt,dt(),Lt,"","That one run writes the architecture brief, adds the ongoing rule to your agent memory (CLAUDE.md / AGENTS.md)","and commits it so teammates inherit it, answers any open questions the writer left, and asks you for tribal","knowledge \u2014 no manual file edits. It also sets up the two-way channel: the writer can ask you questions","(`/inbox` on its side), and you can ask it to document a session on demand (Part 4 of the guide).","","When it finishes, come back to THIS terminal and run:"," write the docs for this repo"]}var Lt,se,aa,Ke=zn(()=>{"use strict";Lt="-".repeat(64),se=7;aa="Re-run dev\u2194docs onboarding (protocol v"});var $a={};Ms($a,{initCommand:()=>Rr,scaffoldInit:()=>Cr});import{input as an,confirm as md}from"@inquirer/prompts";import{basename as fa,join as co}from"node:path";import{existsSync as Wt,readFileSync as hd,readdirSync as gd,writeFileSync as yd}from"node:fs";import{writeProjectConfig as ma,readProjectConfig as wd,projectConfigPath as ha,writerDir as kd,DEFAULT_DOCS_DIR as ga,DEFAULT_CAPTURE_DIR as ya,DEFAULT_OUTPUT_DIR as wa}from"document360-engine";function Cr(e,t="berlin"){let n=ha(e);if(Wt(n))return{created:!1,path:n,profileName:""};let o={projectId:ba(e)??fa(e),docsDir:ga,captureDir:ya,outputDir:wa,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:xa(e)};return ma(o,e),ka(e),{created:!0,path:n,profileName:t}}function ka(e){let t=co(kd(e),".gitignore");Wt(t)||yd(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
216
- `),"utf8")}async function Rr(){let e=process.cwd(),t=ha(e);if(Wt(t)&&!await md({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=ba(e)??fa(e),o=await an({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await an({message:"Capture directory (where document360-capture .spec.ts files live):",default:ya}),i=await an({message:"Screenshot output directory:",default:wa}),c=await an({message:"Default connection profile name:",default:"berlin"}),p=await an({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:ga,captureDir:r,outputDir:i,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:xa(e)},w=wd(e);w?.terminologyGlossary&&(g.terminologyGlossary=w.terminologyGlossary),ma(g,e),ka(e);let k=Mt(e);console.log(""),console.log(N(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of Ut(k))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function ba(e){let t=co(e,"package.json");if(!Wt(t))return null;try{return JSON.parse(hd(t,"utf8")).name??null}catch{return null}}function xa(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Wt(co(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=co(e,n);Wt(o)&&!bd(o)&&t.push(n)}return t}function bd(e){try{return gd(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var uo=zn(()=>{"use strict";U();Ke()});var bl={};Ms(bl,{doctorCommand:()=>mn,renderDoctorChecks:()=>kl,runDoctorChecks:()=>wl});import{existsSync as sf}from"node:fs";import{d360GetAll as af,getAccessToken as lf,isExpired as wi,loadProfileMap as cf,loadTokens as uf,packageSkillsDir as gl,projectConfigPath as df,readProjectConfig as pf,DEFAULT_DOCS_DIR as ff,fetchManifestSummary as mf,resolveActiveProfile as hf,classifyClaudeAuth as gf,CLAUDE_CODE_SETUP_HINT as yl,resolveModelSetting as yf,probeModel as wf,detectAppType as kf,playbookSkillName as bf,D360AuthError as xf}from"document360-engine";async function wl(e){let t=[],n=Number(process.versions.node.split(".")[0]);t.push(n>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let o=gf();o.state==="ready"?t.push({level:"ok",label:`Claude auth: ${o.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):o.state==="maybe"?t.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${yl}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:yl});let r=yf(e);if(t.push({level:"ok",label:`Model: ${r.model} (${r.source==="auto"?"auto \u2014 right-sized for docs; /model to change":r.source})`}),o.state==="ready"){let P=await wf(e,r.model??void 0);P.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(P.latencyMs/1e3).toFixed(1)}s`}):P.timedOut?t.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):t.push({level:"fail",label:`Model call failed \u2014 ${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 i=pf(e);if(!i)return t.push({level:"fail",label:`No ${df(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${i.projectId}`});let c=(i.docsDir??ff).replace(/\/+$/,"");t.push(i.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=i.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let g=i.appType??kf(e);if(g){let P=i.appType?"from config":"auto-detected",R=g==="web"||g==="cli";t.push({level:"ok",label:`Genre: ${g} (${P})${R?` \u2192 ${bf(g)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else t.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let w;try{w=hf(e),t.push({level:"ok",label:`Profile: ${w.name} (${w.connection.name})${w.production?" \u26A0 PRODUCTION":""}`})}catch(P){return t.push({level:"fail",label:`Profile config: ${P.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=uf(w.name);k?wi(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):wi(k)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(k.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${w.name})`}),t.push(w.project.workspaceId?{level:"ok",label:`Workspace: ${w.project.workspaceName??w.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let D=cf(e,w.name);D?D.projectId&&w.project.projectId&&D.projectId!==w.project.projectId?t.push({level:"fail",label:`Category map projectId (${D.projectId}) \u2260 profile projectId (${w.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(D.articles).length} articles, ${Object.keys(D.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${w.name}" (created on first /publish)`}),t.push(sf(gl())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${gl()}`,fix:"Reinstall document360-writer (broken install)"});let x=Se(e);if(x.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${se})`}):x.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${x.completedVersion}, current is v${se}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!wi(k)||k.refreshToken)){let P={profile:w.name,connection:w.connection};try{await lf(P);let S=await af(P,"/v3/projects");t.push({level:"ok",label:`API reachable (${w.connection.apiUrl}) \u2014 ${S.length} project(s) visible`})}catch(S){t.push({level:"fail",label:`API call failed: ${S.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let R=D?.projectId??w.project.projectId;if(R&&w.project.workspaceId)try{let S=await mf(P,R,w.project.workspaceId);if(S){let I=(S.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${w.connection.name} (${S.languages?.length??0} language${(S.languages?.length??0)===1?"":"s"}) \xB7 hash ${I||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${w.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(S){S instanceof xf||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(S.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${w.project.projectName??R})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):t.push({level:"warn",label:`Workspace sync manifest: probe failed (${S.message.slice(0,80)})`})}}return t}function kl(e){let t=[""];for(let r of e){let i=r.level==="ok"?N("\u2713"):r.level==="warn"?O("\u26A0"):$("\u2717");t.push(` ${i} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${_(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?N(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function mn(e,t){console.log(f("Running checks\u2026"));for(let n of kl(await wl(t.cwd)))console.log(n);return{kind:"continue"}}var $o=zn(()=>{"use strict";Ke();U()});import{Command as Wg}from"commander";import{createRequire as Fg}from"node:module";import{AUTH_MODES as Hg}from"document360-engine";import{input as Ou}from"@inquirer/prompts";import{loginPkce as Lu,refreshTokens as Mu,toStoredTokens as Vs,clearTokens as Uu,decodeJwtClaims as Bs,isExpired as Wu,loadTokens as Fu,saveTokens as Gs,resolveActiveProfile as Jn,setProfileProject as Hu,readProjectConfig as qu}from"document360-engine";U();import{select as vu}from"@inquirer/prompts";import{resolveActiveProfile as Cu,setProfileProject as Ru,resolveProjectId as Pu,listWorkspaces as Tu}from"document360-engine";async function rn(e,t){let n=Cu(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Pu(o);return{workspaces:await Tu(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Ws=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function gr(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 Kn(e,t,n,o,r){Ru(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Fs(e,t,n){let o;try{o=await rn(e,n)}catch(i){return console.log($(`Could not list workspaces: ${i.message}`)),1}let r=gr(o.workspaces,t);return r?(Kn(e,o.profile,o.projectId,r.id,r.name),console.log(N(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${o.workspaces.map(i=>i.name??i.id).join(", ")}`)),1)}async function _t(e,t){let n;try{n=await rn(e,t)}catch(w){console.log($(`Could not list workspaces: ${w.message}`));return}let{workspaces:o,projectId:r,profile:i,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let w of o)console.log(` ${w.id===c?_("\u25CF"):" "} ${Ws(w)} ${f(w.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await vu({message:"Select the Document360 workspace for this repo:",choices:o.map(w=>({name:`${Ws(w)}${w.id===c?" (current)":""}`,value:w.id}))}),g=o.find(w=>w.id===p);Kn(e,i,r,p,g?.name),console.log(N(`\u2713 Workspace set to "${g?.name??p}" for profile "${i}".`))}U();import{select as Su}from"@inquirer/prompts";import{resolveActiveProfile as Du,setProfileProject as Au,listProjects as ju}from"document360-engine";async function ze(e,t){let n=Du(e,t),o={profile:n.name,connection:n.connection};return{projects:await ju(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Hs=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function yr(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function Xn(e,t,n,o){Au(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function qs(e,t,n){let o;try{o=await ze(e,n)}catch(i){return console.log($(`Could not list projects: ${i.message}`)),1}let r=yr(o.projects,t);return r?(Xn(e,o.profile,r.id,r.name),console.log(N(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log($(`No project matches "${t}". Available: ${o.projects.map(i=>i.name??i.id).join(", ")}`)),1)}async function Qn(e,t){let n;try{n=await ze(e,t)}catch(g){console.log($(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:i}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===i?_("\u25CF"):" "} ${Hs(g)} ${f(g.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await Su({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${Hs(g)}${g.id===i?" (current)":""}`,value:g.id}))}),p=o.find(g=>g.id===c);Xn(e,r,c,p?.name),console.log(N(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}U();import Eu from"picocolors";function Nu(e=process.env){return e.FORCE_HYPERLINK==="0"||!Eu.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 Iu(e,t=e,n){return Nu(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var _u=/https?:\/\/[^\s\x1b]+/g;function sn(e,t){return e.replace(_u,n=>Iu(n,n,t))}function Ys(e){return{...Bs(e.idToken)??{},...Bs(e.accessToken)??{}}}function Zn(e){let t=Ys(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 eo(e){let t=Jn(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 Lu(n,{manual:e.manual,promptForRedirect:i=>Ou({message:i})},i=>console.log(sn(i))),r=Vs(t.name,o);if(Gs(r),await wr(r,t.name,i=>console.log(f(i))),console.log(""),console.log(N(`\u2713 Logged in to "${t.name}" as ${Zn(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{qu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await _t(process.cwd(),t.name))}catch{}}async function wr(e,t,n){let r=Ys(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Jn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await ze(process.cwd(),t);c=p.find(g=>g.id===r)?.name}catch{}Hu(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function zs(e){let t=Jn(process.cwd(),e.profile),n=t.connection,o=Fu(t.name);if(!o){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${_(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Zn(o)}`),Wu(o))if(o.refreshToken)try{let r=Vs(t.name,await Mu(n,o.refreshToken));Gs(r),console.log(N(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(O(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(O("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function Ks(e){let t=Jn(process.cwd(),e.profile);Uu(t.name)?console.log(N(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}U();import{readProjectConfig as Xs,writeProjectConfig as Bu,resolveActiveProfile as Vu,loadTokens as Gu,isExpired as Yu}from"document360-engine";function to(e){let t=Xs(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?_("\u25CF "):" ",i=o.production?O(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Gu(n),g=p?Yu(p)&&!p.refreshToken?O("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${c}${i} [${g}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function no(e,t){let n=Xs(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log($(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Bu(n,e);let o=n.profiles[t].production?O(" \u26A0 PRODUCTION"):"";console.log(N(`\u2713 Default profile is now "${t}"${o}`))}function oo(e,t){try{let n=Vu(e,t);console.log(""),console.log(`Profile ${_(n.name)}${n.production?O(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}U();import{existsSync as zu,readdirSync as Ku,statSync as Qs}from"node:fs";import{join as Js}from"node:path";import{apiLogDir as Xu}from"document360-engine";function Zs(){let e=Xu();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!zu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Ku(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=(Qs(Js(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=(Qs(Js(e,r)).size/1024).toFixed(1);console.log(` ${$(r)} ${f(`${i} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}U();import{createSession as Qu,resolveAuth as Ju,findByName as Zu,slugify as ed,touchSession as td,upsertSession as nd,resolveActiveProfile as od}from"document360-engine";async function ea(e,t,n,o,r,i){let c=Ju(n);c.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=od(e,r)}catch(x){console.error($(`Document360 profile error: ${x.message}`)),process.exit(2)}p.production&&(console.error(O(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),i||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let g;if(o){let x=Zu(e,o);x||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),g=x.uuid,console.error(f(`Resuming "${x.name}"`))}let w=Qu({cwd:e,resume:g,profileName:r,allowProdWrites:i===!0}),k=g??null,D=1;for await(let x of w.send(t))switch(x.type){case"session":if(!k){k=x.sessionId;let P=new Date().toISOString();nd({uuid:k,name:ed(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(ae(` \u2699 ${x.name}`));break;case"result":D=x.ok?0:1,console.error(f(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${x.message}`)),process.exit(1)}k&&td(k),process.stdout.write(`
217
- `),process.exit(D)}import{createInterface as Vm}from"node:readline/promises";import{createSession as Xi,resolveAuth as Gm,getSession as Ym,setTitle as zm,slugify as Km,touchSession as ac,upsertSession as Xm,generateTitle as Qm,resolveActiveProfile as lc,resolveModelSetting as Jm,readProjectConfig as Zm,resolveAndPersistAppType as eh,decodeJwtClaims as sc,isExpired as th,loadTokens as nh,isDirectiveMention as oh,stripDirectiveMention as rh,appendDirective as ih,reconcileUpgradeActions as sh,stampArticles as ah,listArticleFiles as lh,CONTENT_CAP_VERSION as ch}from"document360-engine";var Te=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --all to author capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then run d360-capture in your app's repo \u2014 it signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot --list",s:"See capture status \u2014 which specs exist and which are done."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"d360-capture is a separate Playwright CLI \u2014 run it in the app's repo (needs its URL + a login)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/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:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"Author capture specs (--all / --list)."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function rd(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 ta(){let e=["document360-writer \u2014 help",""];for(let t of Te){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push(rd(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function kr(){console.log("");for(let e of ta())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}U();import{getSession as id}from"document360-engine";async function na(e,t){let n=t.currentUuid(),o=n?id(n):void 0;return console.log(o?f(`
210
+ `}function Wt(e){ao(ia(e)),ao(ua(e)),ao(Cr(e));for(let n of[ia(e),Cr(e)]){let o=ud(n,".gitkeep");Mt(o)||pt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
211
+ `)}Mt(sa(e))||pt(sa(e),hd()),Mt(aa(e))||pt(aa(e),dd),Mt(la(e))||pt(la(e),pd),pt(lo(e),pa());let t=Se(e);return ma(e,new Date().toISOString()),t}async function fa(e,t){for(let n of Ft(Wt(t.cwd)))console.log(n);return{kind:"continue"}}function ft(){return[`This is document360-writer's dev hand-off setup (v${se}).`,'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; 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 \u2014 fold durable facts into the architecture brief and/or drop"," a reply (`from: dev`, `kind: answer`, `re: <id>`) \u2014 then set the question's frontmatter `status: done`."," If there are none, continue.","5. Then STOP and ask me for tribal knowledge \u2014 present it as a clearly-marked, standalone prompt on its"," own line (NOT buried in prose) and WAIT for my reply before doing anything else. Use this shape:",' "\u23F8 YOUR INPUT NEEDED \u2014 Any tribal knowledge that would help document this product? (folder map,',` terminology, what to prioritize or skip, gotchas.) Type it below, or reply 'none' / 'carry on' to skip."`," If I give you anything, phrase it clearly and append it to `.d360-writer/architecture/CREATOR-NOTES.md`"," (keep the existing header comment and every note already there; only add). If I say 'none'/'carry on', continue.",`6. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${se},`,' "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(`
212
+ `)}function Rr(e){try{let t=ld(da(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function ma(e,t){let o={...Rr(e)??{},emittedVersion:se,emittedAt:t};pt(da(e),`${JSON.stringify(o,null,2)}
213
+ `)}function We(e){try{return cd(ua(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Se(e){let n=Rr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<se?"stale":"current",completedVersion:n}}function co(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:se};try{if(!Mt(lo(e)))return n;let o=Rr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let i=o?.completedVersion??0;se>r&&(ao(Cr(e)),pt(lo(e),pa()),ma(e,t),n.guideRefreshed=!0),se>i&&(md(e).some(p=>p.kind==="request"&&p.subject.startsWith(ca))||(fd(e,{id:`onb${se}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${ca}${se})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${se}${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:","",ft()].join(`
214
+ `)}),n.notifiedBuilder=!0))}catch{}return n}function uo(e){if(!Mt(lo(e)))return[];let t=Se(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${se}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Ut,ft(),Ut,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Pr(){return['document360-writer (its "docs agent") has been removed from this repository. Please undo its dev\u2192docs',"hand-off setup and restore this repo to how it was before \u2014 in order:","","1. In this repo's agent-memory file (CLAUDE.md, or AGENTS.md \u2014 whichever it edited), REMOVE the",' "Documentation hand-off" section that was added (the rule about dropping hint files in'," `.d360-writer/hints/`, keeping `.d360-writer/architecture/` current, checking"," `.d360-writer/messages/`, and relaying `@d360-writer` directives to `.d360-writer/directives.md`)."," Leave everything else in that file untouched.","2. The `.d360-writer/` folder is already deleted on disk. If it was committed, remove it from version"," control too \u2014 `git rm -r --cached .d360-writer` (if it still resolves) \u2014 and commit the deletions.","3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
215
+ `)}function po(){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):",Ut,Pr(),Ut]}function Ft(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${se}.`," 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):",Ut,ft(),Ut,"","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 Ut,se,ca,Ke=Qn(()=>{"use strict";Ut="-".repeat(64),se=7;ca="Re-run dev\u2194docs onboarding (protocol v"});var Ca={};Ws(Ca,{initCommand:()=>Sr,scaffoldInit:()=>Tr});import{input as dn,confirm as gd}from"@inquirer/prompts";import{basename as ha,join as fo}from"node:path";import{existsSync as Ht,readFileSync as wd,readdirSync as yd,writeFileSync as kd}from"node:fs";import{writeProjectConfig as ga,readProjectConfig as bd,projectConfigPath as wa,writerDir as $d,DEFAULT_DOCS_DIR as ya,DEFAULT_CAPTURE_DIR as ka,DEFAULT_OUTPUT_DIR as ba}from"document360-engine";function Tr(e,t="berlin"){let n=wa(e);if(Ht(n))return{created:!1,path:n,profileName:""};let o={projectId:xa(e)??ha(e),docsDir:ya,captureDir:ka,outputDir:ba,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:va(e)};return ga(o,e),$a(e),{created:!0,path:n,profileName:t}}function $a(e){let t=fo($d(e),".gitignore");Ht(t)||kd(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
216
+ `),"utf8")}async function Sr(){let e=process.cwd(),t=wa(e);if(Ht(t)&&!await gd({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=xa(e)??ha(e),o=await dn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await dn({message:"Capture directory (where document360-capture .spec.ts files live):",default:ka}),i=await dn({message:"Screenshot output directory:",default:ba}),c=await dn({message:"Default connection profile name:",default:"berlin"}),p=await dn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),y={projectId:o,docsDir:ya,captureDir:r,outputDir:i,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:va(e)},h=bd(e);h?.terminologyGlossary&&(y.terminologyGlossary=h.terminologyGlossary),ga(y,e),$a(e);let k=Wt(e);console.log(""),console.log(N(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of Ft(k))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function xa(e){let t=fo(e,"package.json");if(!Ht(t))return null;try{return JSON.parse(wd(t,"utf8")).name??null}catch{return null}}function va(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Ht(fo(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=fo(e,n);Ht(o)&&!xd(o)&&t.push(n)}return t}function xd(e){try{return yd(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var mo=Qn(()=>{"use strict";U();Ke()});var xl={};Ws(xl,{doctorCommand:()=>kn,renderDoctorChecks:()=>$l,runDoctorChecks:()=>bl});import{existsSync as lf}from"node:fs";import{d360GetAll as cf,getAccessToken as uf,isExpired as bi,loadProfileMap as df,loadTokens as pf,packageSkillsDir as yl,projectConfigPath as ff,readProjectConfig as mf,DEFAULT_DOCS_DIR as hf,fetchManifestSummary as gf,resolveActiveProfile as wf,classifyClaudeAuth as yf,CLAUDE_CODE_SETUP_HINT as kl,resolveModelSetting as kf,probeModel as bf,detectAppType as $f,playbookSkillName as xf,D360AuthError as vf}from"document360-engine";async function bl(e){let t=[],n=Number(process.versions.node.split(".")[0]);t.push(n>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let o=yf();o.state==="ready"?t.push({level:"ok",label:`Claude auth: ${o.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):o.state==="maybe"?t.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${kl}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:kl});let r=kf(e);if(t.push({level:"ok",label:`Model: ${r.model} (${r.source==="auto"?"auto \u2014 right-sized for docs; /model to change":r.source})`}),o.state==="ready"){let T=await bf(e,r.model??void 0);T.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(T.latencyMs/1e3).toFixed(1)}s`}):T.timedOut?t.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):t.push({level:"fail",label:`Model call failed \u2014 ${T.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let i=mf(e);if(!i)return t.push({level:"fail",label:`No ${ff(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${i.projectId}`});let c=(i.docsDir??hf).replace(/\/+$/,"");t.push(i.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=i.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let y=i.appType??$f(e);if(y){let T=i.appType?"from config":"auto-detected",P=y==="web"||y==="cli";t.push({level:"ok",label:`Genre: ${y} (${T})${P?` \u2192 ${xf(y)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else t.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let h;try{h=wf(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(T){return t.push({level:"fail",label:`Profile config: ${T.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=pf(h.name);k?bi(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):bi(k)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(k.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${h.name})`}),t.push(h.project.workspaceId?{level:"ok",label:`Workspace: ${h.project.workspaceName??h.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let D=df(e,h.name);D?D.projectId&&h.project.projectId&&D.projectId!==h.project.projectId?t.push({level:"fail",label:`Category map projectId (${D.projectId}) \u2260 profile projectId (${h.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(D.articles).length} articles, ${Object.keys(D.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${h.name}" (created on first /publish)`}),t.push(lf(yl())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${yl()}`,fix:"Reinstall document360-writer (broken install)"});let $=Se(e);if($.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${se})`}):$.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${$.completedVersion}, current is v${se}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!bi(k)||k.refreshToken)){let T={profile:h.name,connection:h.connection};try{await uf(T);let S=await cf(T,"/v3/projects");t.push({level:"ok",label:`API reachable (${h.connection.apiUrl}) \u2014 ${S.length} project(s) visible`})}catch(S){t.push({level:"fail",label:`API call failed: ${S.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let P=D?.projectId??h.project.projectId;if(P&&h.project.workspaceId)try{let S=await gf(T,P,h.project.workspaceId);if(S){let I=(S.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${h.connection.name} (${S.languages?.length??0} language${(S.languages?.length??0)===1?"":"s"}) \xB7 hash ${I||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${h.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(S){S instanceof vf||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(S.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${h.project.projectName??P})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):t.push({level:"warn",label:`Workspace sync manifest: probe failed (${S.message.slice(0,80)})`})}}return t}function $l(e){let t=[""];for(let r of e){let i=r.level==="ok"?N("\u2713"):r.level==="warn"?L("\u26A0"):x("\u2717");t.push(` ${i} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${_(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?N(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):x(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function kn(e,t){console.log(f("Running checks\u2026"));for(let n of $l(await bl(t.cwd)))console.log(n);return{kind:"continue"}}var Ro=Qn(()=>{"use strict";Ke();U()});import{Command as Hg}from"commander";import{createRequire as qg}from"node:module";import{AUTH_MODES as Bg}from"document360-engine";import{input as Mu}from"@inquirer/prompts";import{loginPkce as Uu,refreshTokens as Wu,toStoredTokens as Ys,clearTokens as Fu,decodeJwtClaims as Gs,isExpired as Hu,loadTokens as qu,saveTokens as zs,resolveActiveProfile as to,setProfileProject as Bu,readProjectConfig as Vu}from"document360-engine";U();import{select as Ru}from"@inquirer/prompts";import{resolveActiveProfile as Pu,setProfileProject as Tu,resolveProjectId as Su,listWorkspaces as Du}from"document360-engine";async function cn(e,t){let n=Pu(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Su(o);return{workspaces:await Du(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Hs=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function kr(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 Jn(e,t,n,o,r){Tu(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function qs(e,t,n){let o;try{o=await cn(e,n)}catch(i){return console.log(x(`Could not list workspaces: ${i.message}`)),1}let r=kr(o.workspaces,t);return r?(Jn(e,o.profile,o.projectId,r.id,r.name),console.log(N(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(x(`No workspace matches "${t}". Available: ${o.workspaces.map(i=>i.name??i.id).join(", ")}`)),1)}async function Ot(e,t){let n;try{n=await cn(e,t)}catch(h){console.log(x(`Could not list workspaces: ${h.message}`));return}let{workspaces:o,projectId:r,profile:i,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===c?_("\u25CF"):" "} ${Hs(h)} ${f(h.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Ru({message:"Select the Document360 workspace for this repo:",choices:o.map(h=>({name:`${Hs(h)}${h.id===c?" (current)":""}`,value:h.id}))}),y=o.find(h=>h.id===p);Jn(e,i,r,p,y?.name),console.log(N(`\u2713 Workspace set to "${y?.name??p}" for profile "${i}".`))}U();import{select as Au}from"@inquirer/prompts";import{resolveActiveProfile as ju,setProfileProject as Eu,listProjects as Nu}from"document360-engine";async function ze(e,t){let n=ju(e,t),o={profile:n.name,connection:n.connection};return{projects:await Nu(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Bs=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function br(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function Zn(e,t,n,o){Eu(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Vs(e,t,n){let o;try{o=await ze(e,n)}catch(i){return console.log(x(`Could not list projects: ${i.message}`)),1}let r=br(o.projects,t);return r?(Zn(e,o.profile,r.id,r.name),console.log(N(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(x(`No project matches "${t}". Available: ${o.projects.map(i=>i.name??i.id).join(", ")}`)),1)}async function eo(e,t){let n;try{n=await ze(e,t)}catch(y){console.log(x(`Could not list projects: ${y.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 y of o)console.log(` ${y.id===i?_("\u25CF"):" "} ${Bs(y)} ${f(y.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await Au({message:"Select the Document360 project for this repo:",choices:o.map(y=>({name:`${Bs(y)}${y.id===i?" (current)":""}`,value:y.id}))}),p=o.find(y=>y.id===c);Zn(e,r,c,p?.name),console.log(N(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}U();import Iu from"picocolors";function _u(e=process.env){return e.FORCE_HYPERLINK==="0"||!Iu.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 Lu(e,t=e,n){return _u(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Ou=/https?:\/\/[^\s\x1b]+/g;function un(e,t){return e.replace(Ou,n=>Lu(n,n,t))}function Ks(e){return{...Gs(e.idToken)??{},...Gs(e.accessToken)??{}}}function no(e){let t=Ks(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 oo(e){let t=to(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 Uu(n,{manual:e.manual,promptForRedirect:i=>Mu({message:i})},i=>console.log(un(i))),r=Ys(t.name,o);if(zs(r),await $r(r,t.name,i=>console.log(f(i))),console.log(""),console.log(N(`\u2713 Logged in to "${t.name}" as ${no(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{Vu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Ot(process.cwd(),t.name))}catch{}}async function $r(e,t,n){let r=Ks(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(to(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await ze(process.cwd(),t);c=p.find(y=>y.id===r)?.name}catch{}Bu(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Xs(e){let t=to(process.cwd(),e.profile),n=t.connection,o=qu(t.name);if(!o){console.log(x(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${_(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${no(o)}`),Hu(o))if(o.refreshToken)try{let r=Ys(t.name,await Wu(n,o.refreshToken));zs(r),console.log(N(`\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 Qs(e){let t=to(process.cwd(),e.profile);Fu(t.name)?console.log(N(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}U();import{readProjectConfig as Js,writeProjectConfig as Gu,resolveActiveProfile as Yu,loadTokens as zu,isExpired as Ku}from"document360-engine";function ro(e){let t=Js(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(x("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?_("\u25CF "):" ",i=o.production?L(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=zu(n),y=p?Ku(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${c}${i} [${y}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function io(e,t){let n=Js(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(x(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Gu(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(N(`\u2713 Default profile is now "${t}"${o}`))}function so(e,t){try{let n=Yu(e,t);console.log(""),console.log(`Profile ${_(n.name)}${n.production?L(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(x(n.message)),process.exitCode=1}}U();import{existsSync as Xu,readdirSync as Qu,statSync as Zs}from"node:fs";import{join as ea}from"node:path";import{apiLogDir as Ju}from"document360-engine";function ta(){let e=Ju();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Xu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Qu(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=(Zs(ea(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=(Zs(ea(e,r)).size/1024).toFixed(1);console.log(` ${x(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("")}U();import{createSession as Zu,resolveAuth as ed,findByName as td,slugify as nd,touchSession as od,upsertSession as rd,resolveActiveProfile as id}from"document360-engine";async function na(e,t,n,o,r,i){let c=ed(n);c.kind==="none"&&(console.error(""),console.error(x("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=id(e,r)}catch($){console.error(x(`Document360 profile error: ${$.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),i||(console.error(x("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let y;if(o){let $=td(e,o);$||(console.error(x(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),y=$.uuid,console.error(f(`Resuming "${$.name}"`))}let h=Zu({cwd:e,resume:y,profileName:r,allowProdWrites:i===!0}),k=y??null,D=1;for await(let $ of h.send(t))switch($.type){case"session":if(!k){k=$.sessionId;let T=new Date().toISOString();rd({uuid:k,name:nd(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:T,updatedAt:T})}break;case"text":process.stdout.write($.delta);break;case"tool":console.error(le(` \u2699 ${$.name}`));break;case"result":D=$.ok?0:1,console.error(f(`(${$.inputTokens}\u2192${$.outputTokens} tokens`+($.costUsd>0?`, $${$.costUsd<.01?$.costUsd.toFixed(4):$.costUsd.toFixed(2)}`:"")+")")),$.ok||console.error(x("agent finished with an error result"));break;case"error":console.error(""),console.error(x(`agent error: ${$.message}`)),process.exit(1)}k&&od(k),process.stdout.write(`
217
+ `),process.exit(D)}import{createInterface as Ym}from"node:readline/promises";import{createSession as Ji,resolveAuth as zm,getSession as Km,setTitle as Xm,slugify as Qm,touchSession as cc,upsertSession as Jm,generateTitle as Zm,resolveActiveProfile as uc,resolveModelSetting as eh,readProjectConfig as th,resolveAndPersistAppType as nh,decodeJwtClaims as lc,isExpired as oh,loadTokens as rh,isDirectiveMention as ih,stripDirectiveMention as sh,appendDirective as ah,reconcileUpgradeActions as lh,stampArticles as ch,listArticleFiles as uh,CONTENT_CAP_VERSION as dh}from"document360-engine";var Te=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --all to author capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then run d360-capture in your app's repo \u2014 it signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot --list",s:"See capture status \u2014 which specs exist and which are done."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"d360-capture is a separate Playwright CLI \u2014 run it in the app's repo (needs its URL + a login)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/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:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"Author capture specs (--all / --list)."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function sd(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 oa(){let e=["document360-writer \u2014 help",""];for(let t of Te){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push(sd(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function xr(){console.log("");for(let e of oa())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}U();import{getSession as ad}from"document360-engine";async function ra(e,t){let n=t.currentUuid(),o=n?ad(n):void 0;return console.log(o?f(`
218
218
  (conversation reset \u2014 "${o.name}" is still available via /resume)
219
219
  `):f(`
220
220
  (conversation reset \u2014 agent will start fresh on the next prompt)
221
- `)),{kind:"clear"}}async function br(){return{kind:"exit"}}uo();U();import{readMcpConfig as Pr,writeMcpConfig as va}from"document360-engine";async function po(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(xd(),{kind:"continue"}):t==="add"?($d(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(vd(e.slice(1)),{kind:"continue"}):(console.log($(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function xd(){let e=Pr(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
221
+ `)),{kind:"clear"}}async function vr(){return{kind:"exit"}}mo();U();import{readMcpConfig as Dr,writeMcpConfig as Ra}from"document360-engine";async function ho(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(vd(),{kind:"continue"}):t==="add"?(Cd(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Rd(e.slice(1)),{kind:"continue"}):(console.log(x(`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 vd(){let e=Dr(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
222
222
  No MCP servers registered. Add one with /mcp add <name> <type> <ref>
223
- `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${_(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),i=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${_(n)} ${f(`(${o.type})`)} ${o.url}${i}`)}}console.log("")}function $d(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log($("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log($(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Pr(),i;if(n==="stdio")i={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let g=o[++p],w=g?.match(/^([^:=]+)[:=](.+)$/);if(!w){console.log($(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}c[w[1].trim()]=w[2].trim()}else{console.log($(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}i={type:n,url:o[0],headers:Object.keys(c).length>0?c:void 0}}r.servers[t]=i,va(r),console.log(""),console.log(N(`\u2713 Registered "${t}" (${n})`)),console.log(O(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function vd(e){let t=e[0];if(!t){console.log($("Usage: /mcp remove <name>"));return}let n=Pr();if(!n.servers[t]){console.log($(`No server named "${t}".`));return}delete n.servers[t],va(n),console.log(N(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}U();import{readFileSync as Md}from"node:fs";import{join as Ud}from"node:path";import{select as Wd}from"@inquirer/prompts";import{computeSyncStatus as _r,planPartitions as Fd,relatedArticlePaths as Hd,resolveModelForOperation as qd,runPartitioned as Bd,loadProfileMap as Vd,resolveActiveProfile as Gd,resolveCrossLinks as Yd,applyStructureOrder as Na,orderSyncLine as Ia,applyRelatedArticles as _a,relatedSyncLine as Oa}from"document360-engine";import X from"picocolors";import Da from"wrap-ansi";import Er from"string-width";U();import Xe from"picocolors";import Tr from"wrap-ansi";import Sr from"string-width";var Ca=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Ra=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Pa=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Cd(e){let t=e.replace(/\r/g,"").split(`
224
- `),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(Ca(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Ra(t[o+1])){let p=Pa(r);o+=2;let g=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)g.push(Pa(t[o++]));n.push({kind:"table",header:p,rows:g});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 g=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(g),text:g.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Ca(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Ra(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function Dr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Xe.bold(t.slice(2,-2)):t.startsWith("`")?_(t.slice(1,-1)):Xe.italic(t.slice(1,-1)))}var Rd=(e,t)=>e+" ".repeat(Math.max(0,t-Sr(e)));function Pd(e,t,n){let o=e.length,r=e.map((R,S)=>Math.max(Sr(R),...t.map(I=>Sr(I[S]??"")))),i=Math.max(24,n),c=3*o+1,p=[...r],g=()=>p.reduce((R,S)=>R+S,0)+c,w=0;for(;g()>i&&w++<1e4;){let R=-1,S=6;for(let I=0;I<o;I++)p[I]>S&&(S=p[I],R=I);if(R===-1)break;p[R]-=1}let k=(R,S,I)=>Xe.gray(R+p.map(L=>"\u2500".repeat(L+2)).join(S)+I),D=Xe.gray("\u2502"),x=(R,S)=>{let I=p.map((ee,Z)=>{let ue=R[Z]??"",Cn=S?Xe.bold(ue):Dr(ue);return Tr(Cn,ee,{hard:!0}).split(`
225
- `)}),L=Math.max(...I.map(ee=>ee.length)),K=[];for(let ee=0;ee<L;ee++)K.push(p.map((Z,ue)=>`${D} ${Rd(I[ue][ee]??"",Z)} `).join("")+D);return K.join(`
226
- `)},P=[k("\u250C","\u252C","\u2510"),x(e,!0)];return P.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((R,S)=>{P.push(x(R,!1)),P.push(S===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),P.join(`
227
- `)}function Td(e,t){switch(e.kind){case"heading":return Xe.bold(e.text);case"hr":return Xe.gray("\u2500".repeat(t));case"para":return Tr(Dr(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),[c="",...p]=Tr(Dr(o.text),Math.max(10,t-i.length)).split(`
228
- `);return` ${r} ${c}`+p.map(g=>`
229
- ${i}${g}`).join("")}).join(`
223
+ `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${_(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),i=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${_(n)} ${f(`(${o.type})`)} ${o.url}${i}`)}}console.log("")}function Cd(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(x("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(x(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Dr(),i;if(n==="stdio")i={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let y=o[++p],h=y?.match(/^([^:=]+)[:=](.+)$/);if(!h){console.log(x(`-H expects key:value (no spaces). Got: ${y??"(nothing)"}`));return}c[h[1].trim()]=h[2].trim()}else{console.log(x(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}i={type:n,url:o[0],headers:Object.keys(c).length>0?c:void 0}}r.servers[t]=i,Ra(r),console.log(""),console.log(N(`\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 Rd(e){let t=e[0];if(!t){console.log(x("Usage: /mcp remove <name>"));return}let n=Dr();if(!n.servers[t]){console.log(x(`No server named "${t}".`));return}delete n.servers[t],Ra(n),console.log(N(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}U();import{readFileSync as Wd}from"node:fs";import{join as Fd}from"node:path";import{select as Hd}from"@inquirer/prompts";import{computeSyncStatus as Mr,planPartitions as qd,relatedArticlePaths as Bd,resolveModelForOperation as Vd,runPartitioned as Gd,loadProfileMap as Yd,resolveActiveProfile as zd,resolveCrossLinks as Kd,applyStructureOrder as _a,orderSyncLine as La,applyRelatedArticles as Oa,relatedSyncLine as Ma}from"document360-engine";import X from"picocolors";import ja from"wrap-ansi";import _r from"string-width";U();import Xe from"picocolors";import Ar from"wrap-ansi";import jr from"string-width";var Pa=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Ta=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Sa=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Pd(e){let t=e.replace(/\r/g,"").split(`
224
+ `),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(Pa(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Ta(t[o+1])){let p=Sa(r);o+=2;let y=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)y.push(Sa(t[o++]));n.push({kind:"table",header:p,rows:y});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 y=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(y),text:y.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Pa(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Ta(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function Er(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Xe.bold(t.slice(2,-2)):t.startsWith("`")?_(t.slice(1,-1)):Xe.italic(t.slice(1,-1)))}var Td=(e,t)=>e+" ".repeat(Math.max(0,t-jr(e)));function Sd(e,t,n){let o=e.length,r=e.map((P,S)=>Math.max(jr(P),...t.map(I=>jr(I[S]??"")))),i=Math.max(24,n),c=3*o+1,p=[...r],y=()=>p.reduce((P,S)=>P+S,0)+c,h=0;for(;y()>i&&h++<1e4;){let P=-1,S=6;for(let I=0;I<o;I++)p[I]>S&&(S=p[I],P=I);if(P===-1)break;p[P]-=1}let k=(P,S,I)=>Xe.gray(P+p.map(O=>"\u2500".repeat(O+2)).join(S)+I),D=Xe.gray("\u2502"),$=(P,S)=>{let I=p.map((ee,Q)=>{let ae=P[Q]??"",kt=S?Xe.bold(ae):Er(ae);return Ar(kt,ee,{hard:!0}).split(`
225
+ `)}),O=Math.max(...I.map(ee=>ee.length)),z=[];for(let ee=0;ee<O;ee++)z.push(p.map((Q,ae)=>`${D} ${Td(I[ae][ee]??"",Q)} `).join("")+D);return z.join(`
226
+ `)},T=[k("\u250C","\u252C","\u2510"),$(e,!0)];return T.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((P,S)=>{T.push($(P,!1)),T.push(S===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),T.join(`
227
+ `)}function Dd(e,t){switch(e.kind){case"heading":return Xe.bold(e.text);case"hr":return Xe.gray("\u2500".repeat(t));case"para":return Ar(Er(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),[c="",...p]=Ar(Er(o.text),Math.max(10,t-i.length)).split(`
228
+ `);return` ${r} ${c}`+p.map(y=>`
229
+ ${i}${y}`).join("")}).join(`
230
230
  `)}case"code":return e.lines.map(n=>Xe.gray(" "+n)).join(`
231
- `);case"table":return Pd(e.header,e.rows,t)}}function Ar(e,t){let n=Math.max(20,t);return Cd(e).map(o=>Td(o,n)).join(`
232
-
233
- `)}U();import Sd from"picocolors";var Dd=[127,86,217],Ad=[22,38,43],Ta={T:Dd,E:Ad},ln=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],jr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,jd=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Sa(){if(!Sd.isColorSupported)return[];let e=ln[0].length,t=[];for(let n=0;n<ln.length;n+=2){let o="";for(let r=0;r<e;r++){let i=Ta[ln[n][r]],c=n+1<ln.length?Ta[ln[n+1][r]]:void 0;i&&c?o+=`${jr(i)}${jd(c)}\u2580\x1B[49m\x1B[39m`:i?o+=`${jr(i)}\u2580\x1B[39m`:c?o+=`${jr(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function cn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function he(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Qe(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Ft=(e,t)=>` ${e.padEnd(13)}${t}`;function Ed(e,t){let n=[on("\u270E document360-writer")+X.gray(` v${e.version}`),X.gray(" Reads your code, writes your docs."),"",Ft("Claude:",`${e.claude}${X.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Ft("Document360:",e.configured?e.loggedOut?X.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?X.gray(` (${e.sessionHint})`):""}`:X.yellow("not set up \u2014 run /init")),Ft("Profile:",e.configured?`${e.profile}${X.gray(` (${e.apiUrl})`)}${e.prod?X.bold(X.yellow(" \u26A0 PRODUCTION")):""}`:X.gray("\u2014 (run /init)")),Ft("Project:",e.project),Ft("Mode:",X.gray(e.mode)),Ft("cwd:",X.gray(e.cwd))],o=Sa();if(o.length===0)return n.join(`
234
- `);let r=2,i=3,c=Er(o[0]);if(!(t>=r+c+i+Math.max(...n.map(k=>Er(k)))))return[...o.map(k=>" "+k),...n].join(`
235
- `);let g=Math.max(0,Math.floor((n.length-o.length)/2)),w=[];for(let k=0;k<Math.max(o.length+g,n.length);k++){let D=o[k-g]??" ".repeat(c);w.push((" ".repeat(r)+D+" ".repeat(i)+(n[k]??"")).trimEnd())}return w.join(`
236
- `)}var Nd={error:X.red,warn:X.yellow,ok:X.green,info:X.gray};function Nr(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Ed(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",i=Math.max(10,n-4),c=50,p=e.text.split(`
237
- `).flatMap(w=>Da(w,i,{hard:!0}).split(`
238
- `)),g=Math.max(0,p.length-c);return g>0&&(p=[...p.slice(0,c),X.dim(`\u2026 +${g} more lines`)]),`
239
- `+p.map((w,k)=>o+(k===0?_(" \u276F "):" ")+w+" ".repeat(Math.max(0,i-Er(w))+1)+r).join(`
231
+ `);case"table":return Sd(e.header,e.rows,t)}}function Nr(e,t){let n=Math.max(20,t);return Pd(e).map(o=>Dd(o,n)).join(`
232
+
233
+ `)}U();import Ad from"picocolors";var jd=[127,86,217],Ed=[22,38,43],Da={T:jd,E:Ed},pn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Ir=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Nd=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Aa(){if(!Ad.isColorSupported)return[];let e=pn[0].length,t=[];for(let n=0;n<pn.length;n+=2){let o="";for(let r=0;r<e;r++){let i=Da[pn[n][r]],c=n+1<pn.length?Da[pn[n+1][r]]:void 0;i&&c?o+=`${Ir(i)}${Nd(c)}\u2580\x1B[49m\x1B[39m`:i?o+=`${Ir(i)}\u2580\x1B[39m`:c?o+=`${Ir(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function fn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function he(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Qe(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var qt=(e,t)=>` ${e.padEnd(13)}${t}`;function Id(e,t){let n=[ln("\u270E document360-writer")+X.gray(` v${e.version}`),X.gray(" Reads your code, writes your docs."),"",qt("Claude:",`${e.claude}${X.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),qt("Document360:",e.configured?e.loggedOut?X.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?X.gray(` (${e.sessionHint})`):""}`:X.yellow("not set up \u2014 run /init")),qt("Profile:",e.configured?`${e.profile}${X.gray(` (${e.apiUrl})`)}${e.prod?X.bold(X.yellow(" \u26A0 PRODUCTION")):""}`:X.gray("\u2014 (run /init)")),qt("Project:",e.project),qt("Mode:",X.gray(e.mode)),qt("cwd:",X.gray(e.cwd))],o=Aa();if(o.length===0)return n.join(`
234
+ `);let r=2,i=3,c=_r(o[0]);if(!(t>=r+c+i+Math.max(...n.map(k=>_r(k)))))return[...o.map(k=>" "+k),...n].join(`
235
+ `);let y=Math.max(0,Math.floor((n.length-o.length)/2)),h=[];for(let k=0;k<Math.max(o.length+y,n.length);k++){let D=o[k-y]??" ".repeat(c);h.push((" ".repeat(r)+D+" ".repeat(i)+(n[k]??"")).trimEnd())}return h.join(`
236
+ `)}var _d={error:X.red,warn:X.yellow,ok:X.green,info:X.gray};function Lr(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Id(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",i=Math.max(10,n-4),c=50,p=e.text.split(`
237
+ `).flatMap(h=>ja(h,i,{hard:!0}).split(`
238
+ `)),y=Math.max(0,p.length-c);return y>0&&(p=[...p.slice(0,c),X.dim(`\u2026 +${y} more lines`)]),`
239
+ `+p.map((h,k)=>o+(k===0?_(" \u276F "):" ")+h+" ".repeat(Math.max(0,i-_r(h))+1)+r).join(`
240
240
  `)}case"assistant":return`
241
- `+Ar(e.text,n);case"tool":{let o=e.arg!==null?X.gray(`${e.sep}(${e.arg})`):"";return`
242
- `+Da(X.green("\u25CF ")+X.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?X.red:X.gray,r=e.lines.map((i,c)=>o((c===0?" \u23BF ":" ")+i));return e.hidden>0&&r.push(X.dim(` \u2026 +${e.hidden} lines`)),r.join(`
241
+ `+Nr(e.text,n);case"tool":{let o=e.arg!==null?X.gray(`${e.sep}(${e.arg})`):"";return`
242
+ `+ja(X.green("\u25CF ")+X.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?X.red:X.gray,r=e.lines.map((i,c)=>o((c===0?" \u23BF ":" ")+i));return e.hidden>0&&r.push(X.dim(` \u2026 +${e.hidden} lines`)),r.join(`
243
243
  `)}case"diff":{let o=c=>c===1?"":"s",i=[X.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&i.push(X.dim(` \u2026 +${e.hidden} more diff lines`)),i.join(`
244
- `)}case"link":return e.lines.map(o=>_(sn(` \u2B95 ${o}`))).join(`
244
+ `)}case"link":return e.lines.map(o=>_(un(` \u2B95 ${o}`))).join(`
245
245
  `);case"preview":return`
246
- `+on(`\u25A3 Preview \u2014 ${e.name}`)+`
247
-
248
- `+Ar(e.text,n);case"note":return`
249
- `+Nd[e.tone](sn(e.text));case"done":return`
250
- `+(e.ok?X.magenta("\u2736 "):X.red("\u2736 "))+X.gray(`Cooked for ${cn(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${he(e.costUsd)}`:""))}}function Aa(e,t){return e.map(n=>Nr(n,t)).join(`
251
- `)}import{resolveActiveProfile as Id,loadTokens as _d,isExpired as Od,decodeJwtClaims as ja}from"document360-engine";function Ld(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Fe(e,t){try{let n=Id(e,t),o=_d(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Od(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let c={...ja(o.idToken)??{},...ja(o.accessToken)??{}}.doc360_project_id;if(typeof c=="string"&&c&&c!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${Ld(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var un=3;function Or(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(`
252
- `)}var Ea={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function dn(e){return e.filter(t=>t.path!==null&&t.status in Ea&&!t.link).map(t=>({path:t.path,label:Ea[t.status]}))}function fo(e){return e.filter(t=>t.link).length}function Lr(e,t){try{let n=Vd(e,Gd(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Yd(Md(Ud(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 zd(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 La(e){let t=[];e.length>1&&t.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(o=>o.path),indent:!1});let n=new Map;for(let o of e){let r=o.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),i=n.get(r);i?i.push(o):n.set(r,[o])}for(let o of[...n.keys()].sort()){let r=n.get(o).sort((i,c)=>i.path.localeCompare(c.path));t.push({kind:"category",label:`${zd(o)} (${r.length})`,paths:r.map(i=>i.path),indent:!1});for(let i of r){let c=i.path.replace(/\\/g,"/").split("/").pop()??i.path;t.push({kind:"article",label:c,paths:[i.path],indent:!0,note:i.label})}}return t}function mo(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(`
253
- `)}function Mr(e,t,n){let o=x=>t[x.index]?.paths.length??0,r=e.filter(x=>x.ok),i=e.filter(x=>!x.ok),c=e.reduce((x,P)=>x+o(P),0),p=r.reduce((x,P)=>x+o(P),0),g=n==="api"?`${he(e.reduce((x,P)=>x+P.costUsd,0))} total`:Qe(e.reduce((x,P)=>x+P.outputTokens,0)),w=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,k=x=>`${x} article${x===1?"":"s"}`,D=[];if(i.length===0)D.push(`Published ${k(c)} (${w}) successfully \xB7 ${g}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${k(c)} (${w}) \xB7 ${g}.`),D.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 x of i)D.push(` \u2717 ${x.label}${x.error?` \u2014 ${x.error}`:""}`)}return D}async function Ir(e,t){let n=Fd(t),{model:o}=qd(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${un} agents at once) on ${o}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let r of Bd({cwd:e.cwd,partitions:n,promptFor:i=>mo(i.paths),concurrency:un,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:o}))if(r.type==="partition_status")r.status==="running"?console.log(f(` \u25B8 ${r.label} \u2014 publishing\u2026`)):r.status==="done"?console.log(N(` \u2713 ${r.label}`)):console.log($(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let i=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of Mr(r.results,n,i))console.log(r.ok?N(p):O(p));let c=Lr(e.cwd,e.profileName);c&&console.log(f(c));try{let p=Ia(await Na({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}try{let p=Oa(await _a({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}}}catch(r){console.log($(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function ho(e,t,n){let o=Hd(e,n);if(o.length===0)return[];let r=new Set(dn((await _r({cwd:e,profileName:t})).entries).map(i=>i.path));return o.filter(i=>r.has(i))}async function Ma(e,t){let n=Fe(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await ho(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(N("\u2713 All related articles are already published.")),{kind:"continue"}):await Ir(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await _r({cwd:t?.cwd??process.cwd()}),i=dn(r.entries),c=fo(r.entries);if(c>0&&console.log(O(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),i.length===0){if(console.log(N(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let p=Ia(await Na({cwd:t.cwd,profileName:t.profileName}));p&&console.log(f(p));let g=Oa(await _a({cwd:t.cwd,profileName:t.profileName}));g&&console.log(f(g))}catch{}return{kind:"continue"}}return t?await Ir(t,i.map(p=>p.path)):{kind:"forward-to-agent",prompt:mo(i.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log($(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let i=await _r({cwd:t?.cwd??process.cwd()});r=dn(i.entries);let c=fo(i.entries);c>0&&console.log(O(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`))}catch(i){return console.log($(`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(N("\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(()=>Wd({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 Ir(t,r.map(i=>i.path))}return{kind:"forward-to-agent",prompt:Or(o),display:`/publish ${o}`}}async function pn(){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(`
254
- `),display:"/audit"}}U();import{checkbox as Kd}from"@inquirer/prompts";import{inventoryRepo as Xd,readProjectConfig as Ua,writeProjectConfig as Qd}from"document360-engine";function Ur(e,t){let n=Ua(e);n&&(n.authoritativeSourceFiles=t,Qd(n,e))}function go(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 Wa(e,t){let n=t?.cwd??process.cwd();if(!Ua(n))return console.log($("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Xd(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(_("Recommended documentation scope (run /scope in the REPL to choose):"));for(let i of o)console.log(` ${i.recommended?"\u25C9":"\u25CB"} ${i.path} ${f(go(i))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Kd({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(i=>({name:`${i.path} (${go(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"};Ur(n,r),console.log(N(`\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"}}U();import{confirm as op}from"@inquirer/prompts";import{applyPull as Fr,computeSyncStatus as Va,compareRemoteSources as rp,planPull as Ga,planImport as ip,applyImport as sp,establishBaselines as ap,rebaselineServerMeta as lp,D360AuthError as cp}from"document360-engine";U();var Fa=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:$,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:O,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:_,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:$,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:$,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint: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 Jd(e){return e.path?e.path:`${e.title??"(untitled)"} ${ae(`[${e.articleId}]`)}`}function Zd(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 yo(e,t){let n=[],o=e.entries.filter(k=>k.link);if(o.length>0){n.push(""),n.push(Pe("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let k of o)n.push(` ${O("~")} ${O(k.path??"")} ${ae(`\u2192 "${k.link.title}"`)}`)}for(let k of Fa){let D=e.entries.filter(x=>x.status===k.status&&!(k.status==="untracked-local"&&x.link));if(D.length!==0){n.push(""),n.push(Pe(k.header));for(let x of D)n.push(` ${k.paint(k.mark)} ${k.paint(Jd(x))}${x.detail?ae(` (${x.detail})`):""}`)}}let r=e.counts["in-sync"]??0,i=e.entries.length;n.push("");let c={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},p=o.length,g=i===r?N("\u2713 everything up to date"):[r>0?N(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...Fa.map(k=>{let D=(e.counts[k.status]??0)-(k.status==="untracked-local"?p:0);return D>0?`${D} ${c[k.status]}`:null})].filter(Boolean).join(ae(" \xB7 ")),w=t!==void 0?` \xB7 synced in ${Zd(t)}`:"";return n.push(g+ae(` \xB7 ${i} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${w}`)),n}import{structuredPatch as ep}from"diff";import Ha from"picocolors";var qa=80,tp="\x1B[48;2;74;28;28m",np="\x1B[48;2;24;66;24m",Ba="\x1B[49m",Wr=e=>String(e).padStart(5);function pt(e,t,n){let o=x=>{let P=x.replace(/\r\n/g,`
255
- `);return P.endsWith(`
256
- `)||P===""?P:P+`
257
- `},r=o(e),i=o(t);if(r===i)return null;let c=Math.max(20,n-10),p=ep("a","b",r,i,"","",{context:3}),g=0,w=0,k=[];p.hunks.forEach((x,P)=>{P>0&&k.push(Ha.gray(" \u2026"));let R=x.oldStart,S=x.newStart;for(let I of x.lines){let L=I[0],K=I.slice(1).slice(0,c);L==="-"?(w++,k.push(`${tp}${Wr(R++)} - ${K}${Ba}`)):L==="+"?(g++,k.push(`${np}${Wr(S++)} + ${K}${Ba}`)):(k.push(Ha.gray(Wr(S))+" "+K),R++,S++)}});let D=k.slice(0,qa);return{added:g,removed:w,lines:D,hidden:Math.max(0,k.length-qa)}}async function Ya(e,t){let n=Fe(t.cwd,t.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await up(t),{kind:"continue"};if(o==="--baseline")return await dp(t,e.filter(c=>c!=="--baseline")),{kind:"continue"};if(o==="--compare")return await pp(t),{kind:"continue"};if(o)return console.log($(`Unknown option: ${o}`)),console.log(f("Usage: /pull pull portal edits + import new portal articles")),console.log(f(" /pull <path> pull one article (or resolve a conflict)")),console.log(f(" /pull --status drift report only (no writes)")),console.log(f(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await fp(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let i=await Hr({cwd:t.cwd,profileName:t.profileName});for(let c of qr(i))console.log(c.tone==="ok"?N(c.text):c.tone==="warn"?O(c.text):f(c.text));console.log("")}catch(r){r instanceof cp?console.log($(r.message)):console.log($(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Hr(e){let t=await Va({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 Ga({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Fr({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 ip({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});sp({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 wo=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,ft=e=>e===1?"":"s";function qr(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${ft(e.pulled.length)} into local: ${wo(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${ft(e.imported.length)}: ${wo(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${ft(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${ft(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Take the portal copy: /pull <path> \xB7 keep yours: /publish <path>. (${wo(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${ft(e.failed.length)} failed: ${wo(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 up(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Va({cwd:e.cwd,profileName:e.profileName});for(let o of yo(n,Date.now()-t))console.log(o);console.log("")}async function dp(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 lp({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(N("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(N(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(N(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(O(`${o.skipped.length} skipped:`));for(let i of o.skipped)console.log(f(` - ${i.path} (${i.reason})`))}}async function pp(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await rp({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Pe(String(t.legacyCount))} \xB7 Manifest: ${Pe(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(N("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log($(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(O(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(O(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(f(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function fp(e,t){let n=t.replace(/\\/g,"/"),o=await Ga({cwd:e.cwd,profileName:e.profileName,relPath:n});console.log(""),console.log(`${_("\u25CF")} ${Pe(o.title)} ${ae(`(${o.path})`)}`);for(let c of o.notes)console.log(O(` \u26A0 ${c}`));o.overwritesLocalChanges&&console.log(O(" \u26A0 This OVERWRITES local edits made since the last sync."));let r=pt(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.")),Fr({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ae(` \u23BF Added ${r.added} line${ft(r.added)}, removed ${r.removed} line${ft(r.removed)}`));for(let c of r.lines)console.log(c);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>op({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}Fr({cwd:e.cwd,profileName:e.profileName},o),console.log(N(` \u2713 Pulled ${o.path} (sync base advanced).`))}U();import{statSync as mp}from"node:fs";import{resolve as hp}from"node:path";import{estimateBulkCost as gp,planPartitions as yp,readProjectConfig as wp,resolveModelForOperation as kp,runPartitioned as bp,trackedArticlePaths as xp}from"document360-engine";var Br=3;function Vr(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 Gr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Yr(e,t){return t.map(n=>{let o=0;try{o=mp(hp(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function zr(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:
246
+ `+ln(`\u25A3 Preview \u2014 ${e.name}`)+`
247
+
248
+ `+Nr(e.text,n);case"note":return`
249
+ `+_d[e.tone](un(e.text));case"done":return`
250
+ `+(e.ok?X.magenta("\u2736 "):X.red("\u2736 "))+X.gray(`Cooked for ${fn(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${he(e.costUsd)}`:""))}}function Ea(e,t){return e.map(n=>Lr(n,t)).join(`
251
+ `)}import{resolveActiveProfile as Ld,loadTokens as Od,isExpired as Md,decodeJwtClaims as Na}from"document360-engine";function Ud(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Fe(e,t){try{let n=Ld(e,t),o=Od(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Md(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let c={...Na(o.idToken)??{},...Na(o.accessToken)??{}}.doc360_project_id;if(typeof c=="string"&&c&&c!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${Ud(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var mn=3;function Ur(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(`
252
+ `)}var Ia={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function hn(e){return e.filter(t=>t.path!==null&&t.status in Ia&&!t.link).map(t=>({path:t.path,label:Ia[t.status]}))}function go(e){return e.filter(t=>t.link).length}function Wr(e,t){try{let n=Yd(e,zd(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Kd(Wd(Fd(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 Xd(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 Ua(e){let t=[];e.length>1&&t.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(o=>o.path),indent:!1});let n=new Map;for(let o of e){let r=o.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),i=n.get(r);i?i.push(o):n.set(r,[o])}for(let o of[...n.keys()].sort()){let r=n.get(o).sort((i,c)=>i.path.localeCompare(c.path));t.push({kind:"category",label:`${Xd(o)} (${r.length})`,paths:r.map(i=>i.path),indent:!1});for(let i of r){let c=i.path.replace(/\\/g,"/").split("/").pop()??i.path;t.push({kind:"article",label:c,paths:[i.path],indent:!0,note:i.label})}}return t}function wo(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(`
253
+ `)}function Fr(e,t,n){let o=$=>t[$.index]?.paths.length??0,r=e.filter($=>$.ok),i=e.filter($=>!$.ok),c=e.reduce(($,T)=>$+o(T),0),p=r.reduce(($,T)=>$+o(T),0),y=n==="api"?`${he(e.reduce(($,T)=>$+T.costUsd,0))} total`:Qe(e.reduce(($,T)=>$+T.outputTokens,0)),h=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,k=$=>`${$} article${$===1?"":"s"}`,D=[];if(i.length===0)D.push(`Published ${k(c)} (${h}) successfully \xB7 ${y}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${k(c)} (${h}) \xB7 ${y}.`),D.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 $ of i)D.push(` \u2717 ${$.label}${$.error?` \u2014 ${$.error}`:""}`)}return D}async function Or(e,t){let n=qd(t),{model:o}=Vd(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${mn} agents at once) on ${o}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let r of Gd({cwd:e.cwd,partitions:n,promptFor:i=>wo(i.paths),concurrency:mn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:o}))if(r.type==="partition_status")r.status==="running"?console.log(f(` \u25B8 ${r.label} \u2014 publishing\u2026`)):r.status==="done"?console.log(N(` \u2713 ${r.label}`)):console.log(x(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let i=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of Fr(r.results,n,i))console.log(r.ok?N(p):L(p));let c=Wr(e.cwd,e.profileName);c&&console.log(f(c));try{let p=La(await _a({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}try{let p=Ma(await Oa({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}}}catch(r){console.log(x(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function yo(e,t,n){let o=Bd(e,n);if(o.length===0)return[];let r=new Set(hn((await Mr({cwd:e,profileName:t})).entries).map(i=>i.path));return o.filter(i=>r.has(i))}async function Wa(e,t){let n=Fe(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(x(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await yo(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(N("\u2713 All related articles are already published.")),{kind:"continue"}):await Or(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await Mr({cwd:t?.cwd??process.cwd()}),i=hn(r.entries),c=go(r.entries);if(c>0&&console.log(L(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),i.length===0){if(console.log(N(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let p=La(await _a({cwd:t.cwd,profileName:t.profileName}));p&&console.log(f(p));let y=Ma(await Oa({cwd:t.cwd,profileName:t.profileName}));y&&console.log(f(y))}catch{}return{kind:"continue"}}return t?await Or(t,i.map(p=>p.path)):{kind:"forward-to-agent",prompt:wo(i.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log(x(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let i=await Mr({cwd:t?.cwd??process.cwd()});r=hn(i.entries);let c=go(i.entries);c>0&&console.log(L(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`))}catch(i){return console.log(x(`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(N("\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(()=>Hd({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 Or(t,r.map(i=>i.path))}return{kind:"forward-to-agent",prompt:Ur(o),display:`/publish ${o}`}}async function gn(){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(`
254
+ `),display:"/audit"}}U();import{checkbox as Qd}from"@inquirer/prompts";import{inventoryRepo as Jd,readProjectConfig as Fa,writeProjectConfig as Zd}from"document360-engine";function Hr(e,t){let n=Fa(e);n&&(n.authoritativeSourceFiles=t,Zd(n,e))}function ko(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 Ha(e,t){let n=t?.cwd??process.cwd();if(!Fa(n))return console.log(x("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Jd(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(_("Recommended documentation scope (run /scope in the REPL to choose):"));for(let i of o)console.log(` ${i.recommended?"\u25C9":"\u25CB"} ${i.path} ${f(ko(i))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Qd({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(i=>({name:`${i.path} (${ko(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"};Hr(n,r),console.log(N(`\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"}}U();import{confirm as ip}from"@inquirer/prompts";import{applyPull as Br,computeSyncStatus as Ya,compareRemoteSources as sp,planPull as za,planImport as ap,applyImport as lp,establishBaselines as cp,rebaselineServerMeta as up,D360AuthError as dp}from"document360-engine";U();var qa=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:x,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:L,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:_,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:x,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:x,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:le,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:le,mark:"\xB7"}];function ep(e){return e.path?e.path:`${e.title??"(untitled)"} ${le(`[${e.articleId}]`)}`}function tp(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 bo(e,t){let n=[],o=e.entries.filter(k=>k.link);if(o.length>0){n.push(""),n.push(Pe("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let k of o)n.push(` ${L("~")} ${L(k.path??"")} ${le(`\u2192 "${k.link.title}"`)}`)}for(let k of qa){let D=e.entries.filter($=>$.status===k.status&&!(k.status==="untracked-local"&&$.link));if(D.length!==0){n.push(""),n.push(Pe(k.header));for(let $ of D)n.push(` ${k.paint(k.mark)} ${k.paint(ep($))}${$.detail?le(` (${$.detail})`):""}`)}}let r=e.counts["in-sync"]??0,i=e.entries.length;n.push("");let c={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},p=o.length,y=i===r?N("\u2713 everything up to date"):[r>0?N(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...qa.map(k=>{let D=(e.counts[k.status]??0)-(k.status==="untracked-local"?p:0);return D>0?`${D} ${c[k.status]}`:null})].filter(Boolean).join(le(" \xB7 ")),h=t!==void 0?` \xB7 synced in ${tp(t)}`:"";return n.push(y+le(` \xB7 ${i} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${h}`)),n}import{structuredPatch as np}from"diff";import Ba from"picocolors";var Va=80,op="\x1B[48;2;74;28;28m",rp="\x1B[48;2;24;66;24m",Ga="\x1B[49m",qr=e=>String(e).padStart(5);function mt(e,t,n){let o=$=>{let T=$.replace(/\r\n/g,`
255
+ `);return T.endsWith(`
256
+ `)||T===""?T:T+`
257
+ `},r=o(e),i=o(t);if(r===i)return null;let c=Math.max(20,n-10),p=np("a","b",r,i,"","",{context:3}),y=0,h=0,k=[];p.hunks.forEach(($,T)=>{T>0&&k.push(Ba.gray(" \u2026"));let P=$.oldStart,S=$.newStart;for(let I of $.lines){let O=I[0],z=I.slice(1).slice(0,c);O==="-"?(h++,k.push(`${op}${qr(P++)} - ${z}${Ga}`)):O==="+"?(y++,k.push(`${rp}${qr(S++)} + ${z}${Ga}`)):(k.push(Ba.gray(qr(S))+" "+z),P++,S++)}});let D=k.slice(0,Va);return{added:y,removed:h,lines:D,hidden:Math.max(0,k.length-Va)}}async function Ka(e,t){let n=Fe(t.cwd,t.profileName);if(!n.ok)return console.log(x(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await pp(t),{kind:"continue"};if(o==="--baseline")return await fp(t,e.filter(c=>c!=="--baseline")),{kind:"continue"};if(o==="--compare")return await mp(t),{kind:"continue"};if(o)return console.log(x(`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 hp(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let i=await Vr({cwd:t.cwd,profileName:t.profileName});for(let c of Gr(i))console.log(c.tone==="ok"?N(c.text):c.tone==="warn"?L(c.text):f(c.text));console.log("")}catch(r){r instanceof dp?console.log(x(r.message)):console.log(x(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Vr(e){let t=await Ya({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 za({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Br({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 ap({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});lp({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 $o=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,ht=e=>e===1?"":"s";function Gr(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${ht(e.pulled.length)} into local: ${$o(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${ht(e.imported.length)}: ${$o(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${ht(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${ht(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Take the portal copy: /pull <path> \xB7 keep yours: /publish <path>. (${$o(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${ht(e.failed.length)} failed: ${$o(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 pp(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Ya({cwd:e.cwd,profileName:e.profileName});for(let o of bo(n,Date.now()-t))console.log(o);console.log("")}async function fp(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 cp({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await up({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(N("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(N(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(N(`\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 mp(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: ${Pe(String(t.legacyCount))} \xB7 Manifest: ${Pe(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(N("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(x(`\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 hp(e,t){let n=t.replace(/\\/g,"/"),o=await za({cwd:e.cwd,profileName:e.profileName,relPath:n});console.log(""),console.log(`${_("\u25CF")} ${Pe(o.title)} ${le(`(${o.path})`)}`);for(let c of o.notes)console.log(L(` \u26A0 ${c}`));o.overwritesLocalChanges&&console.log(L(" \u26A0 This OVERWRITES local edits made since the last sync."));let r=mt(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.")),Br({cwd:e.cwd,profileName:e.profileName},o);return}console.log(le(` \u23BF Added ${r.added} line${ht(r.added)}, removed ${r.removed} line${ht(r.removed)}`));for(let c of r.lines)console.log(c);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>ip({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}Br({cwd:e.cwd,profileName:e.profileName},o),console.log(N(` \u2713 Pulled ${o.path} (sync base advanced).`))}U();import{statSync as gp}from"node:fs";import{resolve as wp}from"node:path";import{estimateBulkCost as yp,planPartitions as kp,readProjectConfig as bp,resolveModelForOperation as $p,runPartitioned as xp,trackedArticlePaths as vp}from"document360-engine";var Yr=3;function zr(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 Kr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Xr(e,t){return t.map(n=>{let o=0;try{o=gp(wp(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Qr(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:
258
258
  - 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.
259
259
  - 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.
260
260
  - 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.
261
261
  - Work only on these files:
262
262
  `+e.paths.map(t=>`- ${t}`).join(`
263
- `)}function Kr(e,t,n){let o=e.reduce((p,g)=>p+g.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: ${he(r)}\u2013${he(i)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Xr(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),i=e.filter(R=>!R.ok),c=e.reduce((R,S)=>R+o(S),0),p=r.reduce((R,S)=>R+o(S),0),g=e.reduce((R,S)=>R+S.costUsd,0),w=e.reduce((R,S)=>R+S.outputTokens,0),k=n==="api"?`${he(g)} total`:Qe(w),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=R=>`${R} article${R===1?"":"s"}`,P=[];if(i.length===0)P.push(`Converted ${x(c)} (${D}) successfully \xB7 ${k}.`);else{P.push(`Converted ${p}/${x(c)} (${D}) \xB7 ${k}.`),P.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let R of i)P.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return P}async function za(e,t){if(!wp(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Vr(e),r=xp(t.cwd,t.profileName);if(r.length===0)return console.log($("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let i=Gr(r,n);if(i.length===0)return console.log($(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=yp(i),p=`/convert${n?` --scope ${n}`:""} --run`,{model:g,forced:w}=kp(t.cwd,"light");if(!o){let k=gp({files:Yr(t.cwd,i),op:"convert",model:g});n&&console.log(f(`Scope: ${n} (${i.length} of ${r.length} tracked articles).`));for(let D of Kr(c,k,Br))console.log(D);return console.log(f(`Model: ${g}${w?" (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 ${c.length} partitions (\u2264${Br} agents at once) on ${g}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let k of bp({cwd:t.cwd,partitions:c,promptFor:zr,concurrency:Br,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:g}))if(k.type==="partition_status")k.status==="running"?console.log(f(` \u25B8 ${k.label} \u2014 converting\u2026`)):k.status==="done"?console.log(N(` \u2713 ${k.label}`)):console.log($(` \u2717 ${k.label}`));else if(k.type==="run_done"){console.log("");let D=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let x of Xr(k.results,c,D))console.log(k.ok?N(x):O(x))}}catch(k){console.log($(`Convert run failed: ${k.message}`))}return console.log(""),{kind:"continue"}}U();import{statSync as Qa}from"node:fs";import{resolve as Ja}from"node:path";import{estimateBulkCost as Ap,lintDocs as jp,planPartitions as Ep,readDocsPlan as Np,readProjectConfig as Za,DEFAULT_DOCS_DIR as Ip,resolveModelForOperation as _p,runPartitioned as Op,stampArticles as Lp,CONTENT_CAP_VERSION as Mp}from"document360-engine";import{readProjectConfig as $p,loadProfileMap as vp,resolveActiveProfile as Cp,desiredCategoryOrder as Rp,desiredArticleOrder as Pp,DEFAULT_DOCS_DIR as Tp}from"document360-engine";var Qr=e=>e.replace(/\\/g,"/"),Sp=e=>Qr(e).split("/").pop()??e;function Dp(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function Jr(e,t){try{let n=$p(e);if(!n)return[];let o=Cp(e,t),r=vp(e,o.name);if(!r)return[];let i=Qr(n.docsDir??Tp).replace(/\/+$/,""),c=new Map;for(let g of Pp(r))c.set(g.categoryPath,(c.get(g.categoryPath)??0)+1);let p=[];for(let g of Rp(r)){let w=Qr(g.path),k=w.startsWith(`${i}/`)?w.slice(i.length+1):w===i?"":w;k&&p.push({token:k,label:Dp(Sp(w)),count:c.get(g.path)??0})}return p}catch{return[]}}function Ka(e,t){let n=Jr(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 ko(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Xa(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 Up=3,Wp=8;function Zr(e){return e===void 0||!Number.isFinite(e)?Up:Math.max(1,Math.min(Math.floor(e),Wp))}function ei(e){let t,n,o=!1,r=!1,i,c=g=>{let w=Number(g);return g!==void 0&&Number.isFinite(w)?w:void 0};for(let g=0;g<e.length;g++){let w=e[g];if(w==="--preview"||w==="--dry-run")o=!0;else if(w==="--rewrite"||w==="--force")r=!0;else{if(w==="--run"||w==="--yes"||w==="--all")continue;w==="--scope"?t=e[++g]:w?.startsWith("--scope=")?t=w.slice(8):w==="--concurrency"?i=c(e[++g]):w?.startsWith("--concurrency=")?i=c(w.slice(14)):w&&!w.startsWith("--")&&(n=w)}}let p=g=>g?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:i,rewrite:r}}function Fp(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Hp(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function ti(e,t,n){return n.filter(o=>{try{return Qa(Ja(e,t,o)).size===0}catch{return!0}})}function ni(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let i=1;for(let c of o.get(r)?.sources??[])try{i+=Qa(Ja(e,c)).size}catch{}return{path:r,bytes:i}})}function oi(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.
263
+ `)}function Jr(e,t,n){let o=e.reduce((p,y)=>p+y.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: ${he(r)}\u2013${he(i)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Zr(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),i=e.filter(P=>!P.ok),c=e.reduce((P,S)=>P+o(S),0),p=r.reduce((P,S)=>P+o(S),0),y=e.reduce((P,S)=>P+S.costUsd,0),h=e.reduce((P,S)=>P+S.outputTokens,0),k=n==="api"?`${he(y)} total`:Qe(h),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,$=P=>`${P} article${P===1?"":"s"}`,T=[];if(i.length===0)T.push(`Converted ${$(c)} (${D}) successfully \xB7 ${k}.`);else{T.push(`Converted ${p}/${$(c)} (${D}) \xB7 ${k}.`),T.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let P of i)T.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return T}async function Xa(e,t){if(!bp(t.cwd))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=zr(e),r=vp(t.cwd,t.profileName);if(r.length===0)return console.log(x("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let i=Kr(r,n);if(i.length===0)return console.log(x(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=kp(i),p=`/convert${n?` --scope ${n}`:""} --run`,{model:y,forced:h}=$p(t.cwd,"light");if(!o){let k=yp({files:Xr(t.cwd,i),op:"convert",model:y});n&&console.log(f(`Scope: ${n} (${i.length} of ${r.length} tracked articles).`));for(let D of Jr(c,k,Yr))console.log(D);return console.log(f(`Model: ${y}${h?" (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 ${c.length} partitions (\u2264${Yr} agents at once) on ${y}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let k of xp({cwd:t.cwd,partitions:c,promptFor:Qr,concurrency:Yr,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:y}))if(k.type==="partition_status")k.status==="running"?console.log(f(` \u25B8 ${k.label} \u2014 converting\u2026`)):k.status==="done"?console.log(N(` \u2713 ${k.label}`)):console.log(x(` \u2717 ${k.label}`));else if(k.type==="run_done"){console.log("");let D=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let $ of Zr(k.results,c,D))console.log(k.ok?N($):L($))}}catch(k){console.log(x(`Convert run failed: ${k.message}`))}return console.log(""),{kind:"continue"}}U();import{statSync as Za}from"node:fs";import{resolve as el}from"node:path";import{estimateBulkCost as Ep,lintDocs as Np,planPartitions as Ip,readDocsPlan as _p,readProjectConfig as tl,DEFAULT_DOCS_DIR as Lp,resolveModelForOperation as Op,runPartitioned as Mp,stampArticles as Up,CONTENT_CAP_VERSION as Wp}from"document360-engine";import{readProjectConfig as Cp,loadProfileMap as Rp,resolveActiveProfile as Pp,desiredCategoryOrder as Tp,desiredArticleOrder as Sp,DEFAULT_DOCS_DIR as Dp}from"document360-engine";var ei=e=>e.replace(/\\/g,"/"),Ap=e=>ei(e).split("/").pop()??e;function jp(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function wn(e,t){try{let n=Cp(e);if(!n)return[];let o=Pp(e,t),r=Rp(e,o.name);if(!r)return[];let i=ei(n.docsDir??Dp).replace(/\/+$/,""),c=new Map;for(let y of Sp(r))c.set(y.categoryPath,(c.get(y.categoryPath)??0)+1);let p=[];for(let y of Tp(r)){let h=ei(y.path),k=h.startsWith(`${i}/`)?h.slice(i.length+1):h===i?"":h;k&&p.push({token:k,label:jp(Ap(h)),count:c.get(y.path)??0})}return p}catch{return[]}}function Qa(e,t){let n=wn(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 Je(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function Bt(e,t,n,o){let r=wn(e,o);if(r.length<=1)return[];let i=n.filter(h=>h.startsWith("--")).join(" "),c=i?` ${i}`:"",p=`/${t}${c} --all`.replace(/\s+/g," "),y=h=>t==="write"?`/write --scope ${h}${c}`:`/${t} ${h}${c}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((h,k)=>h+k.count,0)} articles). Pick a target:`,` ${p} (everything)`,...r.map(h=>` ${y(h.token)} (${h.label} \xB7 ${h.count} article${h.count===1?"":"s"})`)]}function xo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Ja(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 Fp=3,Hp=8;function ti(e){return e===void 0||!Number.isFinite(e)?Fp:Math.max(1,Math.min(Math.floor(e),Hp))}function ni(e){let t,n,o=!1,r=!1,i,c=y=>{let h=Number(y);return y!==void 0&&Number.isFinite(h)?h:void 0};for(let y=0;y<e.length;y++){let h=e[y];if(h==="--preview"||h==="--dry-run")o=!0;else if(h==="--rewrite"||h==="--force")r=!0;else{if(h==="--run"||h==="--yes"||h==="--all")continue;h==="--scope"?t=e[++y]:h?.startsWith("--scope=")?t=h.slice(8):h==="--concurrency"?i=c(e[++y]):h?.startsWith("--concurrency=")?i=c(h.slice(14)):h&&!h.startsWith("--")&&(n=h)}}let p=y=>y?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:i,rewrite:r}}function qp(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Bp(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function oi(e,t,n){return n.filter(o=>{try{return Za(el(e,t,o)).size===0}catch{return!0}})}function ri(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let i=1;for(let c of o.get(r)?.sources??[])try{i+=Za(el(e,c)).size}catch{}return{path:r,bytes:i}})}function ii(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.
264
264
  `:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
265
265
  - It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose and the source files it draws from (AGENT-PLAN.md has the same table).
266
266
  - Read ONLY those source files plus any shared context you genuinely need, and ground every statement in them. Never invent UI labels, routes, or behaviour \u2014 if the source does not say it, omit it.
@@ -269,79 +269,79 @@ ${i}${g}`).join("")}).join(`
269
269
  - 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.
270
270
  Articles:
271
271
  `+e.paths.map(r=>`- ${r}`).join(`
272
- `)}function ri(e,t,n){let o=e.reduce((c,p)=>c+p.paths.length,0),[r,i]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${he(r)}\u2013${he(i)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function ii(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),i=e.filter(R=>!R.ok),c=e.reduce((R,S)=>R+o(S),0),p=r.reduce((R,S)=>R+o(S),0),g=e.reduce((R,S)=>R+S.costUsd,0),w=e.reduce((R,S)=>R+S.outputTokens,0),k=n==="api"?`${he(g)} total`:Qe(w),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=R=>`${R} article${R===1?"":"s"}`,P=[];if(i.length===0)P.push(`Wrote ${x(c)} (${D}) successfully \xB7 ${k}.`),P.push("Next \u2014 push them to Document360:"),P.push("/publish --all"),P.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{P.push(`Wrote ${p}/${x(c)} (${D}) \xB7 ${k}.`),P.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let R of i)P.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return P}function si(e,t,n){try{let o=jp({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 ai(e,t,n){let o=(Za(e)?.docsDir??Ip).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Fp(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=Hp(r,n.scope);if(n.scope&&i.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:i,planCount:r.length,rewriting:!0};let c=ti(e,o,i);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"",g=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${g} --rewrite to regenerate them all.`}}return{docsDir:o,targets:c,planCount:r.length}}async function el(e,t){if(!Za(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};if(ko(e)){for(let L of Ka(t.cwd,t.profileName))console.log(f(L));return{kind:"continue"}}let n=Np(t.cwd);if(n.length===0)return console.log($("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:i,concurrency:c,rewrite:p}=ei(e),{docsDir:g,targets:w,reason:k,rewriting:D}=ai(t.cwd,n,{scope:o,path:r,rewrite:p});if(w.length===0)return console.log(k?O(k):O("Nothing to write.")),{kind:"continue"};D&&console.log(O(`--rewrite: regenerating ${w.length} already-written article${w.length===1?"":"s"} (overwrites them; git has your baseline).`));let x=Ep(w),P=Zr(c),{model:R,forced:S}=_p(t.cwd,"standard"),I=!!r;if(i&&!I){let L=Ap({files:ni(t.cwd,n,w),op:"write",model:R});o&&console.log(f(`Scope: ${o} (${w.length} pending).`));for(let K of ri(x,L,P))console.log(K);return console.log(f(`Model: ${R}${S?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${w.length} article${w.length===1?"":"s"} across ${x.length} partition${x.length===1?"":"s"} (\u2264${P} agents at once) on ${R}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let L of Op({cwd:t.cwd,partitions:x,promptFor:K=>oi(K,g,{rewrite:D||I}),concurrency:P,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:R}))if(L.type==="partition_status")L.status==="running"?console.log(f(` \u25B8 ${L.label} \u2014 writing\u2026`)):L.status==="done"?console.log(N(` \u2713 ${L.label}`)):console.log($(` \u2717 ${L.label}`));else if(L.type==="run_done"){console.log("");let K=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let Z of ii(L.results,x,K))console.log(L.ok?N(Z):O(Z));if(L.ok)try{Lp(t.cwd,w.map(Z=>`${g}/${Z}`),{writtenCap:Mp})}catch{}let ee=si(t.cwd,g,w);ee&&console.log(O(ee))}}catch(L){console.log($(`Write run failed: ${L.message}`))}return console.log(""),{kind:"continue"}}U();import{existsSync as qp,readdirSync as tl,statSync as nl}from"node:fs";import{join as ol}from"node:path";import{inputDir as Bp,readProjectConfig as Vp}from"document360-engine";var rl=/\.(md|markdown|pdf|txt)$/i;function li(e){let t=Bp(e);if(!qp(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of tl(t)){let i=ol(t,r),c=!1;try{c=nl(i).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=Gp(i);p>0&&n.push({name:r,docCount:p})}else rl.test(r)&&o++}return n.sort((r,i)=>r.name.localeCompare(i.name)),{features:n,looseDocs:o}}function Gp(e){let t=0;for(let n of tl(e))try{nl(ol(e,n)).isFile()&&rl.test(n)&&t++}catch{}return t}function ci(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 bo(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in .d360-writer/input/${e}/`:t?`the input docs in .d360-writer/input/ relevant to: "${t}"`:"the input docs in .d360-writer/input/"}.`,t&&!e?`Use "${t}" as the feature framing.`:"","","Follow the skill: (1) read those PRDs/specs as the primary source (intent, user-facing surface,","terminology, user stories, prerequisites); (2) locate and read the CODE that implements that surface","to pin exact UI strings/routes/states \u2014 never fabricate; flag anything the PRD claims that you","cannot find in source; (3) propose a tight feature-scoped article set (\u22483\u20135) and pin it to",".d360-writer/plan.json + AGENT-PLAN.md, with each article's `sources` listing BOTH the PRD file(s)","AND the grounding code files; (4) flag overlaps with existing articles (do not merge). Then stop and","offer /write. Do NOT write the articles in this turn."].filter(Boolean).join(`
273
- `)}var ui="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function il(e,t){let n=t?.cwd??process.cwd();if(!Vp(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=li(n);if(o.length===0&&r===0)return console.log(f(ui)),{kind:"continue"};let i=e.join(" ").trim();if(!i){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let g of o)console.log(` ${g.name} ${f(`(${g.docCount} doc${g.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:bo(p),display:p?`/draft ${p}`:"/draft"}}let c=ci(o,i);return{kind:"forward-to-agent",prompt:bo(c??"",c?void 0:i),display:`/draft ${i}`}}U();import{listOpenForDocs as Yp,readProjectConfig as zp}from"document360-engine";function di(e){try{return Yp(e).filter(t=>t.kind==="request").length}catch{return 0}}function pi(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function fi(e,t=!1){let n=["Run the document-handoff skill.",""];return e?n.push(`The builder hand-off (what was shipped this session): "${e}".`,"Treat this as the Stage 1 hand-off: ground it in the cited/changed code + the architecture brief,","then decide and APPLY the right doc action \u2014 a new section, a new article, an update to existing","article(s), or a retirement, or a mix. No fixed shape; pick the smallest set that keeps the docs correct."):n.push("No description was given \u2014 call d360_inbox and act on the OPEN `request` messages the builder left:","for each, run the document-handoff flow (ground \u2192 decide \u2192 apply) and mark the request `status: done`","with `resulting_articles` when finished."),n.push("","Draft only \u2014 do not publish. If you would create multiple new articles (a section), call","d360_estimate_cost and present the count + cost band first, then wait for the go-ahead."),t&&n.push("","After the drafts exist and the user confirms any bulk gate, publish the new/updated articles to","Document360 (the publish-to-d360 skill). On a production profile, respect the write-guard."),n.join(`
274
- `)}var mi="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 sl(e,t){let n=t?.cwd??process.cwd();if(!zp(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=pi(e);if(!r&&di(n)===0)return console.log(f(mi)),{kind:"continue"};let i=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:fi(r,o),display:i}}U();import{search as Kp}from"@inquirer/prompts";import{findByName as Xp,getSession as Qp,listSessions as Jp,relativeTime as ll}from"document360-engine";async function cl(e,t){let n=Jp(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=Xp(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),al(n),{kind:"continue"})}if(!process.stdin.isTTY)return al(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Kp({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async i=>{let c=(i??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${ll(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Qp(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function al(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${f(ll(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}U();import{renameSession as Zp}from"document360-engine";function hi(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 ul(e,t){let n=hi(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Zp(o,n)?console.log(N(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(N(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as dl,readProjectConfig as ef,writeProjectConfig as tf}from"document360-engine";U();function gi(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=ef(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 dl().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},tf(o,e),null):`Unknown environment "${r}". Known: ${dl().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function pl(e,t){let n=e[0];if(!n)return to(t.cwd),{kind:"continue"};if(n==="add"){let o=gi(t.cwd,e[1],e[2]);return o?(console.log($(o)),{kind:"continue"}):(console.log(N(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/login")}`),{kind:"continue"})}return no(t.cwd,n),oo(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}U();import{select as nf}from"@inquirer/prompts";import{readProjectConfig as of,readUserConfig as fl,resolveModelSetting as yi,writeUserConfig as ml}from"document360-engine";var Ie=[{value:null,label:"Auto",desc:"Sonnet (latest) \u2014 right-sized for docs work (recommended); heavier models only when you pin them"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus (latest) \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet (latest) \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku (latest) \xB7 fastest for quick answers"}];function xo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Ie.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function rf(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 fn(e,t){let n=()=>yi(e).model;if(t==="default"){let i=fl();return i.defaultModel?(delete i.defaultModel,ml(i),{lines:[`\u2713 Personal model override cleared \u2014 now: ${yi(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}}ml({...fl(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=of(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 hl(e,t){let n=e[0]?.trim();if(!n){let c=yi(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${_(c.model)}${c.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${rf(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=xo(c),g;try{g=await t.withPausedInput(()=>nf({message:`Select model (current: ${c.model}${c.source==="auto"?" \xB7 auto":""})`,default:Ie[p].value,choices:Ie.map((x,P)=>({name:`${x.label}${P===p?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:w,changed:k,effective:D}=fn(t.cwd,g??"default");for(let x of w)console.log(x.startsWith("\u26A0")?O(x):x.startsWith("\u2713")?N(x):f(x));return k&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:i}=fn(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?O(c):c.startsWith("\u2713")?N(c):f(c));return r&&await t.setModel(i),{kind:"continue"}}$o();async function xl(e,t){return await t.withPausedInput(()=>_t(t.cwd)),{kind:"clear"}}async function $l(e,t){return await t.withPausedInput(()=>Qn(t.cwd,t.profileName)),{kind:"clear"}}U();import{resolveActiveProfile as $f}from"document360-engine";async function vl(e,t){let n=!1;try{n=$f(t.cwd).production}catch{}return n?(console.log(O("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}U();var Cl=async(e,t)=>{try{await t.withPausedInput(()=>eo({}))}catch(n){console.log($(`Login failed: ${n.message}`))}return{kind:"continue"}};U();import{resolveActiveProfile as vf,clearTokens as Cf,clearProfileProject as Rf}from"document360-engine";async function Rl(e,t){let n;try{n=vf(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let o=Cf(n);return Rf(t.cwd,n),console.log(o?N(`\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 Pl}from"node:fs";import{isAbsolute as Pf,join as Tf,resolve as Sf}from"node:path";import{readProjectConfig as Df,screenshotPlaceholderIds as Af,DEFAULT_CAPTURE_DIR as jf,DEFAULT_OUTPUT_DIR as Ef}from"document360-engine";var Tl=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function ki(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Tl(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Tl(o),setup:t}:{mode:"single",id:o}}function bi(e,t){let n=Df(e),o=n?.captureDir??jf,r=n?.outputDir??Ef,i=(c,p)=>Pf(c)?Tf(c,p):Sf(e,c,p);return Af(e,{scope:t}).map(({id:c,file:p})=>{let g=Pl(i(r,`${c}.png`))?"captured":Pl(i(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:g}})}var Nf={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},If={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function xi(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(i=>i.file))].sort(),o=e.filter(i=>i.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let i of n){r.push(i);for(let c of e.filter(p=>p.file===i))r.push(` ${Nf[c.state]} ${c.id.padEnd(34)} ${If[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Sl(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(`
272
+ `)}function si(e,t,n){let o=e.reduce((c,p)=>c+p.paths.length,0),[r,i]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${he(r)}\u2013${he(i)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function ai(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),i=e.filter(P=>!P.ok),c=e.reduce((P,S)=>P+o(S),0),p=r.reduce((P,S)=>P+o(S),0),y=e.reduce((P,S)=>P+S.costUsd,0),h=e.reduce((P,S)=>P+S.outputTokens,0),k=n==="api"?`${he(y)} total`:Qe(h),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,$=P=>`${P} article${P===1?"":"s"}`,T=[];if(i.length===0)T.push(`Wrote ${$(c)} (${D}) successfully \xB7 ${k}.`),T.push("Next \u2014 push them to Document360:"),T.push("/publish --all"),T.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{T.push(`Wrote ${p}/${$(c)} (${D}) \xB7 ${k}.`),T.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let P of i)T.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return T}function li(e,t,n){try{let o=Np({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 ci(e,t,n){let o=(tl(e)?.docsDir??Lp).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=qp(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=Bp(r,n.scope);if(n.scope&&i.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:i,planCount:r.length,rewriting:!0};let c=oi(e,o,i);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"",y=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${y} --rewrite to regenerate them all.`}}return{docsDir:o,targets:c,planCount:r.length}}async function nl(e,t){if(!tl(t.cwd))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};if(xo(e)){for(let O of Qa(t.cwd,t.profileName))console.log(f(O));return{kind:"continue"}}if(Je("write",e)){let O=Bt(t.cwd,"write",e,t.profileName);if(O.length>0){for(let z of O)console.log(f(z));return{kind:"continue"}}}let n=_p(t.cwd);if(n.length===0)return console.log(x("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:i,concurrency:c,rewrite:p}=ni(e),{docsDir:y,targets:h,reason:k,rewriting:D}=ci(t.cwd,n,{scope:o,path:r,rewrite:p});if(h.length===0)return console.log(k?L(k):L("Nothing to write.")),{kind:"continue"};D&&console.log(L(`--rewrite: regenerating ${h.length} already-written article${h.length===1?"":"s"} (overwrites them; git has your baseline).`));let $=Ip(h),T=ti(c),{model:P,forced:S}=Op(t.cwd,"standard"),I=!!r;if(i&&!I){let O=Ep({files:ri(t.cwd,n,h),op:"write",model:P});o&&console.log(f(`Scope: ${o} (${h.length} pending).`));for(let z of si($,O,T))console.log(z);return console.log(f(`Model: ${P}${S?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${h.length} article${h.length===1?"":"s"} across ${$.length} partition${$.length===1?"":"s"} (\u2264${T} 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 O of Mp({cwd:t.cwd,partitions:$,promptFor:z=>ii(z,y,{rewrite:D||I}),concurrency:T,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:P}))if(O.type==="partition_status")O.status==="running"?console.log(f(` \u25B8 ${O.label} \u2014 writing\u2026`)):O.status==="done"?console.log(N(` \u2713 ${O.label}`)):console.log(x(` \u2717 ${O.label}`));else if(O.type==="run_done"){console.log("");let z=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let Q of ai(O.results,$,z))console.log(O.ok?N(Q):L(Q));if(O.ok)try{Up(t.cwd,h.map(Q=>`${y}/${Q}`),{writtenCap:Wp})}catch{}let ee=li(t.cwd,y,h);ee&&console.log(L(ee))}}catch(O){console.log(x(`Write run failed: ${O.message}`))}return console.log(""),{kind:"continue"}}U();import{existsSync as Vp,readdirSync as ol,statSync as rl}from"node:fs";import{join as il}from"node:path";import{inputDir as Gp,readProjectConfig as Yp}from"document360-engine";var sl=/\.(md|markdown|pdf|txt)$/i;function ui(e){let t=Gp(e);if(!Vp(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of ol(t)){let i=il(t,r),c=!1;try{c=rl(i).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=zp(i);p>0&&n.push({name:r,docCount:p})}else sl.test(r)&&o++}return n.sort((r,i)=>r.name.localeCompare(i.name)),{features:n,looseDocs:o}}function zp(e){let t=0;for(let n of ol(e))try{rl(il(e,n)).isFile()&&sl.test(n)&&t++}catch{}return t}function di(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 vo(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in .d360-writer/input/${e}/`:t?`the input docs in .d360-writer/input/ relevant to: "${t}"`:"the input docs in .d360-writer/input/"}.`,t&&!e?`Use "${t}" as the feature framing.`:"","","Follow the skill: (1) read those PRDs/specs as the primary source (intent, user-facing surface,","terminology, user stories, prerequisites); (2) locate and read the CODE that implements that surface","to pin exact UI strings/routes/states \u2014 never fabricate; flag anything the PRD claims that you","cannot find in source; (3) propose a tight feature-scoped article set (\u22483\u20135) and pin it to",".d360-writer/plan.json + AGENT-PLAN.md, with each article's `sources` listing BOTH the PRD file(s)","AND the grounding code files; (4) flag overlaps with existing articles (do not merge). Then stop and","offer /write. Do NOT write the articles in this turn."].filter(Boolean).join(`
273
+ `)}var pi="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function al(e,t){let n=t?.cwd??process.cwd();if(!Yp(n))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=ui(n);if(o.length===0&&r===0)return console.log(f(pi)),{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 y of o)console.log(` ${y.name} ${f(`(${y.docCount} doc${y.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:vo(p),display:p?`/draft ${p}`:"/draft"}}let c=di(o,i);return{kind:"forward-to-agent",prompt:vo(c??"",c?void 0:i),display:`/draft ${i}`}}U();import{listOpenForDocs as Kp,readProjectConfig as Xp}from"document360-engine";function fi(e){try{return Kp(e).filter(t=>t.kind==="request").length}catch{return 0}}function mi(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function hi(e,t=!1){let n=["Run the document-handoff skill.",""];return e?n.push(`The builder hand-off (what was shipped this session): "${e}".`,"Treat this as the Stage 1 hand-off: ground it in the cited/changed code + the architecture brief,","then decide and APPLY the right doc action \u2014 a new section, a new article, an update to existing","article(s), or a retirement, or a mix. No fixed shape; pick the smallest set that keeps the docs correct."):n.push("No description was given \u2014 call d360_inbox and act on the OPEN `request` messages the builder left:","for each, run the document-handoff flow (ground \u2192 decide \u2192 apply) and mark the request `status: done`","with `resulting_articles` when finished."),n.push("","Draft only \u2014 do not publish. If you would create multiple new articles (a section), call","d360_estimate_cost and present the count + cost band first, then wait for the go-ahead."),t&&n.push("","After the drafts exist and the user confirms any bulk gate, publish the new/updated articles to","Document360 (the publish-to-d360 skill). On a production profile, respect the write-guard."),n.join(`
274
+ `)}var gi="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 ll(e,t){let n=t?.cwd??process.cwd();if(!Xp(n))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=mi(e);if(!r&&fi(n)===0)return console.log(f(gi)),{kind:"continue"};let i=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:hi(r,o),display:i}}U();import{search as Qp}from"@inquirer/prompts";import{findByName as Jp,getSession as Zp,listSessions as ef,relativeTime as ul}from"document360-engine";async function dl(e,t){let n=ef(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=Jp(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(x(`No session matches "${o}".`)),cl(n),{kind:"continue"})}if(!process.stdin.isTTY)return cl(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Qp({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async i=>{let c=(i??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${ul(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Zp(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function cl(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${f(ul(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}U();import{renameSession as tf}from"document360-engine";function wi(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=wi(e.join(" "));if(!n)return console.log(x("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(tf(o,n)?console.log(N(`\u2713 Session renamed to "${n}"`)):console.log(x("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(N(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as fl,readProjectConfig as nf,writeProjectConfig as of}from"document360-engine";U();function yi(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=nf(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 fl().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},of(o,e),null):`Unknown environment "${r}". Known: ${fl().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function ml(e,t){let n=e[0];if(!n)return ro(t.cwd),{kind:"continue"};if(n==="add"){let o=yi(t.cwd,e[1],e[2]);return o?(console.log(x(o)),{kind:"continue"}):(console.log(N(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/login")}`),{kind:"continue"})}return io(t.cwd,n),so(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}U();import{select as rf}from"@inquirer/prompts";import{readProjectConfig as sf,readUserConfig as hl,resolveModelSetting as ki,writeUserConfig as gl}from"document360-engine";var Ie=[{value:null,label:"Auto",desc:"Sonnet (latest) \u2014 right-sized for docs work (recommended); heavier models only when you pin them"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus (latest) \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet (latest) \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku (latest) \xB7 fastest for quick answers"}];function Co(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Ie.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function af(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 yn(e,t){let n=()=>ki(e).model;if(t==="default"){let i=hl();return i.defaultModel?(delete i.defaultModel,gl(i),{lines:[`\u2713 Personal model override cleared \u2014 now: ${ki(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}}gl({...hl(),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 wl(e,t){let n=e[0]?.trim();if(!n){let c=ki(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${_(c.model)}${c.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${af(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Co(c),y;try{y=await t.withPausedInput(()=>rf({message:`Select model (current: ${c.model}${c.source==="auto"?" \xB7 auto":""})`,default:Ie[p].value,choices:Ie.map(($,T)=>({name:`${$.label}${T===p?" \u2714":""}`,value:$.value,description:$.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:h,changed:k,effective:D}=yn(t.cwd,y??"default");for(let $ of h)console.log($.startsWith("\u26A0")?L($):$.startsWith("\u2713")?N($):f($));return k&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:i}=yn(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?L(c):c.startsWith("\u2713")?N(c):f(c));return r&&await t.setModel(i),{kind:"continue"}}Ro();async function vl(e,t){return await t.withPausedInput(()=>Ot(t.cwd)),{kind:"clear"}}async function Cl(e,t){return await t.withPausedInput(()=>eo(t.cwd,t.profileName)),{kind:"clear"}}U();import{resolveActiveProfile as Cf}from"document360-engine";async function Rl(e,t){let n=!1;try{n=Cf(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"})}U();var Pl=async(e,t)=>{try{await t.withPausedInput(()=>oo({}))}catch(n){console.log(x(`Login failed: ${n.message}`))}return{kind:"continue"}};U();import{resolveActiveProfile as Rf,clearTokens as Pf,clearProfileProject as Tf}from"document360-engine";async function Tl(e,t){let n;try{n=Rf(t.cwd,t.profileName).name}catch(r){return console.log(x(r.message)),{kind:"continue"}}let o=Pf(n);return Tf(t.cwd,n),console.log(o?N(`\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 Sl}from"node:fs";import{isAbsolute as Sf,join as Df,resolve as Af}from"node:path";import{readProjectConfig as jf,screenshotPlaceholderIds as Ef,DEFAULT_CAPTURE_DIR as Nf,DEFAULT_OUTPUT_DIR as If}from"document360-engine";var Dl=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function $i(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Dl(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Dl(o),setup:t}:{mode:"single",id:o}}function xi(e,t){let n=jf(e),o=n?.captureDir??Nf,r=n?.outputDir??If,i=(c,p)=>Sf(c)?Df(c,p):Af(e,c,p);return Ef(e,{scope:t}).map(({id:c,file:p})=>{let y=Sl(i(r,`${c}.png`))?"captured":Sl(i(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:y}})}var _f={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Lf={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function vi(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(i=>i.file))].sort(),o=e.filter(i=>i.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let i of n){r.push(i);for(let c of e.filter(p=>p.file===i))r.push(` ${_f[c.state]} ${c.id.padEnd(34)} ${Lf[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Al(e){return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(t=>`- ${t}`).join(`
275
275
  `),"","For each: locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir); read the product source for","EXACT routes + stable data-testid selectors (never guess); enter the prepared context via","captureScope(); guard data prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts","(skip-with-TODO if a stable selector is missing). Do NOT run other skills. Report the specs you","wrote and any TODO data-testids."].join(`
276
- `)}async function vo(e,t){let n=ki(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of xi(bi(c,n.scope),n.scope))console.log(p);return{kind:"continue"}}if(n.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${n.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${n.id}.spec.ts. Report the spec path and any TODO data-testids or data to stage.`].join(`
276
+ `)}async function Po(e,t){let n=$i(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of vi(xi(c,n.scope),n.scope))console.log(p);return{kind:"continue"}}if(n.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${n.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${n.id}.spec.ts. Report the spec path and any TODO data-testids or data to stage.`].join(`
277
277
  `),display:`/screenshot ${n.id}`};let r=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${n.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${n.scope}`:"every <!-- SCREENSHOT --> placeholder across the docs tree (the configured docsDir)"}.`,"Follow that skill exactly for each: read the SCREENSHOT block; read the product source for EXACT routes","and stable data-testid selectors (never guess); enter the prepared context via captureScope(); guard data",`prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts.${n.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`].join(`
278
- `),i=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:i}}import{existsSync as _f,readFileSync as Of}from"node:fs";import{isAbsolute as Lf,join as Mf,resolve as Uf}from"node:path";import{readProjectConfig as Wf,DEFAULT_CAPTURE_DIR as Ff}from"document360-engine";async function hn(){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(`
279
- `),display:"/capture-setup"}}var Dl="-".repeat(64);function $i(e){let t=Ff;try{let k=Wf(e);k?.captureDir&&(t=k.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Lf(t)?Mf(t,"CAPTURE-TESTID-REQUESTS.json"):Uf(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!_f(n))return null;let o;try{let k=JSON.parse(Of(n,"utf8").replace(/^/,""));o=Array.isArray(k?.requests)?k.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(k=>k.file).filter(Boolean)).size,i=o.length,c=`${i} data-testid attribute${i===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,g=`${t}/CAPTURE-TESTID-REQUESTS.md`,w=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${c} requested across ${p}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",Dl,`Read ${g} and ${w}. They list ${c} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",Dl]}Ke();U();import{listOpenForDocs as Hf,readProjectConfig as qf}from"document360-engine";function vi(e){try{return Hf(e).length}catch{return 0}}function Ci(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape."," \u2022 answer (a reply to a question you asked; `re` = your question id) \u2192 fold the fact into the affected"," article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only \u2014 do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
280
- `)}async function Al(e,t){let n=t?.cwd??process.cwd();return qf(n)?vi(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:Ci(),display:"/inbox"}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{listOpenHints as Bf,listOpenForDocs as Vf,listOpenDirectives as Gf,readProjectConfig as Yf,computeSyncStatus as zf,planPull as Kf,applyPull as Xf,planImport as Qf,applyImport as Jf}from"document360-engine";function gn(e){let t=0,n=0,o=0,r=0;try{t=Bf(e).length}catch{}try{let i=Vf(e);n=i.filter(c=>c.kind==="request").length,o=i.filter(c=>c.kind==="answer").length}catch{}try{r=Gf(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function yn(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 Pi(e){return{publish:e.includes("--publish")}}function Ti({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, 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(`
281
- `)}var Zf={status:zf,plan:Kf,apply:Xf,planImport:Qf,applyImport:Jf};async function Si(e,t=Zf){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 Ri=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Co=e=>e===1?"":"s";function Di(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${Co(e.pulled.length)} into local: ${Ri(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Co(e.imported.length)} into local drafts: ${Ri(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Co(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Ri(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${Co(e.failed.length)} failed \u2014 left for /pull.`),t}async function jl(e,t){let n=t?.cwd??process.cwd();if(!Yf(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Fe(n,t?.profileName);if(!o.ok)return console.log($(o.reason)),{kind:"continue"};let{publish:r}=Pi(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let i=await Si({cwd:n,profileName:t?.profileName});for(let p of Di(i))console.log(p.startsWith("\u2713")?N(p):p.startsWith("\u2139")?f(p):O(p));let c=yn(gn(n));return console.log(f(c?`Catching up on ${c}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Ti({publish:r}),display:`/catch-up${r?" --publish":""}`}}U();import{spawn as em}from"node:child_process";var mt="document360-writer",Ro=`npm i -g ${mt}@latest`;async function Po(){let e=process.platform==="win32";return new Promise(t=>{try{let n=em(`npm i -g ${mt}@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 El(){return console.log(f(`Updating ${mt}\u2026`)),(await Po()).ok?console.log(N("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log($(`Update failed \u2014 run manually: ${Ro}`)),{kind:"continue"}}U();Ke();import{existsSync as Ai,rmSync as tm}from"node:fs";import{basename as Nl,resolve as ji}from"node:path";import{execFileSync as nm}from"node:child_process";import{input as om}from"@inquirer/prompts";import{readProjectConfig as rm,devHintsGuidePath as im}from"document360-engine";var sm=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],am=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),To=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Il=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function _l(e){let t=To(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Il(t)?!0:am.has(t)}function Ei(e){let t=null;try{t=rm(e)}catch{t=null}let n=new Set(sm);for(let o of[To(t?.docsDir),To(t?.captureDir),To(t?.outputDir)])o&&Il(o)&&n.add(o);return[...n].filter(o=>_l(o)&&Ai(ji(e,o)))}function Ni(e,t){let n=[],o=[];for(let r of t){if(!_l(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{tm(ji(e,r),{recursive:!0,force:!0}),n.push(r)}catch(i){o.push({path:r,error:i.message})}}return{removed:n,failed:o}}function Ol(e,t){try{return nm("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
282
- `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function lm(e){return Ol(e,".d360-writer/hints")}function cm(e){return Ol(e,".d360-writer/messages")}function Ii(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=lm(e),o=cm(e),r=Ai(ji(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: ${Nl(e)}`]}async function Ll(e,t){let n=Ei(t.cwd);for(let g of Ii(t.cwd,n))console.log(n.length===0?f(g):g);if(n.length===0)return{kind:"continue"};let o=Nl(t.cwd);if((await t.withPausedInput(()=>om({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(O("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let i=Ai(im(t.cwd)),{removed:c,failed:p}=Ni(t.cwd,n);console.log(N(`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`));for(let g of p)console.log($(` \u2717 ${g.path}: ${g.error}`));if(i){for(let g of lo())console.log(g);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"}}U();import{lintDocs as um}from"document360-engine";function So(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 _i(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(`
278
+ `),i=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:i}}import{existsSync as Of,readFileSync as Mf}from"node:fs";import{isAbsolute as Uf,join as Wf,resolve as Ff}from"node:path";import{readProjectConfig as Hf,DEFAULT_CAPTURE_DIR as qf}from"document360-engine";async function bn(){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(`
279
+ `),display:"/capture-setup"}}var jl="-".repeat(64);function Ci(e){let t=qf;try{let k=Hf(e);k?.captureDir&&(t=k.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Uf(t)?Wf(t,"CAPTURE-TESTID-REQUESTS.json"):Ff(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Of(n))return null;let o;try{let k=JSON.parse(Mf(n,"utf8").replace(/^/,""));o=Array.isArray(k?.requests)?k.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(k=>k.file).filter(Boolean)).size,i=o.length,c=`${i} data-testid attribute${i===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,y=`${t}/CAPTURE-TESTID-REQUESTS.md`,h=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${c} requested across ${p}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",jl,`Read ${y} and ${h}. They list ${c} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",jl]}Ke();U();import{listOpenForDocs as Bf,readProjectConfig as Vf}from"document360-engine";function Ri(e){try{return Bf(e).length}catch{return 0}}function Pi(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape."," \u2022 answer (a reply to a question you asked; `re` = your question id) \u2192 fold the fact into the affected"," article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only \u2014 do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
280
+ `)}async function El(e,t){let n=t?.cwd??process.cwd();return Vf(n)?Ri(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:Pi(),display:"/inbox"}:(console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{listOpenHints as Gf,listOpenForDocs as Yf,listOpenDirectives as zf,readProjectConfig as Kf,computeSyncStatus as Xf,planPull as Qf,applyPull as Jf,planImport as Zf,applyImport as em}from"document360-engine";function $n(e){let t=0,n=0,o=0,r=0;try{t=Gf(e).length}catch{}try{let i=Yf(e);n=i.filter(c=>c.kind==="request").length,o=i.filter(c=>c.kind==="answer").length}catch{}try{r=zf(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function xn(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 Si(e){return{publish:e.includes("--publish")}}function Di({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, 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(`
281
+ `)}var tm={status:Xf,plan:Qf,apply:Jf,planImport:Zf,applyImport:em};async function Ai(e,t=tm){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 Ti=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,To=e=>e===1?"":"s";function ji(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${To(e.pulled.length)} into local: ${Ti(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${To(e.imported.length)} into local drafts: ${Ti(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${To(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Ti(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${To(e.failed.length)} failed \u2014 left for /pull.`),t}async function Nl(e,t){let n=t?.cwd??process.cwd();if(!Kf(n))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Fe(n,t?.profileName);if(!o.ok)return console.log(x(o.reason)),{kind:"continue"};let{publish:r}=Si(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let i=await Ai({cwd:n,profileName:t?.profileName});for(let p of ji(i))console.log(p.startsWith("\u2713")?N(p):p.startsWith("\u2139")?f(p):L(p));let c=xn($n(n));return console.log(f(c?`Catching up on ${c}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Di({publish:r}),display:`/catch-up${r?" --publish":""}`}}U();import{spawn as nm}from"node:child_process";var gt="document360-writer",So=`npm i -g ${gt}@latest`;async function Do(){let e=process.platform==="win32";return new Promise(t=>{try{let n=nm(`npm i -g ${gt}@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 Il(){return console.log(f(`Updating ${gt}\u2026`)),(await Do()).ok?console.log(N("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(x(`Update failed \u2014 run manually: ${So}`)),{kind:"continue"}}U();Ke();import{existsSync as Ei,rmSync as om}from"node:fs";import{basename as _l,resolve as Ni}from"node:path";import{execFileSync as rm}from"node:child_process";import{input as im}from"@inquirer/prompts";import{readProjectConfig as sm,devHintsGuidePath as am}from"document360-engine";var lm=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],cm=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Ao=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Ll=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Ol(e){let t=Ao(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Ll(t)?!0:cm.has(t)}function Ii(e){let t=null;try{t=sm(e)}catch{t=null}let n=new Set(lm);for(let o of[Ao(t?.docsDir),Ao(t?.captureDir),Ao(t?.outputDir)])o&&Ll(o)&&n.add(o);return[...n].filter(o=>Ol(o)&&Ei(Ni(e,o)))}function _i(e,t){let n=[],o=[];for(let r of t){if(!Ol(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{om(Ni(e,r),{recursive:!0,force:!0}),n.push(r)}catch(i){o.push({path:r,error:i.message})}}return{removed:n,failed:o}}function Ml(e,t){try{return rm("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
282
+ `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function um(e){return Ml(e,".d360-writer/hints")}function dm(e){return Ml(e,".d360-writer/messages")}function Li(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=um(e),o=dm(e),r=Ei(Ni(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: ${_l(e)}`]}async function Ul(e,t){let n=Ii(t.cwd);for(let y of Li(t.cwd,n))console.log(n.length===0?f(y):y);if(n.length===0)return{kind:"continue"};let o=_l(t.cwd);if((await t.withPausedInput(()=>im({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let i=Ei(am(t.cwd)),{removed:c,failed:p}=_i(t.cwd,n);console.log(N(`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`));for(let y of p)console.log(x(` \u2717 ${y.path}: ${y.error}`));if(i){for(let y of po())console.log(y);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"}}U();import{lintDocs as pm}from"document360-engine";function jo(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 Oi(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(`
283
283
  `)).join(`
284
284
  `)].join(`
285
- `)}async function Ml(e,t){let n=e.includes("--fix"),o=e.find(c=>!c.startsWith("--")),r=o?` ${o}`:"",i=um({cwd:t.cwd,scope:o});if(n)return i.length===0?(console.log(N("\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:_i(i),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let c of So(i))console.log(i.length===0?N(c):O(c));return i.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}U();import{lintDocs as gm,loadStyleGuide as ym,buildReviewPrompt as wm,readProjectConfig as km,DEFAULT_DOCS_DIR as bm}from"document360-engine";U();import{readProjectConfig as dm,loadProfileMap as pm,resolveActiveProfile as fm,desiredCategoryOrder as mm,desiredArticleOrder as hm}from"document360-engine";function Ul(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Wl=e=>e.replace(/\\/g,"/").split("/").pop()??e;function wn(e,t){try{if(!dm(e))return[];let n=fm(e,t),o=pm(e,n.name);if(!o)return[];let r=new Map;for(let c of hm(o)){let p=r.get(c.categoryPath);p?p.push(c):r.set(c.categoryPath,[c])}let i=[];for(let c of mm(o)){i.push(Ul(Wl(c.path)));for(let p of(r.get(c.path)??[]).sort((g,w)=>g.order-w.order))i.push(` ${Ul(Wl(p.path))}`)}return i}catch{return[]}}async function Fl(e,t){let n=wn(t.cwd,t.profileName);if(n.length===0)return console.log(f("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(_("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Oi(e,t){let n=km(e);if(!n)return null;let o=(n.docsDir??bm).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),i=t.find(k=>!k.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),c=gm({cwd:e}),p=i?c.filter(k=>k.path===`${o}/${i}`||k.path.startsWith(`${o}/${i}/`)):c,g=i?"":wn(e).join(`
286
- `);return{prompt:wm({docsRoot:o,scope:i,styleGuide:ym(e),deterministicFindings:p,fix:r,structure:g||void 0}),display:`/review${i?` ${i}`:""}${r?" --fix":""}`}}async function Hl(e,t){let n=Oi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{readProjectConfig as xm}from"document360-engine";function Li(e,t){if(!xm(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(`
287
- `),display:`/reorder${n?` ${n}`:""}`}}async function ql(e,t){let n=Li(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{readProjectConfig as $m,writeProjectConfig as Bl,isAppType as vm,playbookSkillName as Cm,detectAppType as Vl}from"document360-engine";var Gl=["web","cli","service","library"],Rm=new Set(["web","cli"]);function Mi(e){return Rm.has(e)?`${Cm(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Do(e,t){let n=t.cwd,o=$m(n);if(!o)return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let i=o.appType??Vl(n);if(i){let c=o.appType?"set in config":"auto-detected";console.log(`${_("Genre:")} ${i} (${c}) \u2014 ${Mi(i)}`)}else console.log(O("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${Gl.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,...c}=o;Bl(c,n);let p=Vl(n);return console.log(N(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${Mi(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return vm(r)?(Bl({...o,appType:r},n),console.log(N(`\u2713 Genre set to ${r} \u2014 ${Mi(r)} (applies from your next command).`)),{kind:"continue"}):(console.log($(`Unknown genre "${r}". Choose one of: ${Gl.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}U();import{listRoadmap as Yl,roadmapProgress as zl,stampRoadmapDone as Pm}from"document360-engine";function Ui(e){let t=Yl(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=zl(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 Wi(e,t){if(!t.trim())return{ok:!1,line:"Usage: /roadmap done <step title>"};if(!Pm(e,t,{doneAt:new Date().toISOString()})){let r=Yl(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=zl(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 Kl(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Wi(n,e.slice(1).join(" ").trim());return console.log(r.ok?N(r.line):O(r.line)),{kind:"continue"}}let o=Ui(n);console.log(_(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?f(r):r);return{kind:"continue"}}var Xl={help:kr,"?":kr,clear:na,exit:br,quit:br,init:Rr,mcp:po,publish:Ma,audit:pn,scope:Wa,pull:Ya,convert:za,write:el,draft:il,document:sl,resume:cl,rename:ul,profile:pl,model:hl,doctor:mn,workspace:xl,project:$l,"allow-prod":vl,login:Cl,logout:Rl,screenshot:vo,"capture-setup":hn,devhints:da,inbox:Al,"catch-up":jl,update:El,reset:Ll,check:Ml,review:Hl,reorder:ql,structure:Fl,genre:Do,roadmap:Kl};function Ql(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}Ke();var Tm="Or just tell me what to write or update.",Sm='\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 be(e){return e===1?"":"s"}function Ao(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Fi(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var Dm={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 Am(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:Dm,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${be(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${be(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${be(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
288
- \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${be(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${be(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${be(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${be(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${be(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${be(n)}.`})}return t}function Jl(e,t){let n=t.filter(i=>i.bullet).map(i=>` \u2022 ${i.bullet}`),o=t[0],r=[];o.lead?r.push(Fi(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(" "),Tm].join(`
289
- `)}function kn(e){if(!e.ready)return{kind:"idle"};let t=Am(e);if(!e.hasDocs){let r=t[0];return r&&(r.lead?.kind==="cmd"||r.picker)?{kind:"recommend",rec:{note:Jl("\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:Sm,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${be(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${be(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${be(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:Jl("Welcome back \u2014 where your docs stand:",t),tone:n.tone??"info",lead:n.lead,picker:n.picker}}}import{existsSync as Hi,readdirSync as Bi}from"node:fs";import{spawnSync as jm}from"node:child_process";import{join as jo}from"node:path";import{readProjectConfig as ec,resolveActiveProfile as tc,loadTokens as Em,isExpired as Nm,loadProfileMap as nc,countLocalAhead as Im,readDocsPlan as _m,devHintsGuidePath as Om,DEFAULT_DOCS_DIR as qi,roadmapProgress as Lm}from"document360-engine";Ke();function Zl(e){try{return Bi(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Vi(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Zl(jo(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Zl(jo(e,o)))}function Gi(e,t){try{let n=ec(e);if(!n)return!1;let o=tc(e,t),r=nc(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let i=jo(e,(n.docsDir??qi).replace(/\/+$/,""));return!!(Hi(i)&&Bi(i).length>0||Hi(Om(e)))}catch{return!1}}function bn(e,t,n){try{let o=ec(e);if(!o)return null;let r=tc(e,t),i=Em(r.name),c=!!i&&(!Nm(i)||!!i.refreshToken),p=Gi(e,t)||!Vi(e,o.authoritativeSourceFiles),g=nc(e,r.name),w=g?Object.keys(g.articles).length:0,k=jo(e,(o.docsDir??qi).replace(/\/+$/,"")),D=!1;try{D=Hi(k)&&Bi(k).length>0}catch{}let x=0;if(g?.lastAnalyzedCommit)try{let ee=jm("git",["rev-list","--count",`${g.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});ee.status===0&&(x=parseInt((ee.stdout||"").trim(),10)||0)}catch{}let P=0;try{let ee=_m(e);if(ee.length>0){let Z=(o.docsDir??qi).replace(/\/+$/,"");P=ti(e,Z,ee.map(ue=>ue.path)).length}}catch{}let R=gn(e),S=yn({...R,directives:0}),I=Im(e,t),L=Se(e),K=Lm(e);return{ready:c&&p&&!n.claudeMissing,hasDocs:D,tracked:w,pendingText:S,directives:R.directives,behind:x,pendingWrites:P,localAhead:I,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:L.status,devhintsCompletedVersion:L.completedVersion,devhintsToVersion:se,builderStarted:We(e),genreUnknown:n.genreUnknown,roadmap:K}}catch{return null}}function Yi(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 Eo(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 c of Yi(`${i+1}. ${r.feature}`,76))o.push(n(c));o.push(n());for(let c of Yi(r.why,73))o.push(n(` ${c}`));o.push(n());for(let c of Yi(`\u2192 What to do: ${r.how}`,73))o.push(n(` ${c}`));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}U();var Mm={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"},rc=160,Ki=200,ic=40;function xe(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function oc(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),ic)}`);return t.length>4&&n.push("\u2026"),xe(n.join(", "),rc)}var Je=e=>typeof e=="string"&&e?e:null,zi=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Um(e){let t=Je(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 Wm(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Je(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=Je(t.title),r=zi(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)",zi(t.article_id)?`id ${zi(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",Je(t.name)?`"${xe(Je(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Je(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 No(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...i]=e.split("__"),c=i.join("__");if(r==="document360"){let w=Wm(c,t);if(w)return w}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:oc(t)}}let n=Mm[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:xe(o,rc)}:{title:e,sep:"",arg:oc(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,Ki))]}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),ic)}`);return n.length>0?[xe(n.join(" \xB7 "),Ki)]:null}return null}function qm(e){let t=Je(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Bm(e,t,n){switch(e){case"d360_create_article":{let o=qm(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=Je(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 Io(e,t=4,n,o){let r=e.replace(/\r\n/g,`
290
- `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=Bm(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let i=Hm(r)??r.split(`
291
- `);return{lines:i.slice(0,t).map(c=>xe(c,Ki)),hidden:Math.max(0,i.length-t)}}function _o(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Oo(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 Lo(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 uh=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function dh(e,t,n,o){if(uh.test(e))try{let r=lc(o),i=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=Oo(t,n),p=Lo(n);e.endsWith("publish_article")&&p&&console.log(_(` \u2B95 Live: ${p}`)),c&&i&&console.log(_(` \u2B95 Preview: ${_o(r.connection.portalUrl,i,c,r.project.languageCode??"en")}`))}catch{}}async function cc(e=process.cwd(),t="auto",n){let o=Gm(t);o.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${_("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${_('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),ph(e,n),o.kind==="subscription"&&(o.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,i=Xi({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=Vm({input:process.stdin,output:process.stdout}),g=[],w=null,k=!1;p.on("line",P=>{if(w){let R=w;w=null,R(P)}else g.push(P)}),p.on("close",()=>{if(k=!0,w){let P=w;w=null,P(null)}});function D(){return g.length>0?Promise.resolve(g.shift()):k?Promise.resolve(null):(process.stdout.write(_("> ")),new Promise(P=>{w=P}))}let x={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{i.close(),i=Xi({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setPendingName:P=>{c.pendingName=P},setModel:async P=>i.setModel(P),withPausedInput:async P=>{p.pause();try{return await P()}finally{p.resume()}}};try{for(;;){let P=await D();if(P===null)break;let R=P.trim();if(R){if(R.startsWith("/")){let S=Ql(R);if(!S)continue;let I=Xl[S.name];if(!I){console.log($(`Unknown command: /${S.name}`)),console.log(f("Type /help for the list."));continue}let L=await I(S.args,x);if(L.kind==="exit")break;if(L.kind==="clear"){x.restartAgent();continue}if(L.kind==="allow-prod"){r=!0,x.restartAgent(),console.log(N("\u2713 Production writes authorized for this session.")),console.log("");continue}if(L.kind==="resume"){i.close(),i=Xi({cwd:e,resume:L.uuid,profileName:n,allowProdWrites:r});let K=Ym(L.uuid);c={uuid:L.uuid,firstPrompt:K?.firstPrompt??null,titleFired:!0},ac(L.uuid),console.log(N(`\u2713 Resumed "${L.name}"`)),console.log("");continue}if(L.kind==="forward-to-agent"){c.firstPrompt||(c.firstPrompt=L.display??L.prompt);let K=/^\/(check|review)(?:\s+(?!--)(\S+))?\s+--fix\b/.exec(L.display??""),ee=K?lh(e,K[2]):[];if(await Qi(i,L.prompt,o,c,e),K)try{ah(e,ee,{reviewedCap:ch})}catch{}}else fh(e,n);continue}if(oh(R)){let S=rh(R);if(S){try{ih(e,{title:S,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}c.firstPrompt||(c.firstPrompt=R),await Qi(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${S}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${S}" and the article path(s) you wrote.`,o,c,e);continue}}c.firstPrompt||(c.firstPrompt=R),await Qi(i,R,o,c,e)}}}finally{i.close(),p.close()}}function ph(e,t){console.log(""),console.log(on("document360-writer")),console.log(f(` cwd: ${e}`));let n=Jm(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(mh(e,t)),!Zm(e))console.log(O(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{let o=!1;try{if(so(e),!We(e))for(let r of ao(e))console.log(O(` ${r}`))}catch{}try{let r=eh(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=sh(e);for(let i of Eo(r.applied))console.log(O(` ${i}`))}catch{}try{let r=bn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),i=r?kn(r):null;if(i?.kind==="recommend"&&i.rec.note){let c=i.rec.tone==="warn"?O:f;for(let p of i.rec.note.split(`
292
- `))console.log(c(` ${p}`));i.rec.picker&&console.log(_(` Pick one: ${i.rec.picker.options.map(p=>p.cmd).join(" \xB7 ")}`))}}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function fh(e,t){try{let n=bn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?kn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(f(` Next: ${Fi(o.rec.lead)}`))}catch{}}function mh(e,t){try{let n=lc(e,t),o=n.production?O(" \u26A0 PRODUCTION"):"",r=nh(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let i={...sc(r.idToken)??{},...sc(r.accessToken)??{}},c=i.email??i.preferred_username??"signed in";return th(r)&&!r.refreshToken?O(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function hh(){console.error(""),console.error(`Sign in with your Claude subscription: run ${_("claude")} once, then retry.`),console.error(` (No Claude Code? ${_("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${_("https://console.anthropic.com/settings/keys")}`)}function gh(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Xm({uuid:t,name:r??Km(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function yh(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Qm(o,t).then(r=>{r&&zm(n,r)}).catch(()=>{})}async function Qi(e,t,n,o,r){let i=new Map;for await(let c of e.send(t))wh(c,o,r,n,i)}function wh(e,t,n,o,r){switch(e.type){case"session":t.uuid||gh(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=No(e.name,e.input);i&&(process.stdout.write(`
293
-
294
- `),console.log(`${N("\u25CF")} ${Pe(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=pt(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let c=p=>p===1?"":"s";console.log(ae(` \u23BF Added ${i.added} line${c(i.added)}, removed ${i.removed} line${c(i.removed)}`));for(let p of i.lines)console.log(p);i.hidden>0&&console.log(f(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let c=Io(e.output,4,e.isError?void 0:i.name,i.input),p=e.isError?$:ae;c.lines.forEach((g,w)=>console.log(p((w===0?" \u23BF ":" ")+g))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||dh(i.name,i.input,e.output,n);break}case"result":process.stdout.write(`
295
- `),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&&(ac(t.uuid),t.titleFired||yh(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&hh();break}}import{render as Og}from"ink";import{resolveAuth as Lg}from"document360-engine";import{useCallback as V,useEffect as ve,useMemo as ns,useRef as J,useState as W}from"react";import{Box as ne,Text as A,useApp as Nh,useInput as Ih,useStdout as _h}from"ink";import{existsSync as $n,readFileSync as os,readdirSync as Oh}from"node:fs";import{basename as vn,isAbsolute as Lh,join as rs}from"node:path";import{createSession as Mc,classifyClaudeAuth as cs,CLAUDE_CODE_SETUP_HINT as Mh,loginPkce as Uh,toStoredTokens as Wh,saveTokens as Fh,getAccessToken as Hh,resolveActiveProfile as $e,resolveProjectId as qh,getArticle as Bh,decodeJwtClaims as Bt,isExpired as Ze,loadTokens as gt,clearTokens as Vh,clearProfileProject as Gh,setTitle as Yh,slugify as zh,touchSession as is,upsertSession as Kh,generateTitle as Uc,findByName as Xh,listSessions as Qh,renameSession as Jh,suggestNextAction as Zh,readProjectConfig as te,writeProjectConfig as Wc,resolveAndPersistAppType as eg,detectAppType as tg,resolveModelSetting as us,loadProfileMap as Fc,applyPull as ng,computeSyncStatus as Hc,lintDocs as qc,compareRemoteSources as og,planPull as rg,establishBaselines as ig,rebaselineServerMeta as sg,inventoryRepo as ag,knownEnvironments as lg,resolveEnvironment as cg,planPartitions as ss,partitionEvenly as ug,screenshotPlaceholderIds as dg,trackedArticlePaths as pg,runPartitioned as Go,estimateBulkCost as Bc,resolveModelForOperation as Yo,readDocsPlan as fg,checkForUpdate as mg,detectInstallKind as hg,isSelfUpdatable as gg,devHintsGuidePath as Vc,toolFeedbackPath as yg,reconcileToolFeedback as wg,reconcileUpgradeActions as kg,stampArticles as as,listArticleFiles as Gc,CONTENT_CAP_VERSION as ls,DEFAULT_DOCS_DIR as eu,setProfileProject as bg,writeCrashLog as xg,applyStructureOrder as Yc,orderSyncLine as zc,applyRelatedArticles as Kc,relatedSyncLine as Xc}from"document360-engine";Ke();import{spawn as uc}from"node:child_process";function kh(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function bh(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?uc([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):uc(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",c=>o(c===0)),r.stdin?.on("error",()=>o(!1));let i=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(i)}catch{o(!1)}})}async function dc(e){for(let[t,n]of kh())if(await bh(t,n,e))return!0;return!1}var xh=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Ji(e,t){if(t.closed)return e;let n=e.split(`
296
- `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let i=n[r];if(!t.cueSeen){xh.test(i)&&(t.cueSeen=!0);continue}let c=/^(\s{0,3})[-*•]\s+(.*)$/.exec(i);c?(n[r]=`${c[1]}${++t.num}. ${c[2]}`,o=!0):o&&i.trim()!==""&&/^\S/.test(i)&&(t.closed=!0)}return n.join(`
297
- `)}import{existsSync as $h,mkdirSync as vh,readFileSync as Ch,writeFileSync as Rh}from"node:fs";import{join as pc}from"node:path";import{writerDir as Ph}from"document360-engine";function fc(e){return pc(Ph(e),".sessions")}function mc(e,t){return pc(fc(e),`${t}.json`)}function hc(e,t,n){try{vh(fc(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Rh(mc(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Zi(e,t){try{let n=mc(e,t);if(!$h(n))return[];let o=JSON.parse(Ch(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Th=e=>`\x1B]0;${e}\x07`,Sh=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function gc(e){process.stdout.isTTY&&process.stdout.write(e)}function Ht(e){gc(Th(e))}function Mo(e){gc(Sh(e))}var Uo=["\xB7 "," \xB7"],Wo="\u{1F7E3}";$o();uo();var Fo=[{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:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path>] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Reports issues; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category>]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"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:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"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"}],yc={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/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 wc(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(yc[n])return yc[n];let o=Fo.find(r=>r.name===t);return o?o.desc:""}function kc(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Fo.filter(n=>n.name.startsWith(t))}function bc(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}U();import{Box as xc,Text as le}from"ink";import{jsx as ce,jsxs as Ho}from"react/jsx-runtime";function Dh({row:e}){switch(e.t){case"head":return ce(le,{color:F,bold:!0,children:e.s});case"text":return ce(le,{children:e.s});case"dim":return ce(le,{dimColor:!0,children:e.s});case"sub":return ce(le,{bold:!0,dimColor:!0,children:e.s});case"good":return ce(le,{color:"green",children:e.s});case"step":return Ho(le,{children:[ce(le,{color:F,children:`${e.n}. `}),e.s]});case"cmd":return Ho(le,{children:[" ",ce(le,{color:F,children:e.name.padEnd(20)}),ce(le,{dimColor:!0,children:e.s})]});case"gap":return ce(le,{children:" "})}}function $c({tab:e,width:t}){let n=Te[e]??Te[0],o=6+Te.reduce((i,c)=>i+c.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return Ho(xc,{flexDirection:"column",paddingX:1,children:[Ho(le,{children:[ce(le,{color:F,bold:!0,children:"Help "}),Te.map((i,c)=>c===e?ce(le,{color:"white",backgroundColor:F,bold:!0,children:` ${i.label} `},i.key):ce(le,{dimColor:!0,children:` ${i.label} `},i.key))]}),ce(le,{color:F,children:r}),ce(xc,{flexDirection:"column",marginTop:1,children:n.rows.map((i,c)=>ce(Dh,{row:i},c))}),ce(le,{dimColor:!0,children:`
298
- \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var Ah=/^(?:\d+[.)]|[-*•])\s+/;function vc(e,t,n=4){let o=new Set(t.map(i=>i.toLowerCase())),r=[];for(let i of e.split(`
299
- `)){let c=i.trim().replace(Ah,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let g=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!g||!o.has(g[1].toLowerCase()))continue;let w=`/${g[1].toLowerCase()}${g[2]?` ${g[2]}`:""}`;if(r.includes(w)||r.push(w),r.length>=n)break}return r}U();function xn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function He(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Cc(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var jh=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Rc(e,t,n){if(!jh.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 c=i.replace(/\\/g,"/");return r===c||r.endsWith(`/${c}`)})??null}function es(e){return e.replace(/^[\w.-]+\//,"")}var qo=16,Pc={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function ht(e){return typeof e=="string"?e:e.cmd}function Tc(e){return typeof e=="string"?void 0:e.desc}function ts(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Sc(e,t){let n=ts(t);return e.some(r=>ht(r).trim()===t.trim()||!!n&&ts(ht(r))===n)?e.filter(r=>ht(r).trim()!==t.trim()&&!(n&&ts(ht(r))===n)):[]}import{isDirectiveMention as $g,stripDirectiveMention as vg,appendDirective as Cg}from"document360-engine";var Eh=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Dc(e){return e.replace(/\r\n?/g,`
300
- `)}function Ac(e){return e.includes(`
301
- `)||e.length>200}function jc(e,t){let n=t.split(`
302
- `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Ec(e,t){return e.replace(Eh,n=>t.get(n)??n)}function Nc(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Bo(e,t){let n=Math.max(1,t),o=[],r=0;for(let i of e.split(`
303
- `)){if(i.length===0)o.push({start:r,end:r});else for(let c=0;c<i.length;c+=n)o.push({start:r+c,end:r+Math.min(c+n,i.length)});r+=i.length+1}return o.length>0?o:[{start:0,end:0}]}function Vo(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Ic(e,t,n){let o=Vo(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 _c(e,t,n){let o=e[Vo(e,t)];return n==="start"?o.start:o.end}function Oc(e,t,n){let o=Math.max(1,n),r=e.split(`
304
- `),i=0;for(let c=r.length-1;c>=0;c--){let p=r[c];if(i+=Math.max(1,Math.ceil(p.length/o)),i>=t){let g=i-t;return{text:[g>0?p.slice(g*o):p,...r.slice(c+1)].join(`
305
- `),truncated:c>0||g>0}}}return{text:e,truncated:!1}}function Lc(e){let t=!1,n=0,o=0;for(let r of e.split(`
306
- `)){let i=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&i<e.length&&(n=i+1),o=i+1}return n}import{Fragment as zo,jsx as j,jsxs as B}from"react/jsx-runtime";var Rg={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},Qc=` 1. /init \u2014 pick your Document360 environment & scaffold config
285
+ `)}async function Wl(e,t){let n=e.includes("--fix"),o=e.find(c=>!c.startsWith("--")),r=o?` ${o}`:"",i=pm({cwd:t.cwd,scope:o});if(n)return i.length===0?(console.log(N("\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:Oi(i),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let c of jo(i))console.log(i.length===0?N(c):L(c));return i.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}U();import{lintDocs as ym,loadStyleGuide as km,buildReviewPrompt as bm,readProjectConfig as $m,DEFAULT_DOCS_DIR as xm}from"document360-engine";U();import{readProjectConfig as fm,loadProfileMap as mm,resolveActiveProfile as hm,desiredCategoryOrder as gm,desiredArticleOrder as wm}from"document360-engine";function Fl(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Hl=e=>e.replace(/\\/g,"/").split("/").pop()??e;function vn(e,t){try{if(!fm(e))return[];let n=hm(e,t),o=mm(e,n.name);if(!o)return[];let r=new Map;for(let c of wm(o)){let p=r.get(c.categoryPath);p?p.push(c):r.set(c.categoryPath,[c])}let i=[];for(let c of gm(o)){i.push(Fl(Hl(c.path)));for(let p of(r.get(c.path)??[]).sort((y,h)=>y.order-h.order))i.push(` ${Fl(Hl(p.path))}`)}return i}catch{return[]}}async function ql(e,t){let n=vn(t.cwd,t.profileName);if(n.length===0)return console.log(f("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(_("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Mi(e,t){let n=$m(e);if(!n)return null;let o=(n.docsDir??xm).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),i=t.find(k=>!k.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),c=ym({cwd:e}),p=i?c.filter(k=>k.path===`${o}/${i}`||k.path.startsWith(`${o}/${i}/`)):c,y=i?"":vn(e).join(`
286
+ `);return{prompt:bm({docsRoot:o,scope:i,styleGuide:km(e),deterministicFindings:p,fix:r,structure:y||void 0}),display:`/review${i?` ${i}`:""}${r?" --fix":""}`}}async function Bl(e,t){if(Je("review",e)){let o=Bt(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=Mi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{readProjectConfig as vm}from"document360-engine";function Ui(e,t){if(!vm(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(`
287
+ `),display:`/reorder${n?` ${n}`:""}`}}async function Vl(e,t){if(Je("reorder",e)){let o=Bt(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=Ui(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{readProjectConfig as Cm,writeProjectConfig as Gl,isAppType as Rm,playbookSkillName as Pm,detectAppType as Yl}from"document360-engine";var zl=["web","cli","service","library"],Tm=new Set(["web","cli"]);function Wi(e){return Tm.has(e)?`${Pm(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Eo(e,t){let n=t.cwd,o=Cm(n);if(!o)return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let i=o.appType??Yl(n);if(i){let c=o.appType?"set in config":"auto-detected";console.log(`${_("Genre:")} ${i} (${c}) \u2014 ${Wi(i)}`)}else console.log(L("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${zl.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,...c}=o;Gl(c,n);let p=Yl(n);return console.log(N(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${Wi(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return Rm(r)?(Gl({...o,appType:r},n),console.log(N(`\u2713 Genre set to ${r} \u2014 ${Wi(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(x(`Unknown genre "${r}". Choose one of: ${zl.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}U();import{listRoadmap as Kl,roadmapProgress as Xl,stampRoadmapDone as Sm}from"document360-engine";function Fi(e){let t=Kl(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=Xl(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 Hi(e,t){if(!t.trim())return{ok:!1,line:"Usage: /roadmap done <step title>"};if(!Sm(e,t,{doneAt:new Date().toISOString()})){let r=Kl(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=Xl(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 Ql(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Hi(n,e.slice(1).join(" ").trim());return console.log(r.ok?N(r.line):L(r.line)),{kind:"continue"}}let o=Fi(n);console.log(_(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?f(r):r);return{kind:"continue"}}var Jl={help:xr,"?":xr,clear:ra,exit:vr,quit:vr,init:Sr,mcp:ho,publish:Wa,audit:gn,scope:Ha,pull:Ka,convert:Xa,write:nl,draft:al,document:ll,resume:dl,rename:pl,profile:ml,model:wl,doctor:kn,workspace:vl,project:Cl,"allow-prod":Rl,login:Pl,logout:Tl,screenshot:Po,"capture-setup":bn,devhints:fa,inbox:El,"catch-up":Nl,update:Il,reset:Ul,check:Wl,review:Bl,reorder:Vl,structure:ql,genre:Eo,roadmap:Ql};function Zl(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}Ke();var Dm="Or just tell me what to write or update.",Am='\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 be(e){return e===1?"":"s"}function No(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function qi(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var jm={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 Em(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:jm,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${be(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${be(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${be(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
288
+ \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${be(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${be(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${be(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${be(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${be(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${be(n)}.`})}return t}function ec(e,t){let n=t.filter(i=>i.bullet).map(i=>` \u2022 ${i.bullet}`),o=t[0],r=[];o.lead?r.push(qi(o.lead)):o.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let i of t.slice(1,3))i.follow&&r.push(i.follow);return[e,...n,r.join(" "),Dm].join(`
289
+ `)}function Cn(e){if(!e.ready)return{kind:"idle"};let t=Em(e);if(!e.hasDocs){let r=t[0];return r&&(r.lead?.kind==="cmd"||r.picker)?{kind:"recommend",rec:{note:ec("\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:Am,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${be(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${be(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${be(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:ec("Welcome back \u2014 where your docs stand:",t),tone:n.tone??"info",lead:n.lead,picker:n.picker}}}import{existsSync as Bi,readdirSync as Gi}from"node:fs";import{spawnSync as Nm}from"node:child_process";import{join as Io}from"node:path";import{readProjectConfig as nc,resolveActiveProfile as oc,loadTokens as Im,isExpired as _m,loadProfileMap as rc,countLocalAhead as Lm,readDocsPlan as Om,devHintsGuidePath as Mm,DEFAULT_DOCS_DIR as Vi,roadmapProgress as Um}from"document360-engine";Ke();function tc(e){try{return Gi(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Yi(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>tc(Io(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&tc(Io(e,o)))}function zi(e,t){try{let n=nc(e);if(!n)return!1;let o=oc(e,t),r=rc(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let i=Io(e,(n.docsDir??Vi).replace(/\/+$/,""));return!!(Bi(i)&&Gi(i).length>0||Bi(Mm(e)))}catch{return!1}}function Rn(e,t,n){try{let o=nc(e);if(!o)return null;let r=oc(e,t),i=Im(r.name),c=!!i&&(!_m(i)||!!i.refreshToken),p=zi(e,t)||!Yi(e,o.authoritativeSourceFiles),y=rc(e,r.name),h=y?Object.keys(y.articles).length:0,k=Io(e,(o.docsDir??Vi).replace(/\/+$/,"")),D=!1;try{D=Bi(k)&&Gi(k).length>0}catch{}let $=0;if(y?.lastAnalyzedCommit)try{let ee=Nm("git",["rev-list","--count",`${y.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});ee.status===0&&($=parseInt((ee.stdout||"").trim(),10)||0)}catch{}let T=0;try{let ee=Om(e);if(ee.length>0){let Q=(o.docsDir??Vi).replace(/\/+$/,"");T=oi(e,Q,ee.map(ae=>ae.path)).length}}catch{}let P=$n(e),S=xn({...P,directives:0}),I=Lm(e,t),O=Se(e),z=Um(e);return{ready:c&&p&&!n.claudeMissing,hasDocs:D,tracked:h,pendingText:S,directives:P.directives,behind:$,pendingWrites:T,localAhead:I,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:O.status,devhintsCompletedVersion:O.completedVersion,devhintsToVersion:se,builderStarted:We(e),genreUnknown:n.genreUnknown,roadmap:z}}catch{return null}}function Ki(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 _o(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 c of Ki(`${i+1}. ${r.feature}`,76))o.push(n(c));o.push(n());for(let c of Ki(r.why,73))o.push(n(` ${c}`));o.push(n());for(let c of Ki(`\u2192 What to do: ${r.how}`,73))o.push(n(` ${c}`));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}U();var Wm={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"},sc=160,Qi=200,ac=40;function $e(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function ic(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}: ${$e(typeof r=="string"?r:JSON.stringify(r),ac)}`);return t.length>4&&n.push("\u2026"),$e(n.join(", "),sc)}var Ze=e=>typeof e=="string"&&e?e:null,Xi=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Fm(e){let t=Ze(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(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=Ze(t.title);if(!o)return null;let r=Fm(t.local_path);return n("Create article",`"${$e(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Ze(t.title),r=Xi(t.article_id);return n("Update article",o?`"${$e(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Xi(t.article_id)?`id ${Xi(t.article_id)}\u2026`:null);case"d360_publish_article":{let o=t.version_number;return n("Publish article LIVE",typeof o=="number"?`v${o}`:null)}case"d360_unpublish_article":return n("Unpublish article",null);case"d360_create_category":return n("Create category",Ze(t.name)?`"${$e(Ze(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Ze(t.file_path);return n("Upload image",o?$e(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Lo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...i]=e.split("__"),c=i.join("__");if(r==="document360"){let h=Hm(c,t);if(h)return h}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:ic(t)}}let n=Wm[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:$e(o,sc)}:{title:e,sep:"",arg:ic(t)}}function qm(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 Bm(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(qm).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>$e(r,Qi))]}if(t!==null&&typeof t=="object"){let n=Object.entries(t).filter(([,o])=>o!==null&&(typeof o=="string"||typeof o=="number"||typeof o=="boolean")).slice(0,6).map(([o,r])=>`${o}: ${$e(String(r),ac)}`);return n.length>0?[$e(n.join(" \xB7 "),Qi)]:null}return null}function Vm(e){let t=Ze(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Gm(e,t,n){switch(e){case"d360_create_article":{let o=Vm(t?.local_path);return[`\u2713 draft created${o?` \xB7 ${o}`:""}`]}case"d360_update_article":return["\u2713 draft updated"];case"d360_fork_article":return["\u2713 forked to a new draft"];case"d360_publish_article":return["\u2713 PUBLISHED LIVE \u2014 visible to readers"];case"d360_unpublish_article":return["\u2713 reverted to draft (removed from readers)"];case"d360_create_category":{let o=Ze(t?.name);return[`\u2713 category created${o?` \xB7 "${o}"`:""}`]}case"d360_upload_drive_file":{let o=n.match(/https?:\/\/\S+/);return[`\u2713 uploaded${o?` \xB7 ${$e(o[0],120)}`:""}`]}default:return null}}function Oo(e,t=4,n,o){let r=e.replace(/\r\n/g,`
290
+ `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=Gm(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let i=Bm(r)??r.split(`
291
+ `);return{lines:i.slice(0,t).map(c=>$e(c,Qi)),hidden:Math.max(0,i.length-t)}}function Mo(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Uo(e,t){if(typeof e.article_id=="string"&&e.article_id)return e.article_id;try{let n=JSON.parse(t),r=(Array.isArray(n)?n[0]:n)?.id;return typeof r=="string"&&r?r:null}catch{return null}}function Wo(e){try{let t=JSON.parse(e),o=(Array.isArray(t)?t[0]:t)?.url;return typeof o=="string"&&/^https?:\/\//.test(o)?o:null}catch{return null}}var ph=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function fh(e,t,n,o){if(ph.test(e))try{let r=uc(o),i=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=Uo(t,n),p=Wo(n);e.endsWith("publish_article")&&p&&console.log(_(` \u2B95 Live: ${p}`)),c&&i&&console.log(_(` \u2B95 Preview: ${Mo(r.connection.portalUrl,i,c,r.project.languageCode??"en")}`))}catch{}}async function dc(e=process.cwd(),t="auto",n){let o=zm(t);o.kind==="none"&&(console.error(""),console.error(x("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${_("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${_('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),mh(e,n),o.kind==="subscription"&&(o.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,i=Ji({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=Ym({input:process.stdin,output:process.stdout}),y=[],h=null,k=!1;p.on("line",T=>{if(h){let P=h;h=null,P(T)}else y.push(T)}),p.on("close",()=>{if(k=!0,h){let T=h;h=null,T(null)}});function D(){return y.length>0?Promise.resolve(y.shift()):k?Promise.resolve(null):(process.stdout.write(_("> ")),new Promise(T=>{h=T}))}let $={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{i.close(),i=Ji({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setPendingName:T=>{c.pendingName=T},setModel:async T=>i.setModel(T),withPausedInput:async T=>{p.pause();try{return await T()}finally{p.resume()}}};try{for(;;){let T=await D();if(T===null)break;let P=T.trim();if(P){if(P.startsWith("/")){let S=Zl(P);if(!S)continue;let I=Jl[S.name];if(!I){console.log(x(`Unknown command: /${S.name}`)),console.log(f("Type /help for the list."));continue}let O=await I(S.args,$);if(O.kind==="exit")break;if(O.kind==="clear"){$.restartAgent();continue}if(O.kind==="allow-prod"){r=!0,$.restartAgent(),console.log(N("\u2713 Production writes authorized for this session.")),console.log("");continue}if(O.kind==="resume"){i.close(),i=Ji({cwd:e,resume:O.uuid,profileName:n,allowProdWrites:r});let z=Km(O.uuid);c={uuid:O.uuid,firstPrompt:z?.firstPrompt??null,titleFired:!0},cc(O.uuid),console.log(N(`\u2713 Resumed "${O.name}"`)),console.log("");continue}if(O.kind==="forward-to-agent"){c.firstPrompt||(c.firstPrompt=O.display??O.prompt);let z=(O.display??"").trim().split(/\s+/),ee=(z[0]==="/check"||z[0]==="/review")&&z.includes("--fix"),Q=z.slice(1).find(kt=>!kt.startsWith("--")),ae=ee?uh(e,Q):[];if(await Zi(i,O.prompt,o,c,e),ee)try{ch(e,ae,{reviewedCap:dh})}catch{}}else hh(e,n);continue}if(ih(P)){let S=sh(P);if(S){try{ah(e,{title:S,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}c.firstPrompt||(c.firstPrompt=P),await Zi(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${S}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${S}" and the article path(s) you wrote.`,o,c,e);continue}}c.firstPrompt||(c.firstPrompt=P),await Zi(i,P,o,c,e)}}}finally{i.close(),p.close()}}function mh(e,t){console.log(""),console.log(ln("document360-writer")),console.log(f(` cwd: ${e}`));let n=eh(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(gh(e,t)),!th(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(co(e),!We(e))for(let r of uo(e))console.log(L(` ${r}`))}catch{}try{let r=nh(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=lh(e);for(let i of _o(r.applied))console.log(L(` ${i}`))}catch{}try{let r=Rn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),i=r?Cn(r):null;if(i?.kind==="recommend"&&i.rec.note){let c=i.rec.tone==="warn"?L:f;for(let p of i.rec.note.split(`
292
+ `))console.log(c(` ${p}`));i.rec.picker&&console.log(_(` Pick one: ${i.rec.picker.options.map(p=>p.cmd).join(" \xB7 ")}`))}}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function hh(e,t){try{let n=Rn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Cn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(f(` Next: ${qi(o.rec.lead)}`))}catch{}}function gh(e,t){try{let n=uc(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=rh(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let i={...lc(r.idToken)??{},...lc(r.accessToken)??{}},c=i.email??i.preferred_username??"signed in";return oh(r)&&!r.refreshToken?L(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function wh(){console.error(""),console.error(`Sign in with your Claude subscription: run ${_("claude")} once, then retry.`),console.error(` (No Claude Code? ${_("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${_("https://console.anthropic.com/settings/keys")}`)}function yh(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Jm({uuid:t,name:r??Qm(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function kh(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Zm(o,t).then(r=>{r&&Xm(n,r)}).catch(()=>{})}async function Zi(e,t,n,o,r){let i=new Map;for await(let c of e.send(t))bh(c,o,r,n,i)}function bh(e,t,n,o,r){switch(e.type){case"session":t.uuid||yh(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=Lo(e.name,e.input);i&&(process.stdout.write(`
293
+
294
+ `),console.log(`${N("\u25CF")} ${Pe(i.title)}${i.arg!==null?le(`${i.sep}(${i.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=mt(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let c=p=>p===1?"":"s";console.log(le(` \u23BF Added ${i.added} line${c(i.added)}, removed ${i.removed} line${c(i.removed)}`));for(let p of i.lines)console.log(p);i.hidden>0&&console.log(f(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let c=Oo(e.output,4,e.isError?void 0:i.name,i.input),p=e.isError?x:le;c.lines.forEach((y,h)=>console.log(p((h===0?" \u23BF ":" ")+y))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||fh(i.name,i.input,e.output,n);break}case"result":process.stdout.write(`
295
+ `),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||kh(t,n));break;case"error":console.error(""),console.error(x(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&wh();break}}import{render as Mg}from"ink";import{resolveAuth as Ug}from"document360-engine";import{useCallback as V,useEffect as ve,useMemo as rs,useRef as Z,useState as W}from"react";import{Box as ne,Text as A,useApp as _h,useInput as Lh,useStdout as Oh}from"ink";import{existsSync as Tn,readFileSync as is,readdirSync as Mh}from"node:fs";import{basename as Sn,isAbsolute as Uh,join as ss}from"node:path";import{createSession as Wc,classifyClaudeAuth as ds,CLAUDE_CODE_SETUP_HINT as Wh,loginPkce as Fh,toStoredTokens as Hh,saveTokens as qh,getAccessToken as Bh,resolveActiveProfile as xe,resolveProjectId as Vh,getArticle as Gh,decodeJwtClaims as Yt,isExpired as et,loadTokens as yt,clearTokens as Yh,clearProfileProject as zh,setTitle as Kh,slugify as Xh,touchSession as as,upsertSession as Qh,generateTitle as Fc,findByName as Jh,listSessions as Zh,renameSession as eg,suggestNextAction as tg,readProjectConfig as te,writeProjectConfig as Hc,resolveAndPersistAppType as ng,detectAppType as og,resolveModelSetting as ps,loadProfileMap as qc,applyPull as rg,computeSyncStatus as Bc,lintDocs as Vc,compareRemoteSources as ig,planPull as sg,establishBaselines as ag,rebaselineServerMeta as lg,inventoryRepo as cg,knownEnvironments as ug,resolveEnvironment as dg,planPartitions as ls,partitionEvenly as pg,screenshotPlaceholderIds as fg,trackedArticlePaths as mg,runPartitioned as Ko,estimateBulkCost as Gc,resolveModelForOperation as Xo,readDocsPlan as hg,checkForUpdate as gg,detectInstallKind as wg,isSelfUpdatable as yg,devHintsGuidePath as Yc,toolFeedbackPath as kg,reconcileToolFeedback as bg,reconcileUpgradeActions as $g,stampArticles as cs,listArticleFiles as zc,CONTENT_CAP_VERSION as us,DEFAULT_DOCS_DIR as nu,setProfileProject as xg,writeCrashLog as vg,applyStructureOrder as Kc,orderSyncLine as Xc,applyRelatedArticles as Qc,relatedSyncLine as Jc}from"document360-engine";Ke();import{spawn as pc}from"node:child_process";function $h(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function xh(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",c=>o(c===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 fc(e){for(let[t,n]of $h())if(await xh(t,n,e))return!0;return!1}var vh=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function es(e,t){if(t.closed)return e;let n=e.split(`
296
+ `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let i=n[r];if(!t.cueSeen){vh.test(i)&&(t.cueSeen=!0);continue}let c=/^(\s{0,3})[-*•]\s+(.*)$/.exec(i);c?(n[r]=`${c[1]}${++t.num}. ${c[2]}`,o=!0):o&&i.trim()!==""&&/^\S/.test(i)&&(t.closed=!0)}return n.join(`
297
+ `)}import{existsSync as Ch,mkdirSync as Rh,readFileSync as Ph,writeFileSync as Th}from"node:fs";import{join as mc}from"node:path";import{writerDir as Sh}from"document360-engine";function hc(e){return mc(Sh(e),".sessions")}function gc(e,t){return mc(hc(e),`${t}.json`)}function wc(e,t,n){try{Rh(hc(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Th(gc(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function ts(e,t){try{let n=gc(e,t);if(!Ch(n))return[];let o=JSON.parse(Ph(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Dh=e=>`\x1B]0;${e}\x07`,Ah=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function yc(e){process.stdout.isTTY&&process.stdout.write(e)}function Vt(e){yc(Dh(e))}function Fo(e){yc(Ah(e))}var Ho=["\xB7 "," \xB7"],qo="\u{1F7E3}";Ro();mo();var Bo=[{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:"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:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"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"}],kc={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/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 bc(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(kc[n])return kc[n];let o=Bo.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 Bo.filter(n=>n.name.startsWith(t))}function xc(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}U();import{Box as vc,Text as ce}from"ink";import{jsx as ue,jsxs as Vo}from"react/jsx-runtime";function jh({row:e}){switch(e.t){case"head":return ue(ce,{color:F,bold:!0,children:e.s});case"text":return ue(ce,{children:e.s});case"dim":return ue(ce,{dimColor:!0,children:e.s});case"sub":return ue(ce,{bold:!0,dimColor:!0,children:e.s});case"good":return ue(ce,{color:"green",children:e.s});case"step":return Vo(ce,{children:[ue(ce,{color:F,children:`${e.n}. `}),e.s]});case"cmd":return Vo(ce,{children:[" ",ue(ce,{color:F,children:e.name.padEnd(20)}),ue(ce,{dimColor:!0,children:e.s})]});case"gap":return ue(ce,{children:" "})}}function Cc({tab:e,width:t}){let n=Te[e]??Te[0],o=6+Te.reduce((i,c)=>i+c.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return Vo(vc,{flexDirection:"column",paddingX:1,children:[Vo(ce,{children:[ue(ce,{color:F,bold:!0,children:"Help "}),Te.map((i,c)=>c===e?ue(ce,{color:"white",backgroundColor:F,bold:!0,children:` ${i.label} `},i.key):ue(ce,{dimColor:!0,children:` ${i.label} `},i.key))]}),ue(ce,{color:F,children:r}),ue(vc,{flexDirection:"column",marginTop:1,children:n.rows.map((i,c)=>ue(jh,{row:i},c))}),ue(ce,{dimColor:!0,children:`
298
+ \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var Eh=/^(?:\d+[.)]|[-*•])\s+/;function Rc(e,t,n=4){let o=new Set(t.map(i=>i.toLowerCase())),r=[];for(let i of e.split(`
299
+ `)){let c=i.trim().replace(Eh,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let y=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!y||!o.has(y[1].toLowerCase()))continue;let h=`/${y[1].toLowerCase()}${y[2]?` ${y[2]}`:""}`;if(r.includes(h)||r.push(h),r.length>=n)break}return r}U();function Pn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function He(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Pc(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Nh=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Tc(e,t,n){if(!Nh.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 c=i.replace(/\\/g,"/");return r===c||r.endsWith(`/${c}`)})??null}function ns(e){return e.replace(/^[\w.-]+\//,"")}var Go=16,Sc={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function wt(e){return typeof e=="string"?e:e.cmd}function Dc(e){return typeof e=="string"?void 0:e.desc}function os(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Ac(e,t){let n=os(t);return e.some(r=>wt(r).trim()===t.trim()||!!n&&os(wt(r))===n)?e.filter(r=>wt(r).trim()!==t.trim()&&!(n&&os(wt(r))===n)):[]}import{isDirectiveMention as Cg,stripDirectiveMention as Rg,appendDirective as Pg}from"document360-engine";var Ih=/\[Pasted text #\d+ \+\d+ lines?\]/g;function jc(e){return e.replace(/\r\n?/g,`
300
+ `)}function Ec(e){return e.includes(`
301
+ `)||e.length>200}function Nc(e,t){let n=t.split(`
302
+ `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Ic(e,t){return e.replace(Ih,n=>t.get(n)??n)}function _c(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Yo(e,t){let n=Math.max(1,t),o=[],r=0;for(let i of e.split(`
303
+ `)){if(i.length===0)o.push({start:r,end:r});else for(let c=0;c<i.length;c+=n)o.push({start:r+c,end:r+Math.min(c+n,i.length)});r+=i.length+1}return o.length>0?o:[{start:0,end:0}]}function zo(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Lc(e,t,n){let o=zo(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 Oc(e,t,n){let o=e[zo(e,t)];return n==="start"?o.start:o.end}function Mc(e,t,n){let o=Math.max(1,n),r=e.split(`
304
+ `),i=0;for(let c=r.length-1;c>=0;c--){let p=r[c];if(i+=Math.max(1,Math.ceil(p.length/o)),i>=t){let y=i-t;return{text:[y>0?p.slice(y*o):p,...r.slice(c+1)].join(`
305
+ `),truncated:c>0||y>0}}}return{text:e,truncated:!1}}function Uc(e){let t=!1,n=0,o=0;for(let r of e.split(`
306
+ `)){let i=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&i<e.length&&(n=i+1),o=i+1}return n}import{Fragment as Qo,jsx as j,jsxs as B}from"react/jsx-runtime";var Tg={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},Zc=` 1. /init \u2014 pick your Document360 environment & scaffold config
307
307
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
308
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Pg(e,t,n,o){let r=cs(n),i=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",c=us(e),p=te(e),g=(p?.docsDir??eu).replace(/\/+$/,""),w=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${g}/ + config`,k={version:t,claude:i,model:c.model,modelSource:Rg[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:w};if(p===null)return k;try{let D=$e(e,o);k.profile=D.name,k.apiUrl=D.connection.apiUrl,k.prod=D.production,k.project=D.project.projectName??D.project.projectId??"(chosen at login)";let x=gt(D.name);if(x){let P={...Bt(x.idToken)??{},...Bt(x.accessToken)??{}},R=P.email??P.preferred_username??"signed in";Ze(x)?x.refreshToken&&(k.who=R,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=R,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(x.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function Tg(e,t){try{let n=$e(e,t),o=gt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Bt(o.idToken)??{},...Bt(o.accessToken)??{}},i=r.email??r.preferred_username??"signed in";return Ze(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 Jc=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Vt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Sg="Ask me to write or update an article\u2026";function qt({ch:e,dim:t}){let[n,o]=W(!0);return ve(()=>{let r=setInterval(()=>o(i=>!i),530);return()=>clearInterval(r)},[]),j(A,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Dg=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Zc(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Ag=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function jg({startTime:e,chars:t}){let[n,o]=W(0);ve(()=>{let g=setInterval(()=>o(w=>w+1),120);return()=>clearInterval(g)},[]);let r=Vt[n%Vt.length],i=Jc[Math.floor(n/16)%Jc.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return B(ne,{children:[j(A,{color:F,children:` ${r} ${i}\u2026 `}),j(A,{color:"gray",children:`(${cn(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function Eg({text:e}){let[t,n]=W(0);return ve(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),j(ne,{paddingX:1,children:j(A,{color:F,children:`${Vt[t%Vt.length]} ${e}`})})}var Ng=12e4;function Ig({p:e}){let[t,n]=W(0);ve(()=>{let I=setInterval(()=>n(L=>L+1),150);return()=>clearInterval(I)},[]);let o=Vt[t%Vt.length],r=Math.floor((Date.now()-e.startedAt)/1e3),i=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),p=Date.now()-e.lastAt>=Ng,g=e.verb??"Converting",w=e.unit??"article",k=e.rows.reduce((I,L)=>I+L.items,0),D=g.toLowerCase(),x=e.rows,P=0;if(x.length>qo){let I=x.findIndex(K=>K.status==="active"||K.status==="pending"),L=Math.max(0,Math.min(I-2,x.length-qo));P=x.slice(0,L).filter(K=>K.status==="done").length,x=x.slice(L,L+qo)}let R=Math.min(40,Math.max(...x.map(I=>es(I.label).length),0)),S=I=>I==="failed"?"red":I==="active"?F:void 0;return B(ne,{flexDirection:"column",children:[B(ne,{children:[j(A,{color:F,children:` ${o} ${g} ${k} ${w}${k===1?"":"s"} `}),j(A,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${cn(r)} \xB7 esc to stop`})]}),P>0&&j(A,{dimColor:!0,children:` \u2714 +${P} done`}),x.map(I=>B(A,{color:S(I.status),dimColor:I.status==="done"||I.status==="pending",children:[` ${Pc[I.status]} ${es(I.label).padEnd(R)}`,I.status==="active"&&I.itemsDone!==void 0?` (${I.itemsDone}/${I.items} ${w}${I.items===1?"":"s"})`:I.status!=="pending"?` (${I.items} ${w}${I.items===1?"":"s"})`:"",I.status==="active"?` \u2190 ${D}\u2026`:""]},I.label)),p&&j(A,{color:"yellow",children:` \u26A0 no activity for ${cn(i)} \u2014 press esc to stop if it's wedged`})]})}var _g=10800*1e3;function tu({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Nh(),[i,c]=W(n),[p,g]=W(null),[w,k]=W({text:"",pos:0}),D=w.text,x=V(l=>{k(a=>{let s=typeof l=="function"?l(a.text):l;return{text:s,pos:s.length}})},[]),P=V(l=>{k(a=>({text:a.text.slice(0,a.pos)+l+a.text.slice(a.pos),pos:a.pos+l.length}))},[]),R=V(()=>{k(l=>{if(l.pos===0)return l;let a=l.text.slice(0,l.pos),s=Nc(a)??a.slice(0,-1);return{text:s+l.text.slice(l.pos),pos:s.length}})},[]),[S,I]=W(!1),[L,K]=W(!1),[ee,Z]=W(0),[ue,Cn]=W(null),[Ko,ms]=W(null),[et,tt]=W([]),Rn=J(!1),Xo=J(!1),[Qo,hs]=W(!1),Pn=J(0),[cu,Tn]=W(!1),[uu,Sn]=W(!1),[Jo,gs]=W(null),[du,yt]=W(0),nt=J(0),[Gt,wt]=W(0),[kt,Dn]=W(null),ys=J(new Map),pu=J(0),bt=J([]),Ce=J(null);Ce.current===null&&(Ce.current=Mc({cwd:e,profileName:i,allowProdWrites:!1}));let _e=J({uuid:null,firstPrompt:null,titleFired:!1}),An=J(new Map),xt=J(!1),Zo=J([]),Ae=J([]),jn=J(null),[ws,ot]=W(null),er=J(null),[rt,it]=W(null),[Oe,$t]=W(null),[Le,vt]=W(null),[pe,Ct]=W(null),[ge,st]=W(null),[qe,Rt]=W(null),[Me,Pt]=W(null),[ks,Yt]=W(null),[ye,at]=W(null),[fe,Tt]=W(null),[bs,tr]=W([]),lt=J([]),zt=J(!1),Re=J(null),[En,oe]=W(null),[xs,$s]=W(null),Nn=J(!1),In=J(null),Kt=J(null),[we,ct]=W(null),[_n,Xt]=W(null),nr=!!(Le||pe||ge||qe||Me||ye||fe||we||_n),[vs,St]=W(0),[Cs,Dt]=W(0),[fu,Rs]=W(0),or=ns(()=>{try{let l=us(e);return l.source==="auto"?`${l.model} (auto)`:l.model}catch{return null}},[e,fu]),{stdout:je}=_h(),[,mu]=W(0),Ps=J(`${je.columns??80}x${je.rows??24}`),Be=V(()=>Math.max(20,(je.columns??80)-1),[je]),d=V(l=>{bt.current.push(l),console.log(Nr(l,Be()))},[Be]),me=V((l,a)=>{Pn.current++,Cn(l),ms(a??null)},[]),Ve=V(()=>{Pn.current++,Cn(null),ms(null)},[]),z=V(l=>me(l,Ao({kind:"cmd",cmd:l,reason:""})),[me]),Ts=V((l,a)=>{!a?.silent&&l.note&&d({kind:"note",tone:l.tone,text:l.note}),l.picker&&(tt(l.picker.options.map(s=>({cmd:s.cmd,desc:s.desc}))),Yt(l.picker.title)),l.lead&&me(l.lead.kind==="cmd"?l.lead.cmd:l.lead.text,Ao(l.lead))},[d,me]),At=V((l,a,s="info")=>{l&&d({kind:"note",tone:s,text:l}),a&&me(a.kind==="cmd"?a.cmd:a.text,Ao(a))},[d,me]),[Qt,rr]=W(null),[hu,Ss]=W(!1),jt=V(l=>{rr(l),Ss(!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]),ir=J(!1),sr=V(async()=>{try{if(ir.current||!gg(hg())||te(e)?.mode==="engineer")return;let l=await mg({pkg:mt,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;ir.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${mt} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),Sn(!0),(await Po().finally(()=>Sn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),z("/exit"),gs(l.latest)):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${Ro}`})}catch{}},[e,o,d,z]),ar=V(l=>{let a=Fe(e,i);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),Kt.current=l,z("/login"),!1)},[e,i,d,z]),[lr,cr]=W(null),Jt=J(!0),On=J(0),Zt=J(0);ve(()=>{let l=setInterval(()=>{if(Jt.current){On.current=0,Zt.current=0;return}if(!S)try{if(!$n(Vc(e)))return;if(Se(e).status==="current"){Jt.current=!0,On.current=0,Zt.current=0,d({kind:"note",tone:"ok",text:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs."}),rr(null),me("write the docs for this repo");return}On.current+=1;let a=On.current;if((a===4||a%15===0)&&Zt.current<3){Zt.current+=1;let s=Zt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:We(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${s}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${s}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,S,d]),ve(()=>{let l=ws??vn(e);if(!S){Mo(0),Ht(`${Wo} ${l}`);return}Mo(3);let a=0;Ht(`${Uo[0]} ${l}`);let s=setInterval(()=>{a=(a+1)%Uo.length,Ht(`${Uo[a]} ${l}`)},400);return()=>clearInterval(s)},[S,e,ws]),ve(()=>()=>Mo(0),[]);let en=V(l=>{let a=bn(e,i,{claudeMissing:cs(t).state==="missing",allowAutoAudit:l,genreUnknown:Xo.current});return a?kn(a):{kind:"idle"}},[e,i,t]);ve(()=>{let l=performance.now(),a=[],s=(y,v)=>{let T=performance.now();try{return v()}finally{let Y=Math.round(performance.now()-T);Y>=80&&a.push(`${y}: ${Y}ms`)}};d({kind:"banner",info:s("banner",()=>Pg(e,o,t,i))});let h=cs(t).state==="missing";if(h&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
309
- ${Mh}
308
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Sg(e,t,n,o){let r=ds(n),i=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",c=ps(e),p=te(e),y=(p?.docsDir??nu).replace(/\/+$/,""),h=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${y}/ + config`,k={version:t,claude:i,model:c.model,modelSource:Tg[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:h};if(p===null)return k;try{let D=xe(e,o);k.profile=D.name,k.apiUrl=D.connection.apiUrl,k.prod=D.production,k.project=D.project.projectName??D.project.projectId??"(chosen at login)";let $=yt(D.name);if($){let T={...Yt($.idToken)??{},...Yt($.accessToken)??{}},P=T.email??T.preferred_username??"signed in";et($)?$.refreshToken&&(k.who=P,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=P,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date($.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function Dg(e,t){try{let n=xe(e,t),o=yt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Yt(o.idToken)??{},...Yt(o.accessToken)??{}},i=r.email??r.preferred_username??"signed in";return et(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 eu=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],zt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ag="Ask me to write or update an article\u2026";function Gt({ch:e,dim:t}){let[n,o]=W(!0);return ve(()=>{let r=setInterval(()=>o(i=>!i),530);return()=>clearInterval(r)},[]),j(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 tu(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Eg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ng({startTime:e,chars:t}){let[n,o]=W(0);ve(()=>{let y=setInterval(()=>o(h=>h+1),120);return()=>clearInterval(y)},[]);let r=zt[n%zt.length],i=eu[Math.floor(n/16)%eu.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return B(ne,{children:[j(A,{color:F,children:` ${r} ${i}\u2026 `}),j(A,{color:"gray",children:`(${fn(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function Ig({text:e}){let[t,n]=W(0);return ve(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),j(ne,{paddingX:1,children:j(A,{color:F,children:`${zt[t%zt.length]} ${e}`})})}var _g=12e4;function Lg({p:e}){let[t,n]=W(0);ve(()=>{let I=setInterval(()=>n(O=>O+1),150);return()=>clearInterval(I)},[]);let o=zt[t%zt.length],r=Math.floor((Date.now()-e.startedAt)/1e3),i=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),p=Date.now()-e.lastAt>=_g,y=e.verb??"Converting",h=e.unit??"article",k=e.rows.reduce((I,O)=>I+O.items,0),D=y.toLowerCase(),$=e.rows,T=0;if($.length>Go){let I=$.findIndex(z=>z.status==="active"||z.status==="pending"),O=Math.max(0,Math.min(I-2,$.length-Go));T=$.slice(0,O).filter(z=>z.status==="done").length,$=$.slice(O,O+Go)}let P=Math.min(40,Math.max(...$.map(I=>ns(I.label).length),0)),S=I=>I==="failed"?"red":I==="active"?F:void 0;return B(ne,{flexDirection:"column",children:[B(ne,{children:[j(A,{color:F,children:` ${o} ${y} ${k} ${h}${k===1?"":"s"} `}),j(A,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${fn(r)} \xB7 esc to stop`})]}),T>0&&j(A,{dimColor:!0,children:` \u2714 +${T} done`}),$.map(I=>B(A,{color:S(I.status),dimColor:I.status==="done"||I.status==="pending",children:[` ${Sc[I.status]} ${ns(I.label).padEnd(P)}`,I.status==="active"&&I.itemsDone!==void 0?` (${I.itemsDone}/${I.items} ${h}${I.items===1?"":"s"})`:I.status!=="pending"?` (${I.items} ${h}${I.items===1?"":"s"})`:"",I.status==="active"?` \u2190 ${D}\u2026`:""]},I.label)),p&&j(A,{color:"yellow",children:` \u26A0 no activity for ${fn(i)} \u2014 press esc to stop if it's wedged`})]})}var Og=10800*1e3;function ou({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=_h(),[i,c]=W(n),[p,y]=W(null),[h,k]=W({text:"",pos:0}),D=h.text,$=V(l=>{k(a=>{let s=typeof l=="function"?l(a.text):l;return{text:s,pos:s.length}})},[]),T=V(l=>{k(a=>({text:a.text.slice(0,a.pos)+l+a.text.slice(a.pos),pos:a.pos+l.length}))},[]),P=V(()=>{k(l=>{if(l.pos===0)return l;let a=l.text.slice(0,l.pos),s=_c(a)??a.slice(0,-1);return{text:s+l.text.slice(l.pos),pos:s.length}})},[]),[S,I]=W(!1),[O,z]=W(!1),[ee,Q]=W(0),[ae,kt]=W(null),[Jo,gs]=W(null),[tt,nt]=W([]),Dn=Z(!1),Zo=Z(!1),[er,ws]=W(!1),An=Z(0),[du,jn]=W(!1),[pu,En]=W(!1),[tr,ys]=W(null),[fu,bt]=W(0),ot=Z(0),[Kt,$t]=W(0),[xt,Nn]=W(null),ks=Z(new Map),mu=Z(0),vt=Z([]),Ce=Z(null);Ce.current===null&&(Ce.current=Wc({cwd:e,profileName:i,allowProdWrites:!1}));let _e=Z({uuid:null,firstPrompt:null,titleFired:!1}),In=Z(new Map),Ct=Z(!1),nr=Z([]),Ae=Z([]),_n=Z(null),[bs,rt]=W(null),or=Z(null),[it,st]=W(null),[Le,Rt]=W(null),[Oe,Pt]=W(null),[pe,Tt]=W(null),[ge,at]=W(null),[qe,St]=W(null),[Me,lt]=W(null),[$s,Xt]=W(null),[we,ct]=W(null),[fe,Dt]=W(null),[xs,rr]=W([]),ut=Z([]),Qt=Z(!1),Re=Z(null),[Ln,oe]=W(null),[vs,Cs]=W(null),On=Z(!1),Mn=Z(null),Jt=Z(null),[ye,dt]=W(null),[Un,Zt]=W(null),ir=!!(Oe||pe||ge||qe||Me||we||fe||ye||Un),[Rs,At]=W(0),[Ps,jt]=W(0),[hu,Ts]=W(0),sr=rs(()=>{try{let l=ps(e);return l.source==="auto"?`${l.model} (auto)`:l.model}catch{return null}},[e,hu]),{stdout:je}=Oh(),[,gu]=W(0),Ss=Z(`${je.columns??80}x${je.rows??24}`),Be=V(()=>Math.max(20,(je.columns??80)-1),[je]),d=V(l=>{vt.current.push(l),console.log(Lr(l,Be()))},[Be]),me=V((l,a)=>{An.current++,kt(l),gs(a??null)},[]),Ve=V(()=>{An.current++,kt(null),gs(null)},[]),K=V(l=>me(l,No({kind:"cmd",cmd:l,reason:""})),[me]),Ds=V((l,a)=>{!a?.silent&&l.note&&d({kind:"note",tone:l.tone,text:l.note}),l.picker&&(nt(l.picker.options.map(s=>({cmd:s.cmd,desc:s.desc}))),Xt(l.picker.title)),l.lead&&me(l.lead.kind==="cmd"?l.lead.cmd:l.lead.text,No(l.lead))},[d,me]),Et=V((l,a,s="info")=>{l&&d({kind:"note",tone:s,text:l}),a&&me(a.kind==="cmd"?a.cmd:a.text,No(a))},[d,me]),[en,ar]=W(null),[wu,As]=W(!1),Nt=V(l=>{ar(l),As(!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]),lr=Z(!1),cr=V(async()=>{try{if(lr.current||!yg(wg())||te(e)?.mode==="engineer")return;let l=await gg({pkg:gt,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;lr.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${gt} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),En(!0),(await Do().finally(()=>En(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),K("/exit"),ys(l.latest)):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${So}`})}catch{}},[e,o,d,K]),ur=V(l=>{let a=Fe(e,i);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),Jt.current=l,K("/login"),!1)},[e,i,d,K]),[dr,pr]=W(null),tn=Z(!0),Wn=Z(0),nn=Z(0);ve(()=>{let l=setInterval(()=>{if(tn.current){Wn.current=0,nn.current=0;return}if(!S)try{if(!Tn(Yc(e)))return;if(Se(e).status==="current"){tn.current=!0,Wn.current=0,nn.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."}),ar(null),me("write the docs for this repo");return}Wn.current+=1;let a=Wn.current;if((a===4||a%15===0)&&nn.current<3){nn.current+=1;let s=nn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:We(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${s}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${s}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,S,d]),ve(()=>{let l=bs??Sn(e);if(!S){Fo(0),Vt(`${qo} ${l}`);return}Fo(3);let a=0;Vt(`${Ho[0]} ${l}`);let s=setInterval(()=>{a=(a+1)%Ho.length,Vt(`${Ho[a]} ${l}`)},400);return()=>clearInterval(s)},[S,e,bs]),ve(()=>()=>Fo(0),[]);let on=V(l=>{let a=Rn(e,i,{claudeMissing:ds(t).state==="missing",allowAutoAudit:l,genreUnknown:Zo.current});return a?Cn(a):{kind:"idle"}},[e,i,t]);ve(()=>{let l=performance.now(),a=[],s=(w,v)=>{let R=performance.now();try{return v()}finally{let Y=Math.round(performance.now()-R);Y>=80&&a.push(`${w}: ${Y}ms`)}};d({kind:"banner",info:s("banner",()=>Sg(e,o,t,i))});let g=ds(t).state==="missing";if(g&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
309
+ ${Wh}
310
310
  Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!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:
311
- ${Qc}`}),z(h?"/doctor":"/init");return}h&&z("/doctor");try{let y=$e(e,i),v=gt(y.name);v&&Ze(v)&&v.refreshToken?Hh({profile:y.name,connection:y.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),Z(T=>T+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),z("/login")}):(!v||Ze(v))&&(d({kind:"note",tone:"warn",text:`Profile "${y.name}" is not signed in \u2014 sign in with /login.`}),z("/login"))}catch{}try{let y=te(e),v=$e(e,i),T=gt(v.name);y&&T&&!Ze(T)&&Vi(e,y.authoritativeSourceFiles)&&!Gi(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."}),z("/scope"))}catch{}try{let y=s("resolve-genre",()=>eg(e));y.persisted&&y.appType?d({kind:"note",tone:"ok",text:`\u2713 Detected a ${y.appType} app \u2014 enabled the ${y.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):y.source==="unknown"&&te(e)&&(Xo.current=!0)}catch{}let u=Se(e);try{if(s("reconcile-devhints",()=>so(e)),u.status!=="current"&&!We(e)){let y=ao(e);y.length&&(d({kind:"note",tone:"warn",text:y.join(`
312
- `)}),jt(dt()),Jt.current=!1)}}catch{}try{let y=s("reconcile-feedback",()=>wg(e));y.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${y.archived} resolved item${y.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${y.open>0?`; ${y.open} still open`:""}.`})}catch{}try{let y=s("upgrade-actions",()=>kg(e));y.applied.length>0&&d({kind:"note",tone:"warn",text:Eo(y.applied).join(`
313
- `)})}catch{}let m=s("ready-decision",()=>en(!0));m.kind==="autoAudit"?(d({kind:"note",tone:"info",text:m.note}),pn().then(y=>{y.kind==="forward-to-agent"&&y.prompt&&ie(y.prompt,{display:y.display,quietUser:!0})})):m.kind==="recommend"&&Ts(m.rec);let b=Math.round(performance.now()-l);b>=800&&xg({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(`
311
+ ${Zc}`}),K(g?"/doctor":"/init");return}g&&K("/doctor");try{let w=xe(e,i),v=yt(w.name);v&&et(v)&&v.refreshToken?Bh({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),Q(R=>R+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),K("/login")}):(!v||et(v))&&(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),v=xe(e,i),R=yt(v.name);w&&R&&!et(R)&&Yi(e,w.authoritativeSourceFiles)&&!zi(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",()=>ng(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)&&(Zo.current=!0)}catch{}let u=Se(e);try{if(s("reconcile-devhints",()=>co(e)),u.status!=="current"&&!We(e)){let w=uo(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
312
+ `)}),Nt(ft()),tn.current=!1)}}catch{}try{let w=s("reconcile-feedback",()=>bg(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",()=>$g(e));w.applied.length>0&&d({kind:"note",tone:"warn",text:_o(w.applied).join(`
313
+ `)})}catch{}let m=s("ready-decision",()=>on(!0));m.kind==="autoAudit"?(d({kind:"note",tone:"info",text:m.note}),gn().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&ie(w.prompt,{display:w.display,quietUser:!0})})):m.kind==="recommend"&&Ds(m.rec);let b=Math.round(performance.now()-l);b>=800&&vg({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(`
314
314
  `):"no single phase \u226580ms"}
315
- cwd: ${e}`}),sr()},[]),ve(()=>{let l=setInterval(()=>{sr()},_g);return()=>clearInterval(l)},[sr]),ve(()=>{if(S||Qo||Rn.current||ue!==null||et.length>0||D!==""||Qt!==null||Ae.current.length>0||jn.current||nr)return;let l=en(!1);l.kind==="recommend"&&(l.rec.lead||l.rec.picker)&&Ts(l.rec,{silent:!0})},[S,ue,et,D,Qt,nr,ee,en,Qo]),ve(()=>{let l=null,a=null,s=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let h=`${je.columns??80}x${je.rows??24}`;h!==Ps.current&&(Ps.current=h,mu(u=>u+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Aa(bt.current,Be())+"\x1B[?2026l")},80))},400)};return je.on("resize",s),()=>{l&&clearTimeout(l),a&&clearTimeout(a),je.off("resize",s)}},[je,Be]);let Ee=Math.max(20,(je.columns??80)-1),Ds=ns(()=>Tg(e,i),[e,i,ee]),ur=(()=>{if(uu)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Jo!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Jo?` v${Jo}`:""}\u2026`,isSetup:!0};if(Qt)return hu?{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(Ae.current.length>0)return{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let l=te(e);if(!l)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let a=rs(e,(l.docsDir??eu).replace(/\/+$/,"")),s=(()=>{try{return $n(a)&&Oh(a).length>0}catch{return!1}})();try{let h=$e(e,i),u=gt(h.name);if(!(!!u&&!(Ze(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:Sg,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),tn=kc(D),As=tn.length>0&&!S,dr=p!==null?Oc(p,8,Ee):null,Ln=ye?ye.paths.filter(l=>!ye.query||l.toLowerCase().includes(ye.query.toLowerCase())).slice(0,8):[],Mn=we?we.sessions.filter(l=>{let a=we.query.toLowerCase();return!a||l.name.toLowerCase().includes(a)||l.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],ke=V((l,a)=>{Ce.current?.close(),Ce.current=Mc({cwd:e,resume:l,profileName:a??i,allowProdWrites:xt.current}),l||(_e.current={uuid:null,firstPrompt:null,titleFired:!1},ot(null)),St(0),Dt(0)},[e,i]),js=V((l,a,s)=>{if(Dg.test(l))try{let h=$e(e,i),u=typeof a.project_id=="string"&&a.project_id||h.project.projectId,m=Oo(a,s),b=[],y=Lo(s);l.endsWith("publish_article")&&y&&b.push(`Live: ${y}`),m&&u&&b.push(`Preview: ${_o(h.connection.portalUrl,u,m,h.project.languageCode??"en")}`),b.length>0&&d({kind:"link",lines:b})}catch{}},[e,i,d]),ie=V(async(l,a)=>{Tn(!0),Rn.current=!1,Ve(),tt([]),Yt(null),rr(null),cr(null);let s=Pn.current;a?.quietUser||d({kind:"user",text:a?.echoDisplay&&a.display?a.display:l});let h=_e.current;h.firstPrompt||(h.firstPrompt=a?.display??l),nt.current=Date.now(),yt(0),I(!0),An.current.clear();let u="",m=!1,b=!1,y="",v={num:0,closed:!1,cueSeen:!1},T=null,Y=()=>{T||(T=setTimeout(()=>{T=null,g(y.length>0?y:null)},60))},H=()=>{T&&clearTimeout(T),T=null,g(null)},M=()=>{if(y.trim()){let C=Ji(y.trimEnd(),v);d({kind:"assistant",text:C})}y="",H()};try{for await(let C of Ce.current.send(l))if(C.type==="session"){if(!h.uuid){h.uuid=C.sessionId;let E=new Date().toISOString(),q=er.current,Q=q??zh(h.firstPrompt??"session");Kh({uuid:C.sessionId,name:Q,renamed:!!q,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:E,updatedAt:E}),ot(Q),er.current=null}}else if(C.type==="text"){y+=C.delta,u+=C.delta;let E=Lc(y);if(E>0){let q=y.slice(0,E).trimEnd();q&&d({kind:"assistant",text:Ji(q,v)}),y=y.slice(E)}Y(),yt(q=>q+C.delta.length)}else if(C.type==="tool"){m=!0;let E=No(C.name,C.input);E&&(M(),d({kind:"tool",title:E.title,sep:E.sep,arg:E.arg}),An.current.set(C.id,{name:C.name,input:C.input}))}else if(C.type==="article_diff"){let E=pt(C.oldContent,C.newContent,Be());E&&(M(),d({kind:"diff",added:E.added,removed:E.removed,lines:E.lines,hidden:E.hidden}))}else if(C.type==="tool_result"){C.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(C.output)&&(Nn.current=!0);let E=An.current.get(C.id);if(E){An.current.delete(C.id),M();let q=Io(C.output,4,C.isError?void 0:E.name,E.input);d({kind:"tool-result",lines:q.lines,hidden:q.hidden,isError:C.isError}),C.isError||js(E.name,E.input,C.output)}}else if(C.type==="result"){if(M(),St(E=>E+C.outputTokens),Dt(E=>E+C.costUsd),d({kind:"done",seconds:Math.round((Date.now()-nt.current)/1e3),tokens:C.outputTokens,costUsd:C.costUsd,ok:C.ok}),!b&&!m&&!u.trim()&&!zt.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)."}),C.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let E=yg(e);if($n(E)){let q=os(E,"utf8").trim();q&&(cr(q),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(C.ok&&v.cueSeen)hs(!0),tt([]);else{let E=C.ok?vc(u,Fo.map(q=>q.name)):[];if(E.length>0)z(E[0]);else if(C.ok&&u.trim()){let q=en(!1);q.kind==="recommend"&&(q.rec.lead||q.rec.picker)||Zh(l,u,e).then(Q=>{Q&&Pn.current===s&&me(Q)}).catch(()=>{})}}if(h.uuid&&(is(h.uuid),!h.titleFired)){h.titleFired=!0;let E=h.uuid,q=h.firstPrompt;q&&Uc(q,e).then(Q=>{Q&&(Yh(E,Q),ot(Q))}).catch(()=>{})}}else C.type==="error"&&(M(),b=!0,C.kind==="auth"&&(Nn.current=!0),d({kind:"note",text:`agent error: ${C.message}`,tone:"error"}))}finally{I(!1),H(),Z(C=>C+1),_e.current.uuid&&hc(e,_e.current.uuid,bt.current),Nn.current&&(Nn.current=!1,In.current=a?.display??l,me("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")),zt.current&&(zt.current=!1,lt.current.length>0&&(d({kind:"note",tone:"info",text:`(${lt.current.length} queued message(s) discarded)`}),lt.current=[],tr([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,js,Be,me,z,Ve,en]),Un=V(async l=>{let a=ss(l),s=Yo(e,"standard");nt.current=Date.now(),yt(0),I(!0);let h=new AbortController;Re.current=h,oe({verb:"Publishing",total:a.length,done:0,active:[],rows:xn(a),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${a.length} partition${a.length===1?"":"s"} (\u2264${un} agents at once) on ${s.model}\u2026 (esc to stop)`});try{for await(let u of Go({cwd:e,partitions:a,promptFor:m=>mo(m.paths),concurrency:un,profileName:i,allowProdWrites:xt.current,model:s.model,signal:h.signal}))if(u.type==="partition_status")u.status==="running"?oe(m=>m&&{...m,active:[...m.active,u.label],rows:He(m.rows,u.label,"active"),lastAt:Date.now()}):oe(m=>m&&{...m,active:m.active.filter(b=>b!==u.label),done:m.done+1,rows:He(m.rows,u.label,u.status==="done"?"done":"failed"),lastAt:Date.now()});else if(u.type==="partition_event")oe(m=>{if(!m)return m;let b={...m,lastAt:Date.now()};return u.event.type==="tool"?b.tools=m.tools+1:u.event.type==="text"&&(b.chars=m.chars+u.event.delta.length),b});else if(u.type==="run_done"){Dt(v=>v+u.totalCostUsd),St(v=>v+u.results.reduce((T,Y)=>T+Y.outputTokens,0));let m=u.aborted?"Stopped. ":"",b=t.kind==="api"?"api":"subscription";d({kind:"note",tone:u.aborted?"warn":u.ok?"ok":"warn",text:m+Mr(u.results,a,b).join(`
316
- `)});let y=Lr(e,i);if(y&&d({kind:"note",tone:"info",text:y}),!u.aborted){try{let v=await Yc({cwd:e,profileName:i}),T=zc(v);T?d({kind:"note",tone:"info",text:T}):v.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${v.skipped}`})}catch(v){d({kind:"note",tone:"warn",text:`Order sync failed: ${v.message}`})}try{let v=Xc(await Kc({cwd:e,profileName:i}));v&&d({kind:"note",tone:"info",text:v})}catch(v){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${v.message}`})}}}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{Re.current=null,oe(null),I(!1),Z(u=>u+1)}},[e,i,d,t]),pr=V(async l=>{await ie(Or(l),{display:`/publish ${l}`,quietUser:!0});try{let a=await ho(e,i,l.replace(/\\/g,"/"));a.length>0&&(Yt(`Related articles not yet published (${a.length}):`),tt([`/publish --related ${l}`,...a.map(s=>`/publish ${s}`)]))}catch{}},[e,i,ie]),fr=V(l=>{let a=gt(l);if(!a||Ze(a)&&!a.refreshToken)return null;let s={...Bt(a.idToken)??{},...Bt(a.accessToken)??{}};return s.email??s.preferred_username??"signed in"},[]),mr=V((l,a)=>{if(a){let s=te(e);s&&(s.defaultProfile=l,Wc(s,e))}c(l),ke(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),fr(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 sign in with /login.`}),z("/login")),Z(s=>s+1)},[e,d,ke,fr,z]),Wn=V((l,a,s)=>{Kn(e,l,a,s.id,s.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${s.name??s.id}" (agent restarted).`}),ke(),Fc(e,l)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:Ut(Mt(e)).join(`
317
- `)}),jt(dt()),Jt.current=Se(e).status==="current"||We(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,ke,jt]),Fn=V(async l=>{let a;try{a=await rn(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),z("/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],m=a.workspaces.length-h.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),Wn(a.profile,a.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),z("/workspace")},[e,d,Wn,z]),Hn=V((l,a)=>{Xn(e,l,a.id,a.name),d({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),ke(),Fn(l)},[e,d,ke,Fn]),Es=V(async l=>{let a;try{a=$e(e,l)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:s}=await ze(e,a.name),h=s.find(u=>u.id===a.project.projectId);h?.name&&bg(e,a.name,{projectName:h.name})}catch{}await Fn(a.name);return}try{let{projects:s}=await ze(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}".`}),Hn(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?"}),st({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."}),z("/project")}},[e,d,Fn,Hn,z]),qn=V(()=>{let l=Ae.current[0];if(!l)return;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let s of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${s}`});l.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let a=pt(l.oldContent,l.newContent,Be());d(a?{kind:"diff",added:a.added,removed:a.removed,lines:a.lines,hidden:a.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,Be]),Ns=V(l=>{if(Ae.current.length===0)return!1;let a=l.trim().toLowerCase();if(a==="y"||a==="yes"){let s=Ae.current.shift();try{ng({cwd:e,profileName:i},s),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${s.path} (sync base advanced).`}),Ae.current.length===0&&z("/pull")}catch(h){d({kind:"note",tone:"error",text:`Pull failed: ${h.message}`})}}else if(a==="n"||a==="no"){let s=Ae.current.shift();d({kind:"note",tone:"info",text:`Skipped ${s.path}.`})}else{let s=Ae.current.length;return Ae.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${s} article(s) left untouched).`}),!0}return qn(),!0},[e,i,qn,d]),Is=V(l=>{let a=jn.current;if(!a)return!1;if(jn.current=null,Ve(),l.trim()!==a.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:s,failed:h}=Ni(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:lo().join(`
318
- `)}),jt(vr())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
319
- ${Qc}`}),z("/init"),Tn(!1),!0},[e,d,jt,Ve,z]),Bn=V(async l=>{let a=l.slice(1).trim().split(/\s+/),s=(a[0]??"").toLowerCase(),h=a.slice(1);if(Tn(!0),ko(h)&&["write","check","review","reorder"].includes(s)){let u=Jr(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 m=b=>s==="write"?`/write ${Xa(h,b).join(" ")}`.trim():`/${s} ${[b,...h.filter(y=>y!=="--scope")].join(" ")}`.trim();if(u.length===1){Bn(m(u[0].token));return}Pt({cursor:0,rows:u,run:b=>{Bn(m(b))}});return}switch(s){case"help":Xt({tab:0});return;case"exit":case"quit":Ce.current?.close(),r();return;case"clear":ke(),bt.current=[],Tn(!1),Ve(),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=$e(e,i)}catch(m){d({kind:"note",tone:"error",text:m.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),K(!0);try{let m=await Uh(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},y=>d({kind:"note",tone:"info",text:y})),b=Wh(u.name,m);if(Fh(b),await wr(b,u.name,y=>d({kind:"note",tone:"info",text:y})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${Zn(b)}`}),await Es(i),Kt.current){let y=Kt.current;Kt.current=null;let v=Fe(e,i);v.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${y}.`}),z(y)):(d({kind:"note",tone:"warn",text:`${v.reason} (then ${y}.)`}),z("/login"),Kt.current=y)}else In.current&&(me(In.current,"\u21E5 tab to re-send your last prompt\u2026"),In.current=null)}catch(m){d({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{K(!1),Z(m=>m+1)}return}case"allow-prod":{let u=!1;try{u=$e(e,i).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}xt.current=!0,ke(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=hi(h.join(" ")),m=_e.current.uuid;if(!m){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}er.current=u,ot(u),Ht(`${Wo} ${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=_e.current.firstPrompt??"";Uc(b,e).then(y=>{y?(me(`/rename ${y}`),d({kind:"note",tone:"info",text:`Suggestion: "${y}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Jh(m,u),ot(u),Ht(`${Wo} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=h[0],m=te(e);if(!u){let b=Object.entries(m?.profiles??{});if(b.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let y=b.map(([Y,H])=>({name:Y,env:H.connection?.environment??"custom",prod:H.production===!0,who:fr(Y)})),v=i??m?.defaultProfile,T=Math.max(0,y.findIndex(Y=>Y.name===v));$t({cursor:T,current:T,rows:y});return}if(u==="add"){let b=gi(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]}).`}),mr(h[1],!1);return}if(!m?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}mr(u,!0);return}case"doctor":await mn(h,{cwd:e});return;case"genre":{await Do(h,{cwd:e});try{Xo.current=!(te(e)?.appType??tg(e))}catch{}Z(u=>u+1);return}case"roadmap":{if(h[0]?.toLowerCase()==="done"){let u=Wi(e,h.slice(1).join(" ").trim());d({kind:"note",tone:u.ok?"ok":"warn",text:u.line}),Z(m=>m+1);return}d({kind:"note",tone:"info",text:Ui(e).join(`
320
- `)});return}case"mcp":await po(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=lg().map(m=>({name:m,apiUrl:cg(m).apiUrl}));vt({cursor:0,rows:u});return}case"resume":{let u=h.join(" ").trim(),m=Qh(e).filter(v=>v.uuid!==_e.current.uuid);if(!u){if(!m.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}ct({query:"",cursor:0,sessions:m});return}let b=Xh(e,u);if(!b){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}ke(b.uuid),_e.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},ot(b.name),is(b.uuid),bt.current=[];let y=Zi(e,b.uuid);for(let v of y)d(v);d({kind:"note",tone:"ok",text:y.length?`Resumed "${b.name}" \u2014 restored ${y.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(),m;try{m=await rn(e,i)}catch(y){d({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!u){let y=m.workspaces.map(T=>({id:T.id,name:T.name??T.id,type:T.workspace_type}));if(y.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let v=Math.max(0,y.findIndex(T=>T.id===m.current));Ct({cursor:v,current:v,rows:y,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let b=gr(m.workspaces,u);if(!b){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}Wn(m.profile,m.projectId,b);return}case"project":{let u=h.join(" ").trim(),m;try{m=await ze(e,i)}catch(y){d({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!u){let y=m.projects.map(T=>({id:T.id,name:T.name??T.id,sub:T.sub_domain}));if(y.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let v=y.findIndex(T=>T.id===m.current);st({cursor:Math.max(0,v),current:v,rows:y,profile:m.profile,environment:m.environment});return}let b=yr(m.projects,u);if(!b){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${m.projects.map(y=>y.name??y.id).join(", ")}`});return}Hn(m.profile,b);return}case"logout":{let u;try{u=$e(e,i).name}catch(b){d({kind:"note",tone:"error",text:b.message});return}let m=Vh(u);Gh(e,u),ke(),Z(b=>b+1),d({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${u}" and cleared its project/workspace selection.`:`Profile "${u}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),z("/login");return}case"publish":{if(!ar(l.trim()))return;if(h[0]==="--related"&&h[1]){let m=await ho(e,i,h[1].replace(/\\/g,"/"));if(m.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Un(m);return}if(h[0]&&h[0]!=="--all"){await pr(h[0]);return}let u=h[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Hc({cwd:e,profileName:i}),b=dn(m.entries),y=fo(m.entries);if(y>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${y} article${y===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),b.length===0){d({kind:"note",tone:"ok",text:y>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let v=m.counts["unknown-base"]??0;v>0&&d({kind:"note",tone:"info",text:`(${v} 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 T=await Yc({cwd:e,profileName:i}),Y=Xc(await Kc({cwd:e,profileName:i})),H=zc(T);H?d({kind:"note",tone:"info",text:H}):T.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${T.skipped}`}),Y&&d({kind:"note",tone:"info",text:Y}),d({kind:"note",tone:"ok",text:H||Y?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(H||Y)&&z("/structure")}catch(T){d({kind:"note",tone:"warn",text:`Structure sync failed: ${T.message}`})}finally{$s(null)}return}if(u){await Un(b.map(v=>v.path));return}Rt({cursor:0,rows:La(b)})}catch(m){d({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let u=h.join(" ").trim();if(!u){let b=[];try{b=Object.keys(Fc(e,$e(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}at({query:"",cursor:0,paths:b});return}let m=Lh(u)?u:rs(e,u);if($n(m)){try{d({kind:"preview",name:vn(m),text:Zc(os(m,"utf8"))})}catch(b){d({kind:"note",tone:"error",text:`Could not read ${m}: ${b.message}`})}return}if(Ag.test(u)){try{let b=$e(e,i),y={profile:b.name,connection:b.connection},v=b.project.projectId??qh(y),T=await Bh(y,v,u);d({kind:"preview",name:T.title??u,text:T.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 v=xo(us(e));it({cursor:v,current:v});return}let{lines:m,changed:b,effective:y}=fn(e,u);for(let v of m)d({kind:"note",tone:v.startsWith("\u26A0")?"warn":v.startsWith("\u2713")?"ok":"info",text:v});b&&(Rs(v=>v+1),Ce.current?.setModel(y));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:m}=Vr(h),b=pg(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 y=Gr(b,u);if(y.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${b.length} are tracked overall.)`});return}let v=ss(y),T=3,Y=`/convert${u?` --scope ${u}`:""} --run`,H=Yo(e,"light");if(!m){let C=Bc({files:Yr(e,y),op:"convert",model:H.model}),E=u?`Scope: ${u} (${y.length} of ${b.length} tracked)
315
+ cwd: ${e}`}),cr()},[]),ve(()=>{let l=setInterval(()=>{cr()},Og);return()=>clearInterval(l)},[cr]),ve(()=>{if(S||er||Dn.current||ae!==null||tt.length>0||D!==""||en!==null||Ae.current.length>0||_n.current||ir)return;let l=on(!1);l.kind==="recommend"&&(l.rec.lead||l.rec.picker)&&Ds(l.rec,{silent:!0})},[S,ae,tt,D,en,ir,ee,on,er]),ve(()=>{let l=null,a=null,s=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${je.columns??80}x${je.rows??24}`;g!==Ss.current&&(Ss.current=g,gu(u=>u+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Ea(vt.current,Be())+"\x1B[?2026l")},80))},400)};return je.on("resize",s),()=>{l&&clearTimeout(l),a&&clearTimeout(a),je.off("resize",s)}},[je,Be]);let Ee=Math.max(20,(je.columns??80)-1),js=rs(()=>Dg(e,i),[e,i,ee]),fr=(()=>{if(pu)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(tr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${tr?` v${tr}`:""}\u2026`,isSetup:!0};if(en)return wu?{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(Ae.current.length>0)return{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let l=te(e);if(!l)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let a=ss(e,(l.docsDir??nu).replace(/\/+$/,"")),s=(()=>{try{return Tn(a)&&Mh(a).length>0}catch{return!1}})();try{let g=xe(e,i),u=yt(g.name);if(!(!!u&&!(et(u)&&!u.refreshToken)))return{text:`Sign in with /login (profile "${g.name}")\u2026`,isSetup:!0};if(!g.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!g.project.workspaceId&&!s)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return s?{text:Ag,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),rn=$c(D),Es=rn.length>0&&!S,mr=p!==null?Mc(p,8,Ee):null,Fn=we?we.paths.filter(l=>!we.query||l.toLowerCase().includes(we.query.toLowerCase())).slice(0,8):[],Hn=ye?ye.sessions.filter(l=>{let a=ye.query.toLowerCase();return!a||l.name.toLowerCase().includes(a)||l.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],ke=V((l,a)=>{Ce.current?.close(),Ce.current=Wc({cwd:e,resume:l,profileName:a??i,allowProdWrites:Ct.current}),l||(_e.current={uuid:null,firstPrompt:null,titleFired:!1},rt(null)),At(0),jt(0)},[e,i]),Ns=V((l,a,s)=>{if(jg.test(l))try{let g=xe(e,i),u=typeof a.project_id=="string"&&a.project_id||g.project.projectId,m=Uo(a,s),b=[],w=Wo(s);l.endsWith("publish_article")&&w&&b.push(`Live: ${w}`),m&&u&&b.push(`Preview: ${Mo(g.connection.portalUrl,u,m,g.project.languageCode??"en")}`),b.length>0&&d({kind:"link",lines:b})}catch{}},[e,i,d]),ie=V(async(l,a)=>{jn(!0),Dn.current=!1,Ve(),nt([]),Xt(null),ar(null),pr(null);let s=An.current;a?.quietUser||d({kind:"user",text:a?.echoDisplay&&a.display?a.display:l});let g=_e.current;g.firstPrompt||(g.firstPrompt=a?.display??l),ot.current=Date.now(),bt(0),I(!0),In.current.clear();let u="",m=!1,b=!1,w="",v={num:0,closed:!1,cueSeen:!1},R=null,Y=()=>{R||(R=setTimeout(()=>{R=null,y(w.length>0?w:null)},60))},H=()=>{R&&clearTimeout(R),R=null,y(null)},M=()=>{if(w.trim()){let C=es(w.trimEnd(),v);d({kind:"assistant",text:C})}w="",H()};try{for await(let C of Ce.current.send(l))if(C.type==="session"){if(!g.uuid){g.uuid=C.sessionId;let E=new Date().toISOString(),q=or.current,J=q??Xh(g.firstPrompt??"session");Qh({uuid:C.sessionId,name:J,renamed:!!q,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:E,updatedAt:E}),rt(J),or.current=null}}else if(C.type==="text"){w+=C.delta,u+=C.delta;let E=Uc(w);if(E>0){let q=w.slice(0,E).trimEnd();q&&d({kind:"assistant",text:es(q,v)}),w=w.slice(E)}Y(),bt(q=>q+C.delta.length)}else if(C.type==="tool"){m=!0;let E=Lo(C.name,C.input);E&&(M(),d({kind:"tool",title:E.title,sep:E.sep,arg:E.arg}),In.current.set(C.id,{name:C.name,input:C.input}))}else if(C.type==="article_diff"){let E=mt(C.oldContent,C.newContent,Be());E&&(M(),d({kind:"diff",added:E.added,removed:E.removed,lines:E.lines,hidden:E.hidden}))}else if(C.type==="tool_result"){C.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(C.output)&&(On.current=!0);let E=In.current.get(C.id);if(E){In.current.delete(C.id),M();let q=Oo(C.output,4,C.isError?void 0:E.name,E.input);d({kind:"tool-result",lines:q.lines,hidden:q.hidden,isError:C.isError}),C.isError||Ns(E.name,E.input,C.output)}}else if(C.type==="result"){if(M(),At(E=>E+C.outputTokens),jt(E=>E+C.costUsd),d({kind:"done",seconds:Math.round((Date.now()-ot.current)/1e3),tokens:C.outputTokens,costUsd:C.costUsd,ok:C.ok}),!b&&!m&&!u.trim()&&!Qt.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),C.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let E=kg(e);if(Tn(E)){let q=is(E,"utf8").trim();q&&(pr(q),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(C.ok&&v.cueSeen)ws(!0),nt([]);else{let E=C.ok?Rc(u,Bo.map(q=>q.name)):[];if(E.length>0)K(E[0]);else if(C.ok&&u.trim()){let q=on(!1);q.kind==="recommend"&&(q.rec.lead||q.rec.picker)||tg(l,u,e).then(J=>{J&&An.current===s&&me(J)}).catch(()=>{})}}if(g.uuid&&(as(g.uuid),!g.titleFired)){g.titleFired=!0;let E=g.uuid,q=g.firstPrompt;q&&Fc(q,e).then(J=>{J&&(Kh(E,J),rt(J))}).catch(()=>{})}}else C.type==="error"&&(M(),b=!0,C.kind==="auth"&&(On.current=!0),d({kind:"note",text:`agent error: ${C.message}`,tone:"error"}))}finally{I(!1),H(),Q(C=>C+1),_e.current.uuid&&wc(e,_e.current.uuid,vt.current),On.current&&(On.current=!1,Mn.current=a?.display??l,me("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")),Qt.current&&(Qt.current=!1,ut.current.length>0&&(d({kind:"note",tone:"info",text:`(${ut.current.length} queued message(s) discarded)`}),ut.current=[],rr([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Ns,Be,me,K,Ve,on]),qn=V(async l=>{let a=ls(l),s=Xo(e,"standard");ot.current=Date.now(),bt(0),I(!0);let g=new AbortController;Re.current=g,oe({verb:"Publishing",total:a.length,done:0,active:[],rows:Pn(a),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${a.length} partition${a.length===1?"":"s"} (\u2264${mn} agents at once) on ${s.model}\u2026 (esc to stop)`});try{for await(let u of Ko({cwd:e,partitions:a,promptFor:m=>wo(m.paths),concurrency:mn,profileName:i,allowProdWrites:Ct.current,model:s.model,signal:g.signal}))if(u.type==="partition_status")u.status==="running"?oe(m=>m&&{...m,active:[...m.active,u.label],rows:He(m.rows,u.label,"active"),lastAt:Date.now()}):oe(m=>m&&{...m,active:m.active.filter(b=>b!==u.label),done:m.done+1,rows:He(m.rows,u.label,u.status==="done"?"done":"failed"),lastAt:Date.now()});else if(u.type==="partition_event")oe(m=>{if(!m)return m;let b={...m,lastAt:Date.now()};return u.event.type==="tool"?b.tools=m.tools+1:u.event.type==="text"&&(b.chars=m.chars+u.event.delta.length),b});else if(u.type==="run_done"){jt(v=>v+u.totalCostUsd),At(v=>v+u.results.reduce((R,Y)=>R+Y.outputTokens,0));let m=u.aborted?"Stopped. ":"",b=t.kind==="api"?"api":"subscription";d({kind:"note",tone:u.aborted?"warn":u.ok?"ok":"warn",text:m+Fr(u.results,a,b).join(`
316
+ `)});let w=Wr(e,i);if(w&&d({kind:"note",tone:"info",text:w}),!u.aborted){try{let v=await Kc({cwd:e,profileName:i}),R=Xc(v);R?d({kind:"note",tone:"info",text:R}):v.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${v.skipped}`})}catch(v){d({kind:"note",tone:"warn",text:`Order sync failed: ${v.message}`})}try{let v=Jc(await Qc({cwd:e,profileName:i}));v&&d({kind:"note",tone:"info",text:v})}catch(v){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${v.message}`})}}}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{Re.current=null,oe(null),I(!1),Q(u=>u+1)}},[e,i,d,t]),hr=V(async l=>{await ie(Ur(l),{display:`/publish ${l}`,quietUser:!0});try{let a=await yo(e,i,l.replace(/\\/g,"/"));a.length>0&&(Xt(`Related articles not yet published (${a.length}):`),nt([`/publish --related ${l}`,...a.map(s=>`/publish ${s}`)]))}catch{}},[e,i,ie]),gr=V(l=>{let a=yt(l);if(!a||et(a)&&!a.refreshToken)return null;let s={...Yt(a.idToken)??{},...Yt(a.accessToken)??{}};return s.email??s.preferred_username??"signed in"},[]),wr=V((l,a)=>{if(a){let s=te(e);s&&(s.defaultProfile=l,Hc(s,e))}c(l),ke(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),gr(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 sign in with /login.`}),K("/login")),Q(s=>s+1)},[e,d,ke,gr,K]),Bn=V((l,a,s)=>{Jn(e,l,a,s.id,s.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${s.name??s.id}" (agent restarted).`}),ke(),qc(e,l)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:Ft(Wt(e)).join(`
317
+ `)}),Nt(ft()),tn.current=Se(e).status==="current"||We(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,ke,Nt]),Vn=V(async l=>{let a;try{a=await cn(e,l)}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"),g=s.length>0?s:a.workspaces;if(g.length===1){let u=g[0],m=a.workspaces.length-g.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),Bn(a.profile,a.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),K("/workspace")},[e,d,Bn,K]),Gn=V((l,a)=>{Zn(e,l,a.id,a.name),d({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),ke(),Vn(l)},[e,d,ke,Vn]),Is=V(async l=>{let a;try{a=xe(e,l)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:s}=await ze(e,a.name),g=s.find(u=>u.id===a.project.projectId);g?.name&&xg(e,a.name,{projectName:g.name})}catch{}await Vn(a.name);return}try{let{projects:s}=await ze(e,a.name);if(s.length===1){let g=s[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),Gn(a.name,{id:g.id,name:g.name});return}if(s.length>1){let g=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?"}),at({cursor:0,current:-1,rows:g,profile:a.name,environment:a.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),K("/project")}},[e,d,Vn,Gn,K]),Yn=V(()=>{let l=Ae.current[0];if(!l)return;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let s of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${s}`});l.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let a=mt(l.oldContent,l.newContent,Be());d(a?{kind:"diff",added:a.added,removed:a.removed,lines:a.lines,hidden:a.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,Be]),_s=V(l=>{if(Ae.current.length===0)return!1;let a=l.trim().toLowerCase();if(a==="y"||a==="yes"){let s=Ae.current.shift();try{rg({cwd:e,profileName:i},s),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${s.path} (sync base advanced).`}),Ae.current.length===0&&K("/pull")}catch(g){d({kind:"note",tone:"error",text:`Pull failed: ${g.message}`})}}else if(a==="n"||a==="no"){let s=Ae.current.shift();d({kind:"note",tone:"info",text:`Skipped ${s.path}.`})}else{let s=Ae.current.length;return Ae.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${s} article(s) left untouched).`}),!0}return Yn(),!0},[e,i,Yn,d]),Ls=V(l=>{let a=_n.current;if(!a)return!1;if(_n.current=null,Ve(),l.trim()!==a.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:s,failed:g}=_i(e,a.targets);d({kind:"note",tone:g.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 g)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return a.hadDevhints&&(d({kind:"note",tone:"warn",text:po().join(`
318
+ `)}),Nt(Pr())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
319
+ ${Zc}`}),K("/init"),jn(!1),!0},[e,d,Nt,Ve,K]),sn=V(async l=>{let a=l.slice(1).trim().split(/\s+/),s=(a[0]??"").toLowerCase(),g=a.slice(1);if(jn(!0),xo(g)&&["write","check","review","reorder"].includes(s)){let u=wn(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 m=b=>s==="write"?`/write ${Ja(g,b).join(" ")}`.trim():`/${s} ${[b,...g.filter(w=>w!=="--scope")].join(" ")}`.trim();if(u.length===1){sn(m(u[0].token));return}lt({cursor:0,rows:u,run:b=>{sn(m(b))}});return}if(Je(s,g)){let u=wn(e,i);if(u.length>1){let m=g.filter(R=>R.startsWith("--")).join(" "),b=R=>`/${s}${R?` ${s==="write"?`--scope ${R}`:R}`:""}${m?` ${m}`:""} ${R?"":"--all"}`.replace(/\s+/g," ").trim(),w=u.reduce((R,Y)=>R+Y.count,0),v={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};lt({cursor:0,rows:[v,...u],run:R=>{sn(b(R))}});return}}switch(s){case"help":Zt({tab:0});return;case"exit":case"quit":Ce.current?.close(),r();return;case"clear":ke(),vt.current=[],jn(!1),Ve(),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=xe(e,i)}catch(m){d({kind:"note",tone:"error",text:m.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),z(!0);try{let m=await Fh(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=Hh(u.name,m);if(qh(b),await $r(b,u.name,w=>d({kind:"note",tone:"info",text:w})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${no(b)}`}),await Is(i),Jt.current){let w=Jt.current;Jt.current=null;let v=Fe(e,i);v.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:`${v.reason} (then ${w}.)`}),K("/login"),Jt.current=w)}else Mn.current&&(me(Mn.current,"\u21E5 tab to re-send your last prompt\u2026"),Mn.current=null)}catch(m){d({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{z(!1),Q(m=>m+1)}return}case"allow-prod":{let u=!1;try{u=xe(e,i).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Ct.current=!0,ke(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=wi(g.join(" ")),m=_e.current.uuid;if(!m){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}or.current=u,rt(u),Vt(`${qo} ${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=_e.current.firstPrompt??"";Fc(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}eg(m,u),rt(u),Vt(`${qo} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=g[0],m=te(e);if(!u){let b=Object.entries(m?.profiles??{});if(b.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let w=b.map(([Y,H])=>({name:Y,env:H.connection?.environment??"custom",prod:H.production===!0,who:gr(Y)})),v=i??m?.defaultProfile,R=Math.max(0,w.findIndex(Y=>Y.name===v));Rt({cursor:R,current:R,rows:w});return}if(u==="add"){let b=yi(e,g[1],g[2]);if(b){d({kind:"note",tone:"error",text:b});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),wr(g[1],!1);return}if(!m?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}wr(u,!0);return}case"doctor":await kn(g,{cwd:e});return;case"genre":{await Eo(g,{cwd:e});try{Zo.current=!(te(e)?.appType??og(e))}catch{}Q(u=>u+1);return}case"roadmap":{if(g[0]?.toLowerCase()==="done"){let u=Hi(e,g.slice(1).join(" ").trim());d({kind:"note",tone:u.ok?"ok":"warn",text:u.line}),Q(m=>m+1);return}d({kind:"note",tone:"info",text:Fi(e).join(`
320
+ `)});return}case"mcp":await ho(g);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=ug().map(m=>({name:m,apiUrl:dg(m).apiUrl}));Pt({cursor:0,rows:u});return}case"resume":{let u=g.join(" ").trim(),m=Zh(e).filter(v=>v.uuid!==_e.current.uuid);if(!u){if(!m.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}dt({query:"",cursor:0,sessions:m});return}let b=Jh(e,u);if(!b){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}ke(b.uuid),_e.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},rt(b.name),as(b.uuid),vt.current=[];let w=ts(e,b.uuid);for(let v of w)d(v);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=g.join(" ").trim(),m;try{m=await cn(e,i)}catch(w){d({kind:"note",tone:"error",text:`Could not list workspaces: ${w.message}`});return}if(!u){let w=m.workspaces.map(R=>({id:R.id,name:R.name??R.id,type:R.workspace_type}));if(w.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let v=Math.max(0,w.findIndex(R=>R.id===m.current));Tt({cursor:v,current:v,rows:w,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let b=kr(m.workspaces,u);if(!b){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}Bn(m.profile,m.projectId,b);return}case"project":{let u=g.join(" ").trim(),m;try{m=await ze(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=m.projects.map(R=>({id:R.id,name:R.name??R.id,sub:R.sub_domain}));if(w.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let v=w.findIndex(R=>R.id===m.current);at({cursor:Math.max(0,v),current:v,rows:w,profile:m.profile,environment:m.environment});return}let b=br(m.projects,u);if(!b){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${m.projects.map(w=>w.name??w.id).join(", ")}`});return}Gn(m.profile,b);return}case"logout":{let u;try{u=xe(e,i).name}catch(b){d({kind:"note",tone:"error",text:b.message});return}let m=Yh(u);zh(e,u),ke(),Q(b=>b+1),d({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${u}" and cleared its project/workspace selection.`:`Profile "${u}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),K("/login");return}case"publish":{if(!ur(l.trim()))return;if(g[0]==="--related"&&g[1]){let m=await yo(e,i,g[1].replace(/\\/g,"/"));if(m.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await qn(m);return}if(g[0]&&g[0]!=="--all"){await hr(g[0]);return}let u=g[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Bc({cwd:e,profileName:i}),b=hn(m.entries),w=go(m.entries);if(w>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${w} article${w===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.`}),b.length===0){d({kind:"note",tone:"ok",text:w>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let v=m.counts["unknown-base"]??0;v>0&&d({kind:"note",tone:"info",text:`(${v} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Cs("Reconciling structure on Document360 (order + related articles)\u2026");try{let R=await Kc({cwd:e,profileName:i}),Y=Jc(await Qc({cwd:e,profileName:i})),H=Xc(R);H?d({kind:"note",tone:"info",text:H}):R.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${R.skipped}`}),Y&&d({kind:"note",tone:"info",text:Y}),d({kind:"note",tone:"ok",text:H||Y?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(H||Y)&&K("/structure")}catch(R){d({kind:"note",tone:"warn",text:`Structure sync failed: ${R.message}`})}finally{Cs(null)}return}if(u){await qn(b.map(v=>v.path));return}St({cursor:0,rows:Ua(b)})}catch(m){d({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let u=g.join(" ").trim();if(!u){let b=[];try{b=Object.keys(qc(e,xe(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}ct({query:"",cursor:0,paths:b});return}let m=Uh(u)?u:ss(e,u);if(Tn(m)){try{d({kind:"preview",name:Sn(m),text:tu(is(m,"utf8"))})}catch(b){d({kind:"note",tone:"error",text:`Could not read ${m}: ${b.message}`})}return}if(Eg.test(u)){try{let b=xe(e,i),w={profile:b.name,connection:b.connection},v=b.project.projectId??Vh(w),R=await Gh(w,v,u);d({kind:"preview",name:R.title??u,text:R.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=g[0]?.trim();if(!u){let v=Co(ps(e));st({cursor:v,current:v});return}let{lines:m,changed:b,effective:w}=yn(e,u);for(let v of m)d({kind:"note",tone:v.startsWith("\u26A0")?"warn":v.startsWith("\u2713")?"ok":"info",text:v});b&&(Ts(v=>v+1),Ce.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:m}=zr(g),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=Kr(b,u);if(w.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${b.length} are tracked overall.)`});return}let v=ls(w),R=3,Y=`/convert${u?` --scope ${u}`:""} --run`,H=Xo(e,"light");if(!m){let C=Gc({files:Xr(e,w),op:"convert",model:H.model}),E=u?`Scope: ${u} (${w.length} of ${b.length} tracked)
321
321
  `:"",q=`
322
- Model: ${H.model}${H.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:E+Kr(v,C,T).join(`
323
- `)+q}),z(Y);return}nt.current=Date.now(),yt(0),I(!0);let M=new AbortController;Re.current=M,oe({verb:"Converting",total:v.length,done:0,active:[],rows:xn(v),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${y.length} articles across ${v.length} partitions (\u2264${T} agents at once) on ${H.model}\u2026 (esc to stop)`});try{for await(let C of Go({cwd:e,partitions:v,promptFor:zr,concurrency:T,profileName:i,allowProdWrites:xt.current,model:H.model,signal:M.signal}))if(C.type==="partition_status")C.status==="running"?oe(E=>E&&{...E,active:[...E.active,C.label],rows:He(E.rows,C.label,"active"),lastAt:Date.now()}):oe(E=>E&&{...E,active:E.active.filter(q=>q!==C.label),done:E.done+1,rows:He(E.rows,C.label,C.status==="done"?"done":"failed"),lastAt:Date.now()});else if(C.type==="partition_event")oe(E=>{if(!E)return E;let q={...E,lastAt:Date.now()};return C.event.type==="tool"?q.tools=E.tools+1:C.event.type==="text"&&(q.chars=E.chars+C.event.delta.length),q});else if(C.type==="run_done"){Dt(Q=>Q+C.totalCostUsd),St(Q=>Q+C.results.reduce((Nt,It)=>Nt+It.outputTokens,0));let E=C.aborted?"Stopped. ":"",q=t.kind==="api"?"api":"subscription";d({kind:"note",tone:C.aborted?"warn":C.ok?"ok":"warn",text:E+Xr(C.results,v,q).join(`
324
- `)})}}catch(C){d({kind:"note",tone:"error",text:`Convert run failed: ${C.message}`})}finally{Re.current=null,oe(null),I(!1),Z(C=>C+1)}return}case"write":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=fg(e);if(u.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:b,preview:y,concurrency:v,rewrite:T}=ei(h),{docsDir:Y,targets:H,reason:M,rewriting:C}=ai(e,u,{scope:m,path:b,rewrite:T});if(H.length===0){d({kind:"note",tone:"warn",text:M??"Nothing to write."});return}C&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${H.length} already-written article${H.length===1?"":"s"} (overwrites them; git has your baseline).`});let E=ss(H),q=Zr(v),Q=Yo(e,"standard"),Nt=!!b;if(y&&!Nt){let G=Bc({files:ni(e,u,H),op:"write",model:Q.model}),re=m?`Scope: ${m} (${H.length} pending)
322
+ Model: ${H.model}${H.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:E+Jr(v,C,R).join(`
323
+ `)+q}),K(Y);return}ot.current=Date.now(),bt(0),I(!0);let M=new AbortController;Re.current=M,oe({verb:"Converting",total:v.length,done:0,active:[],rows:Pn(v),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${w.length} articles across ${v.length} partitions (\u2264${R} agents at once) on ${H.model}\u2026 (esc to stop)`});try{for await(let C of Ko({cwd:e,partitions:v,promptFor:Qr,concurrency:R,profileName:i,allowProdWrites:Ct.current,model:H.model,signal:M.signal}))if(C.type==="partition_status")C.status==="running"?oe(E=>E&&{...E,active:[...E.active,C.label],rows:He(E.rows,C.label,"active"),lastAt:Date.now()}):oe(E=>E&&{...E,active:E.active.filter(q=>q!==C.label),done:E.done+1,rows:He(E.rows,C.label,C.status==="done"?"done":"failed"),lastAt:Date.now()});else if(C.type==="partition_event")oe(E=>{if(!E)return E;let q={...E,lastAt:Date.now()};return C.event.type==="tool"?q.tools=E.tools+1:C.event.type==="text"&&(q.chars=E.chars+C.event.delta.length),q});else if(C.type==="run_done"){jt(J=>J+C.totalCostUsd),At(J=>J+C.results.reduce((_t,Lt)=>_t+Lt.outputTokens,0));let E=C.aborted?"Stopped. ":"",q=t.kind==="api"?"api":"subscription";d({kind:"note",tone:C.aborted?"warn":C.ok?"ok":"warn",text:E+Zr(C.results,v,q).join(`
324
+ `)})}}catch(C){d({kind:"note",tone:"error",text:`Convert run failed: ${C.message}`})}finally{Re.current=null,oe(null),I(!1),Q(C=>C+1)}return}case"write":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=hg(e);if(u.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:b,preview:w,concurrency:v,rewrite:R}=ni(g),{docsDir:Y,targets:H,reason:M,rewriting:C}=ci(e,u,{scope:m,path:b,rewrite:R});if(H.length===0){d({kind:"note",tone:"warn",text:M??"Nothing to write."});return}C&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${H.length} already-written article${H.length===1?"":"s"} (overwrites them; git has your baseline).`});let E=ls(H),q=ti(v),J=Xo(e,"standard"),_t=!!b;if(w&&!_t){let G=Gc({files:ri(e,u,H),op:"write",model:J.model}),re=m?`Scope: ${m} (${H.length} pending)
325
325
  `:"",de=`
326
- Model: ${Q.model}${Q.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:re+ri(E,G,q).join(`
327
- `)+de}),z(`/write${m?` --scope ${m}`:""}`);return}nt.current=Date.now(),yt(0),I(!0);let It=new AbortController;Re.current=It,oe({verb:"Writing",total:E.length,done:0,active:[],rows:xn(E),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 ${E.length} partition${E.length===1?"":"s"} (\u2264${q} agents at once) on ${Q.model}${Q.forced?" (forced)":""}\u2026 (esc to stop)`});let Yn=new Set;try{for await(let G of Go({cwd:e,partitions:E,promptFor:re=>oi(re,Y,{rewrite:C||Nt}),concurrency:q,profileName:i,allowProdWrites:xt.current,model:Q.model,signal:It.signal}))if(G.type==="partition_status")G.status==="running"?oe(re=>re&&{...re,active:[...re.active,G.label],rows:He(re.rows,G.label,"active"),lastAt:Date.now()}):oe(re=>re&&{...re,active:re.active.filter(de=>de!==G.label),done:re.done+1,rows:He(re.rows,G.label,G.status==="done"?"done":"failed"),lastAt:Date.now()});else if(G.type==="partition_event"){let re=null;if(G.event.type==="tool"){let de=Rc(G.event.name,G.event.input,E[G.index]?.paths??[]);de&&!Yn.has(de)&&(Yn.add(de),re=G.label)}oe(de=>{if(!de)return de;let Ne={...de,lastAt:Date.now()};return G.event.type==="tool"?Ne.tools=de.tools+1:G.event.type==="text"&&(Ne.chars=de.chars+G.event.delta.length),re&&(Ne.rows=Cc(Ne.rows,re)),Ne})}else if(G.type==="run_done"){Dt(Ge=>Ge+G.totalCostUsd),St(Ge=>Ge+G.results.reduce((Ue,wu)=>Ue+wu.outputTokens,0));let re=G.aborted?"Stopped. ":"",de=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:G.aborted?"warn":G.ok?"ok":"warn",text:re+ii(G.results,E,de).join(`
328
- `)}),!G.aborted&&G.ok)try{let Ge=(Yn.size>0?[...Yn]:H).map(Ue=>`${Y}/${Ue}`);as(e,Ge,{writtenCap:ls})}catch{}let Ne=G.aborted?null:si(e,Y,H);if(Ne&&d({kind:"note",tone:"warn",text:Ne}),!G.aborted&&G.ok){let Ge=m??b??"",Ue=Ge?` ${Ge}`:"";At(Ne?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${Ue} --fix, then /review${Ue} --fix for editorial quality, then /publish --all (add /screenshot --all first if you want images).`:`Written. I\u2019d run /review${Ue} --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:Ne?`/check${Ue} --fix`:`/review${Ue} --fix`,reason:""})}}}catch(G){d({kind:"note",tone:"error",text:`Write run failed: ${G.message}`})}finally{Re.current=null,oe(null),I(!1),Z(G=>G+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:m}=li(e);if(u.length===0&&m===0){d({kind:"note",tone:"info",text:ui});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?
329
- ${u.map(T=>` \u2022 ${T.name} (${T.docCount} doc${T.docCount===1?"":"s"})`).join(`
330
- `)}`}),tt(u.map(T=>`/draft ${T.name}`));return}let y="",v;if(b){let T=ci(u,b);T?y=T:v=b}else y=u[0]?.name??"";await ie(bo(y,v),{display:b?`/draft ${b}`:"/draft",quietUser:!0});return}case"pull":{if(!ar(l.trim()))return;let u=h.find(m=>m.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let y=Date.now(),v=await Hc({cwd:e,profileName:i});d({kind:"note",tone:"info",text:yo(v,Date.now()-y).join(`
331
- `)});return}if(u==="--baseline"){let y=h.find(H=>!H.startsWith("--")),v=y?y.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:v?`Setting the sync baseline for ${v}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let T=await ig({cwd:e,profileName:i,relPaths:v?[v]:void 0}),Y=v?{rebaselined:[],skipped:[]}:await sg({cwd:e,profileName:i});if(T.baselined.length===0&&T.skipped.length===0&&Y.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}T.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${T.baselined.length} article${T.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),Y.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${Y.rebaselined.length} article${Y.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),T.skipped.length>0&&d({kind:"note",tone:"warn",text:`${T.skipped.length} skipped:
332
- ${T.skipped.map(H=>` - ${H.path} (${H.reason})`).join(`
333
- `)}`}),Z(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 y=await og({cwd:e,profileName:i}),v=y.onlyInLegacy.length===0&&y.onlyInManifest.length===0&&y.mappedMissingFromManifest.length===0,T=[`Legacy listing: ${y.legacyCount} \xB7 Manifest: ${y.manifestCount} \xB7 in both: ${y.inBoth}`];v?T.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(y.mappedMissingFromManifest.length&&T.push(`\u2717 ${y.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${y.mappedMissingFromManifest.slice(0,5).join(", ")}`),y.onlyInLegacy.length&&T.push(`\u26A0 ${y.onlyInLegacy.length} only in the legacy listing: ${y.onlyInLegacy.slice(0,5).join(", ")}`),y.onlyInManifest.length&&T.push(`\u26A0 ${y.onlyInManifest.length} only in the manifest: ${y.onlyInManifest.slice(0,5).join(", ")}`),T.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:v?"ok":"warn",text:T.join(`
334
- `)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=h[0];if(m){let y=await rg({cwd:e,profileName:i,relPath:m.replace(/\\/g,"/")});Ae.current=[y],qn();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let b=await Hr({cwd:e,profileName:i});for(let y of qr(b))d({kind:"note",tone:y.tone,text:y.text});Z(y=>y+1)}catch(m){d({kind:"note",tone:"error",text:`Pull failed: ${m.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}Tt({cursor:0,rows:u.map(m=>({...m,checked:m.recommended}))});return}case"audit":{if(h[0]==="--auto"){let m=te(e);if(!m){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=h[1]!=="off";Wc({...m,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 pn();u.kind==="forward-to-agent"&&u.prompt&&await ie(u.prompt,{display:u.display,quietUser:!0});return}case"check":{let u=h.find(y=>!y.startsWith("--")),m=u?` ${u}`:"",b=qc({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 y=Gc(e,u);await ie(_i(b),{display:`/check${m} --fix`,quietUser:!0});try{as(e,y,{reviewedCap:ls})}catch{}let v=qc({cwd:e,scope:u});d({kind:"note",tone:v.length===0?"ok":"warn",text:v.length===0?"\u2713 Doc-checker: all issues resolved.":So(v).join(`
335
- `)}),At(v.length===0?`Deterministic issues fixed. Next: /review${m} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${m} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${m} --fix`,reason:""});return}d({kind:"note",tone:b.length===0?"ok":"warn",text:So(b).join(`
336
- `)}),b.length>0&&At(`Found ${b.length} doc issue${b.length===1?"":"s"} above. /check${m} --fix has the agent fix them in place (or /review${m} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${m} --fix`,reason:""});return}case"structure":{let u=wn(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(`
337
- `)});return}case"reorder":{let u=Li(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}),At("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let u=Oi(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=h.includes("--fix"),b=h.filter(v=>v!=="--fix").join(" ").trim()||void 0,y=m?Gc(e,b):[];if(await ie(u.prompt,{display:u.display,quietUser:!0}),m)try{as(e,y,{reviewedCap:ls})}catch{}if(m)At("\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 v=h.filter(T=>T!=="--fix").join(" ");At(`The review listed issues above. /review${v?` ${v}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${v?` ${v}`:""} --fix`,reason:""})}return}case"capture-setup":{let u=await hn();u.kind==="forward-to-agent"&&u.prompt&&await ie(u.prompt,{display:u.display,quietUser:!0});let m=$i(e);m&&d({kind:"note",tone:"info",text:m.join(`
338
- `)});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:Ut(Mt(e)).join(`
339
- `)}),jt(dt()),Jt.current=Se(e).status==="current"||We(e);return}case"inbox":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(vi(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(Ci(),{display:"/inbox",quietUser:!0});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:m}=pi(h);if(!m&&di(e)===0){d({kind:"note",tone:"info",text:mi});return}let b=`/document${m?` ${m}`:""}${u?" --publish":""}`;await ie(fi(m,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(!ar(l.trim()))return;let{publish:u}=Pi(h);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let m=await Si({cwd:e,profileName:i});for(let y of Di(m))d({kind:"note",tone:y.startsWith("\u2713")?"ok":y.startsWith("\u2139")?"info":"warn",text:y});let b=yn(gn(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(Ti({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{ir.current=!0,d({kind:"note",tone:"info",text:`Updating ${mt}\u2026 (don\u2019t close this window)`}),Sn(!0),(await Po().finally(()=>Sn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),z("/exit"),gs("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Ro}`});return}case"screenshot":{let u=ki(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:xi(bi(e,u.scope),u.scope).join(`
340
- `)});return}if(u.mode==="single"){let M=await vo(h);M.kind==="forward-to-agent"&&M.prompt&&await ie(M.prompt,{display:M.display,quietUser:!0});return}if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=u.mode==="scope"?u.scope:void 0,b=dg(e,{scope:m}).map(M=>M.id);if(b.length===0){d({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let y=6,v=ug(b,3),T=Yo(e,"standard");nt.current=Date.now(),yt(0),I(!0);let Y=new AbortController;Re.current=Y,oe({verb:"Authoring",unit:"spec",total:v.length,done:0,active:[],rows:xn(v),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 ${v.length} partition${v.length===1?"":"s"} (\u2264${y} agents at once) on ${T.model}${T.forced?" (forced)":""}\u2026 (esc to stop)`});let H=!1;try{for await(let M of Go({cwd:e,partitions:v,promptFor:Sl,concurrency:y,profileName:i,allowProdWrites:xt.current,model:T.model,signal:Y.signal}))if(M.type==="partition_status")M.status==="running"?oe(C=>C&&{...C,active:[...C.active,M.label],rows:He(C.rows,M.label,"active"),lastAt:Date.now()}):oe(C=>C&&{...C,active:C.active.filter(E=>E!==M.label),done:C.done+1,rows:He(C.rows,M.label,M.status==="done"?"done":"failed"),lastAt:Date.now()});else if(M.type==="partition_event")oe(C=>{if(!C)return C;let E={...C,lastAt:Date.now()};return M.event.type==="tool"?E.tools=C.tools+1:M.event.type==="text"&&(E.chars=C.chars+M.event.delta.length),E});else if(M.type==="run_done"){Dt(Q=>Q+M.totalCostUsd),St(Q=>Q+M.results.reduce((Nt,It)=>Nt+It.outputTokens,0));let C=M.results.filter(Q=>Q.ok).length,E=M.aborted?"Stopped. ":"";H=!M.aborted&&u.setup;let q=M.aborted?"":H?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:M.aborted?"warn":M.ok?"ok":"warn",text:`${E}Authored specs \u2014 ${C}/${M.results.length} batches ok.${q}`})}}catch(M){d({kind:"note",tone:"error",text:`Spec authoring failed: ${M.message}`})}finally{Re.current=null,oe(null),I(!1),Z(M=>M+1)}if(H){let M=await hn();M.kind==="forward-to-agent"&&M.prompt&&await ie(M.prompt,{display:M.display,quietUser:!0});let C=$i(e);C&&d({kind:"note",tone:"info",text:C.join(`
341
- `)})}return}case"reset":{let u=Ei(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}jn.current={repoName:vn(e),targets:u,hadDevhints:$n(Vc(e))},d({kind:"note",tone:"warn",text:Ii(e,u).join(`
342
- `)}),me(vn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${s} \u2014 type /help.`})}},[e,r,i,qn,d,ke,ie,Un,pr,Es]),Vn=V(l=>{let a=(l??D).trim();if(x(""),Dn(null),wt(0),a.startsWith("/")&&(Rn.current=!1,Ve(),Yt(null),tt(h=>Sc(h,a))),!a||(hs(!1),Is(a))||Ns(a))return;Zo.current.push(a);let s=Ec(a,ys.current);if(a.startsWith("/"))d({kind:"user",text:a}),Bn(s);else if($g(s)){d({kind:"user",text:a});let h=vg(s);if(!h)ie(s,{display:a,quietUser:!0});else{try{Cg(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})},[D,Is,Ns,Bn,ie]),_s=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let a=Dc(l);if(Ac(a)){let s=jc(++pu.current,a);ys.current.set(s,a),P(s)}else P(a);return}P(l)},[P]),Et=Math.max(10,Ee-6),Os=ns(()=>Bo(w.text,Et),[w.text,Et]),hr=V(l=>k(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+l))})),[]),Gn=V(l=>k(a=>({...a,pos:Ic(Bo(a.text,Et),a.pos,l)})),[Et]),nn=V(l=>k(a=>({...a,pos:_c(Bo(a.text,Et),a.pos,l)})),[Et]),gu=["\x1B[H","\x1B[1~","\x1BOH"],yu=["\x1B[F","\x1B[4~","\x1BOF"],Ls=V((l,a)=>a.leftArrow?(hr(-1),!0):a.rightArrow?(hr(1),!0):l&&gu.includes(l)?(nn("start"),!0):l&&yu.includes(l)?(nn("end"),!0):a.ctrl&&l==="a"?(nn("start"),!0):a.ctrl&&l==="e"?(nn("end"),!0):!1,[hr,nn]);return Ih((l,a)=>{if(a.ctrl&&l==="c"){Ce.current?.close(),r();return}if(!L){if(S){if(a.escape){if(Re.current){if(!Re.current.signal.aborted){let s=(En?.verb??"work").toLowerCase(),h=En?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${s} run (finishing in-flight ${h}s)\u2026`}),Re.current.abort()}return}zt.current||(zt.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Ce.current?.interrupt());return}if(a.return){let s=D.trim();if(!s)return;lt.current.push(s),tr([...lt.current]),x("");return}if(Ls(l,a))return;if(a.upArrow){Gn(-1);return}if(a.downArrow){Gn(1);return}if(a.backspace||a.delete){R();return}l&&!a.ctrl&&!a.meta&&_s(l);return}if(rt){if(a.upArrow){it(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){it(s=>s&&{...s,cursor:Math.min(Ie.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ie.length){it(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Ie[rt.cursor];it(null);let{lines:h,changed:u,effective:m}=fn(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&&(Rs(b=>b+1),Ce.current?.setModel(m));return}if(l==="s"){let s=Ie[rt.cursor];it(null),Ce.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){it(null);return}return}if(Oe){if(a.upArrow){$t(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){$t(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Oe.rows.length){$t(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return||l==="s"){let s=Oe.rows[Oe.cursor];$t(null),mr(s.name,a.return===!0);return}if(a.escape){$t(null);return}return}if(_n){if(a.escape){Xt(null);return}if(a.leftArrow||a.tab&&a.shift){Xt(s=>s&&{tab:(s.tab-1+Te.length)%Te.length});return}if(a.rightArrow||a.tab){Xt(s=>s&&{tab:(s.tab+1)%Te.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Te.length){Xt({tab:Number(l)-1});return}return}if(Le){if(a.upArrow){vt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){vt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Le.rows.length){vt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Le.rows[Le.cursor].name;if(vt(null),!Cr(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 m=gt(s);u=!!m&&!(Ze(m)&&!m.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.`}),z("/login"),Z(m=>m+1);return}if(a.escape){vt(null);return}return}if(pe){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(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=pe.rows.length){Ct(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=pe.rows[pe.cursor],{profile:h,projectId:u}=pe;Ct(null),Wn(h,u,s);return}if(a.escape){Ct(null);return}return}if(ge){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(l&&/^[1-9]$/.test(l)&&Number(l)<=ge.rows.length){st(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=ge.rows[ge.cursor],{profile:h}=ge;st(null),Hn(h,s);return}if(a.escape){st(null);return}return}if(fe){if(a.upArrow){Tt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Tt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l===" "){Tt(s=>s&&{...s,rows:s.rows.map((h,u)=>u===s.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let s=fe.rows.filter(h=>h.checked).map(h=>h.path);if(Tt(null),s.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Ur(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){Tt(null);return}return}if(Me){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(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Me.rows.length){Pt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Me.rows[Me.cursor],h=Me.run;Pt(null),h(s.token);return}if(a.escape){Pt(null);return}return}if(qe){if(a.upArrow){Rt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Rt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=qe.rows.length){Rt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=qe.rows[qe.cursor];Rt(null),s.kind==="article"?pr(s.paths[0]):Un(s.paths);return}if(a.escape){Rt(null);return}return}if(ye){if(a.escape){at(null);return}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(Math.max(0,Ln.length-1),s.cursor+1)});return}if(a.return){let s=Ln[ye.cursor];if(s){at(null);try{d({kind:"preview",name:vn(s),text:Zc(os(rs(e,s),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${s}: ${h.message}`})}}return}if(a.backspace||a.delete){at(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){at(s=>s&&{...s,query:s.query+l,cursor:0});return}return}if(we){if(a.escape){ct(null);return}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(Math.max(0,Mn.length-1),s.cursor+1)});return}if(a.return){let s=Mn[we.cursor];if(s){ct(null),ke(s.uuid),_e.current={uuid:s.uuid,firstPrompt:s.firstPrompt,titleFired:!0},ot(s.name),is(s.uuid),bt.current=[];let h=Zi(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){ct(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){ct(s=>s&&{...s,query:s.query+l,cursor:0});return}return}if(a.tab&&!D&&ue){x(ue),Ve();return}if(!D&&et.length>0&&!Qo&&l&&/^[1-9]$/.test(l)){let s=et[Number(l)-1];if(s){x(ht(s));return}}if(!D&&(lr||Qt)&&l==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let s=lr!=null;dc(lr??Qt).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&&cr(null),u&&!s&&Ss(!0)});return}if(!Ls(l,a)){if(As){if(a.upArrow){wt(s=>Math.max(0,s-1));return}if(a.downArrow){wt(s=>Math.min(tn.length-1,s+1));return}if(a.tab){x("/"+(tn[Gt]?.name??"")+" "),wt(0);return}if(a.return){let s=tn[Gt];if(s){let h=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(bc(s.usage)&&!h){x("/"+s.name+" "),wt(0);return}Vn("/"+s.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(D!==""&&kt===null){Gn(-1);return}let s=Zo.current;if(!s.length)return;let h=kt===null?s.length-1:Math.max(0,kt-1);Dn(h),x(s[h]??"");return}if(a.downArrow){if(D!==""&&kt===null){Gn(1);return}let s=Zo.current;if(kt===null)return;let h=kt+1;h>=s.length?(Dn(null),x("")):(Dn(h),x(s[h]??""));return}}if(a.return){Vn();return}if(a.backspace||a.delete){R();return}if(a.escape){x(""),wt(0),Ve(),tt([]),Yt(null),Rn.current=!0;return}l&&!a.ctrl&&!a.meta&&_s(l)}}}),ve(()=>{if(S||L)return;let l=lt.current.shift();l!==void 0&&(tr([...lt.current]),Vn(l))},[S,L,Vn]),B(ne,{flexDirection:"column",width:Ee,children:[dr!==null&&B(ne,{marginTop:1,flexDirection:"column",children:[dr.truncated&&j(A,{dimColor:!0,children:"\u2026"}),j(A,{children:dr.text})]}),S&&(En?j(Ig,{p:En}):j(jg,{startTime:nt.current,chars:du})),!S&&xs?j(Eg,{text:xs}):null,j(ne,{borderStyle:"round",borderColor:Ds.prod?"yellow":F,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?Os.map((l,a)=>{let s=w.text.slice(l.start,l.end),h=a===Vo(Os,w.pos),u=Math.min(w.pos,l.end)-l.start;return B(A,{children:[j(A,{color:F,children:a===0?"> ":" "}),h?B(zo,{children:[s.slice(0,u),j(qt,{ch:s[u]??" "}),s.slice(u+1)]}):s||" "]},`${a}-${l.start}`)}):B(A,{children:[j(A,{color:F,children:"> "}),nr?j(qt,{ch:" "}):ue&&!S&&Ko?B(zo,{children:[j(qt,{ch:Ko[0],dim:!0}),j(A,{color:"gray",children:Ko.slice(1)})]}):ue&&!S?B(zo,{children:[j(qt,{ch:ue[0],dim:!0}),j(A,{color:"gray",children:ue.slice(1)}),j(A,{dimColor:!0,children:" (tab)"})]}):(ur.isSetup||!cu)&&!S?B(zo,{children:[j(qt,{ch:ur.text[0],dim:!0}),j(A,{color:"gray",children:ur.text.slice(1)})]}):j(qt,{ch:" "})]})}),bs.length>0&&j(ne,{flexDirection:"column",paddingX:1,children:bs.map((l,a)=>j(A,{color:"gray",children:`\u29D7 queued: ${l}`},`${a}-${l.slice(0,24)}`))}),_n?j($c,{tab:_n.tab,width:Ee}):rt?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Select model"}),j(A,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ie.map((l,a)=>B(A,{color:a===rt.cursor?F:void 0,children:[a===rt.cursor?"\u276F ":" ",`${a+1}. ${l.label}${a===rt.current?" \u2714":""}`.padEnd(16),j(A,{color:"gray",children:l.desc})]},l.label)),j(A,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Oe?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Switch connection profile"}),Oe.rows.map((l,a)=>B(A,{color:a===Oe.cursor?F:void 0,children:[a===Oe.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===Oe.current?" \u2714":""}`.padEnd(20),j(A,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?j(A,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),j(A,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Le?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Pick your Document360 environment"}),Le.rows.map((l,a)=>B(A,{color:a===Le.cursor?F:void 0,children:[a===Le.cursor?"\u276F ":" ",`${a+1}. ${l.name}`.padEnd(16),j(A,{color:"gray",children:l.apiUrl})]},l.name)),j(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):pe?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Switch workspace"}),j(A,{dimColor:!0,children:`environment ${pe.environment} \xB7 project ${pe.projectName??`${pe.projectId.slice(0,8)}\u2026`}`}),pe.rows.map((l,a)=>B(A,{color:a===pe.cursor?F:void 0,children:[a===pe.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===pe.current?" \u2714":""}`.padEnd(30),j(A,{color:"gray",children:l.type??""})]},l.id)),j(A,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ge?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Choose project"}),j(A,{dimColor:!0,children:`environment ${ge.environment}`}),ge.rows.map((l,a)=>B(A,{color:a===ge.cursor?F:void 0,children:[a===ge.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===ge.current?" \u2714":""}`.padEnd(30),j(A,{color:"gray",children:l.sub??""})]},l.id)),j(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?(()=>{let a=Math.min(Math.max(0,fe.cursor-Math.floor(7)),Math.max(0,fe.rows.length-14)),s=fe.rows.slice(a,a+14),h=fe.rows.filter(u=>u.checked).length;return B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:`Which folders back the user docs? (${h} selected of ${fe.rows.length})`}),a>0?j(A,{dimColor:!0,children:` \u2191 ${a} more`}):null,s.map((u,m)=>{let b=a+m;return B(A,{color:b===fe.cursor?F:void 0,children:[b===fe.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Ee-34)),j(A,{color:"gray",children:go(u)})]},u.path)}),a+14<fe.rows.length?j(A,{dimColor:!0,children:` \u2193 ${fe.rows.length-a-14} more`}):null,j(A,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Me?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Which category? (pick one to scope to)"}),Me.rows.map((l,a)=>{let s=a===Me.cursor,h=`${a+1}.`.padEnd(3);return B(A,{color:s?F:void 0,children:[s?"\u276F ":" ",`${h} ${l.label} (${l.count})`.padEnd(Math.min(44,Math.max(20,Ee-24))),j(A,{color:"gray",children:` ${l.token}`})]},l.token)}),j(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):qe?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),qe.rows.map((l,a)=>{let s=a===qe.cursor,h=l.indent?" ":" ",u=`${a+1}.`.padEnd(3);return B(A,{color:s?F:void 0,bold:l.kind==="category"&&!s,children:[s?"\u276F ":" ",`${h}${u} ${l.label}`.padEnd(Math.min(56,Ee-24)),l.note?j(A,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),j(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ye?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:`Preview article${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),Ln.length===0?j(A,{color:"gray",children:"no articles match"}):Ln.map((l,a)=>B(A,{color:a===ye.cursor?F:void 0,children:[a===ye.cursor?"\u276F ":" ",l]},l)),j(A,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):we?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:`Resume session${we.query?` \u2014 filter: ${we.query}`:" (type to filter)"}`}),Mn.length===0?j(A,{color:"gray",children:"no sessions match"}):Mn.map((l,a)=>B(A,{color:a===we.cursor?F:void 0,children:[a===we.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),j(A,{color:a===we.cursor?F:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ee-40))})]},l.uuid)),j(A,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):As?B(ne,{flexDirection:"column",children:[tn.map((l,a)=>B(A,{color:a===Gt?F:void 0,children:[a===Gt?"\u276F ":" ",l.usage.padEnd(22)," ",j(A,{color:a===Gt?F:"gray",children:l.name==="model"&&or?`${l.desc} (currently ${or})`:l.desc})]},l.name)),j(A,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!S&&!D&&et.length>0?B(ne,{flexDirection:"column",paddingX:1,children:[ks?j(A,{color:F,children:ks}):null,et.map((l,a)=>{let s=ht(l),h=s.slice(0,Math.max(20,Ee-5)),u=Ee-h.length-7,m=u>=12?(Tc(l)??wc(s)).slice(0,u):"";return B(A,{children:[j(A,{color:F,children:a+1})," ",h,m?j(A,{dimColor:!0,children:` \u2014 ${m}`}):null]},s)}),j(A,{dimColor:!0,children:`press 1-${et.length} to fill \xB7 esc cancel`})]}):j(ne,{paddingX:1,children:B(A,{color:"gray",children:[Ds.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${or??"model n/a"}${t.kind==="api"?Cs>0?` \xB7 ${he(Cs)}`:"":vs>0?` \xB7 ${Qe(vs)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}U();import{jsx as Mg}from"react/jsx-runtime";async function nu(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Lg(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:i}=Og(Mg(tu,{cwd:e,auth:r,profileName:n,version:o}));await i(),process.stdout.write(`
343
- `),process.exit(0)}U();import{writeCrashLog as ou,isBenignTransportError as Ug}from"document360-engine";var ru=!1;function ds(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function iu(e){if(ru)return;ru=!0;let t=(n,o)=>{if(Ug(o)){ou({kind:n,level:"transport",message:ds(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=ou({kind:n,level:"fatal",message:ds(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
344
- `+$(`\u2717 d360-writer crashed: ${ds(o)}`)+`
326
+ Model: ${J.model}${J.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:re+si(E,G,q).join(`
327
+ `)+de}),K(`/write${m?` --scope ${m}`:""}`);return}ot.current=Date.now(),bt(0),I(!0);let Lt=new AbortController;Re.current=Lt,oe({verb:"Writing",total:E.length,done:0,active:[],rows:Pn(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${H.length} article${H.length===1?"":"s"} across ${E.length} partition${E.length===1?"":"s"} (\u2264${q} agents at once) on ${J.model}${J.forced?" (forced)":""}\u2026 (esc to stop)`});let Xn=new Set;try{for await(let G of Ko({cwd:e,partitions:E,promptFor:re=>ii(re,Y,{rewrite:C||_t}),concurrency:q,profileName:i,allowProdWrites:Ct.current,model:J.model,signal:Lt.signal}))if(G.type==="partition_status")G.status==="running"?oe(re=>re&&{...re,active:[...re.active,G.label],rows:He(re.rows,G.label,"active"),lastAt:Date.now()}):oe(re=>re&&{...re,active:re.active.filter(de=>de!==G.label),done:re.done+1,rows:He(re.rows,G.label,G.status==="done"?"done":"failed"),lastAt:Date.now()});else if(G.type==="partition_event"){let re=null;if(G.event.type==="tool"){let de=Tc(G.event.name,G.event.input,E[G.index]?.paths??[]);de&&!Xn.has(de)&&(Xn.add(de),re=G.label)}oe(de=>{if(!de)return de;let Ne={...de,lastAt:Date.now()};return G.event.type==="tool"?Ne.tools=de.tools+1:G.event.type==="text"&&(Ne.chars=de.chars+G.event.delta.length),re&&(Ne.rows=Pc(Ne.rows,re)),Ne})}else if(G.type==="run_done"){jt(Ge=>Ge+G.totalCostUsd),At(Ge=>Ge+G.results.reduce((Ue,bu)=>Ue+bu.outputTokens,0));let re=G.aborted?"Stopped. ":"",de=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:G.aborted?"warn":G.ok?"ok":"warn",text:re+ai(G.results,E,de).join(`
328
+ `)}),!G.aborted&&G.ok)try{let Ge=(Xn.size>0?[...Xn]:H).map(Ue=>`${Y}/${Ue}`);cs(e,Ge,{writtenCap:us})}catch{}let Ne=G.aborted?null:li(e,Y,H);if(Ne&&d({kind:"note",tone:"warn",text:Ne}),!G.aborted&&G.ok){let Ge=m??b??"",Ue=Ge?` ${Ge}`:"";Et(Ne?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${Ue} --fix, then /review${Ue} --fix for editorial quality, then /publish --all (add /screenshot --all first if you want images).`:`Written. I\u2019d run /review${Ue} --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:Ne?`/check${Ue} --fix`:`/review${Ue} --fix`,reason:""})}}}catch(G){d({kind:"note",tone:"error",text:`Write run failed: ${G.message}`})}finally{Re.current=null,oe(null),I(!1),Q(G=>G+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:m}=ui(e);if(u.length===0&&m===0){d({kind:"note",tone:"info",text:pi});return}let b=g.join(" ").trim();if(!b&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
329
+ ${u.map(R=>` \u2022 ${R.name} (${R.docCount} doc${R.docCount===1?"":"s"})`).join(`
330
+ `)}`}),nt(u.map(R=>`/draft ${R.name}`));return}let w="",v;if(b){let R=di(u,b);R?w=R:v=b}else w=u[0]?.name??"";await ie(vo(w,v),{display:b?`/draft ${b}`:"/draft",quietUser:!0});return}case"pull":{if(!ur(l.trim()))return;let u=g.find(m=>m.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let w=Date.now(),v=await Bc({cwd:e,profileName:i});d({kind:"note",tone:"info",text:bo(v,Date.now()-w).join(`
331
+ `)});return}if(u==="--baseline"){let w=g.find(H=>!H.startsWith("--")),v=w?w.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:v?`Setting the sync baseline for ${v}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let R=await ag({cwd:e,profileName:i,relPaths:v?[v]:void 0}),Y=v?{rebaselined:[],skipped:[]}:await lg({cwd:e,profileName:i});if(R.baselined.length===0&&R.skipped.length===0&&Y.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}R.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${R.baselined.length} article${R.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),Y.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${Y.rebaselined.length} article${Y.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),R.skipped.length>0&&d({kind:"note",tone:"warn",text:`${R.skipped.length} skipped:
332
+ ${R.skipped.map(H=>` - ${H.path} (${H.reason})`).join(`
333
+ `)}`}),Q(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 ig({cwd:e,profileName:i}),v=w.onlyInLegacy.length===0&&w.onlyInManifest.length===0&&w.mappedMissingFromManifest.length===0,R=[`Legacy listing: ${w.legacyCount} \xB7 Manifest: ${w.manifestCount} \xB7 in both: ${w.inBoth}`];v?R.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(w.mappedMissingFromManifest.length&&R.push(`\u2717 ${w.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${w.mappedMissingFromManifest.slice(0,5).join(", ")}`),w.onlyInLegacy.length&&R.push(`\u26A0 ${w.onlyInLegacy.length} only in the legacy listing: ${w.onlyInLegacy.slice(0,5).join(", ")}`),w.onlyInManifest.length&&R.push(`\u26A0 ${w.onlyInManifest.length} only in the manifest: ${w.onlyInManifest.slice(0,5).join(", ")}`),R.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:v?"ok":"warn",text:R.join(`
334
+ `)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=g[0];if(m){let w=await sg({cwd:e,profileName:i,relPath:m.replace(/\\/g,"/")});Ae.current=[w],Yn();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let b=await Vr({cwd:e,profileName:i});for(let w of Gr(b))d({kind:"note",tone:w.tone,text:w.text});Q(w=>w+1)}catch(m){d({kind:"note",tone:"error",text:`Pull failed: ${m.message}`})}return}case"scope":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=cg(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}Dt({cursor:0,rows:u.map(m=>({...m,checked:m.recommended}))});return}case"audit":{if(g[0]==="--auto"){let m=te(e);if(!m){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=g[1]!=="off";Hc({...m,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 gn();u.kind==="forward-to-agent"&&u.prompt&&await ie(u.prompt,{display:u.display,quietUser:!0});return}case"check":{let u=g.find(w=>!w.startsWith("--")),m=u?` ${u}`:"",b=Vc({cwd:e,scope:u});if(g.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=zc(e,u);await ie(Oi(b),{display:`/check${m} --fix`,quietUser:!0});try{cs(e,w,{reviewedCap:us})}catch{}let v=Vc({cwd:e,scope:u});d({kind:"note",tone:v.length===0?"ok":"warn",text:v.length===0?"\u2713 Doc-checker: all issues resolved.":jo(v).join(`
335
+ `)}),Et(v.length===0?`Deterministic issues fixed. Next: /review${m} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${m} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${m} --fix`,reason:""});return}d({kind:"note",tone:b.length===0?"ok":"warn",text:jo(b).join(`
336
+ `)}),b.length>0&&Et(`Found ${b.length} doc issue${b.length===1?"":"s"} above. /check${m} --fix has the agent fix them in place (or /review${m} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${m} --fix`,reason:""});return}case"structure":{let u=vn(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(`
337
+ `)});return}case"reorder":{let u=Ui(e,g);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}),Et("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let u=Mi(e,g);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=g.includes("--fix"),b=g.find(v=>!v.startsWith("--")),w=m?zc(e,b):[];if(await ie(u.prompt,{display:u.display,quietUser:!0}),m)try{cs(e,w,{reviewedCap:us})}catch{}if(m)Et("\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 v=g.filter(R=>R!=="--fix").join(" ");Et(`The review listed issues above. /review${v?` ${v}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${v?` ${v}`:""} --fix`,reason:""})}return}case"capture-setup":{let u=await bn();u.kind==="forward-to-agent"&&u.prompt&&await ie(u.prompt,{display:u.display,quietUser:!0});let m=Ci(e);m&&d({kind:"note",tone:"info",text:m.join(`
338
+ `)});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:Ft(Wt(e)).join(`
339
+ `)}),Nt(ft()),tn.current=Se(e).status==="current"||We(e);return}case"inbox":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Ri(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(Pi(),{display:"/inbox",quietUser:!0});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:m}=mi(g);if(!m&&fi(e)===0){d({kind:"note",tone:"info",text:gi});return}let b=`/document${m?` ${m}`:""}${u?" --publish":""}`;await ie(hi(m,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(!ur(l.trim()))return;let{publish:u}=Si(g);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let m=await Ai({cwd:e,profileName:i});for(let w of ji(m))d({kind:"note",tone:w.startsWith("\u2713")?"ok":w.startsWith("\u2139")?"info":"warn",text:w});let b=xn($n(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(Di({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{lr.current=!0,d({kind:"note",tone:"info",text:`Updating ${gt}\u2026 (don\u2019t close this window)`}),En(!0),(await Do().finally(()=>En(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),K("/exit"),ys("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${So}`});return}case"screenshot":{let u=$i(g);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:vi(xi(e,u.scope),u.scope).join(`
340
+ `)});return}if(u.mode==="single"){let M=await Po(g);M.kind==="forward-to-agent"&&M.prompt&&await ie(M.prompt,{display:M.display,quietUser:!0});return}if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=u.mode==="scope"?u.scope:void 0,b=fg(e,{scope:m}).map(M=>M.id);if(b.length===0){d({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let w=6,v=pg(b,3),R=Xo(e,"standard");ot.current=Date.now(),bt(0),I(!0);let Y=new AbortController;Re.current=Y,oe({verb:"Authoring",unit:"spec",total:v.length,done:0,active:[],rows:Pn(v),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 ${v.length} partition${v.length===1?"":"s"} (\u2264${w} agents at once) on ${R.model}${R.forced?" (forced)":""}\u2026 (esc to stop)`});let H=!1;try{for await(let M of Ko({cwd:e,partitions:v,promptFor:Al,concurrency:w,profileName:i,allowProdWrites:Ct.current,model:R.model,signal:Y.signal}))if(M.type==="partition_status")M.status==="running"?oe(C=>C&&{...C,active:[...C.active,M.label],rows:He(C.rows,M.label,"active"),lastAt:Date.now()}):oe(C=>C&&{...C,active:C.active.filter(E=>E!==M.label),done:C.done+1,rows:He(C.rows,M.label,M.status==="done"?"done":"failed"),lastAt:Date.now()});else if(M.type==="partition_event")oe(C=>{if(!C)return C;let E={...C,lastAt:Date.now()};return M.event.type==="tool"?E.tools=C.tools+1:M.event.type==="text"&&(E.chars=C.chars+M.event.delta.length),E});else if(M.type==="run_done"){jt(J=>J+M.totalCostUsd),At(J=>J+M.results.reduce((_t,Lt)=>_t+Lt.outputTokens,0));let C=M.results.filter(J=>J.ok).length,E=M.aborted?"Stopped. ":"";H=!M.aborted&&u.setup;let q=M.aborted?"":H?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:M.aborted?"warn":M.ok?"ok":"warn",text:`${E}Authored specs \u2014 ${C}/${M.results.length} batches ok.${q}`})}}catch(M){d({kind:"note",tone:"error",text:`Spec authoring failed: ${M.message}`})}finally{Re.current=null,oe(null),I(!1),Q(M=>M+1)}if(H){let M=await bn();M.kind==="forward-to-agent"&&M.prompt&&await ie(M.prompt,{display:M.display,quietUser:!0});let C=Ci(e);C&&d({kind:"note",tone:"info",text:C.join(`
341
+ `)})}return}case"reset":{let u=Ii(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}_n.current={repoName:Sn(e),targets:u,hadDevhints:Tn(Yc(e))},d({kind:"note",tone:"warn",text:Li(e,u).join(`
342
+ `)}),me(Sn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${s} \u2014 type /help.`})}},[e,r,i,Yn,d,ke,ie,qn,hr,Is]),zn=V(l=>{let a=(l??D).trim();if($(""),Nn(null),$t(0),a.startsWith("/")&&(Dn.current=!1,Ve(),Xt(null),nt(g=>Ac(g,a))),!a||(ws(!1),Ls(a))||_s(a))return;nr.current.push(a);let s=Ic(a,ks.current);if(a.startsWith("/"))d({kind:"user",text:a}),sn(s);else if(Cg(s)){d({kind:"user",text:a});let g=Rg(s);if(!g)ie(s,{display:a,quietUser:!0});else{try{Pg(e,{title:g,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ie(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${g}". 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 "${g}" and the article path(s) you wrote.`,{display:a,quietUser:!0})}}else ie(s,{display:a})},[D,Ls,_s,sn,ie]),Os=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let a=jc(l);if(Ec(a)){let s=Nc(++mu.current,a);ks.current.set(s,a),T(s)}else T(a);return}T(l)},[T]),It=Math.max(10,Ee-6),Ms=rs(()=>Yo(h.text,It),[h.text,It]),yr=V(l=>k(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+l))})),[]),Kn=V(l=>k(a=>({...a,pos:Lc(Yo(a.text,It),a.pos,l)})),[It]),an=V(l=>k(a=>({...a,pos:Oc(Yo(a.text,It),a.pos,l)})),[It]),yu=["\x1B[H","\x1B[1~","\x1BOH"],ku=["\x1B[F","\x1B[4~","\x1BOF"],Us=V((l,a)=>a.leftArrow?(yr(-1),!0):a.rightArrow?(yr(1),!0):l&&yu.includes(l)?(an("start"),!0):l&&ku.includes(l)?(an("end"),!0):a.ctrl&&l==="a"?(an("start"),!0):a.ctrl&&l==="e"?(an("end"),!0):!1,[yr,an]);return Lh((l,a)=>{if(a.ctrl&&l==="c"){Ce.current?.close(),r();return}if(!O){if(S){if(a.escape){if(Re.current){if(!Re.current.signal.aborted){let s=(Ln?.verb??"work").toLowerCase(),g=Ln?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${s} run (finishing in-flight ${g}s)\u2026`}),Re.current.abort()}return}Qt.current||(Qt.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Ce.current?.interrupt());return}if(a.return){let s=D.trim();if(!s)return;ut.current.push(s),rr([...ut.current]),$("");return}if(Us(l,a))return;if(a.upArrow){Kn(-1);return}if(a.downArrow){Kn(1);return}if(a.backspace||a.delete){P();return}l&&!a.ctrl&&!a.meta&&Os(l);return}if(it){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(Ie.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ie.length){st(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Ie[it.cursor];st(null);let{lines:g,changed:u,effective:m}=yn(e,s.value??"default");for(let b of g)d({kind:"note",tone:b.startsWith("\u26A0")?"warn":b.startsWith("\u2713")?"ok":"info",text:b});u&&(Ts(b=>b+1),Ce.current?.setModel(m));return}if(l==="s"){let s=Ie[it.cursor];st(null),Ce.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){st(null);return}return}if(Le){if(a.upArrow){Rt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Rt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Le.rows.length){Rt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return||l==="s"){let s=Le.rows[Le.cursor];Rt(null),wr(s.name,a.return===!0);return}if(a.escape){Rt(null);return}return}if(Un){if(a.escape){Zt(null);return}if(a.leftArrow||a.tab&&a.shift){Zt(s=>s&&{tab:(s.tab-1+Te.length)%Te.length});return}if(a.rightArrow||a.tab){Zt(s=>s&&{tab:(s.tab+1)%Te.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Te.length){Zt({tab:Number(l)-1});return}return}if(Oe){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(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Oe.rows.length){Pt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Oe.rows[Oe.cursor].name;if(Pt(null),!Tr(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 m=yt(s);u=!!m&&!(et(m)&&!m.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"),Q(m=>m+1);return}if(a.escape){Pt(null);return}return}if(pe){if(a.upArrow){Tt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Tt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=pe.rows.length){Tt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=pe.rows[pe.cursor],{profile:g,projectId:u}=pe;Tt(null),Bn(g,u,s);return}if(a.escape){Tt(null);return}return}if(ge){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(l&&/^[1-9]$/.test(l)&&Number(l)<=ge.rows.length){at(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=ge.rows[ge.cursor],{profile:g}=ge;at(null),Gn(g,s);return}if(a.escape){at(null);return}return}if(fe){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(l===" "){Dt(s=>s&&{...s,rows:s.rows.map((g,u)=>u===s.cursor?{...g,checked:!g.checked}:g)});return}if(a.return){let s=fe.rows.filter(g=>g.checked).map(g=>g.path);if(Dt(null),s.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Hr(e,s),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${s.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let g of s)d({kind:"note",tone:"info",text:` ${g}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){Dt(null);return}return}if(Me){if(a.upArrow){lt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){lt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Me.rows.length){lt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Me.rows[Me.cursor],g=Me.run;lt(null),g(s.token);return}if(a.escape){lt(null);return}return}if(qe){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(l&&/^[1-9]$/.test(l)&&Number(l)<=qe.rows.length){St(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=qe.rows[qe.cursor];St(null),s.kind==="article"?hr(s.paths[0]):qn(s.paths);return}if(a.escape){St(null);return}return}if(we){if(a.escape){ct(null);return}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(Math.max(0,Fn.length-1),s.cursor+1)});return}if(a.return){let s=Fn[we.cursor];if(s){ct(null);try{d({kind:"preview",name:Sn(s),text:tu(is(ss(e,s),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${s}: ${g.message}`})}}return}if(a.backspace||a.delete){ct(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){ct(s=>s&&{...s,query:s.query+l,cursor:0});return}return}if(ye){if(a.escape){dt(null);return}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(Math.max(0,Hn.length-1),s.cursor+1)});return}if(a.return){let s=Hn[ye.cursor];if(s){dt(null),ke(s.uuid),_e.current={uuid:s.uuid,firstPrompt:s.firstPrompt,titleFired:!0},rt(s.name),as(s.uuid),vt.current=[];let g=ts(e,s.uuid);for(let u of g)d(u);d({kind:"note",tone:"ok",text:g.length?`Resumed "${s.name}" \u2014 restored ${g.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){dt(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){dt(s=>s&&{...s,query:s.query+l,cursor:0});return}return}if(a.tab&&!D&&ae){$(ae),Ve();return}if(!D&&tt.length>0&&!er&&l&&/^[1-9]$/.test(l)){let s=tt[Number(l)-1];if(s){$(wt(s));return}}if(!D&&(dr||en)&&l==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let s=dr!=null;fc(dr??en).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&&pr(null),u&&!s&&As(!0)});return}if(!Us(l,a)){if(Es){if(a.upArrow){$t(s=>Math.max(0,s-1));return}if(a.downArrow){$t(s=>Math.min(rn.length-1,s+1));return}if(a.tab){$("/"+(rn[Kt]?.name??"")+" "),$t(0);return}if(a.return){let s=rn[Kt];if(s){let g=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(xc(s.usage)&&!g){$("/"+s.name+" "),$t(0);return}zn("/"+s.name+(g?" "+g:""));return}}}else{if(a.upArrow){if(D!==""&&xt===null){Kn(-1);return}let s=nr.current;if(!s.length)return;let g=xt===null?s.length-1:Math.max(0,xt-1);Nn(g),$(s[g]??"");return}if(a.downArrow){if(D!==""&&xt===null){Kn(1);return}let s=nr.current;if(xt===null)return;let g=xt+1;g>=s.length?(Nn(null),$("")):(Nn(g),$(s[g]??""));return}}if(a.return){zn();return}if(a.backspace||a.delete){P();return}if(a.escape){$(""),$t(0),Ve(),nt([]),Xt(null),Dn.current=!0;return}l&&!a.ctrl&&!a.meta&&Os(l)}}}),ve(()=>{if(S||O)return;let l=ut.current.shift();l!==void 0&&(rr([...ut.current]),zn(l))},[S,O,zn]),B(ne,{flexDirection:"column",width:Ee,children:[mr!==null&&B(ne,{marginTop:1,flexDirection:"column",children:[mr.truncated&&j(A,{dimColor:!0,children:"\u2026"}),j(A,{children:mr.text})]}),S&&(Ln?j(Lg,{p:Ln}):j(Ng,{startTime:ot.current,chars:fu})),!S&&vs?j(Ig,{text:vs}):null,j(ne,{borderStyle:"round",borderColor:js.prod?"yellow":F,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?Ms.map((l,a)=>{let s=h.text.slice(l.start,l.end),g=a===zo(Ms,h.pos),u=Math.min(h.pos,l.end)-l.start;return B(A,{children:[j(A,{color:F,children:a===0?"> ":" "}),g?B(Qo,{children:[s.slice(0,u),j(Gt,{ch:s[u]??" "}),s.slice(u+1)]}):s||" "]},`${a}-${l.start}`)}):B(A,{children:[j(A,{color:F,children:"> "}),ir?j(Gt,{ch:" "}):ae&&!S&&Jo?B(Qo,{children:[j(Gt,{ch:Jo[0],dim:!0}),j(A,{color:"gray",children:Jo.slice(1)})]}):ae&&!S?B(Qo,{children:[j(Gt,{ch:ae[0],dim:!0}),j(A,{color:"gray",children:ae.slice(1)}),j(A,{dimColor:!0,children:" (tab)"})]}):(fr.isSetup||!du)&&!S?B(Qo,{children:[j(Gt,{ch:fr.text[0],dim:!0}),j(A,{color:"gray",children:fr.text.slice(1)})]}):j(Gt,{ch:" "})]})}),xs.length>0&&j(ne,{flexDirection:"column",paddingX:1,children:xs.map((l,a)=>j(A,{color:"gray",children:`\u29D7 queued: ${l}`},`${a}-${l.slice(0,24)}`))}),Un?j(Cc,{tab:Un.tab,width:Ee}):it?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Select model"}),j(A,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ie.map((l,a)=>B(A,{color:a===it.cursor?F:void 0,children:[a===it.cursor?"\u276F ":" ",`${a+1}. ${l.label}${a===it.current?" \u2714":""}`.padEnd(16),j(A,{color:"gray",children:l.desc})]},l.label)),j(A,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Le?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Switch connection profile"}),Le.rows.map((l,a)=>B(A,{color:a===Le.cursor?F:void 0,children:[a===Le.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===Le.current?" \u2714":""}`.padEnd(20),j(A,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?j(A,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),j(A,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Oe?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Pick your Document360 environment"}),Oe.rows.map((l,a)=>B(A,{color:a===Oe.cursor?F:void 0,children:[a===Oe.cursor?"\u276F ":" ",`${a+1}. ${l.name}`.padEnd(16),j(A,{color:"gray",children:l.apiUrl})]},l.name)),j(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):pe?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Switch workspace"}),j(A,{dimColor:!0,children:`environment ${pe.environment} \xB7 project ${pe.projectName??`${pe.projectId.slice(0,8)}\u2026`}`}),pe.rows.map((l,a)=>B(A,{color:a===pe.cursor?F:void 0,children:[a===pe.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===pe.current?" \u2714":""}`.padEnd(30),j(A,{color:"gray",children:l.type??""})]},l.id)),j(A,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ge?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Choose project"}),j(A,{dimColor:!0,children:`environment ${ge.environment}`}),ge.rows.map((l,a)=>B(A,{color:a===ge.cursor?F:void 0,children:[a===ge.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===ge.current?" \u2714":""}`.padEnd(30),j(A,{color:"gray",children:l.sub??""})]},l.id)),j(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?(()=>{let a=Math.min(Math.max(0,fe.cursor-Math.floor(7)),Math.max(0,fe.rows.length-14)),s=fe.rows.slice(a,a+14),g=fe.rows.filter(u=>u.checked).length;return B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:`Which folders back the user docs? (${g} selected of ${fe.rows.length})`}),a>0?j(A,{dimColor:!0,children:` \u2191 ${a} more`}):null,s.map((u,m)=>{let b=a+m;return B(A,{color:b===fe.cursor?F:void 0,children:[b===fe.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Ee-34)),j(A,{color:"gray",children:ko(u)})]},u.path)}),a+14<fe.rows.length?j(A,{dimColor:!0,children:` \u2193 ${fe.rows.length-a-14} more`}):null,j(A,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Me?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Which category? (pick one to scope to)"}),Me.rows.map((l,a)=>{let s=a===Me.cursor,g=`${a+1}.`.padEnd(3);return B(A,{color:s?F:void 0,children:[s?"\u276F ":" ",`${g} ${l.label} (${l.count})`.padEnd(Math.min(44,Math.max(20,Ee-24))),j(A,{color:"gray",children:` ${l.token}`})]},l.token)}),j(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):qe?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),qe.rows.map((l,a)=>{let s=a===qe.cursor,g=l.indent?" ":" ",u=`${a+1}.`.padEnd(3);return B(A,{color:s?F:void 0,bold:l.kind==="category"&&!s,children:[s?"\u276F ":" ",`${g}${u} ${l.label}`.padEnd(Math.min(56,Ee-24)),l.note?j(A,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),j(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):we?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:`Preview article${we.query?` \u2014 filter: ${we.query}`:" (type to filter)"}`}),Fn.length===0?j(A,{color:"gray",children:"no articles match"}):Fn.map((l,a)=>B(A,{color:a===we.cursor?F:void 0,children:[a===we.cursor?"\u276F ":" ",l]},l)),j(A,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):ye?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:`Resume session${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),Hn.length===0?j(A,{color:"gray",children:"no sessions match"}):Hn.map((l,a)=>B(A,{color:a===ye.cursor?F:void 0,children:[a===ye.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),j(A,{color:a===ye.cursor?F:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ee-40))})]},l.uuid)),j(A,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Es?B(ne,{flexDirection:"column",children:[rn.map((l,a)=>B(A,{color:a===Kt?F:void 0,children:[a===Kt?"\u276F ":" ",l.usage.padEnd(22)," ",j(A,{color:a===Kt?F:"gray",children:l.name==="model"&&sr?`${l.desc} (currently ${sr})`:l.desc})]},l.name)),j(A,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!S&&!D&&tt.length>0?B(ne,{flexDirection:"column",paddingX:1,children:[$s?j(A,{color:F,children:$s}):null,tt.map((l,a)=>{let s=wt(l),g=s.slice(0,Math.max(20,Ee-5)),u=Ee-g.length-7,m=u>=12?(Dc(l)??bc(s)).slice(0,u):"";return B(A,{children:[j(A,{color:F,children:a+1})," ",g,m?j(A,{dimColor:!0,children:` \u2014 ${m}`}):null]},s)}),j(A,{dimColor:!0,children:`press 1-${tt.length} to fill \xB7 esc cancel`})]}):j(ne,{paddingX:1,children:B(A,{color:"gray",children:[js.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${sr??"model n/a"}${t.kind==="api"?Ps>0?` \xB7 ${he(Ps)}`:"":Rs>0?` \xB7 ${Qe(Rs)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}U();import{jsx as Wg}from"react/jsx-runtime";async function ru(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Ug(t);r.kind==="none"&&(console.error(""),console.error(x("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:i}=Mg(Wg(ou,{cwd:e,auth:r,profileName:n,version:o}));await i(),process.stdout.write(`
343
+ `),process.exit(0)}U();import{writeCrashLog as iu,isBenignTransportError as Fg}from"document360-engine";var su=!1;function fs(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function au(e){if(su)return;su=!0;let t=(n,o)=>{if(Fg(o)){iu({kind:n,level:"transport",message:fs(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=iu({kind:n,level:"fatal",message:fs(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
344
+ `+x(`\u2717 d360-writer crashed: ${fs(o)}`)+`
345
345
  `),r&&process.stderr.write(f(` Crash details: ${r}`)+`
346
346
  `+f(" Run: d360-writer logs")+`
347
- `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var qg=Fg(import.meta.url),su=qg("../package.json");iu("d360-writer");var De=new Wg;function ps(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}De.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=>{ps(e),await eo({profile:e.profile,manual:e.manual})});De.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{ps(e),await Ks({profile:e.profile})});De.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{ps(e),await zs({profile:e.profile})});var fs=De.command("profile").description("Manage connection profiles for the current repo");fs.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>to(process.cwd()));fs.command("use <name>").description("Set the default profile for this repo").action(e=>no(process.cwd(),e));fs.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>oo(process.cwd(),e));var au=De.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");au.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>_t(process.cwd(),e.profile));au.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Fs(process.cwd(),e,t.profile)});var lu=De.command("project").description("Choose the Document360 project for this repo (active profile's identity)");lu.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Qn(process.cwd(),e.profile));lu.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await qs(process.cwd(),e,t.profile)});De.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(uo(),$a));await e()});De.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>Zs());De.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(()=>($o(),bl)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});De.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(su.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(Hg.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 ea(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 cc(e.cwd,e.auth,e.profile):await nu(e.cwd,e.auth,e.profile,su.version)});De.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
347
+ `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Vg=qg(import.meta.url),lu=Vg("../package.json");au("d360-writer");var De=new Hg;function ms(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}De.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=>{ms(e),await oo({profile:e.profile,manual:e.manual})});De.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{ms(e),await Qs({profile:e.profile})});De.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{ms(e),await Xs({profile:e.profile})});var hs=De.command("profile").description("Manage connection profiles for the current repo");hs.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>ro(process.cwd()));hs.command("use <name>").description("Set the default profile for this repo").action(e=>io(process.cwd(),e));hs.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>so(process.cwd(),e));var cu=De.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");cu.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Ot(process.cwd(),e.profile));cu.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await qs(process.cwd(),e,t.profile)});var uu=De.command("project").description("Choose the Document360 project for this repo (active profile's identity)");uu.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>eo(process.cwd(),e.profile));uu.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Vs(process.cwd(),e,t.profile)});De.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(mo(),Ca));await e()});De.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>ta());De.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(()=>(Ro(),xl)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});De.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(lu.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(Bg.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 na(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 dc(e.cwd,e.auth,e.profile):await ru(e.cwd,e.auth,e.profile,lu.version)});De.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});