document360-writer 0.5.51 → 0.5.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +97 -97
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var uc=Object.defineProperty;var Dn=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var ei=(e,t)=>{for(var n in t)uc(e,n,{get:t[n],enumerable:!0})};import Be from"picocolors";var F,dc,pc,fc,ti,zt,f,$,M,j,_,se,Pe,W=Dn(()=>{"use strict";F="#7f56d9",[dc,pc,fc]=[127,86,217],ti=e=>Be.isColorSupported?`\x1B[38;2;${dc};${pc};${fc}m${e}\x1B[39m`:e,zt=e=>Be.bold(ti(e)),f=e=>Be.dim(e),$=e=>Be.red(e),M=e=>Be.yellow(e),j=e=>Be.green(e),_=ti,se=e=>Be.gray(e),Pe=e=>Be.bold(e)});import{existsSync as Wn,writeFileSync as Qt,readFileSync as Qc,readdirSync as Jc}from"node:fs";import{join as Zc}from"node:path";import{devHintsGuidePath as Fn,hintsDir as ki,architectureDir as $i,messagesDir as tr,creatorNotesPath as bi,devhintsStatePath as vi,ensureDir as Un,writeMessage as eu,listOpenForDev as tu}from"document360-engine";function Ci(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var dc=Object.defineProperty;var En=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var oi=(e,t)=>{for(var n in t)dc(e,n,{get:t[n],enumerable:!0})};import Be from"picocolors";var F,pc,fc,mc,ri,Kt,f,$,M,j,_,se,Pe,W=En(()=>{"use strict";F="#7f56d9",[pc,fc,mc]=[127,86,217],ri=e=>Be.isColorSupported?`\x1B[38;2;${pc};${fc};${mc}m${e}\x1B[39m`:e,Kt=e=>Be.bold(ri(e)),f=e=>Be.dim(e),$=e=>Be.red(e),M=e=>Be.yellow(e),j=e=>Be.green(e),_=ri,se=e=>Be.gray(e),Pe=e=>Be.bold(e)});import{existsSync as qn,writeFileSync as Zt,readFileSync as Jc,readdirSync as Zc}from"node:fs";import{join as eu}from"node:path";import{devHintsGuidePath as Bn,hintsDir as $i,architectureDir as Pi,messagesDir as rr,creatorNotesPath as vi,devhintsStatePath as Ri,ensureDir as Hn,writeMessage as tu,listOpenForDev as nu}from"document360-engine";function Ti(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
3
3
 
4
4
  <!-- devhints script v${re} \xB7 maintained by document360-writer (/devhints). -->
5
5
 
@@ -159,7 +159,7 @@ whenever \`git status\` shows changes under \`.d360-writer/\`, commit them (e.g.
159
159
  \`git add .d360-writer && git commit -m "docs: sync d360-writer output"\`) before you push. The docs agent
160
160
  will remind you when it leaves changes, but it's your call to commit them. Without this, the team's docs
161
161
  and \u2014 critically \u2014 the sync map are stranded on one machine.
162
- `}function nu(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
162
+ `}function ou(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
163
163
 
164
164
  <!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
165
165
  The builder agent reads this FIRST and treats it as authoritative when writing the architecture
@@ -173,60 +173,60 @@ Anything only a human knows that would help document this product. For example:
173
173
  - Gotchas or non-obvious behavior.
174
174
 
175
175
  (Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
176
- `}function Et(e){Un(ki(e)),Un($i(e)),Un(tr(e));for(let n of[ki(e),tr(e)]){let o=Zc(n,".gitkeep");Wn(o)||Qt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
177
- `)}Wn(bi(e))||Qt(bi(e),nu()),Qt(Fn(e),Ci());let t=Me(e);return Ri(e,new Date().toISOString()),t}async function Pi(e,t){for(let n of It(Et(t.cwd)))console.log(n);return{kind:"continue"}}function at(){return[`This is document360-writer's dev hand-off setup (v${re}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20134). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current; AND each session, check"," `.d360-writer/messages/` for open questions from the docs agent and answer them \u2014 all per"," `.d360-writer/DEV-HINTS-GUIDE.md`. If that section is already there, leave it (refine in place only if"," wrong) \u2014 do NOT add a duplicate. Then commit `.d360-writer/` and the memory-file change ONLY if"," something actually changed.","4. Two-way messages (Part 3): check `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each \u2014 fold durable facts into the architecture brief and/or drop"," a reply (`from: dev`, `kind: answer`, `re: <id>`) \u2014 then set the question's frontmatter `status: done`."," If there are none, continue.","5. Then STOP and ask me for tribal knowledge \u2014 present it as a clearly-marked, standalone prompt on its"," own line (NOT buried in prose) and WAIT for my reply before doing anything else. Use this shape:",' "\u23F8 YOUR INPUT NEEDED \u2014 Any tribal knowledge that would help document this product? (folder map,',` terminology, what to prioritize or skip, gotchas.) Type it below, or reply 'none' / 'carry on' to skip."`," If I give you anything, phrase it clearly and append it to `.d360-writer/architecture/CREATOR-NOTES.md`"," (keep the existing header comment and every note already there; only add). If I say 'none'/'carry on', continue.",`6. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${re},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","7. When everything is done, print the completion line, THEN the next command as its own copy-paste"," block so it is unmistakable. Pick the matching first line:",' \u2022 first-time setup: "\u2705 Setup complete. Now switch to the document360-writer terminal and paste this:"',' \u2022 a refresh (brief/notes already existed): "\u2705 Hand-off refreshed. Back in the document360-writer terminal, paste this:"'," Then, on its OWN line, fenced as a code block so it copies cleanly:"," ```"," write the docs for this repo"," ```"].join(`
178
- `)}function nr(e){try{let t=Qc(vi(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Ri(e,t){let o={...nr(e)??{},emittedVersion:re,emittedAt:t};Qt(vi(e),`${JSON.stringify(o,null,2)}
179
- `)}function Jt(e){try{return Jc($i(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Me(e){let n=nr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<re?"stale":"current",completedVersion:n}}function Hn(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:re};try{if(!Wn(Fn(e)))return n;let o=nr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;re>r&&(Un(tr(e)),Qt(Fn(e),Ci()),Ri(e,t),n.guideRefreshed=!0),re>s&&(tu(e).some(p=>p.kind==="request"&&p.subject.startsWith(xi))||(eu(e,{id:`onb${re}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${xi}${re})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${re}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",at()].join(`
180
- `)}),n.notifiedBuilder=!0))}catch{}return n}function qn(e){if(!Wn(Fn(e)))return[];let t=Me(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${re}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,At,at(),At,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function or(){return['document360-writer (its "docs agent") has been removed from this repository. Please undo its dev\u2192docs',"hand-off setup and restore this repo to how it was before \u2014 in order:","","1. In this repo's agent-memory file (CLAUDE.md, or AGENTS.md \u2014 whichever it edited), REMOVE the",' "Documentation hand-off" section that was added (the rule about dropping hint files in'," `.d360-writer/hints/`, keeping `.d360-writer/architecture/` current, and checking"," `.d360-writer/messages/`). Leave everything else in that file untouched.","2. The `.d360-writer/` folder is already deleted on disk. If it was committed, remove it from version"," control too \u2014 `git rm -r --cached .d360-writer` (if it still resolves) \u2014 and commit the deletions.","3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
181
- `)}function Bn(){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):",At,or(),At]}function It(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${re}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",At,at(),At,"","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 At,re,xi,lt=Dn(()=>{"use strict";At="-".repeat(64),re=5;xi="Re-run dev\u2194docs onboarding (protocol v"});var Mi={};ei(Mi,{initCommand:()=>sr,scaffoldInit:()=>rr});import{input as Zt,confirm as ou}from"@inquirer/prompts";import{basename as Ti,join as Gn}from"node:path";import{existsSync as Nt,readFileSync as ru,readdirSync as su,writeFileSync as iu}from"node:fs";import{writeProjectConfig as Si,readProjectConfig as au,projectConfigPath as Di,writerDir as lu,DEFAULT_DOCS_DIR as ji,DEFAULT_CAPTURE_DIR as Ai,DEFAULT_OUTPUT_DIR as Ei}from"document360-engine";function rr(e,t="berlin"){let n=Di(e);if(Nt(n))return{created:!1,path:n,profileName:""};let o={projectId:Ni(e)??Ti(e),docsDir:ji,captureDir:Ai,outputDir:Ei,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:_i(e)};return Si(o,e),Ii(e),{created:!0,path:n,profileName:t}}function Ii(e){let t=Gn(lu(e),".gitignore");Nt(t)||iu(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
182
- `),"utf8")}async function sr(){let e=process.cwd(),t=Di(e);if(Nt(t)&&!await ou({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Ni(e)??Ti(e),o=await Zt({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Zt({message:"Capture directory (where document360-capture .spec.ts files live):",default:Ai}),s=await Zt({message:"Screenshot output directory:",default:Ei}),u=await Zt({message:"Default connection profile name:",default:"berlin"}),p=await Zt({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),h={projectId:o,docsDir:ji,captureDir:r,outputDir:s,profiles:{[u]:{connection:{environment:p},production:!1}},defaultProfile:u,authoritativeSourceFiles:_i(e)},k=au(e);k?.terminologyGlossary&&(h.terminologyGlossary=k.terminologyGlossary),Si(h,e),Ii(e);let x=Et(e);console.log(""),console.log(j(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${u}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of It(x))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Ni(e){let t=Gn(e,"package.json");if(!Nt(t))return null;try{return JSON.parse(ru(t,"utf8")).name??null}catch{return null}}function _i(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Nt(Gn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Gn(e,n);Nt(o)&&!cu(o)&&t.push(n)}return t}function cu(e){try{return su(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Yn=Dn(()=>{"use strict";W();lt()});var Sa={};ei(Sa,{doctorCommand:()=>an,renderDoctorChecks:()=>Ta,runDoctorChecks:()=>Ra});import{existsSync as Od}from"node:fs";import{d360GetAll as Ud,getAccessToken as Wd,isExpired as Kr,loadProfileMap as Fd,loadTokens as Hd,packageSkillsDir as Ca,projectConfigPath as qd,readProjectConfig as Bd,DEFAULT_DOCS_DIR as Gd,fetchManifestSummary as Yd,resolveActiveProfile as Vd,classifyClaudeAuth as zd,CLAUDE_CODE_SETUP_HINT as Pa,resolveModelSetting as Xd,probeModel as Kd,D360AuthError as Qd}from"document360-engine";async function Ra(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=zd();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. ${Pa}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Pa});let r=Xd(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let b=await Kd(e,r.model??void 0);b.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(b.latencyMs/1e3).toFixed(1)}s`}):b.timedOut?t.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):t.push({level:"fail",label:`Model call failed \u2014 ${b.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let s=Bd(e);if(!s)return t.push({level:"fail",label:`No ${qd(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let u=(s.docsDir??Gd).replace(/\/+$/,"");t.push(s.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${u}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let h;try{h=Vd(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(b){return t.push({level:"fail",label:`Profile config: ${b.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=Hd(h.name);k?Kr(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Kr(k)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(k.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${h.name})`}),t.push(h.project.workspaceId?{level:"ok",label:`Workspace: ${h.project.workspaceName??h.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let x=Fd(e,h.name);x?x.projectId&&h.project.projectId&&x.projectId!==h.project.projectId?t.push({level:"fail",label:`Category map projectId (${x.projectId}) \u2260 profile projectId (${h.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(x.articles).length} articles, ${Object.keys(x.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${h.name}" (created on first /publish)`}),t.push(Od(Ca())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Ca()}`,fix:"Reinstall document360-writer (broken install)"});let D=Me(e);if(D.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${re})`}):D.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${D.completedVersion}, current is v${re}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!Kr(k)||k.refreshToken)){let b={profile:h.name,connection:h.connection};try{await Wd(b);let C=await Ud(b,"/v3/projects");t.push({level:"ok",label:`API reachable (${h.connection.apiUrl}) \u2014 ${C.length} project(s) visible`})}catch(C){t.push({level:"fail",label:`API call failed: ${C.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let P=x?.projectId??h.project.projectId;if(P&&h.project.workspaceId)try{let C=await Yd(b,P,h.project.workspaceId);if(C){let N=(C.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${h.connection.name} (${C.languages?.length??0} language${(C.languages?.length??0)===1?"":"s"}) \xB7 hash ${N||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${h.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(C){C instanceof Qd||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(C.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${h.project.projectName??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 (${C.message.slice(0,80)})`})}}return t}function Ta(e){let t=[""];for(let r of e){let s=r.level==="ok"?j("\u2713"):r.level==="warn"?M("\u26A0"):$("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${_(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?j(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function an(e,t){console.log(f("Running checks\u2026"));for(let n of Ta(await Ra(t.cwd)))console.log(n);return{kind:"continue"}}var no=Dn(()=>{"use strict";lt();W()});import{Command as Im}from"commander";import{createRequire as Nm}from"node:module";import{AUTH_MODES as _m}from"document360-engine";import{input as Tc}from"@inquirer/prompts";import{loginPkce as Sc,refreshTokens as Dc,toStoredTokens as ai,clearTokens as jc,decodeJwtClaims as ii,isExpired as Ac,loadTokens as Ec,saveTokens as li,resolveActiveProfile as In,setProfileProject as Ic,readProjectConfig as Nc}from"document360-engine";W();import{select as mc}from"@inquirer/prompts";import{resolveActiveProfile as hc,setProfileProject as gc,resolveProjectId as wc,listWorkspaces as yc}from"document360-engine";async function Xt(e,t){let n=hc(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??wc(o);return{workspaces:await yc(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var ni=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Ko(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){gc(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function oi(e,t,n){let o;try{o=await Xt(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=Ko(o.workspaces,t);return r?(jn(e,o.profile,o.projectId,r.id,r.name),console.log(j(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function jt(e,t){let n;try{n=await Xt(e,t)}catch(k){console.log($(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:u}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===u?_("\u25CF"):" "} ${ni(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await mc({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${ni(k)}${k.id===u?" (current)":""}`,value:k.id}))}),h=o.find(k=>k.id===p);jn(e,s,r,p,h?.name),console.log(j(`\u2713 Workspace set to "${h?.name??p}" for profile "${s}".`))}W();import{select as kc}from"@inquirer/prompts";import{resolveActiveProfile as bc,setProfileProject as xc,listProjects as $c}from"document360-engine";async function Ge(e,t){let n=bc(e,t),o={profile:n.name,connection:n.connection};return{projects:await $c(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ri=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Qo(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 An(e,t,n,o){xc(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function si(e,t,n){let o;try{o=await Ge(e,n)}catch(s){return console.log($(`Could not list projects: ${s.message}`)),1}let r=Qo(o.projects,t);return r?(An(e,o.profile,r.id,r.name),console.log(j(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log($(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function En(e,t){let n;try{n=await Ge(e,t)}catch(h){console.log($(`Could not list projects: ${h.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===s?_("\u25CF"):" "} ${ri(h)} ${f(h.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let u=await kc({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${ri(h)}${h.id===s?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===u);An(e,r,u,p?.name),console.log(j(`\u2713 Project set to "${p?.name??u}" for profile "${r}". Next: pick a workspace.`))}W();import vc from"picocolors";function Cc(e=process.env){return e.FORCE_HYPERLINK==="0"||!vc.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 Pc(e,t=e,n){return Cc(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Rc=/https?:\/\/[^\s\x1b]+/g;function Kt(e,t){return e.replace(Rc,n=>Pc(n,n,t))}function ci(e){return{...ii(e.idToken)??{},...ii(e.accessToken)??{}}}function Nn(e){let t=ci(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 _n(e){let t=In(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 Sc(n,{manual:e.manual,promptForRedirect:s=>Tc({message:s})},s=>console.log(Kt(s))),r=ai(t.name,o);if(li(r),await Jo(r,t.name,s=>console.log(f(s))),console.log(""),console.log(j(`\u2713 Logged in to "${t.name}" as ${Nn(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{Nc(process.cwd())?.profiles?.[t.name]&&(console.log(""),await jt(process.cwd(),t.name))}catch{}}async function Jo(e,t,n){let r=ci(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(In(process.cwd(),t).project.projectId)return;let u;try{let{projects:p}=await Ge(process.cwd(),t);u=p.find(h=>h.id===r)?.name}catch{}Ic(process.cwd(),t,{projectId:r,projectName:u}),n(` Project "${u??r}" written to profile "${t}".`)}catch{}}async function ui(e){let t=In(process.cwd(),e.profile),n=t.connection,o=Ec(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":""}: ${Nn(o)}`),Ac(o))if(o.refreshToken)try{let r=ai(t.name,await Dc(n,o.refreshToken));li(r),console.log(j(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(M(`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(M("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 di(e){let t=In(process.cwd(),e.profile);jc(t.name)?console.log(j(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as pi,writeProjectConfig as _c,resolveActiveProfile as Mc,loadTokens as Lc,isExpired as Oc}from"document360-engine";function Mn(e){let t=pi(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?_("\u25CF "):" ",s=o.production?M(" \u26A0 PRODUCTION"):"",u=o.connection.environment??"(inline)",p=Lc(n),h=p?Oc(p)&&!p.refreshToken?M("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${u}${s} [${h}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Ln(e,t){let n=pi(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,_c(n,e);let o=n.profiles[t].production?M(" \u26A0 PRODUCTION"):"";console.log(j(`\u2713 Default profile is now "${t}"${o}`))}function On(e,t){try{let n=Mc(e,t);console.log(""),console.log(`Profile ${_(n.name)}${n.production?M(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}W();import{existsSync as Uc,readdirSync as Wc,statSync as fi}from"node:fs";import{join as mi}from"node:path";import{apiLogDir as Fc}from"document360-engine";function hi(){let e=Fc();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Uc(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Wc(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(fi(mi(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(fi(mi(e,r)).size/1024).toFixed(1);console.log(` ${$(r)} ${f(`${s} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as Hc,resolveAuth as qc,findByName as Bc,slugify as Gc,touchSession as Yc,upsertSession as Vc,resolveActiveProfile as zc}from"document360-engine";async function gi(e,t,n,o,r,s){let u=qc(n);u.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)),u.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=zc(e,r)}catch(b){console.error($(`Document360 profile error: ${b.message}`)),process.exit(2)}p.production&&(console.error(M(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let h;if(o){let b=Bc(e,o);b||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),h=b.uuid,console.error(f(`Resuming "${b.name}"`))}let k=Hc({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),x=h??null,D=1;for await(let b of k.send(t))switch(b.type){case"session":if(!x){x=b.sessionId;let P=new Date().toISOString();Vc({uuid:x,name:Gc(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(b.delta);break;case"tool":console.error(se(` \u2699 ${b.name}`));break;case"result":D=b.ok?0:1,console.error(f(`(${b.inputTokens}\u2192${b.outputTokens} tokens`+(b.costUsd>0?`, $${b.costUsd<.01?b.costUsd.toFixed(4):b.costUsd.toFixed(2)}`:"")+")")),b.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${b.message}`)),process.exit(1)}x&&Yc(x),process.stdout.write(`
183
- `),process.exit(D)}import{createInterface as Kp}from"node:readline/promises";import{createSession as ws,resolveAuth as Qp,getSession as Jp,setTitle as Zp,slugify as ef,touchSession as tl,upsertSession as tf,generateTitle as nf,resolveActiveProfile as nl,resolveModelSetting as of,readProjectConfig as rf,decodeJwtClaims as Za,isExpired as sf,loadTokens as af}from"document360-engine";var Re=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --all to author capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then run d360-capture in your app's repo \u2014 it signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot --list",s:"See capture status \u2014 which specs exist and which are done."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"d360-capture is a separate Playwright CLI \u2014 run it in the app's repo (needs its URL + a login)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"Author capture specs (--all / --list)."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function Xc(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 wi(){let e=["document360-writer \u2014 help",""];for(let t of Re){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push(Xc(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function Zo(){console.log("");for(let e of wi())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}W();import{getSession as Kc}from"document360-engine";async function yi(e,t){let n=t.currentUuid(),o=n?Kc(n):void 0;return console.log(o?f(`
176
+ `}function Nt(e){Hn($i(e)),Hn(Pi(e)),Hn(rr(e));for(let n of[$i(e),rr(e)]){let o=eu(n,".gitkeep");qn(o)||Zt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
177
+ `)}qn(vi(e))||Zt(vi(e),ou()),Zt(Bn(e),Ti());let t=Me(e);return Di(e,new Date().toISOString()),t}async function Si(e,t){for(let n of _t(Nt(t.cwd)))console.log(n);return{kind:"continue"}}function lt(){return[`This is document360-writer's dev hand-off setup (v${re}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20134). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current; AND each session, check"," `.d360-writer/messages/` for open questions from the docs agent and answer them \u2014 all per"," `.d360-writer/DEV-HINTS-GUIDE.md`. If that section is already there, leave it (refine in place only if"," wrong) \u2014 do NOT add a duplicate. Then commit `.d360-writer/` and the memory-file change ONLY if"," something actually changed.","4. Two-way messages (Part 3): check `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each \u2014 fold durable facts into the architecture brief and/or drop"," a reply (`from: dev`, `kind: answer`, `re: <id>`) \u2014 then set the question's frontmatter `status: done`."," If there are none, continue.","5. Then STOP and ask me for tribal knowledge \u2014 present it as a clearly-marked, standalone prompt on its"," own line (NOT buried in prose) and WAIT for my reply before doing anything else. Use this shape:",' "\u23F8 YOUR INPUT NEEDED \u2014 Any tribal knowledge that would help document this product? (folder map,',` terminology, what to prioritize or skip, gotchas.) Type it below, or reply 'none' / 'carry on' to skip."`," If I give you anything, phrase it clearly and append it to `.d360-writer/architecture/CREATOR-NOTES.md`"," (keep the existing header comment and every note already there; only add). If I say 'none'/'carry on', continue.",`6. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${re},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","7. When everything is done, print the completion line, THEN the next command as its own copy-paste"," block so it is unmistakable. Pick the matching first line:",' \u2022 first-time setup: "\u2705 Setup complete. Now switch to the document360-writer terminal and paste this:"',' \u2022 a refresh (brief/notes already existed): "\u2705 Hand-off refreshed. Back in the document360-writer terminal, paste this:"'," Then, on its OWN line, fenced as a code block so it copies cleanly:"," ```"," write the docs for this repo"," ```"].join(`
178
+ `)}function sr(e){try{let t=Jc(Ri(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Di(e,t){let o={...sr(e)??{},emittedVersion:re,emittedAt:t};Zt(Ri(e),`${JSON.stringify(o,null,2)}
179
+ `)}function en(e){try{return Zc(Pi(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Me(e){let n=sr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<re?"stale":"current",completedVersion:n}}function Gn(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:re};try{if(!qn(Bn(e)))return n;let o=sr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;re>r&&(Hn(rr(e)),Zt(Bn(e),Ti()),Di(e,t),n.guideRefreshed=!0),re>s&&(nu(e).some(p=>p.kind==="request"&&p.subject.startsWith(Ci))||(tu(e,{id:`onb${re}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Ci}${re})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${re}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",lt()].join(`
180
+ `)}),n.notifiedBuilder=!0))}catch{}return n}function Yn(e){if(!qn(Bn(e)))return[];let t=Me(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${re}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,It,lt(),It,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function ir(){return['document360-writer (its "docs agent") has been removed from this repository. Please undo its dev\u2192docs',"hand-off setup and restore this repo to how it was before \u2014 in order:","","1. In this repo's agent-memory file (CLAUDE.md, or AGENTS.md \u2014 whichever it edited), REMOVE the",' "Documentation hand-off" section that was added (the rule about dropping hint files in'," `.d360-writer/hints/`, keeping `.d360-writer/architecture/` current, and checking"," `.d360-writer/messages/`). Leave everything else in that file untouched.","2. The `.d360-writer/` folder is already deleted on disk. If it was committed, remove it from version"," control too \u2014 `git rm -r --cached .d360-writer` (if it still resolves) \u2014 and commit the deletions.","3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
181
+ `)}function Vn(){return['\u{1F9F9} One leftover: your builder still has the "Documentation hand-off" rule in its CLAUDE.md / AGENTS.md'," (reset only clears d360-writer's own .d360-writer/ folder \u2014 never your repo's files)."," To restore it, paste this prompt into your repo's coding agent (Claude Code / Codex / Cursor):",It,ir(),It]}function _t(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${re}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",It,lt(),It,"","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 It,re,Ci,ct=En(()=>{"use strict";It="-".repeat(64),re=5;Ci="Re-run dev\u2194docs onboarding (protocol v"});var Ui={};oi(Ui,{initCommand:()=>lr,scaffoldInit:()=>ar});import{input as tn,confirm as ru}from"@inquirer/prompts";import{basename as ji,join as zn}from"node:path";import{existsSync as Mt,readFileSync as su,readdirSync as iu,writeFileSync as au}from"node:fs";import{writeProjectConfig as Ai,readProjectConfig as lu,projectConfigPath as Ei,writerDir as cu,DEFAULT_DOCS_DIR as Ii,DEFAULT_CAPTURE_DIR as Ni,DEFAULT_OUTPUT_DIR as _i}from"document360-engine";function ar(e,t="berlin"){let n=Ei(e);if(Mt(n))return{created:!1,path:n,profileName:""};let o={projectId:Li(e)??ji(e),docsDir:Ii,captureDir:Ni,outputDir:_i,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Oi(e)};return Ai(o,e),Mi(e),{created:!0,path:n,profileName:t}}function Mi(e){let t=zn(cu(e),".gitignore");Mt(t)||au(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
182
+ `),"utf8")}async function lr(){let e=process.cwd(),t=Ei(e);if(Mt(t)&&!await ru({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Li(e)??ji(e),o=await tn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await tn({message:"Capture directory (where document360-capture .spec.ts files live):",default:Ni}),s=await tn({message:"Screenshot output directory:",default:_i}),c=await tn({message:"Default connection profile name:",default:"berlin"}),p=await tn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:Ii,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Oi(e)},k=lu(e);k?.terminologyGlossary&&(g.terminologyGlossary=k.terminologyGlossary),Ai(g,e),Mi(e);let x=Nt(e);console.log(""),console.log(j(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of _t(x))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Li(e){let t=zn(e,"package.json");if(!Mt(t))return null;try{return JSON.parse(su(t,"utf8")).name??null}catch{return null}}function Oi(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Mt(zn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=zn(e,n);Mt(o)&&!uu(o)&&t.push(n)}return t}function uu(e){try{return iu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Xn=En(()=>{"use strict";W();ct()});var Aa={};oi(Aa,{doctorCommand:()=>cn,renderDoctorChecks:()=>ja,runDoctorChecks:()=>Da});import{existsSync as Ud}from"node:fs";import{d360GetAll as Wd,getAccessToken as Fd,isExpired as Zr,loadProfileMap as Hd,loadTokens as qd,packageSkillsDir as Ta,projectConfigPath as Bd,readProjectConfig as Gd,DEFAULT_DOCS_DIR as Yd,fetchManifestSummary as Vd,resolveActiveProfile as zd,classifyClaudeAuth as Xd,CLAUDE_CODE_SETUP_HINT as Sa,resolveModelSetting as Kd,probeModel as Qd,D360AuthError as Jd}from"document360-engine";async function Da(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=Xd();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. ${Sa}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Sa});let r=Kd(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let b=await Qd(e,r.model??void 0);b.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(b.latencyMs/1e3).toFixed(1)}s`}):b.timedOut?t.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):t.push({level:"fail",label:`Model call failed \u2014 ${b.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let s=Gd(e);if(!s)return t.push({level:"fail",label:`No ${Bd(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??Yd).replace(/\/+$/,"");t.push(s.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let g;try{g=zd(e),t.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(b){return t.push({level:"fail",label:`Profile config: ${b.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=qd(g.name);k?Zr(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Zr(k)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(k.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${g.name})`}),t.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let x=Hd(e,g.name);x?x.projectId&&g.project.projectId&&x.projectId!==g.project.projectId?t.push({level:"fail",label:`Category map projectId (${x.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(x.articles).length} articles, ${Object.keys(x.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),t.push(Ud(Ta())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Ta()}`,fix:"Reinstall document360-writer (broken install)"});let D=Me(e);if(D.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${re})`}):D.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${D.completedVersion}, current is v${re}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!Zr(k)||k.refreshToken)){let b={profile:g.name,connection:g.connection};try{await Fd(b);let C=await Wd(b,"/v3/projects");t.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${C.length} project(s) visible`})}catch(C){t.push({level:"fail",label:`API call failed: ${C.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let P=x?.projectId??g.project.projectId;if(P&&g.project.workspaceId)try{let C=await Vd(b,P,g.project.workspaceId);if(C){let N=(C.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${g.connection.name} (${C.languages?.length??0} language${(C.languages?.length??0)===1?"":"s"}) \xB7 hash ${N||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${g.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(C){C instanceof Jd||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(C.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.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 (${C.message.slice(0,80)})`})}}return t}function ja(e){let t=[""];for(let r of e){let s=r.level==="ok"?j("\u2713"):r.level==="warn"?M("\u26A0"):$("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${_(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?j(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function cn(e,t){console.log(f("Running checks\u2026"));for(let n of ja(await Da(t.cwd)))console.log(n);return{kind:"continue"}}var so=En(()=>{"use strict";ct();W()});import{Command as Nm}from"commander";import{createRequire as _m}from"node:module";import{AUTH_MODES as Mm}from"document360-engine";import{input as Sc}from"@inquirer/prompts";import{loginPkce as Dc,refreshTokens as jc,toStoredTokens as ui,clearTokens as Ac,decodeJwtClaims as ci,isExpired as Ec,loadTokens as Ic,saveTokens as di,resolveActiveProfile as Mn,setProfileProject as Nc,readProjectConfig as _c}from"document360-engine";W();import{select as hc}from"@inquirer/prompts";import{resolveActiveProfile as gc,setProfileProject as wc,resolveProjectId as yc,listWorkspaces as kc}from"document360-engine";async function Qt(e,t){let n=gc(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??yc(o);return{workspaces:await kc(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var si=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Zo(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function In(e,t,n,o,r){wc(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ii(e,t,n){let o;try{o=await Qt(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=Zo(o.workspaces,t);return r?(In(e,o.profile,o.projectId,r.id,r.name),console.log(j(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Et(e,t){let n;try{n=await Qt(e,t)}catch(k){console.log($(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===c?_("\u25CF"):" "} ${si(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await hc({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${si(k)}${k.id===c?" (current)":""}`,value:k.id}))}),g=o.find(k=>k.id===p);In(e,s,r,p,g?.name),console.log(j(`\u2713 Workspace set to "${g?.name??p}" for profile "${s}".`))}W();import{select as bc}from"@inquirer/prompts";import{resolveActiveProfile as xc,setProfileProject as $c,listProjects as vc}from"document360-engine";async function Ge(e,t){let n=xc(e,t),o={profile:n.name,connection:n.connection};return{projects:await vc(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ai=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function er(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function Nn(e,t,n,o){$c(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function li(e,t,n){let o;try{o=await Ge(e,n)}catch(s){return console.log($(`Could not list projects: ${s.message}`)),1}let r=er(o.projects,t);return r?(Nn(e,o.profile,r.id,r.name),console.log(j(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log($(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function _n(e,t){let n;try{n=await Ge(e,t)}catch(g){console.log($(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===s?_("\u25CF"):" "} ${ai(g)} ${f(g.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await bc({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${ai(g)}${g.id===s?" (current)":""}`,value:g.id}))}),p=o.find(g=>g.id===c);Nn(e,r,c,p?.name),console.log(j(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import Cc from"picocolors";function Pc(e=process.env){return e.FORCE_HYPERLINK==="0"||!Cc.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 Rc(e,t=e,n){return Pc(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Tc=/https?:\/\/[^\s\x1b]+/g;function Jt(e,t){return e.replace(Tc,n=>Rc(n,n,t))}function pi(e){return{...ci(e.idToken)??{},...ci(e.accessToken)??{}}}function Ln(e){let t=pi(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 On(e){let t=Mn(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 Dc(n,{manual:e.manual,promptForRedirect:s=>Sc({message:s})},s=>console.log(Jt(s))),r=ui(t.name,o);if(di(r),await tr(r,t.name,s=>console.log(f(s))),console.log(""),console.log(j(`\u2713 Logged in to "${t.name}" as ${Ln(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{_c(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Et(process.cwd(),t.name))}catch{}}async function tr(e,t,n){let r=pi(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Mn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await Ge(process.cwd(),t);c=p.find(g=>g.id===r)?.name}catch{}Nc(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function fi(e){let t=Mn(process.cwd(),e.profile),n=t.connection,o=Ic(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":""}: ${Ln(o)}`),Ec(o))if(o.refreshToken)try{let r=ui(t.name,await jc(n,o.refreshToken));di(r),console.log(j(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(M(`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(M("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 mi(e){let t=Mn(process.cwd(),e.profile);Ac(t.name)?console.log(j(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as hi,writeProjectConfig as Mc,resolveActiveProfile as Lc,loadTokens as Oc,isExpired as Uc}from"document360-engine";function Un(e){let t=hi(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?_("\u25CF "):" ",s=o.production?M(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Oc(n),g=p?Uc(p)&&!p.refreshToken?M("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${c}${s} [${g}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Wn(e,t){let n=hi(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,Mc(n,e);let o=n.profiles[t].production?M(" \u26A0 PRODUCTION"):"";console.log(j(`\u2713 Default profile is now "${t}"${o}`))}function Fn(e,t){try{let n=Lc(e,t);console.log(""),console.log(`Profile ${_(n.name)}${n.production?M(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}W();import{existsSync as Wc,readdirSync as Fc,statSync as gi}from"node:fs";import{join as wi}from"node:path";import{apiLogDir as Hc}from"document360-engine";function yi(){let e=Hc();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Wc(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Fc(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(gi(wi(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(gi(wi(e,r)).size/1024).toFixed(1);console.log(` ${$(r)} ${f(`${s} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as qc,resolveAuth as Bc,findByName as Gc,slugify as Yc,touchSession as Vc,upsertSession as zc,resolveActiveProfile as Xc}from"document360-engine";async function ki(e,t,n,o,r,s){let c=Bc(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=Xc(e,r)}catch(b){console.error($(`Document360 profile error: ${b.message}`)),process.exit(2)}p.production&&(console.error(M(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let g;if(o){let b=Gc(e,o);b||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),g=b.uuid,console.error(f(`Resuming "${b.name}"`))}let k=qc({cwd:e,resume:g,profileName:r,allowProdWrites:s===!0}),x=g??null,D=1;for await(let b of k.send(t))switch(b.type){case"session":if(!x){x=b.sessionId;let P=new Date().toISOString();zc({uuid:x,name:Yc(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(b.delta);break;case"tool":console.error(se(` \u2699 ${b.name}`));break;case"result":D=b.ok?0:1,console.error(f(`(${b.inputTokens}\u2192${b.outputTokens} tokens`+(b.costUsd>0?`, $${b.costUsd<.01?b.costUsd.toFixed(4):b.costUsd.toFixed(2)}`:"")+")")),b.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${b.message}`)),process.exit(1)}x&&Vc(x),process.stdout.write(`
183
+ `),process.exit(D)}import{createInterface as Qp}from"node:readline/promises";import{createSession as bs,resolveAuth as Jp,getSession as Zp,setTitle as ef,slugify as tf,touchSession as rl,upsertSession as nf,generateTitle as of,resolveActiveProfile as sl,resolveModelSetting as rf,readProjectConfig as sf,decodeJwtClaims as nl,isExpired as af,loadTokens as lf}from"document360-engine";var Re=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --all to author capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then run d360-capture in your app's repo \u2014 it signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot --list",s:"See capture status \u2014 which specs exist and which are done."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"d360-capture is a separate Playwright CLI \u2014 run it in the app's repo (needs its URL + a login)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"Author capture specs (--all / --list)."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function Kc(e){switch(e.t){case"head":return e.s;case"text":return` ${e.s}`;case"dim":return` ${e.s}`;case"sub":return e.s;case"good":return` ${e.s}`;case"step":return` ${e.n}. ${e.s}`;case"cmd":return` ${e.name.padEnd(20)} ${e.s}`;case"gap":return""}}function bi(){let e=["document360-writer \u2014 help",""];for(let t of Re){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push(Kc(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function nr(){console.log("");for(let e of bi())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}W();import{getSession as Qc}from"document360-engine";async function xi(e,t){let n=t.currentUuid(),o=n?Qc(n):void 0;return console.log(o?f(`
184
184
  (conversation reset \u2014 "${o.name}" is still available via /resume)
185
185
  `):f(`
186
186
  (conversation reset \u2014 agent will start fresh on the next prompt)
187
- `)),{kind:"clear"}}async function er(){return{kind:"exit"}}Yn();W();import{readMcpConfig as ir,writeMcpConfig as Li}from"document360-engine";async function Vn(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(uu(),{kind:"continue"}):t==="add"?(du(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(pu(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 uu(){let e=ir(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
187
+ `)),{kind:"clear"}}async function or(){return{kind:"exit"}}Xn();W();import{readMcpConfig as cr,writeMcpConfig as Wi}from"document360-engine";async function Kn(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(du(),{kind:"continue"}):t==="add"?(pu(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(fu(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 du(){let e=cr(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
188
188
  No MCP servers registered. Add one with /mcp add <name> <type> <ref>
189
- `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${_(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${_(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function du(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=ir(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let u={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let h=o[++p],k=h?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log($(`-H expects key:value (no spaces). Got: ${h??"(nothing)"}`));return}u[k[1].trim()]=k[2].trim()}else{console.log($(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(u).length>0?u:void 0}}r.servers[t]=s,Li(r),console.log(""),console.log(j(`\u2713 Registered "${t}" (${n})`)),console.log(M(" 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 pu(e){let t=e[0];if(!t){console.log($("Usage: /mcp remove <name>"));return}let n=ir();if(!n.servers[t]){console.log($(`No server named "${t}".`));return}delete n.servers[t],Li(n),console.log(j(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as Tu}from"node:fs";import{join as Su}from"node:path";import{select as Du}from"@inquirer/prompts";import{computeSyncStatus as hr,planPartitions as ju,relatedArticlePaths as Au,resolveModelForOperation as Eu,runPartitioned as Iu,loadProfileMap as Nu,resolveActiveProfile as _u,resolveCrossLinks as Mu}from"document360-engine";import z from"picocolors";import qi from"wrap-ansi";import pr from"string-width";W();import Ye from"picocolors";import ar from"wrap-ansi";import lr from"string-width";var Oi=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Ui=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Wi=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function fu(e){let t=e.replace(/\r/g,"").split(`
190
- `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(Oi(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Ui(t[o+1])){let p=Wi(r);o+=2;let h=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)h.push(Wi(t[o++]));n.push({kind:"table",header:p,rows:h});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);)p.push(t[o++].replace(/^\s*([-*]|\d+\.)\s+/,""));n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let u=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Oi(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Ui(t[o+1]));)u.push(t[o++]);n.push({kind:"para",text:u.join(" ")})}return n}function cr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ye.bold(t.slice(2,-2)):t.startsWith("`")?_(t.slice(1,-1)):Ye.italic(t.slice(1,-1)))}var mu=(e,t)=>e+" ".repeat(Math.max(0,t-lr(e)));function hu(e,t,n){let o=e.length,r=e.map((C,N)=>Math.max(lr(C),...t.map(I=>lr(I[N]??"")))),s=Math.max(24,n),u=3*o+1,p=[...r],h=()=>p.reduce((C,N)=>C+N,0)+u,k=0;for(;h()>s&&k++<1e4;){let C=-1,N=6;for(let I=0;I<o;I++)p[I]>N&&(N=p[I],C=I);if(C===-1)break;p[C]-=1}let x=(C,N,I)=>Ye.gray(C+p.map(O=>"\u2500".repeat(O+2)).join(N)+I),D=Ye.gray("\u2502"),b=(C,N)=>{let I=p.map((pe,ne)=>{let De=C[ne]??"",ue=N?Ye.bold(De):cr(De);return ar(ue,pe,{hard:!0}).split(`
191
- `)}),O=Math.max(...I.map(pe=>pe.length)),J=[];for(let pe=0;pe<O;pe++)J.push(p.map((ne,De)=>`${D} ${mu(I[De][pe]??"",ne)} `).join("")+D);return J.join(`
189
+ `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${_(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${_(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function pu(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log($("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log($(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=cr(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let g=o[++p],k=g?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log($(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}c[k[1].trim()]=k[2].trim()}else{console.log($(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(c).length>0?c:void 0}}r.servers[t]=s,Wi(r),console.log(""),console.log(j(`\u2713 Registered "${t}" (${n})`)),console.log(M(" 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 fu(e){let t=e[0];if(!t){console.log($("Usage: /mcp remove <name>"));return}let n=cr();if(!n.servers[t]){console.log($(`No server named "${t}".`));return}delete n.servers[t],Wi(n),console.log(j(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as Su}from"node:fs";import{join as Du}from"node:path";import{select as ju}from"@inquirer/prompts";import{computeSyncStatus as yr,planPartitions as Au,relatedArticlePaths as Eu,resolveModelForOperation as Iu,runPartitioned as Nu,loadProfileMap as _u,resolveActiveProfile as Mu,resolveCrossLinks as Lu}from"document360-engine";import z from"picocolors";import Yi from"wrap-ansi";import hr from"string-width";W();import Ye from"picocolors";import ur from"wrap-ansi";import dr from"string-width";var Fi=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Hi=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),qi=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function mu(e){let t=e.replace(/\r/g,"").split(`
190
+ `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(Fi(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Hi(t[o+1])){let p=qi(r);o+=2;let g=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)g.push(qi(t[o++]));n.push({kind:"table",header:p,rows:g});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);)p.push(t[o++].replace(/^\s*([-*]|\d+\.)\s+/,""));n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Fi(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Hi(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function pr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ye.bold(t.slice(2,-2)):t.startsWith("`")?_(t.slice(1,-1)):Ye.italic(t.slice(1,-1)))}var hu=(e,t)=>e+" ".repeat(Math.max(0,t-dr(e)));function gu(e,t,n){let o=e.length,r=e.map((C,N)=>Math.max(dr(C),...t.map(I=>dr(I[N]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],g=()=>p.reduce((C,N)=>C+N,0)+c,k=0;for(;g()>s&&k++<1e4;){let C=-1,N=6;for(let I=0;I<o;I++)p[I]>N&&(N=p[I],C=I);if(C===-1)break;p[C]-=1}let x=(C,N,I)=>Ye.gray(C+p.map(O=>"\u2500".repeat(O+2)).join(N)+I),D=Ye.gray("\u2502"),b=(C,N)=>{let I=p.map((pe,ne)=>{let De=C[ne]??"",ue=N?Ye.bold(De):pr(De);return ur(ue,pe,{hard:!0}).split(`
191
+ `)}),O=Math.max(...I.map(pe=>pe.length)),J=[];for(let pe=0;pe<O;pe++)J.push(p.map((ne,De)=>`${D} ${hu(I[De][pe]??"",ne)} `).join("")+D);return J.join(`
192
192
  `)},P=[x("\u250C","\u252C","\u2510"),b(e,!0)];return P.push(t.length===0?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524")),t.forEach((C,N)=>{P.push(b(C,!1)),P.push(N===t.length-1?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524"))}),P.join(`
193
- `)}function gu(e,t){switch(e.kind){case"heading":return Ye.bold(e.text);case"hr":return Ye.gray("\u2500".repeat(t));case"para":return ar(cr(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=ar(cr(n),Math.max(10,t-4)).split(`
193
+ `)}function wu(e,t){switch(e.kind){case"heading":return Ye.bold(e.text);case"hr":return Ye.gray("\u2500".repeat(t));case"para":return ur(pr(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=ur(pr(n),Math.max(10,t-4)).split(`
194
194
  `);return" \u2022 "+o+r.map(s=>`
195
195
  `+s).join("")}).join(`
196
196
  `);case"code":return e.lines.map(n=>Ye.gray(" "+n)).join(`
197
- `);case"table":return hu(e.header,e.rows,t)}}function ur(e,t){let n=Math.max(20,t);return fu(e).map(o=>gu(o,n)).join(`
198
-
199
- `)}W();import wu from"picocolors";var yu=[127,86,217],ku=[22,38,43],Fi={T:yu,E:ku},en=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],dr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,bu=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Hi(){if(!wu.isColorSupported)return[];let e=en[0].length,t=[];for(let n=0;n<en.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Fi[en[n][r]],u=n+1<en.length?Fi[en[n+1][r]]:void 0;s&&u?o+=`${dr(s)}${bu(u)}\u2580\x1B[49m\x1B[39m`:s?o+=`${dr(s)}\u2580\x1B[39m`:u?o+=`${dr(u)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function tn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function me(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Ve(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var _t=(e,t)=>` ${e.padEnd(13)}${t}`;function xu(e,t){let n=[zt("\u270E document360-writer")+z.gray(` v${e.version}`),z.gray(" Reads your code, writes your docs."),"",_t("Claude:",`${e.claude}${z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),_t("Document360:",e.configured?e.loggedOut?z.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?z.gray(` (${e.sessionHint})`):""}`:z.yellow("not set up \u2014 run /init")),_t("Profile:",e.configured?`${e.profile}${z.gray(` (${e.apiUrl})`)}${e.prod?z.bold(z.yellow(" \u26A0 PRODUCTION")):""}`:z.gray("\u2014 (run /init)")),_t("Project:",e.project),_t("Mode:",z.gray(e.mode)),_t("cwd:",z.gray(e.cwd))],o=Hi();if(o.length===0)return n.join(`
200
- `);let r=2,s=3,u=pr(o[0]);if(!(t>=r+u+s+Math.max(...n.map(x=>pr(x)))))return[...o.map(x=>" "+x),...n].join(`
201
- `);let h=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let x=0;x<Math.max(o.length+h,n.length);x++){let D=o[x-h]??" ".repeat(u);k.push((" ".repeat(r)+D+" ".repeat(s)+(n[x]??"")).trimEnd())}return k.join(`
202
- `)}var $u={error:z.red,warn:z.yellow,ok:z.green,info:z.gray};function fr(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return xu(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),u=50,p=e.text.split(`
203
- `).flatMap(k=>qi(k,s,{hard:!0}).split(`
204
- `)),h=Math.max(0,p.length-u);return h>0&&(p=[...p.slice(0,u),z.dim(`\u2026 +${h} more lines`)]),`
205
- `+p.map((k,x)=>o+(x===0?_(" \u276F "):" ")+k+" ".repeat(Math.max(0,s-pr(k))+1)+r).join(`
197
+ `);case"table":return gu(e.header,e.rows,t)}}function fr(e,t){let n=Math.max(20,t);return mu(e).map(o=>wu(o,n)).join(`
198
+
199
+ `)}W();import yu from"picocolors";var ku=[127,86,217],bu=[22,38,43],Bi={T:ku,E:bu},nn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],mr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,xu=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Gi(){if(!yu.isColorSupported)return[];let e=nn[0].length,t=[];for(let n=0;n<nn.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Bi[nn[n][r]],c=n+1<nn.length?Bi[nn[n+1][r]]:void 0;s&&c?o+=`${mr(s)}${xu(c)}\u2580\x1B[49m\x1B[39m`:s?o+=`${mr(s)}\u2580\x1B[39m`:c?o+=`${mr(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function on(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function me(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Ve(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Lt=(e,t)=>` ${e.padEnd(13)}${t}`;function $u(e,t){let n=[Kt("\u270E document360-writer")+z.gray(` v${e.version}`),z.gray(" Reads your code, writes your docs."),"",Lt("Claude:",`${e.claude}${z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Lt("Document360:",e.configured?e.loggedOut?z.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?z.gray(` (${e.sessionHint})`):""}`:z.yellow("not set up \u2014 run /init")),Lt("Profile:",e.configured?`${e.profile}${z.gray(` (${e.apiUrl})`)}${e.prod?z.bold(z.yellow(" \u26A0 PRODUCTION")):""}`:z.gray("\u2014 (run /init)")),Lt("Project:",e.project),Lt("Mode:",z.gray(e.mode)),Lt("cwd:",z.gray(e.cwd))],o=Gi();if(o.length===0)return n.join(`
200
+ `);let r=2,s=3,c=hr(o[0]);if(!(t>=r+c+s+Math.max(...n.map(x=>hr(x)))))return[...o.map(x=>" "+x),...n].join(`
201
+ `);let g=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let x=0;x<Math.max(o.length+g,n.length);x++){let D=o[x-g]??" ".repeat(c);k.push((" ".repeat(r)+D+" ".repeat(s)+(n[x]??"")).trimEnd())}return k.join(`
202
+ `)}var vu={error:z.red,warn:z.yellow,ok:z.green,info:z.gray};function gr(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return $u(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),c=50,p=e.text.split(`
203
+ `).flatMap(k=>Yi(k,s,{hard:!0}).split(`
204
+ `)),g=Math.max(0,p.length-c);return g>0&&(p=[...p.slice(0,c),z.dim(`\u2026 +${g} more lines`)]),`
205
+ `+p.map((k,x)=>o+(x===0?_(" \u276F "):" ")+k+" ".repeat(Math.max(0,s-hr(k))+1)+r).join(`
206
206
  `)}case"assistant":return`
207
- `+ur(e.text,n);case"tool":{let o=e.arg!==null?z.gray(`${e.sep}(${e.arg})`):"";return`
208
- `+qi(z.green("\u25CF ")+z.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?z.red:z.gray,r=e.lines.map((s,u)=>o((u===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(z.dim(` \u2026 +${e.hidden} lines`)),r.join(`
209
- `)}case"diff":{let o=u=>u===1?"":"s",s=[z.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(z.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
210
- `)}case"link":return e.lines.map(o=>_(Kt(` \u2B95 ${o}`))).join(`
207
+ `+fr(e.text,n);case"tool":{let o=e.arg!==null?z.gray(`${e.sep}(${e.arg})`):"";return`
208
+ `+Yi(z.green("\u25CF ")+z.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?z.red:z.gray,r=e.lines.map((s,c)=>o((c===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(z.dim(` \u2026 +${e.hidden} lines`)),r.join(`
209
+ `)}case"diff":{let o=c=>c===1?"":"s",s=[z.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(z.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
210
+ `)}case"link":return e.lines.map(o=>_(Jt(` \u2B95 ${o}`))).join(`
211
211
  `);case"preview":return`
212
- `+zt(`\u25A3 Preview \u2014 ${e.name}`)+`
213
-
214
- `+ur(e.text,n);case"note":return`
215
- `+$u[e.tone](Kt(e.text));case"done":return`
216
- `+(e.ok?z.magenta("\u2736 "):z.red("\u2736 "))+z.gray(`Cooked for ${tn(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${me(e.costUsd)}`:""))}}function Bi(e,t){return e.map(n=>fr(n,t)).join(`
217
- `)}import{resolveActiveProfile as vu,loadTokens as Cu,isExpired as Pu,decodeJwtClaims as Gi}from"document360-engine";function Ru(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Le(e,t){try{let n=vu(e,t),o=Cu(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Pu(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let u={...Gi(o.idToken)??{},...Gi(o.accessToken)??{}}.doc360_project_id;if(typeof u=="string"&&u&&u!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${Ru(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var nn=3;function gr(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, strip every <!-- SCREENSHOT ... --> block while keeping the visible [Screenshot: ...] line, normalize cross-article links).","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself \u2014 do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
218
- `)}var Yi={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function on(e){return e.filter(t=>t.path!==null&&t.status in Yi&&!t.link).map(t=>({path:t.path,label:Yi[t.status]}))}function zn(e){return e.filter(t=>t.link).length}function wr(e,t){try{let n=Nu(e,_u(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Mu(Tu(Su(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages not published yet \u2014 they show as plain text for now and turn into live links once those pages are published.`}catch{return null}}function Lu(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 Vi(e){let t=[];e.length>1&&t.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(o=>o.path),indent:!1});let n=new Map;for(let o of e){let r=o.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),s=n.get(r);s?s.push(o):n.set(r,[o])}for(let o of[...n.keys()].sort()){let r=n.get(o).sort((s,u)=>s.path.localeCompare(u.path));t.push({kind:"category",label:`${Lu(o)} (${r.length})`,paths:r.map(s=>s.path),indent:!1});for(let s of r){let u=s.path.replace(/\\/g,"/").split("/").pop()??s.path;t.push({kind:"article",label:u,paths:[s.path],indent:!0,note:s.label})}}return t}function Xn(e){return[`Run the publish-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures) and remind me drafts need review in the portal."].join(`
219
- `)}function yr(e,t,n){let o=b=>t[b.index]?.paths.length??0,r=e.filter(b=>b.ok),s=e.filter(b=>!b.ok),u=e.reduce((b,P)=>b+o(P),0),p=r.reduce((b,P)=>b+o(P),0),h=n==="api"?`${me(e.reduce((b,P)=>b+P.costUsd,0))} total`:Ve(e.reduce((b,P)=>b+P.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,x=b=>`${b} article${b===1?"":"s"}`,D=[];if(s.length===0)D.push(`Published ${x(u)} (${k}) successfully \xB7 ${h}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${x(u)} (${k}) \xB7 ${h}.`),D.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let b of s)D.push(` \u2717 ${b.label}${b.error?` \u2014 ${b.error}`:""}`)}return D}async function mr(e,t){let n=ju(t),{model:o}=Eu(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${nn} 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 Iu({cwd:e.cwd,partitions:n,promptFor:s=>Xn(s.paths),concurrency:nn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:o}))if(r.type==="partition_status")r.status==="running"?console.log(f(` \u25B8 ${r.label} \u2014 publishing\u2026`)):r.status==="done"?console.log(j(` \u2713 ${r.label}`)):console.log($(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let s=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of yr(r.results,n,s))console.log(r.ok?j(p):M(p));let u=wr(e.cwd,e.profileName);u&&console.log(f(u))}}catch(r){console.log($(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Kn(e,t,n){let o=Au(e,n);if(o.length===0)return[];let r=new Set(on((await hr({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function zi(e,t){let n=Le(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Kn(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(j("\u2713 All related articles are already published.")),{kind:"continue"}):await mr(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await hr({cwd:t?.cwd??process.cwd()}),s=on(r.entries),u=zn(r.entries);return u>0&&console.log(M(`\u26A0 ${u} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),s.length===0?(console.log(j(u>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):t?await mr(t,s.map(p=>p.path)):{kind:"forward-to-agent",prompt:Xn(s.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log($(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let s=await hr({cwd:t?.cwd??process.cwd()});r=on(s.entries);let u=zn(s.entries);u>0&&console.log(M(`\u26A0 ${u} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`))}catch(s){return console.log($(`Could not compute sync status: ${s.message}`)),console.log(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(j("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(f(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${f(`(${s.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>Du({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await mr(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:gr(o),display:`/publish ${o}`}}async function rn(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
220
- `),display:"/audit"}}W();import{checkbox as Ou}from"@inquirer/prompts";import{inventoryRepo as Uu,readProjectConfig as Xi,writeProjectConfig as Wu}from"document360-engine";function kr(e,t){let n=Xi(e);n&&(n.authoritativeSourceFiles=t,Wu(n,e))}function Qn(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 Ki(e,t){let n=t?.cwd??process.cwd();if(!Xi(n))return console.log($("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Uu(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(_("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(Qn(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Ou({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Qn(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(f("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};kr(n,r),console.log(j(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as Yu}from"@inquirer/prompts";import{applyPull as xr,computeSyncStatus as ta,compareRemoteSources as Vu,planPull as na,planImport as zu,applyImport as Xu,establishBaselines as Ku,rebaselineServerMeta as Qu,D360AuthError as Ju}from"document360-engine";W();var Qi=[{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:M,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:se,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:se,mark:"\xB7"}];function Fu(e){return e.path?e.path:`${e.title??"(untitled)"} ${se(`[${e.articleId}]`)}`}function Hu(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 Jn(e,t){let n=[],o=e.entries.filter(x=>x.link);if(o.length>0){n.push(""),n.push(Pe("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let x of o)n.push(` ${M("~")} ${M(x.path??"")} ${se(`\u2192 "${x.link.title}"`)}`)}for(let x of Qi){let D=e.entries.filter(b=>b.status===x.status&&!(x.status==="untracked-local"&&b.link));if(D.length!==0){n.push(""),n.push(Pe(x.header));for(let b of D)n.push(` ${x.paint(x.mark)} ${x.paint(Fu(b))}${b.detail?se(` (${b.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let u={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},p=o.length,h=s===r?j("\u2713 everything up to date"):[r>0?j(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...Qi.map(x=>{let D=(e.counts[x.status]??0)-(x.status==="untracked-local"?p:0);return D>0?`${D} ${u[x.status]}`:null})].filter(Boolean).join(se(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${Hu(t)}`:"";return n.push(h+se(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as qu}from"diff";import Ji from"picocolors";var Zi=80,Bu="\x1B[48;2;74;28;28m",Gu="\x1B[48;2;24;66;24m",ea="\x1B[49m",br=e=>String(e).padStart(5);function ct(e,t,n){let o=b=>{let P=b.replace(/\r\n/g,`
212
+ `+Kt(`\u25A3 Preview \u2014 ${e.name}`)+`
213
+
214
+ `+fr(e.text,n);case"note":return`
215
+ `+vu[e.tone](Jt(e.text));case"done":return`
216
+ `+(e.ok?z.magenta("\u2736 "):z.red("\u2736 "))+z.gray(`Cooked for ${on(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${me(e.costUsd)}`:""))}}function Vi(e,t){return e.map(n=>gr(n,t)).join(`
217
+ `)}import{resolveActiveProfile as Cu,loadTokens as Pu,isExpired as Ru,decodeJwtClaims as zi}from"document360-engine";function Tu(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Le(e,t){try{let n=Cu(e,t),o=Pu(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Ru(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={...zi(o.idToken)??{},...zi(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 ${Tu(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var rn=3;function kr(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, strip every <!-- SCREENSHOT ... --> block while keeping the visible [Screenshot: ...] line, normalize cross-article links).","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself \u2014 do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
218
+ `)}var Xi={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function sn(e){return e.filter(t=>t.path!==null&&t.status in Xi&&!t.link).map(t=>({path:t.path,label:Xi[t.status]}))}function Qn(e){return e.filter(t=>t.link).length}function br(e,t){try{let n=_u(e,Mu(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Lu(Su(Du(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 Ou(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 Ki(e){let t=[];e.length>1&&t.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(o=>o.path),indent:!1});let n=new Map;for(let o of e){let r=o.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),s=n.get(r);s?s.push(o):n.set(r,[o])}for(let o of[...n.keys()].sort()){let r=n.get(o).sort((s,c)=>s.path.localeCompare(c.path));t.push({kind:"category",label:`${Ou(o)} (${r.length})`,paths:r.map(s=>s.path),indent:!1});for(let s of r){let c=s.path.replace(/\\/g,"/").split("/").pop()??s.path;t.push({kind:"article",label:c,paths:[s.path],indent:!0,note:s.label})}}return t}function Jn(e){return[`Run the publish-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures) and remind me drafts need review in the portal."].join(`
219
+ `)}function xr(e,t,n){let o=b=>t[b.index]?.paths.length??0,r=e.filter(b=>b.ok),s=e.filter(b=>!b.ok),c=e.reduce((b,P)=>b+o(P),0),p=r.reduce((b,P)=>b+o(P),0),g=n==="api"?`${me(e.reduce((b,P)=>b+P.costUsd,0))} total`:Ve(e.reduce((b,P)=>b+P.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,x=b=>`${b} article${b===1?"":"s"}`,D=[];if(s.length===0)D.push(`Published ${x(c)} (${k}) successfully \xB7 ${g}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${x(c)} (${k}) \xB7 ${g}.`),D.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let b of s)D.push(` \u2717 ${b.label}${b.error?` \u2014 ${b.error}`:""}`)}return D}async function wr(e,t){let n=Au(t),{model:o}=Iu(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${rn} agents at once) on ${o}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let r of Nu({cwd:e.cwd,partitions:n,promptFor:s=>Jn(s.paths),concurrency:rn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:o}))if(r.type==="partition_status")r.status==="running"?console.log(f(` \u25B8 ${r.label} \u2014 publishing\u2026`)):r.status==="done"?console.log(j(` \u2713 ${r.label}`)):console.log($(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let s=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of xr(r.results,n,s))console.log(r.ok?j(p):M(p));let c=br(e.cwd,e.profileName);c&&console.log(f(c))}}catch(r){console.log($(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Zn(e,t,n){let o=Eu(e,n);if(o.length===0)return[];let r=new Set(sn((await yr({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Qi(e,t){let n=Le(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Zn(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(j("\u2713 All related articles are already published.")),{kind:"continue"}):await wr(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await yr({cwd:t?.cwd??process.cwd()}),s=sn(r.entries),c=Qn(r.entries);return c>0&&console.log(M(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),s.length===0?(console.log(j(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):t?await wr(t,s.map(p=>p.path)):{kind:"forward-to-agent",prompt:Jn(s.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log($(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let s=await yr({cwd:t?.cwd??process.cwd()});r=sn(s.entries);let c=Qn(s.entries);c>0&&console.log(M(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`))}catch(s){return console.log($(`Could not compute sync status: ${s.message}`)),console.log(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(j("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(f(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${f(`(${s.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>ju({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await wr(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:kr(o),display:`/publish ${o}`}}async function an(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
220
+ `),display:"/audit"}}W();import{checkbox as Uu}from"@inquirer/prompts";import{inventoryRepo as Wu,readProjectConfig as Ji,writeProjectConfig as Fu}from"document360-engine";function $r(e,t){let n=Ji(e);n&&(n.authoritativeSourceFiles=t,Fu(n,e))}function eo(e){let t=[`${e.fileCount}${e.fileCount>=5e3?"+":""} files`];return e.stacks.length&&t.push(e.stacks.join("+")),t.push(e.reason),t.join(" \xB7 ")}async function Zi(e,t){let n=t?.cwd??process.cwd();if(!Ji(n))return console.log($("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Wu(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(_("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(eo(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Uu({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${eo(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(f("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};$r(n,r),console.log(j(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as Vu}from"@inquirer/prompts";import{applyPull as Cr,computeSyncStatus as ra,compareRemoteSources as zu,planPull as sa,planImport as Xu,applyImport as Ku,establishBaselines as Qu,rebaselineServerMeta as Ju,D360AuthError as Zu}from"document360-engine";W();var ea=[{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:M,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:se,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:se,mark:"\xB7"}];function Hu(e){return e.path?e.path:`${e.title??"(untitled)"} ${se(`[${e.articleId}]`)}`}function qu(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60);return`${n}m ${Math.round(t-n*60)}s`}function to(e,t){let n=[],o=e.entries.filter(x=>x.link);if(o.length>0){n.push(""),n.push(Pe("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let x of o)n.push(` ${M("~")} ${M(x.path??"")} ${se(`\u2192 "${x.link.title}"`)}`)}for(let x of ea){let D=e.entries.filter(b=>b.status===x.status&&!(x.status==="untracked-local"&&b.link));if(D.length!==0){n.push(""),n.push(Pe(x.header));for(let b of D)n.push(` ${x.paint(x.mark)} ${x.paint(Hu(b))}${b.detail?se(` (${b.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let c={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},p=o.length,g=s===r?j("\u2713 everything up to date"):[r>0?j(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...ea.map(x=>{let D=(e.counts[x.status]??0)-(x.status==="untracked-local"?p:0);return D>0?`${D} ${c[x.status]}`:null})].filter(Boolean).join(se(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${qu(t)}`:"";return n.push(g+se(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as Bu}from"diff";import ta from"picocolors";var na=80,Gu="\x1B[48;2;74;28;28m",Yu="\x1B[48;2;24;66;24m",oa="\x1B[49m",vr=e=>String(e).padStart(5);function ut(e,t,n){let o=b=>{let P=b.replace(/\r\n/g,`
221
221
  `);return P.endsWith(`
222
222
  `)||P===""?P:P+`
223
- `},r=o(e),s=o(t);if(r===s)return null;let u=Math.max(20,n-10),p=qu("a","b",r,s,"","",{context:3}),h=0,k=0,x=[];p.hunks.forEach((b,P)=>{P>0&&x.push(Ji.gray(" \u2026"));let C=b.oldStart,N=b.newStart;for(let I of b.lines){let O=I[0],J=I.slice(1).slice(0,u);O==="-"?(k++,x.push(`${Bu}${br(C++)} - ${J}${ea}`)):O==="+"?(h++,x.push(`${Gu}${br(N++)} + ${J}${ea}`)):(x.push(Ji.gray(br(N))+" "+J),C++,N++)}});let D=x.slice(0,Zi);return{added:h,removed:k,lines:D,hidden:Math.max(0,x.length-Zi)}}async function oa(e,t){let n=Le(t.cwd,t.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Zu(t),{kind:"continue"};if(o==="--baseline")return await ed(t,e.filter(u=>u!=="--baseline")),{kind:"continue"};if(o==="--compare")return await td(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 nd(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await $r({cwd:t.cwd,profileName:t.profileName});for(let u of vr(s))console.log(u.tone==="ok"?j(u.text):u.tone==="warn"?M(u.text):f(u.text));console.log("")}catch(r){r instanceof Ju?console.log($(r.message)):console.log($(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function $r(e){let t=await ta({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 na({cwd:e.cwd,profileName:e.profileName,relPath:o.path});xr({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 zu({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Xu({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 Zn=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,ut=e=>e===1?"":"s";function vr(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${ut(e.pulled.length)} into local: ${Zn(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${ut(e.imported.length)}: ${Zn(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${ut(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${ut(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Take the portal copy: /pull <path> \xB7 keep yours: /publish <path>. (${Zn(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${ut(e.failed.length)} failed: ${Zn(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 Zu(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await ta({cwd:e.cwd,profileName:e.profileName});for(let o of Jn(n,Date.now()-t))console.log(o);console.log("")}async function ed(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 Ku({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Qu({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(j("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(j(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(j(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(M(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(f(` - ${s.path} (${s.reason})`))}}async function td(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Vu({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Pe(String(t.legacyCount))} \xB7 Manifest: ${Pe(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(j("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log($(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(M(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(M(` ${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 nd(e,t){let n=t.replace(/\\/g,"/"),o=await na({cwd:e.cwd,profileName:e.profileName,relPath:n});console.log(""),console.log(`${_("\u25CF")} ${Pe(o.title)} ${se(`(${o.path})`)}`);for(let u of o.notes)console.log(M(` \u26A0 ${u}`));o.overwritesLocalChanges&&console.log(M(" \u26A0 This OVERWRITES local edits made since the last sync."));let r=ct(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.")),xr({cwd:e.cwd,profileName:e.profileName},o);return}console.log(se(` \u23BF Added ${r.added} line${ut(r.added)}, removed ${r.removed} line${ut(r.removed)}`));for(let u of r.lines)console.log(u);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Yu({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}xr({cwd:e.cwd,profileName:e.profileName},o),console.log(j(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as od}from"node:fs";import{resolve as rd}from"node:path";import{estimateBulkCost as sd,planPartitions as id,readProjectConfig as ad,resolveModelForOperation as ld,runPartitioned as cd,trackedArticlePaths as ud}from"document360-engine";var Cr=3;function Pr(e){let t,n=!1;for(let r=0;r<e.length;r++){let s=e[r];s==="--run"||s==="--yes"?n=!0:s==="--scope"?t=e[++r]:s?.startsWith("--scope=")&&(t=s.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function Rr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Tr(e,t){return t.map(n=>{let o=0;try{o=od(rd(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Sr(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite \u2014 be efficient:
223
+ `},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=Bu("a","b",r,s,"","",{context:3}),g=0,k=0,x=[];p.hunks.forEach((b,P)=>{P>0&&x.push(ta.gray(" \u2026"));let C=b.oldStart,N=b.newStart;for(let I of b.lines){let O=I[0],J=I.slice(1).slice(0,c);O==="-"?(k++,x.push(`${Gu}${vr(C++)} - ${J}${oa}`)):O==="+"?(g++,x.push(`${Yu}${vr(N++)} + ${J}${oa}`)):(x.push(ta.gray(vr(N))+" "+J),C++,N++)}});let D=x.slice(0,na);return{added:g,removed:k,lines:D,hidden:Math.max(0,x.length-na)}}async function ia(e,t){let n=Le(t.cwd,t.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await ed(t),{kind:"continue"};if(o==="--baseline")return await td(t,e.filter(c=>c!=="--baseline")),{kind:"continue"};if(o==="--compare")return await nd(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 od(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await Pr({cwd:t.cwd,profileName:t.profileName});for(let c of Rr(s))console.log(c.tone==="ok"?j(c.text):c.tone==="warn"?M(c.text):f(c.text));console.log("")}catch(r){r instanceof Zu?console.log($(r.message)):console.log($(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Pr(e){let t=await ra({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 sa({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Cr({cwd:e.cwd,profileName:e.profileName},r),n.pulled.push(o.path)}catch(r){n.failed.push({ref:o.path,error:r.message})}else if(o.status==="untracked-remote"&&o.articleId)try{let r=await Xu({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Ku({cwd:e.cwd,profileName:e.profileName},r),n.imported.push({title:r.title,path:r.path})}catch(r){n.failed.push({ref:o.title??o.articleId,error:r.message})}else o.status==="conflict"&&o.path?n.conflicts.push(o.path):(o.status==="local-ahead"||o.status==="untracked-local"&&!o.link)&&o.path&&n.toPublish++;return n}var no=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,dt=e=>e===1?"":"s";function Rr(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${dt(e.pulled.length)} into local: ${no(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${dt(e.imported.length)}: ${no(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${dt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${dt(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Take the portal copy: /pull <path> \xB7 keep yours: /publish <path>. (${no(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${dt(e.failed.length)} failed: ${no(e.failed.map(n=>n.ref))}`}),t.length===0&&t.push({tone:"ok",text:"\u2713 Already in sync with Document360 \u2014 nothing to pull."}),t}async function ed(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await ra({cwd:e.cwd,profileName:e.profileName});for(let o of to(n,Date.now()-t))console.log(o);console.log("")}async function td(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 Qu({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Ju({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(j("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(j(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(j(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(M(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(f(` - ${s.path} (${s.reason})`))}}async function nd(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await zu({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Pe(String(t.legacyCount))} \xB7 Manifest: ${Pe(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(j("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log($(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(M(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(M(` ${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 od(e,t){let n=t.replace(/\\/g,"/"),o=await sa({cwd:e.cwd,profileName:e.profileName,relPath:n});console.log(""),console.log(`${_("\u25CF")} ${Pe(o.title)} ${se(`(${o.path})`)}`);for(let c of o.notes)console.log(M(` \u26A0 ${c}`));o.overwritesLocalChanges&&console.log(M(" \u26A0 This OVERWRITES local edits made since the last sync."));let r=ut(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(f(" Local file already matches the remote content \u2014 advancing the sync base only.")),Cr({cwd:e.cwd,profileName:e.profileName},o);return}console.log(se(` \u23BF Added ${r.added} line${dt(r.added)}, removed ${r.removed} line${dt(r.removed)}`));for(let c of r.lines)console.log(c);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Vu({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}Cr({cwd:e.cwd,profileName:e.profileName},o),console.log(j(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as rd}from"node:fs";import{resolve as sd}from"node:path";import{estimateBulkCost as id,planPartitions as ad,readProjectConfig as ld,resolveModelForOperation as cd,runPartitioned as ud,trackedArticlePaths as dd}from"document360-engine";var Tr=3;function Sr(e){let t,n=!1;for(let r=0;r<e.length;r++){let s=e[r];s==="--run"||s==="--yes"?n=!0:s==="--scope"?t=e[++r]:s?.startsWith("--scope=")&&(t=s.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function Dr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function jr(e,t){return t.map(n=>{let o=0;try{o=rd(sd(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Ar(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite \u2014 be efficient:
224
224
  - Read ONLY the article files listed below. Do NOT read source code, other articles, or fetch the live portal \u2014 you already have everything you need.
225
225
  - Convert in place: wrap callouts, FAQs, tabs, accordions, and media embeds per the d360-markdown skill. Preserve all wording, headings, and structure; change only GFM\u2192DFM syntax.
226
226
  - Publish each as a draft with a single update call. Do NOT re-read, re-verify, or polish after converting, and skip articles already in DFM.
227
227
  - Work only on these files:
228
228
  `+e.paths.map(t=>`- ${t}`).join(`
229
- `)}function Dr(e,t,n){let o=e.reduce((p,h)=>p+h.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${me(r)}\u2013${me(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function jr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),u=e.reduce((C,N)=>C+o(N),0),p=r.reduce((C,N)=>C+o(N),0),h=e.reduce((C,N)=>C+N.costUsd,0),k=e.reduce((C,N)=>C+N.outputTokens,0),x=n==="api"?`${me(h)} total`:Ve(k),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Converted ${b(u)} (${D}) successfully \xB7 ${x}.`);else{P.push(`Converted ${p}/${b(u)} (${D}) \xB7 ${x}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}async function ra(e,t){if(!ad(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Pr(e),r=ud(t.cwd,t.profileName);if(r.length===0)return console.log($("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Rr(r,n);if(s.length===0)return console.log($(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let u=id(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:h,forced:k}=ld(t.cwd,"light");if(!o){let x=sd({files:Tr(t.cwd,s),op:"convert",model:h});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let D of Dr(u,x,Cr))console.log(D);return console.log(f(`Model: ${h}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${u.length} partitions (\u2264${Cr} agents at once) on ${h}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let x of cd({cwd:t.cwd,partitions:u,promptFor:Sr,concurrency:Cr,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:h}))if(x.type==="partition_status")x.status==="running"?console.log(f(` \u25B8 ${x.label} \u2014 converting\u2026`)):x.status==="done"?console.log(j(` \u2713 ${x.label}`)):console.log($(` \u2717 ${x.label}`));else if(x.type==="run_done"){console.log("");let D=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let b of jr(x.results,u,D))console.log(x.ok?j(b):M(b))}}catch(x){console.log($(`Convert run failed: ${x.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as sa}from"node:fs";import{resolve as ia}from"node:path";import{estimateBulkCost as dd,lintDocs as pd,planPartitions as fd,readDocsPlan as md,readProjectConfig as aa,DEFAULT_DOCS_DIR as hd,resolveModelForOperation as gd,runPartitioned as wd}from"document360-engine";var yd=3,kd=8;function Ar(e){return e===void 0||!Number.isFinite(e)?yd:Math.max(1,Math.min(Math.floor(e),kd))}function Er(e){let t,n,o=!1,r=!1,s,u=h=>{let k=Number(h);return h!==void 0&&Number.isFinite(k)?k:void 0};for(let h=0;h<e.length;h++){let k=e[h];if(k==="--preview"||k==="--dry-run")o=!0;else if(k==="--rewrite"||k==="--force")r=!0;else{if(k==="--run"||k==="--yes"||k==="--all")continue;k==="--scope"?t=e[++h]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?s=u(e[++h]):k?.startsWith("--concurrency=")?s=u(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=h=>h?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function bd(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function xd(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Ir(e,t,n){return n.filter(o=>{try{return sa(ia(e,t,o)).size===0}catch{return!0}})}function Nr(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let u of o.get(r)?.sources??[])try{s+=sa(ia(e,u)).size}catch{}return{path:r,bytes:s}})}function _r(e,t,n={}){let o=n.rewrite?`- Some or all of these articles ALREADY EXIST on disk \u2014 this is a re-author (rewrite/upgrade), NOT a first draft. For any that exist, do NOT preserve or lightly-edit the current file: RE-AUTHOR it from scratch against the plan + sources + the active doc-type playbook standard. The existing file is what you're replacing \u2014 its structure is NOT the target; match only the project's voice/terminology.
229
+ `)}function Er(e,t,n){let o=e.reduce((p,g)=>p+g.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${me(r)}\u2013${me(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Ir(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,N)=>C+o(N),0),p=r.reduce((C,N)=>C+o(N),0),g=e.reduce((C,N)=>C+N.costUsd,0),k=e.reduce((C,N)=>C+N.outputTokens,0),x=n==="api"?`${me(g)} total`:Ve(k),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Converted ${b(c)} (${D}) successfully \xB7 ${x}.`);else{P.push(`Converted ${p}/${b(c)} (${D}) \xB7 ${x}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}async function aa(e,t){if(!ld(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Sr(e),r=dd(t.cwd,t.profileName);if(r.length===0)return console.log($("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Dr(r,n);if(s.length===0)return console.log($(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=ad(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:g,forced:k}=cd(t.cwd,"light");if(!o){let x=id({files:jr(t.cwd,s),op:"convert",model:g});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let D of Er(c,x,Tr))console.log(D);return console.log(f(`Model: ${g}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${c.length} partitions (\u2264${Tr} agents at once) on ${g}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let x of ud({cwd:t.cwd,partitions:c,promptFor:Ar,concurrency:Tr,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:g}))if(x.type==="partition_status")x.status==="running"?console.log(f(` \u25B8 ${x.label} \u2014 converting\u2026`)):x.status==="done"?console.log(j(` \u2713 ${x.label}`)):console.log($(` \u2717 ${x.label}`));else if(x.type==="run_done"){console.log("");let D=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let b of Ir(x.results,c,D))console.log(x.ok?j(b):M(b))}}catch(x){console.log($(`Convert run failed: ${x.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as la}from"node:fs";import{resolve as ca}from"node:path";import{estimateBulkCost as pd,lintDocs as fd,planPartitions as md,readDocsPlan as hd,readProjectConfig as ua,DEFAULT_DOCS_DIR as gd,resolveModelForOperation as wd,runPartitioned as yd}from"document360-engine";var kd=3,bd=8;function Nr(e){return e===void 0||!Number.isFinite(e)?kd:Math.max(1,Math.min(Math.floor(e),bd))}function _r(e){let t,n,o=!1,r=!1,s,c=g=>{let k=Number(g);return g!==void 0&&Number.isFinite(k)?k:void 0};for(let g=0;g<e.length;g++){let k=e[g];if(k==="--preview"||k==="--dry-run")o=!0;else if(k==="--rewrite"||k==="--force")r=!0;else{if(k==="--run"||k==="--yes"||k==="--all")continue;k==="--scope"?t=e[++g]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?s=c(e[++g]):k?.startsWith("--concurrency=")?s=c(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=g=>g?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function xd(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function $d(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Mr(e,t,n){return n.filter(o=>{try{return la(ca(e,t,o)).size===0}catch{return!0}})}function Lr(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let c of o.get(r)?.sources??[])try{s+=la(ca(e,c)).size}catch{}return{path:r,bytes:s}})}function Or(e,t,n={}){let o=n.rewrite?`- Some or all of these articles ALREADY EXIST on disk \u2014 this is a re-author (rewrite/upgrade), NOT a first draft. For any that exist, do NOT preserve or lightly-edit the current file: RE-AUTHOR it from scratch against the plan + sources + the active doc-type playbook standard. The existing file is what you're replacing \u2014 its structure is NOT the target; match only the project's voice/terminology.
230
230
  `:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
231
231
  - It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose and the source files it draws from (AGENT-PLAN.md has the same table).
232
232
  - Read ONLY those source files plus any shared context you genuinely need, and ground every statement in them. Never invent UI labels, routes, or behaviour \u2014 if the source does not say it, omit it.
@@ -235,72 +235,72 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
235
235
  - Each article is independent. Do NOT write, edit, or publish any article not in this list, and do NOT publish to Document360 \u2014 these are local drafts.
236
236
  Articles:
237
237
  `+e.paths.map(r=>`- ${r}`).join(`
238
- `)}function Mr(e,t,n){let o=e.reduce((u,p)=>u+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(u=>` \u2022 ${u.label} \u2014 ${u.paths.length} article${u.paths.length===1?"":"s"}`),"",`Estimated cost: ${me(r)}\u2013${me(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Lr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),u=e.reduce((C,N)=>C+o(N),0),p=r.reduce((C,N)=>C+o(N),0),h=e.reduce((C,N)=>C+N.costUsd,0),k=e.reduce((C,N)=>C+N.outputTokens,0),x=n==="api"?`${me(h)} total`:Ve(k),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Wrote ${b(u)} (${D}) successfully \xB7 ${x}.`),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}/${b(u)} (${D}) \xB7 ${x}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}function Or(e,t,n){try{let o=pd({cwd:e,paths:n.map(s=>`${t}/${s}`)});if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 run /check to see + fix.`}catch{return null}}function Ur(e,t,n){let o=(aa(e)?.docsDir??hd).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=bd(n.path,o);return r.includes(p)?{docsDir:o,targets:[p],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${p}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=xd(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let u=Ir(e,o,s);if(u.length===0){let p=n.scope?` under "${n.scope}"`:"",h=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${h} --rewrite to regenerate them all.`}}return{docsDir:o,targets:u,planCount:r.length}}async function la(e,t){if(!aa(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=md(t.cwd);if(n.length===0)return console.log($("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:u,rewrite:p}=Er(e),{docsDir:h,targets:k,reason:x,rewriting:D}=Ur(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(x?M(x):M("Nothing to write.")),{kind:"continue"};D&&console.log(M(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let b=fd(k),P=Ar(u),{model:C,forced:N}=gd(t.cwd,"standard"),I=!!r;if(s&&!I){let O=dd({files:Nr(t.cwd,n,k),op:"write",model:C});o&&console.log(f(`Scope: ${o} (${k.length} pending).`));for(let J of Mr(b,O,P))console.log(J);return console.log(f(`Model: ${C}${N?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${k.length} article${k.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${P} agents at once) on ${C}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let O of wd({cwd:t.cwd,partitions:b,promptFor:J=>_r(J,h,{rewrite:D||I}),concurrency:P,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(O.type==="partition_status")O.status==="running"?console.log(f(` \u25B8 ${O.label} \u2014 writing\u2026`)):O.status==="done"?console.log(j(` \u2713 ${O.label}`)):console.log($(` \u2717 ${O.label}`));else if(O.type==="run_done"){console.log("");let J=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let ne of Lr(O.results,b,J))console.log(O.ok?j(ne):M(ne));let pe=Or(t.cwd,h,k);pe&&console.log(M(pe))}}catch(O){console.log($(`Write run failed: ${O.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as $d,readdirSync as ca,statSync as ua}from"node:fs";import{join as da}from"node:path";import{inputDir as vd,readProjectConfig as Cd}from"document360-engine";var pa=/\.(md|markdown|pdf|txt)$/i;function Wr(e){let t=vd(e);if(!$d(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of ca(t)){let s=da(t,r),u=!1;try{u=ua(s).isDirectory()}catch{continue}if(u){if(r.startsWith("."))continue;let p=Pd(s);p>0&&n.push({name:r,docCount:p})}else pa.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Pd(e){let t=0;for(let n of ca(e))try{ua(da(e,n)).isFile()&&pa.test(n)&&t++}catch{}return t}function Fr(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 eo(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in .d360-writer/input/${e}/`:t?`the input docs in .d360-writer/input/ relevant to: "${t}"`:"the input docs in .d360-writer/input/"}.`,t&&!e?`Use "${t}" as the feature framing.`:"","","Follow the skill: (1) read those PRDs/specs as the primary source (intent, user-facing surface,","terminology, user stories, prerequisites); (2) locate and read the CODE that implements that surface","to pin exact UI strings/routes/states \u2014 never fabricate; flag anything the PRD claims that you","cannot find in source; (3) propose a tight feature-scoped article set (\u22483\u20135) and pin it to",".d360-writer/plan.json + AGENT-PLAN.md, with each article's `sources` listing BOTH the PRD file(s)","AND the grounding code files; (4) flag overlaps with existing articles (do not merge). Then stop and","offer /write. Do NOT write the articles in this turn."].filter(Boolean).join(`
239
- `)}var Hr="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function fa(e,t){let n=t?.cwd??process.cwd();if(!Cd(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Wr(n);if(o.length===0&&r===0)return console.log(f(Hr)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let h of o)console.log(` ${h.name} ${f(`(${h.docCount} doc${h.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:eo(p),display:p?`/draft ${p}`:"/draft"}}let u=Fr(o,s);return{kind:"forward-to-agent",prompt:eo(u??"",u?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as Rd,readProjectConfig as Td}from"document360-engine";function qr(e){try{return Rd(e).filter(t=>t.kind==="request").length}catch{return 0}}function Br(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Gr(e,t=!1){let n=["Run the document-handoff skill.",""];return e?n.push(`The builder hand-off (what was shipped this session): "${e}".`,"Treat this as the Stage 1 hand-off: ground it in the cited/changed code + the architecture brief,","then decide and APPLY the right doc action \u2014 a new section, a new article, an update to existing","article(s), or a retirement, or a mix. No fixed shape; pick the smallest set that keeps the docs correct."):n.push("No description was given \u2014 call d360_inbox and act on the OPEN `request` messages the builder left:","for each, run the document-handoff flow (ground \u2192 decide \u2192 apply) and mark the request `status: done`","with `resulting_articles` when finished."),n.push("","Draft only \u2014 do not publish. If you would create multiple new articles (a section), call","d360_estimate_cost and present the count + cost band first, then wait for the go-ahead."),t&&n.push("","After the drafts exist and the user confirms any bulk gate, publish the new/updated articles to","Document360 (the publish-to-d360 skill). On a production profile, respect the write-guard."),n.join(`
240
- `)}var Yr="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 ma(e,t){let n=t?.cwd??process.cwd();if(!Td(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Br(e);if(!r&&qr(n)===0)return console.log(f(Yr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Gr(r,o),display:s}}W();import{search as Sd}from"@inquirer/prompts";import{findByName as Dd,getSession as jd,listSessions as Ad,relativeTime as ga}from"document360-engine";async function wa(e,t){let n=Ad(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=Dd(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),ha(n),{kind:"continue"})}if(!process.stdin.isTTY)return ha(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Sd({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let u=(s??"").toLowerCase();return n.filter(p=>!u||p.name.toLowerCase().includes(u)||p.firstPrompt.toLowerCase().includes(u)).map(p=>({name:`${p.name} ${ga(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=jd(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function ha(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${f(ga(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Ed}from"document360-engine";function Vr(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 ya(e,t){let n=Vr(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Ed(o,n)?console.log(j(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(j(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as ka,readProjectConfig as Id,writeProjectConfig as Nd}from"document360-engine";W();function zr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Id(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 ka().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Nd(o,e),null):`Unknown environment "${r}". Known: ${ka().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function ba(e,t){let n=e[0];if(!n)return Mn(t.cwd),{kind:"continue"};if(n==="add"){let o=zr(t.cwd,e[1],e[2]);return o?(console.log($(o)),{kind:"continue"}):(console.log(j(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/login")}`),{kind:"continue"})}return Ln(t.cwd,n),On(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as _d}from"@inquirer/prompts";import{readProjectConfig as Md,readUserConfig as xa,resolveModelSetting as Xr,writeUserConfig as $a}from"document360-engine";var Ee=[{value:null,label:"Auto",desc:"Engine right-sizes per task \u2014 Sonnet for routine work, Opus for analysis (recommended)"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus 4.8 \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet 4.6 \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku 4.5 \xB7 fastest for quick answers"}];function to(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=Ee.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Ld(e){switch(e.source){case"project":return".d360-writer/config.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"claude-settings":return"Claude Code's own settings (~/.claude/settings.json)";case"claude-default":return"Claude Code default (no override configured)"}}function sn(e,t){let n=()=>{let s=Xr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=xa();return s.defaultModel?(delete s.defaultModel,$a(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Xr(e).model??"Claude Code default"} (applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}$a({...xa(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Md(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 va(e,t){let n=e[0]?.trim();if(!n){let u=Xr(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${_(u.model??"Claude Code default")}`),console.log(f(` source: ${Ld(u)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=to(u),h;try{h=await t.withPausedInput(()=>_d({message:`Select model (current: ${u.model??"Claude Code default"})`,default:Ee[p].value,choices:Ee.map((b,P)=>({name:`${b.label}${P===p?" \u2714":""}`,value:b.value,description:b.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:x,effective:D}=sn(t.cwd,h??"default");for(let b of k)console.log(b.startsWith("\u26A0")?M(b):b.startsWith("\u2713")?j(b):f(b));return x&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:s}=sn(t.cwd,n);for(let u of o)console.log(u.startsWith("\u26A0")?M(u):u.startsWith("\u2713")?j(u):f(u));return r&&await t.setModel(s),{kind:"continue"}}no();async function Da(e,t){return await t.withPausedInput(()=>jt(t.cwd)),{kind:"clear"}}async function ja(e,t){return await t.withPausedInput(()=>En(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as Jd}from"document360-engine";async function Aa(e,t){let n=!1;try{n=Jd(t.cwd).production}catch{}return n?(console.log(M("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var Ea=async(e,t)=>{try{await t.withPausedInput(()=>_n({}))}catch(n){console.log($(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as Zd,clearTokens as ep,clearProfileProject as tp}from"document360-engine";async function Ia(e,t){let n;try{n=Zd(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let o=ep(n);return tp(t.cwd,n),console.log(o?j(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):f(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(f("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as Na}from"node:fs";import{isAbsolute as np,join as op,resolve as rp}from"node:path";import{readProjectConfig as sp,screenshotPlaceholderIds as ip,DEFAULT_CAPTURE_DIR as ap,DEFAULT_OUTPUT_DIR as lp}from"document360-engine";var _a=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Qr(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?_a(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:_a(o),setup:t}:{mode:"single",id:o}}function Jr(e,t){let n=sp(e),o=n?.captureDir??ap,r=n?.outputDir??lp,s=(u,p)=>np(u)?op(u,p):rp(e,u,p);return ip(e,{scope:t}).map(({id:u,file:p})=>{let h=Na(s(r,`${u}.png`))?"captured":Na(s(o,`${u}.spec.ts`))?"spec":"placeholder";return{id:u,file:p,state:h}})}var cp={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},up={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Zr(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(s=>s.file))].sort(),o=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of n){r.push(s);for(let u of e.filter(p=>p.file===s))r.push(` ${cp[u.state]} ${u.id.padEnd(34)} ${up[u.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Ma(e){return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(t=>`- ${t}`).join(`
238
+ `)}function Ur(e,t,n){let o=e.reduce((c,p)=>c+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${me(r)}\u2013${me(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Wr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,N)=>C+o(N),0),p=r.reduce((C,N)=>C+o(N),0),g=e.reduce((C,N)=>C+N.costUsd,0),k=e.reduce((C,N)=>C+N.outputTokens,0),x=n==="api"?`${me(g)} total`:Ve(k),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Wrote ${b(c)} (${D}) successfully \xB7 ${x}.`),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}/${b(c)} (${D}) \xB7 ${x}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}function Fr(e,t,n){try{let o=fd({cwd:e,paths:n.map(s=>`${t}/${s}`)});if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 /check --fix corrects them.`}catch{return null}}function Hr(e,t,n){let o=(ua(e)?.docsDir??gd).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=xd(n.path,o);return r.includes(p)?{docsDir:o,targets:[p],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${p}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=$d(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let c=Mr(e,o,s);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 da(e,t){if(!ua(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=hd(t.cwd);if(n.length===0)return console.log($("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:c,rewrite:p}=_r(e),{docsDir:g,targets:k,reason:x,rewriting:D}=Hr(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(x?M(x):M("Nothing to write.")),{kind:"continue"};D&&console.log(M(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let b=md(k),P=Nr(c),{model:C,forced:N}=wd(t.cwd,"standard"),I=!!r;if(s&&!I){let O=pd({files:Lr(t.cwd,n,k),op:"write",model:C});o&&console.log(f(`Scope: ${o} (${k.length} pending).`));for(let J of Ur(b,O,P))console.log(J);return console.log(f(`Model: ${C}${N?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${k.length} article${k.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${P} agents at once) on ${C}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let O of yd({cwd:t.cwd,partitions:b,promptFor:J=>Or(J,g,{rewrite:D||I}),concurrency:P,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(O.type==="partition_status")O.status==="running"?console.log(f(` \u25B8 ${O.label} \u2014 writing\u2026`)):O.status==="done"?console.log(j(` \u2713 ${O.label}`)):console.log($(` \u2717 ${O.label}`));else if(O.type==="run_done"){console.log("");let J=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let ne of Wr(O.results,b,J))console.log(O.ok?j(ne):M(ne));let pe=Fr(t.cwd,g,k);pe&&console.log(M(pe))}}catch(O){console.log($(`Write run failed: ${O.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as vd,readdirSync as pa,statSync as fa}from"node:fs";import{join as ma}from"node:path";import{inputDir as Cd,readProjectConfig as Pd}from"document360-engine";var ha=/\.(md|markdown|pdf|txt)$/i;function qr(e){let t=Cd(e);if(!vd(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of pa(t)){let s=ma(t,r),c=!1;try{c=fa(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=Rd(s);p>0&&n.push({name:r,docCount:p})}else ha.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Rd(e){let t=0;for(let n of pa(e))try{fa(ma(e,n)).isFile()&&ha.test(n)&&t++}catch{}return t}function Br(e,t){let n=t.trim().toLowerCase();return n?e.find(o=>o.name.toLowerCase()===n)?.name??e.find(o=>o.name.toLowerCase().startsWith(n))?.name??e.find(o=>o.name.toLowerCase().includes(n))?.name??null:null}function oo(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in .d360-writer/input/${e}/`:t?`the input docs in .d360-writer/input/ relevant to: "${t}"`:"the input docs in .d360-writer/input/"}.`,t&&!e?`Use "${t}" as the feature framing.`:"","","Follow the skill: (1) read those PRDs/specs as the primary source (intent, user-facing surface,","terminology, user stories, prerequisites); (2) locate and read the CODE that implements that surface","to pin exact UI strings/routes/states \u2014 never fabricate; flag anything the PRD claims that you","cannot find in source; (3) propose a tight feature-scoped article set (\u22483\u20135) and pin it to",".d360-writer/plan.json + AGENT-PLAN.md, with each article's `sources` listing BOTH the PRD file(s)","AND the grounding code files; (4) flag overlaps with existing articles (do not merge). Then stop and","offer /write. Do NOT write the articles in this turn."].filter(Boolean).join(`
239
+ `)}var Gr="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function ga(e,t){let n=t?.cwd??process.cwd();if(!Pd(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=qr(n);if(o.length===0&&r===0)return console.log(f(Gr)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let 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:oo(p),display:p?`/draft ${p}`:"/draft"}}let c=Br(o,s);return{kind:"forward-to-agent",prompt:oo(c??"",c?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as Td,readProjectConfig as Sd}from"document360-engine";function Yr(e){try{return Td(e).filter(t=>t.kind==="request").length}catch{return 0}}function Vr(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function zr(e,t=!1){let n=["Run the document-handoff skill.",""];return e?n.push(`The builder hand-off (what was shipped this session): "${e}".`,"Treat this as the Stage 1 hand-off: ground it in the cited/changed code + the architecture brief,","then decide and APPLY the right doc action \u2014 a new section, a new article, an update to existing","article(s), or a retirement, or a mix. No fixed shape; pick the smallest set that keeps the docs correct."):n.push("No description was given \u2014 call d360_inbox and act on the OPEN `request` messages the builder left:","for each, run the document-handoff flow (ground \u2192 decide \u2192 apply) and mark the request `status: done`","with `resulting_articles` when finished."),n.push("","Draft only \u2014 do not publish. If you would create multiple new articles (a section), call","d360_estimate_cost and present the count + cost band first, then wait for the go-ahead."),t&&n.push("","After the drafts exist and the user confirms any bulk gate, publish the new/updated articles to","Document360 (the publish-to-d360 skill). On a production profile, respect the write-guard."),n.join(`
240
+ `)}var Xr="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function wa(e,t){let n=t?.cwd??process.cwd();if(!Sd(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Vr(e);if(!r&&Yr(n)===0)return console.log(f(Xr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:zr(r,o),display:s}}W();import{search as Dd}from"@inquirer/prompts";import{findByName as jd,getSession as Ad,listSessions as Ed,relativeTime as ka}from"document360-engine";async function ba(e,t){let n=Ed(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=jd(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),ya(n),{kind:"continue"})}if(!process.stdin.isTTY)return ya(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Dd({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${ka(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Ad(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function ya(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${f(ka(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Id}from"document360-engine";function Kr(e){let t=e.trim();return t.length>=2&&(t[0]==='"'&&t.endsWith('"')||t[0]==="'"&&t.endsWith("'"))?t.slice(1,-1).trim():t}async function xa(e,t){let n=Kr(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Id(o,n)?console.log(j(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(j(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as $a,readProjectConfig as Nd,writeProjectConfig as _d}from"document360-engine";W();function Qr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Nd(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 $a().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},_d(o,e),null):`Unknown environment "${r}". Known: ${$a().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function va(e,t){let n=e[0];if(!n)return Un(t.cwd),{kind:"continue"};if(n==="add"){let o=Qr(t.cwd,e[1],e[2]);return o?(console.log($(o)),{kind:"continue"}):(console.log(j(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/login")}`),{kind:"continue"})}return Wn(t.cwd,n),Fn(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Md}from"@inquirer/prompts";import{readProjectConfig as Ld,readUserConfig as Ca,resolveModelSetting as Jr,writeUserConfig as Pa}from"document360-engine";var Ee=[{value:null,label:"Auto",desc:"Engine right-sizes per task \u2014 Sonnet for routine work, Opus for analysis (recommended)"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus 4.8 \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet 4.6 \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku 4.5 \xB7 fastest for quick answers"}];function ro(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=Ee.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Od(e){switch(e.source){case"project":return".d360-writer/config.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"claude-settings":return"Claude Code's own settings (~/.claude/settings.json)";case"claude-default":return"Claude Code default (no override configured)"}}function ln(e,t){let n=()=>{let s=Jr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Ca();return s.defaultModel?(delete s.defaultModel,Pa(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Jr(e).model??"Claude Code default"} (applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}Pa({...Ca(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Ld(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 Ra(e,t){let n=e[0]?.trim();if(!n){let c=Jr(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${_(c.model??"Claude Code default")}`),console.log(f(` source: ${Od(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=ro(c),g;try{g=await t.withPausedInput(()=>Md({message:`Select model (current: ${c.model??"Claude Code default"})`,default:Ee[p].value,choices:Ee.map((b,P)=>({name:`${b.label}${P===p?" \u2714":""}`,value:b.value,description:b.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:x,effective:D}=ln(t.cwd,g??"default");for(let b of k)console.log(b.startsWith("\u26A0")?M(b):b.startsWith("\u2713")?j(b):f(b));return x&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:s}=ln(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?M(c):c.startsWith("\u2713")?j(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}so();async function Ea(e,t){return await t.withPausedInput(()=>Et(t.cwd)),{kind:"clear"}}async function Ia(e,t){return await t.withPausedInput(()=>_n(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as Zd}from"document360-engine";async function Na(e,t){let n=!1;try{n=Zd(t.cwd).production}catch{}return n?(console.log(M("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var _a=async(e,t)=>{try{await t.withPausedInput(()=>On({}))}catch(n){console.log($(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as ep,clearTokens as tp,clearProfileProject as np}from"document360-engine";async function Ma(e,t){let n;try{n=ep(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let o=tp(n);return np(t.cwd,n),console.log(o?j(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):f(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(f("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as La}from"node:fs";import{isAbsolute as op,join as rp,resolve as sp}from"node:path";import{readProjectConfig as ip,screenshotPlaceholderIds as ap,DEFAULT_CAPTURE_DIR as lp,DEFAULT_OUTPUT_DIR as cp}from"document360-engine";var Oa=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function es(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Oa(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Oa(o),setup:t}:{mode:"single",id:o}}function ts(e,t){let n=ip(e),o=n?.captureDir??lp,r=n?.outputDir??cp,s=(c,p)=>op(c)?rp(c,p):sp(e,c,p);return ap(e,{scope:t}).map(({id:c,file:p})=>{let g=La(s(r,`${c}.png`))?"captured":La(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:g}})}var up={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},dp={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function ns(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(s=>s.file))].sort(),o=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of n){r.push(s);for(let c of e.filter(p=>p.file===s))r.push(` ${up[c.state]} ${c.id.padEnd(34)} ${dp[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Ua(e){return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(t=>`- ${t}`).join(`
241
241
  `),"","For each: locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir); read the product source for","EXACT routes + stable data-testid selectors (never guess); enter the prepared context via","captureScope(); guard data prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts","(skip-with-TODO if a stable selector is missing). Do NOT run other skills. Report the specs you","wrote and any TODO data-testids."].join(`
242
- `)}async function oo(e,t){let n=Qr(e);if(n.mode==="list"){let u=t?.cwd??process.cwd();for(let p of Zr(Jr(u,n.scope),n.scope))console.log(p);return{kind:"continue"}}if(n.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${n.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${n.id}.spec.ts. Report the spec path and any TODO data-testids or data to stage.`].join(`
242
+ `)}async function io(e,t){let n=es(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of ns(ts(c,n.scope),n.scope))console.log(p);return{kind:"continue"}}if(n.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${n.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${n.id}.spec.ts. Report the spec path and any TODO data-testids or data to stage.`].join(`
243
243
  `),display:`/screenshot ${n.id}`};let r=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${n.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${n.scope}`:"every <!-- SCREENSHOT --> placeholder across the docs tree (the configured docsDir)"}.`,"Follow that skill exactly for each: read the SCREENSHOT block; read the product source for EXACT routes","and stable data-testid selectors (never guess); enter the prepared context via captureScope(); guard data",`prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts.${n.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`].join(`
244
- `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as dp,readFileSync as pp}from"node:fs";import{isAbsolute as fp,join as mp,resolve as hp}from"node:path";import{readProjectConfig as gp,DEFAULT_CAPTURE_DIR as wp}from"document360-engine";async function ln(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-SETUP.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
245
- `),display:"/capture-setup"}}var La="-".repeat(64);function es(e){let t=wp;try{let x=gp(e);x?.captureDir&&(t=x.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=fp(t)?mp(t,"CAPTURE-TESTID-REQUESTS.json"):hp(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!dp(n))return null;let o;try{let x=JSON.parse(pp(n,"utf8").replace(/^/,""));o=Array.isArray(x?.requests)?x.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(x=>x.file).filter(Boolean)).size,s=o.length,u=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,h=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${u} 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.","",La,`Read ${h} and ${k}. They list ${u} 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.",La]}lt();W();import{listOpenForDocs as yp,readProjectConfig as kp}from"document360-engine";function ts(e){try{return yp(e).length}catch{return 0}}function ns(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape."," \u2022 answer (a reply to a question you asked; `re` = your question id) \u2192 fold the fact into the affected"," article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only \u2014 do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
246
- `)}async function Oa(e,t){let n=t?.cwd??process.cwd();return kp(n)?ts(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:ns(),display:"/inbox"}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as bp,listOpenForDocs as xp,readProjectConfig as $p,computeSyncStatus as vp,planPull as Cp,applyPull as Pp}from"document360-engine";function Mt(e){let t=0,n=0,o=0;try{t=bp(e).length}catch{}try{let r=xp(e);n=r.filter(s=>s.kind==="request").length,o=r.filter(s=>s.kind==="answer").length}catch{}return{hints:t,requests:n,answers:o}}function Lt(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),t.length?t.join(", "):null}function rs(e){return{publish:e.includes("--publish")}}function ss({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already reconciled before this run: clean portal edits were pulled into local, and any conflicts / new-portal-articles were surfaced to the user. Do NOT re-pull. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.","2. Gather the pending work: d360_pending_hints (the builder's per-change hints) AND d360_inbox (open requests + answers).","3. Decide the right doc actions across all of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), and fold any answers into the affected article(s) + the architecture brief.","4. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","5. Write/update the articles as drafts, grounded in the cited sources.","6. Close the loop: stamp consumed hints, and mark handled messages status: done with resulting_articles.","7. Push the drafts to Document360.","8. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs \u2014 only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)"];return t.push(e?"9. Then publish the new/updated articles live (publish-to-d360 skill), respecting the production write-guard.":"Leave everything as DRAFTS for review \u2014 do not publish live (run /publish when you want them live)."),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (plus the d360_ask_builder question you left for it)."),t.join(`
247
- `)}var Rp={status:vp,plan:Cp,apply:Pp};async function is(e,t=Rp){let n={pulled:[],conflicts:[],untrackedRemote:[],failed:[]},o;try{o=await t.status({cwd:e.cwd,profileName:e.profileName})}catch(r){return n.error=r.message,n}for(let r of o.entries)if(r.status==="conflict"&&r.path)n.conflicts.push(r.path);else if(r.status==="untracked-remote")n.untrackedRemote.push(r.title??r.articleId??"(untitled)");else if(r.status==="remote-ahead"&&r.path)try{let s=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},s),n.pulled.push(r.path)}catch(s){n.failed.push({path:r.path,error:s.message})}return n}var os=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,ro=e=>e===1?"":"s";function as(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${ro(e.pulled.length)} into local: ${os(e.pulled)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${ro(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${os(e.conflicts)}`),e.untrackedRemote.length&&t.push(`\u2139 ${e.untrackedRemote.length} new article${ro(e.untrackedRemote.length)} in the portal aren't local yet \u2014 run /pull to bring them in: ${os(e.untrackedRemote)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull${ro(e.failed.length)} failed \u2014 left for /pull.`),t}async function Ua(e,t){let n=t?.cwd??process.cwd();if(!$p(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Le(n,t?.profileName);if(!o.ok)return console.log($(o.reason)),{kind:"continue"};let{publish:r}=rs(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await is({cwd:n,profileName:t?.profileName});for(let p of as(s))console.log(p.startsWith("\u2713")?j(p):p.startsWith("\u2139")?f(p):M(p));let u=Lt(Mt(n));return console.log(f(u?`Catching up on ${u}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:ss({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as Tp}from"node:child_process";var dt="document360-writer",so=`npm i -g ${dt}@latest`;async function io(){let e=process.platform==="win32";return new Promise(t=>{try{let n=Tp(`npm i -g ${dt}@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 Wa(){return console.log(f(`Updating ${dt}\u2026`)),(await io()).ok?console.log(j("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log($(`Update failed \u2014 run manually: ${so}`)),{kind:"continue"}}W();lt();import{existsSync as ls,rmSync as Sp}from"node:fs";import{basename as Fa,resolve as cs}from"node:path";import{execFileSync as Dp}from"node:child_process";import{input as jp}from"@inquirer/prompts";import{readProjectConfig as Ap,devHintsGuidePath as Ep}from"document360-engine";var Ip=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Np=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),ao=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Ha=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function qa(e){let t=ao(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Ha(t)?!0:Np.has(t)}function us(e){let t=null;try{t=Ap(e)}catch{t=null}let n=new Set(Ip);for(let o of[ao(t?.docsDir),ao(t?.captureDir),ao(t?.outputDir)])o&&Ha(o)&&n.add(o);return[...n].filter(o=>qa(o)&&ls(cs(e,o)))}function ds(e,t){let n=[],o=[];for(let r of t){if(!qa(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Sp(cs(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Ba(e,t){try{return Dp("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
248
- `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function _p(e){return Ba(e,".d360-writer/hints")}function Mp(e){return Ba(e,".d360-writer/messages")}function ps(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=_p(e),o=Mp(e),r=ls(cs(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(s=>` \u2022 ${s}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o>0?[`\u26A0 ${o} message(s) under .d360-writer/messages/ are not committed \u2014 commit them first or they're gone.`]:[],...r?["Note: a repo-root user-docs/ is NOT touched (only .d360-writer/ is removed)."]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${Fa(e)}`]}async function Ga(e,t){let n=us(t.cwd);for(let h of ps(t.cwd,n))console.log(n.length===0?f(h):h);if(n.length===0)return{kind:"continue"};let o=Fa(t.cwd);if((await t.withPausedInput(()=>jp({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(M("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=ls(Ep(t.cwd)),{removed:u,failed:p}=ds(t.cwd,n);console.log(j(`\u2713 Reset complete \u2014 removed ${u.length} item${u.length===1?"":"s"}. The repo is back to its original state.`));for(let h of p)console.log($(` \u2717 ${h.path}: ${h.error}`));if(s){for(let h of Bn())console.log(h);console.log(f("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}W();import{lintDocs as Lp}from"document360-engine";function lo(e){if(e.length===0)return["\u2713 No issues found \u2014 no leaked internals, unknown commands, or stale version facts in the docs."];let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}let n=[`\u26A0 ${e.length} doc issue${e.length===1?"":"s"} in ${t.size} article${t.size===1?"":"s"} (leaked internals / unknown commands / stale facts):`];for(let[o,r]of t){n.push(` ${o}`);for(let s of r)n.push(` L${s.line}: "${s.term}" \u2014 ${s.message}`)}return n}function fs(e){let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}return["The documentation quality check found issues in already-written articles. FIX each one by EDITING the","article in place \u2014 do not rewrite whole articles, just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","How to fix, by issue type:","- internal-leak (an agent codename, an internal skill name, or a d360_* tool name): this is the"," documentation engine's own machinery and must NOT appear in user docs. Reword the sentence to describe"," the behavior in plain user terms, or delete the internal aside. Do NOT swap it for another internal term.","- unknown-command: the named /command or --flag does not exist in the product source. Find the correct"," command/flag in the source and use it; if there is no real equivalent, remove the claim.","- stale-fact: the version contradicts the product's package.json engines \u2014 correct it to the real value.","","Rules: edit ONLY the listed articles; do not touch others; do not publish; introduce no new internal","nouns, invented commands, or wrong facts. When done, every listed issue should be gone.","","Issues:",[...t.entries()].map(([o,r])=>[o,...r.map(s=>` - L${s.line} [${s.kind}]: "${s.term}" \u2014 ${s.message}`)].join(`
244
+ `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as pp,readFileSync as fp}from"node:fs";import{isAbsolute as mp,join as hp,resolve as gp}from"node:path";import{readProjectConfig as wp,DEFAULT_CAPTURE_DIR as yp}from"document360-engine";async function un(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-SETUP.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
245
+ `),display:"/capture-setup"}}var Wa="-".repeat(64);function os(e){let t=yp;try{let x=wp(e);x?.captureDir&&(t=x.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=mp(t)?hp(t,"CAPTURE-TESTID-REQUESTS.json"):gp(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!pp(n))return null;let o;try{let x=JSON.parse(fp(n,"utf8").replace(/^/,""));o=Array.isArray(x?.requests)?x.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(x=>x.file).filter(Boolean)).size,s=o.length,c=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,g=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${c} requested across ${p}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",Wa,`Read ${g} and ${k}. They list ${c} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",Wa]}ct();W();import{listOpenForDocs as kp,readProjectConfig as bp}from"document360-engine";function rs(e){try{return kp(e).length}catch{return 0}}function ss(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape."," \u2022 answer (a reply to a question you asked; `re` = your question id) \u2192 fold the fact into the affected"," article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only \u2014 do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
246
+ `)}async function Fa(e,t){let n=t?.cwd??process.cwd();return bp(n)?rs(n)===0?(console.log(f("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:ss(),display:"/inbox"}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as xp,listOpenForDocs as $p,readProjectConfig as vp,computeSyncStatus as Cp,planPull as Pp,applyPull as Rp}from"document360-engine";function Ot(e){let t=0,n=0,o=0;try{t=xp(e).length}catch{}try{let r=$p(e);n=r.filter(s=>s.kind==="request").length,o=r.filter(s=>s.kind==="answer").length}catch{}return{hints:t,requests:n,answers:o}}function Ut(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),t.length?t.join(", "):null}function as(e){return{publish:e.includes("--publish")}}function ls({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already reconciled before this run: clean portal edits were pulled into local, and any conflicts / new-portal-articles were surfaced to the user. Do NOT re-pull. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.","2. Gather the pending work: d360_pending_hints (the builder's per-change hints) AND d360_inbox (open requests + answers).","3. Decide the right doc actions across all of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), and fold any answers into the affected article(s) + the architecture brief.","4. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","5. Write/update the articles as drafts, grounded in the cited sources.","6. Close the loop: stamp consumed hints, and mark handled messages status: done with resulting_articles.","7. Push the drafts to Document360.","8. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs \u2014 only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)"];return t.push(e?"9. Then publish the new/updated articles live (publish-to-d360 skill), respecting the production write-guard.":"Leave everything as DRAFTS for review \u2014 do not publish live (run /publish when you want them live)."),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (plus the d360_ask_builder question you left for it)."),t.join(`
247
+ `)}var Tp={status:Cp,plan:Pp,apply:Rp};async function cs(e,t=Tp){let n={pulled:[],conflicts:[],untrackedRemote:[],failed:[]},o;try{o=await t.status({cwd:e.cwd,profileName:e.profileName})}catch(r){return n.error=r.message,n}for(let r of o.entries)if(r.status==="conflict"&&r.path)n.conflicts.push(r.path);else if(r.status==="untracked-remote")n.untrackedRemote.push(r.title??r.articleId??"(untitled)");else if(r.status==="remote-ahead"&&r.path)try{let s=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},s),n.pulled.push(r.path)}catch(s){n.failed.push({path:r.path,error:s.message})}return n}var is=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,ao=e=>e===1?"":"s";function us(e){if(e.error)return[`\u26A0 Couldn't check Document360 for portal changes (${e.error.slice(0,100)}) \u2014 proceeding; the agent will re-check.`];let t=[];return e.pulled.length&&t.push(`\u2713 Pulled ${e.pulled.length} portal edit${ao(e.pulled.length)} into local: ${is(e.pulled)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${ao(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${is(e.conflicts)}`),e.untrackedRemote.length&&t.push(`\u2139 ${e.untrackedRemote.length} new article${ao(e.untrackedRemote.length)} in the portal aren't local yet \u2014 run /pull to bring them in: ${is(e.untrackedRemote)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull${ao(e.failed.length)} failed \u2014 left for /pull.`),t}async function Ha(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 o=Le(n,t?.profileName);if(!o.ok)return console.log($(o.reason)),{kind:"continue"};let{publish:r}=as(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await cs({cwd:n,profileName:t?.profileName});for(let p of us(s))console.log(p.startsWith("\u2713")?j(p):p.startsWith("\u2139")?f(p):M(p));let c=Ut(Ot(n));return console.log(f(c?`Catching up on ${c}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:ls({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as Sp}from"node:child_process";var pt="document360-writer",lo=`npm i -g ${pt}@latest`;async function co(){let e=process.platform==="win32";return new Promise(t=>{try{let n=Sp(`npm i -g ${pt}@latest`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});n.on("error",o=>t({ok:!1,output:String(o)})),n.on("close",o=>t({ok:o===0,output:""})),e||n.unref()}catch(n){t({ok:!1,output:String(n)})}})}async function qa(){return console.log(f(`Updating ${pt}\u2026`)),(await co()).ok?console.log(j("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log($(`Update failed \u2014 run manually: ${lo}`)),{kind:"continue"}}W();ct();import{existsSync as ds,rmSync as Dp}from"node:fs";import{basename as Ba,resolve as ps}from"node:path";import{execFileSync as jp}from"node:child_process";import{input as Ap}from"@inquirer/prompts";import{readProjectConfig as Ep,devHintsGuidePath as Ip}from"document360-engine";var Np=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],_p=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),uo=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Ga=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Ya(e){let t=uo(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Ga(t)?!0:_p.has(t)}function fs(e){let t=null;try{t=Ep(e)}catch{t=null}let n=new Set(Np);for(let o of[uo(t?.docsDir),uo(t?.captureDir),uo(t?.outputDir)])o&&Ga(o)&&n.add(o);return[...n].filter(o=>Ya(o)&&ds(ps(e,o)))}function ms(e,t){let n=[],o=[];for(let r of t){if(!Ya(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Dp(ps(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Va(e,t){try{return jp("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
248
+ `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Mp(e){return Va(e,".d360-writer/hints")}function Lp(e){return Va(e,".d360-writer/messages")}function hs(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Mp(e),o=Lp(e),r=ds(ps(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(s=>` \u2022 ${s}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o>0?[`\u26A0 ${o} message(s) under .d360-writer/messages/ are not committed \u2014 commit them first or they're gone.`]:[],...r?["Note: a repo-root user-docs/ is NOT touched (only .d360-writer/ is removed)."]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${Ba(e)}`]}async function za(e,t){let n=fs(t.cwd);for(let g of hs(t.cwd,n))console.log(n.length===0?f(g):g);if(n.length===0)return{kind:"continue"};let o=Ba(t.cwd);if((await t.withPausedInput(()=>Ap({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(M("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=ds(Ip(t.cwd)),{removed:c,failed:p}=ms(t.cwd,n);console.log(j(`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`));for(let g of p)console.log($(` \u2717 ${g.path}: ${g.error}`));if(s){for(let g of Vn())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"}}W();import{lintDocs as Op}from"document360-engine";function po(e){if(e.length===0)return["\u2713 No issues found \u2014 no leaked internals, unknown commands, or stale version facts in the docs."];let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}let n=[`\u26A0 ${e.length} doc issue${e.length===1?"":"s"} in ${t.size} article${t.size===1?"":"s"} (leaked internals / unknown commands / stale facts):`];for(let[o,r]of t){n.push(` ${o}`);for(let s of r)n.push(` L${s.line}: "${s.term}" \u2014 ${s.message}`)}return n}function gs(e){let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}return["The documentation quality check found issues in already-written articles. FIX each one by EDITING the","article in place \u2014 do not rewrite whole articles, just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","How to fix, by issue type:","- internal-leak (an agent codename, an internal skill name, or a d360_* tool name): this is the"," documentation engine's own machinery and must NOT appear in user docs. Reword the sentence to describe"," the behavior in plain user terms, or delete the internal aside. Do NOT swap it for another internal term.","- unknown-command: the named /command or --flag does not exist in the product source. Find the correct"," command/flag in the source and use it; if there is no real equivalent, remove the claim.","- stale-fact: the version contradicts the product's package.json engines \u2014 correct it to the real value.","","Rules: edit ONLY the listed articles; do not touch others; do not publish; introduce no new internal","nouns, invented commands, or wrong facts. When done, every listed issue should be gone.","","Issues:",[...t.entries()].map(([o,r])=>[o,...r.map(s=>` - L${s.line} [${s.kind}]: "${s.term}" \u2014 ${s.message}`)].join(`
249
249
  `)).join(`
250
250
  `)].join(`
251
- `)}async function Ya(e,t){let n=e.includes("--fix"),o=Lp({cwd:t.cwd});if(n)return o.length===0?(console.log(j("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${o.length} doc issue${o.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:fs(o),display:"/check --fix"});console.log(f("Linting the docs (engine internals, unknown commands, stale facts)\u2026"));for(let r of lo(o))console.log(o.length===0?j(r):M(r));return o.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}W();import{lintDocs as Op,loadStyleGuide as Up,buildReviewPrompt as Wp,readProjectConfig as Fp,DEFAULT_DOCS_DIR as Hp}from"document360-engine";function ms(e,t){let n=Fp(e);if(!n)return null;let o=(n.docsDir??Hp).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(k=>!k.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),u=Op({cwd:e}),p=s?u.filter(k=>k.path===`${o}/${s}`||k.path.startsWith(`${o}/${s}/`)):u;return{prompt:Wp({docsRoot:o,scope:s,styleGuide:Up(e),deterministicFindings:p,fix:r}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function Va(e,t){let n=ms(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}var za={help:Zo,"?":Zo,clear:yi,exit:er,quit:er,init:sr,mcp:Vn,publish:zi,audit:rn,scope:Ki,pull:oa,convert:ra,write:la,draft:fa,document:ma,resume:wa,rename:ya,profile:ba,model:va,doctor:an,workspace:Da,project:ja,"allow-prod":Aa,login:Ea,logout:Ia,screenshot:oo,"capture-setup":ln,devhints:Pi,inbox:Oa,"catch-up":Ua,update:Wa,reset:Ga,check:Ya,review:Va};function Xa(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}lt();W();var qp={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"},Qa=160,gs=200,Ja=40;function ke(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Ka(e){let t=Object.entries(e).filter(([,o])=>o!=null&&o!=="");if(t.length===0)return null;let n=t.slice(0,4).map(([o,r])=>`${o}: ${ke(typeof r=="string"?r:JSON.stringify(r),Ja)}`);return t.length>4&&n.push("\u2026"),ke(n.join(", "),Qa)}var ze=e=>typeof e=="string"&&e?e:null,hs=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Bp(e){let t=ze(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function Gp(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=Bp(t.local_path);return n("Create article",`"${ke(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=ze(t.title),r=hs(t.article_id);return n("Update article",o?`"${ke(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",hs(t.article_id)?`id ${hs(t.article_id)}\u2026`:null);case"d360_publish_article":{let o=t.version_number;return n("Publish article LIVE",typeof o=="number"?`v${o}`:null)}case"d360_unpublish_article":return n("Unpublish article",null);case"d360_create_category":return n("Create category",ze(t.name)?`"${ke(ze(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=ze(t.file_path);return n("Upload image",o?ke(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function co(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),u=s.join("__");if(r==="document360"){let k=Gp(u,t);if(k)return k}let p=u.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Ka(t)}}let n=qp[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:ke(o,Qa)}:{title:e,sep:"",arg:Ka(t)}}function Yp(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 Vp(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Yp).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>ke(r,gs))]}if(t!==null&&typeof t=="object"){let n=Object.entries(t).filter(([,o])=>o!==null&&(typeof o=="string"||typeof o=="number"||typeof o=="boolean")).slice(0,6).map(([o,r])=>`${o}: ${ke(String(r),Ja)}`);return n.length>0?[ke(n.join(" \xB7 "),gs)]:null}return null}function zp(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 Xp(e,t,n){switch(e){case"d360_create_article":{let o=zp(t?.local_path);return[`\u2713 draft created${o?` \xB7 ${o}`:""}`]}case"d360_update_article":return["\u2713 draft updated"];case"d360_fork_article":return["\u2713 forked to a new draft"];case"d360_publish_article":return["\u2713 PUBLISHED LIVE \u2014 visible to readers"];case"d360_unpublish_article":return["\u2713 reverted to draft (removed from readers)"];case"d360_create_category":{let o=ze(t?.name);return[`\u2713 category created${o?` \xB7 "${o}"`:""}`]}case"d360_upload_drive_file":{let o=n.match(/https?:\/\/\S+/);return[`\u2713 uploaded${o?` \xB7 ${ke(o[0],120)}`:""}`]}default:return null}}function uo(e,t=4,n,o){let r=e.replace(/\r\n/g,`
252
- `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let u=Xp(n.slice(18),o,r);if(u)return{lines:u,hidden:0}}let s=Vp(r)??r.split(`
253
- `);return{lines:s.slice(0,t).map(u=>ke(u,gs)),hidden:Math.max(0,s.length-t)}}function po(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function fo(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 mo(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 lf=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function cf(e,t,n,o){if(lf.test(e))try{let r=nl(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,u=fo(t,n),p=mo(n);e.endsWith("publish_article")&&p&&console.log(_(` \u2B95 Live: ${p}`)),u&&s&&console.log(_(` \u2B95 Preview: ${po(r.connection.portalUrl,s,u,r.project.languageCode??"en")}`))}catch{}}async function ol(e=process.cwd(),t="auto",n){let o=Qp(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)),uf(e,n),o.kind==="subscription"&&(o.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,s=ws({cwd:e,profileName:n,allowProdWrites:r}),u={uuid:null,firstPrompt:null,titleFired:!1},p=Kp({input:process.stdin,output:process.stdout}),h=[],k=null,x=!1;p.on("line",P=>{if(k){let C=k;k=null,C(P)}else h.push(P)}),p.on("close",()=>{if(x=!0,k){let P=k;k=null,P(null)}});function D(){return h.length>0?Promise.resolve(h.shift()):x?Promise.resolve(null):(process.stdout.write(_("> ")),new Promise(P=>{k=P}))}let b={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=ws({cwd:e,profileName:n,allowProdWrites:r}),u={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>u.uuid,setPendingName:P=>{u.pendingName=P},setModel:async P=>s.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 C=P.trim();if(C){if(C.startsWith("/")){let N=Xa(C);if(!N)continue;let I=za[N.name];if(!I){console.log($(`Unknown command: /${N.name}`)),console.log(f("Type /help for the list."));continue}let O=await I(N.args,b);if(O.kind==="exit")break;if(O.kind==="clear"){b.restartAgent();continue}if(O.kind==="allow-prod"){r=!0,b.restartAgent(),console.log(j("\u2713 Production writes authorized for this session.")),console.log("");continue}if(O.kind==="resume"){s.close(),s=ws({cwd:e,resume:O.uuid,profileName:n,allowProdWrites:r});let J=Jp(O.uuid);u={uuid:O.uuid,firstPrompt:J?.firstPrompt??null,titleFired:!0},tl(O.uuid),console.log(j(`\u2713 Resumed "${O.name}"`)),console.log("");continue}O.kind==="forward-to-agent"&&(u.firstPrompt||(u.firstPrompt=O.display??O.prompt),await el(s,O.prompt,o,u,e));continue}u.firstPrompt||(u.firstPrompt=C),await el(s,C,o,u,e)}}}finally{s.close(),p.close()}}function uf(e,t){console.log(""),console.log(zt("document360-writer")),console.log(f(` cwd: ${e}`));let n=of(e);if(console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(df(e,t)),!rf(e))console.log(M(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{try{Hn(e);for(let o of qn(e))console.log(M(` ${o}`))}catch{}try{let o=Lt(Mt(e));o&&console.log(M(` \u{1F4CB} ${o} from the repo's coding agent \u2014 run /catch-up.`))}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function df(e,t){try{let n=nl(e,t),o=n.production?M(" \u26A0 PRODUCTION"):"",r=af(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Za(r.idToken)??{},...Za(r.accessToken)??{}},u=s.email??s.preferred_username??"signed in";return sf(r)&&!r.refreshToken?M(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${u} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function pf(){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 ff(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;tf({uuid:t,name:r??ef(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function mf(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||nf(o,t).then(r=>{r&&Zp(n,r)}).catch(()=>{})}async function el(e,t,n,o,r){let s=new Map;for await(let u of e.send(t))hf(u,o,r,n,s)}function hf(e,t,n,o,r){switch(e.type){case"session":t.uuid||ff(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=co(e.name,e.input);s&&(process.stdout.write(`
254
-
255
- `),console.log(`${j("\u25CF")} ${Pe(s.title)}${s.arg!==null?se(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=ct(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let u=p=>p===1?"":"s";console.log(se(` \u23BF Added ${s.added} line${u(s.added)}, removed ${s.removed} line${u(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(f(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let u=uo(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?$:se;u.lines.forEach((h,k)=>console.log(p((k===0?" \u23BF ":" ")+h))),u.hidden>0&&console.log(f(` \u2026 +${u.hidden} lines`)),e.isError||cf(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
256
- `),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&&(tl(t.uuid),t.titleFired||mf(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&pf();break}}import{render as Dm}from"ink";import{resolveAuth as jm}from"document360-engine";import{useCallback as V,useEffect as Te,useMemo as vs,useRef as Q,useState as H}from"react";import{Box as oe,Text as T,useApp as If,useInput as Nf,useStdout as _f}from"ink";import{existsSync as Xe,readFileSync as Cs,readdirSync as To}from"node:fs";import{spawnSync as Mf}from"node:child_process";import{basename as un,isAbsolute as Lf,join as ft}from"node:path";import{createSession as Il,classifyClaudeAuth as Ss,CLAUDE_CODE_SETUP_HINT as Of,loginPkce as Uf,toStoredTokens as Wf,saveTokens as Ff,getAccessToken as Hf,resolveActiveProfile as de,resolveProjectId as qf,getArticle as Bf,decodeJwtClaims as Ut,isExpired as We,loadTokens as Ke,clearTokens as Gf,clearProfileProject as Yf,setTitle as Vf,slugify as zf,touchSession as Ps,upsertSession as Xf,generateTitle as Nl,findByName as Kf,listSessions as Qf,renameSession as Jf,suggestNextAction as Zf,readProjectConfig as Z,writeProjectConfig as _l,resolveModelSetting as Ds,loadProfileMap as Ro,applyPull as em,computeSyncStatus as Ml,countLocalAhead as tm,lintDocs as Ll,compareRemoteSources as nm,planPull as om,establishBaselines as rm,rebaselineServerMeta as sm,inventoryRepo as im,knownEnvironments as am,resolveEnvironment as lm,planPartitions as Rs,partitionEvenly as cm,screenshotPlaceholderIds as um,trackedArticlePaths as dm,runPartitioned as vo,estimateBulkCost as Ol,resolveModelForOperation as Co,readDocsPlan as Ul,checkForUpdate as pm,detectInstallKind as fm,isSelfUpdatable as mm,devHintsGuidePath as js,toolFeedbackPath as hm,reconcileToolFeedback as gm,DEFAULT_DOCS_DIR as dn,setProfileProject as wm,writeCrashLog as ym}from"document360-engine";lt();import{spawn as rl}from"node:child_process";function gf(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function wf(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?rl([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):rl(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",u=>o(u===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function sl(e){for(let[t,n]of gf())if(await wf(t,n,e))return!0;return!1}var yf=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function ys(e,t){if(t.closed)return e;let n=e.split(`
257
- `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){yf.test(s)&&(t.cueSeen=!0);continue}let u=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);u?(n[r]=`${u[1]}${++t.num}. ${u[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
258
- `)}import{existsSync as kf,mkdirSync as bf,readFileSync as xf,writeFileSync as $f}from"node:fs";import{join as il}from"node:path";import{writerDir as vf}from"document360-engine";function al(e){return il(vf(e),".sessions")}function ll(e,t){return il(al(e),`${t}.json`)}function cl(e,t,n){try{bf(al(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");$f(ll(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function ks(e,t){try{let n=ll(e,t);if(!kf(n))return[];let o=JSON.parse(xf(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Cf=e=>`\x1B]0;${e}\x07`,Pf=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function ul(e){process.stdout.isTTY&&process.stdout.write(e)}function Ot(e){ul(Cf(e))}function ho(e){ul(Pf(e))}var go=["\xB7 "," \xB7"],wo="\u{1F7E3}";no();Yn();var yo=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"check",usage:"/check [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). --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:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],dl={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function pl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(dl[n])return dl[n];let o=yo.find(r=>r.name===t);return o?o.desc:""}function fl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return yo.filter(n=>n.name.startsWith(t))}function ml(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as hl,Text as ie}from"ink";import{jsx as le,jsxs as ko}from"react/jsx-runtime";function Rf({row:e}){switch(e.t){case"head":return le(ie,{color:F,bold:!0,children:e.s});case"text":return le(ie,{children:e.s});case"dim":return le(ie,{dimColor:!0,children:e.s});case"sub":return le(ie,{bold:!0,dimColor:!0,children:e.s});case"good":return le(ie,{color:"green",children:e.s});case"step":return ko(ie,{children:[le(ie,{color:F,children:`${e.n}. `}),e.s]});case"cmd":return ko(ie,{children:[" ",le(ie,{color:F,children:e.name.padEnd(20)}),le(ie,{dimColor:!0,children:e.s})]});case"gap":return le(ie,{children:" "})}}function gl({tab:e,width:t}){let n=Re[e]??Re[0],o=6+Re.reduce((s,u)=>s+u.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return ko(hl,{flexDirection:"column",paddingX:1,children:[ko(ie,{children:[le(ie,{color:F,bold:!0,children:"Help "}),Re.map((s,u)=>u===e?le(ie,{color:"white",backgroundColor:F,bold:!0,children:` ${s.label} `},s.key):le(ie,{dimColor:!0,children:` ${s.label} `},s.key))]}),le(ie,{color:F,children:r}),le(hl,{flexDirection:"column",marginTop:1,children:n.rows.map((s,u)=>le(Rf,{row:s},u))}),le(ie,{dimColor:!0,children:`
259
- \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var Tf=/^(?:\d+[.)]|[-*•])\s+/;function wl(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
260
- `)){let u=s.trim().replace(Tf,""),p=u.match(/^`([^`]+)`$/);p&&(u=p[1].trim());let h=u.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!h||!o.has(h[1].toLowerCase()))continue;let k=`/${h[1].toLowerCase()}${h[2]?` ${h[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}W();function cn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Oe(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function yl(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Sf=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function kl(e,t,n){if(!Sf.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(s=>{let u=s.replace(/\\/g,"/");return r===u||r.endsWith(`/${u}`)})??null}function bs(e){return e.replace(/^[\w.-]+\//,"")}var bo=16,bl={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function pt(e){return typeof e=="string"?e:e.cmd}function xl(e){return typeof e=="string"?void 0:e.desc}function xs(e){return e.trim().split(/\s+/).slice(1).join(" ")}function $l(e,t){let n=xs(t);return e.some(r=>pt(r).trim()===t.trim()||!!n&&xs(pt(r))===n)?e.filter(r=>pt(r).trim()!==t.trim()&&!(n&&xs(pt(r))===n)):[]}var Df='\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 jf(e,t){switch(e){case"/write":return"finish the planned articles that aren\u2019t written yet";case"/catch-up":return"write up everything your builder flagged";case"/audit":return t?"also scan the code for other changes":"check the code for anything new or missing in the docs";case"/pull":return"pull edits + new articles from Document360";case"/publish":return"push your local changes up to Document360";default:return""}}function Ue(e){return e===1?"":"s"}function Af(e){switch(e){case"/write":return"it finishes the articles already planned";case"/catch-up":return"it clears everything your builder queued";case"/audit":return"it shows what the latest code changes touch";case"/pull":return"it reconciles anything changed on Document360";case"/publish":return"it pushes your local edits up to Document360";default:return"it\u2019s the most useful next step"}}function $s(e,t,n){let o=[];e.pendingWrites>0&&o.push(` \u2022 ${e.pendingWrites} planned article${Ue(e.pendingWrites)} still unwritten`),e.localAhead>0&&o.push(` \u2022 ${e.localAhead} article${Ue(e.localAhead)} changed locally \u2014 ready to publish`),e.pendingText&&o.push(` \u2022 your builder left ${e.pendingText}`),e.behind>0&&o.push(` \u2022 ${e.behind} code change${Ue(e.behind)} since your last docs check`);let r=o.length>0?["Welcome back \u2014 where your docs stand:",...o,`I\u2019d start with ${t[0]} \u2014 ${Af(t[0])}.`]:[`Welcome back. Your ${e.tracked} tracked article${Ue(e.tracked)} are all in sync.`];return r.push("",...t.map((s,u)=>` ${u+1} ${s.padEnd(9)} ${jf(s,n)}`),"Or just tell me what to write or update."),r.join(`
261
- `)}function vl(e){if(!e.ready)return{kind:"idle"};let t=!!e.pendingText;if(!e.hasDocs)return{kind:"noDocs",note:Df,ghost:"write the docs for this repo",title:t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:null,options:t?["/catch-up","/audit"]:["/audit"]};if(e.pendingWrites>0){let r=t?["/write","/catch-up"]:["/write","/audit"],s=`\u{1F4DD} ${e.pendingWrites} planned article${Ue(e.pendingWrites)} not written yet \u2014 pick up where you left off:`;return{kind:"actions",note:$s(e,r,t),title:s,options:r}}if(e.localAhead>0){let r=t?["/publish","/catch-up"]:["/publish","/audit"],s=`\u{1F4E4} ${e.localAhead} article${Ue(e.localAhead)} changed locally \u2014 ready to publish to Document360:`;return{kind:"actions",note:$s(e,r,t),title:s,options:r}}if(!t&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${Ue(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`};let n=t?["/catch-up","/audit"]:["/audit","/pull"],o=t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:e.behind>0?`\u{1F4CB} ${e.behind} code change${Ue(e.behind)} since your last docs check \u2014 /audit to see what needs updating (or /audit --auto on to run it for you):`:`\u{1F4DA} ${e.tracked} article${Ue(e.tracked)} tracked for "${e.profileName}". What next?`;return{kind:"actions",note:$s(e,n,t),title:o,options:n}}var Ef=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Cl(e){return e.replace(/\r\n?/g,`
262
- `)}function Pl(e){return e.includes(`
263
- `)||e.length>200}function Rl(e,t){let n=t.split(`
264
- `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Tl(e,t){return e.replace(Ef,n=>t.get(n)??n)}function Sl(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function xo(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
265
- `)){if(s.length===0)o.push({start:r,end:r});else for(let u=0;u<s.length;u+=n)o.push({start:r+u,end:r+Math.min(u+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function $o(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Dl(e,t,n){let o=$o(e,t),r=o+n;if(r<0||r>=e.length)return t;let s=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+s,e[r].end)}function jl(e,t,n){let o=e[$o(e,t)];return n==="start"?o.start:o.end}function Al(e,t,n){let o=Math.max(1,n),r=e.split(`
266
- `),s=0;for(let u=r.length-1;u>=0;u--){let p=r[u];if(s+=Math.max(1,Math.ceil(p.length/o)),s>=t){let h=s-t;return{text:[h>0?p.slice(h*o):p,...r.slice(u+1)].join(`
267
- `),truncated:u>0||h>0}}}return{text:e,truncated:!1}}function El(e){let t=!1,n=0,o=0;for(let r of e.split(`
268
- `)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as Ts,jsx as E,jsxs as G}from"react/jsx-runtime";var km={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},Wl=` 1. /init \u2014 pick your Document360 environment & scaffold config
251
+ `)}async function Xa(e,t){let n=e.includes("--fix"),o=e.find(c=>!c.startsWith("--")),r=o?` ${o}`:"",s=Op({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(j("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:gs(s),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts)\u2026"));for(let c of po(s))console.log(s.length===0?j(c):M(c));return s.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}W();import{lintDocs as Up,loadStyleGuide as Wp,buildReviewPrompt as Fp,readProjectConfig as Hp,DEFAULT_DOCS_DIR as qp}from"document360-engine";function ws(e,t){let n=Hp(e);if(!n)return null;let o=(n.docsDir??qp).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(k=>!k.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),c=Up({cwd:e}),p=s?c.filter(k=>k.path===`${o}/${s}`||k.path.startsWith(`${o}/${s}/`)):c;return{prompt:Fp({docsRoot:o,scope:s,styleGuide:Wp(e),deterministicFindings:p,fix:r}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function Ka(e,t){let n=ws(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}var Qa={help:nr,"?":nr,clear:xi,exit:or,quit:or,init:lr,mcp:Kn,publish:Qi,audit:an,scope:Zi,pull:ia,convert:aa,write:da,draft:ga,document:wa,resume:ba,rename:xa,profile:va,model:Ra,doctor:cn,workspace:Ea,project:Ia,"allow-prod":Na,login:_a,logout:Ma,screenshot:io,"capture-setup":un,devhints:Si,inbox:Fa,"catch-up":Ha,update:qa,reset:za,check:Xa,review:Ka};function Ja(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),o=(n[0]??"").toLowerCase();return o?{name:o,args:n.slice(1)}:null}ct();W();var Bp={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"},el=160,ks=200,tl=40;function ke(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Za(e){let t=Object.entries(e).filter(([,o])=>o!=null&&o!=="");if(t.length===0)return null;let n=t.slice(0,4).map(([o,r])=>`${o}: ${ke(typeof r=="string"?r:JSON.stringify(r),tl)}`);return t.length>4&&n.push("\u2026"),ke(n.join(", "),el)}var ze=e=>typeof e=="string"&&e?e:null,ys=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Gp(e){let t=ze(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function Yp(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=Gp(t.local_path);return n("Create article",`"${ke(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=ze(t.title),r=ys(t.article_id);return n("Update article",o?`"${ke(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",ys(t.article_id)?`id ${ys(t.article_id)}\u2026`:null);case"d360_publish_article":{let o=t.version_number;return n("Publish article LIVE",typeof o=="number"?`v${o}`:null)}case"d360_unpublish_article":return n("Unpublish article",null);case"d360_create_category":return n("Create category",ze(t.name)?`"${ke(ze(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=ze(t.file_path);return n("Upload image",o?ke(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function fo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),c=s.join("__");if(r==="document360"){let k=Yp(c,t);if(k)return k}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Za(t)}}let n=Bp[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:ke(o,el)}:{title:e,sep:"",arg:Za(t)}}function Vp(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 zp(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Vp).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>ke(r,ks))]}if(t!==null&&typeof t=="object"){let n=Object.entries(t).filter(([,o])=>o!==null&&(typeof o=="string"||typeof o=="number"||typeof o=="boolean")).slice(0,6).map(([o,r])=>`${o}: ${ke(String(r),tl)}`);return n.length>0?[ke(n.join(" \xB7 "),ks)]:null}return null}function Xp(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 Kp(e,t,n){switch(e){case"d360_create_article":{let o=Xp(t?.local_path);return[`\u2713 draft created${o?` \xB7 ${o}`:""}`]}case"d360_update_article":return["\u2713 draft updated"];case"d360_fork_article":return["\u2713 forked to a new draft"];case"d360_publish_article":return["\u2713 PUBLISHED LIVE \u2014 visible to readers"];case"d360_unpublish_article":return["\u2713 reverted to draft (removed from readers)"];case"d360_create_category":{let o=ze(t?.name);return[`\u2713 category created${o?` \xB7 "${o}"`:""}`]}case"d360_upload_drive_file":{let o=n.match(/https?:\/\/\S+/);return[`\u2713 uploaded${o?` \xB7 ${ke(o[0],120)}`:""}`]}default:return null}}function mo(e,t=4,n,o){let r=e.replace(/\r\n/g,`
252
+ `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=Kp(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let s=zp(r)??r.split(`
253
+ `);return{lines:s.slice(0,t).map(c=>ke(c,ks)),hidden:Math.max(0,s.length-t)}}function ho(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function go(e,t){if(typeof e.article_id=="string"&&e.article_id)return e.article_id;try{let n=JSON.parse(t),r=(Array.isArray(n)?n[0]:n)?.id;return typeof r=="string"&&r?r:null}catch{return null}}function wo(e){try{let t=JSON.parse(e),o=(Array.isArray(t)?t[0]:t)?.url;return typeof o=="string"&&/^https?:\/\//.test(o)?o:null}catch{return null}}var cf=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function uf(e,t,n,o){if(cf.test(e))try{let r=sl(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=go(t,n),p=wo(n);e.endsWith("publish_article")&&p&&console.log(_(` \u2B95 Live: ${p}`)),c&&s&&console.log(_(` \u2B95 Preview: ${ho(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function il(e=process.cwd(),t="auto",n){let o=Jp(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)),df(e,n),o.kind==="subscription"&&(o.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,s=bs({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=Qp({input:process.stdin,output:process.stdout}),g=[],k=null,x=!1;p.on("line",P=>{if(k){let C=k;k=null,C(P)}else g.push(P)}),p.on("close",()=>{if(x=!0,k){let P=k;k=null,P(null)}});function D(){return g.length>0?Promise.resolve(g.shift()):x?Promise.resolve(null):(process.stdout.write(_("> ")),new Promise(P=>{k=P}))}let b={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=bs({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setPendingName:P=>{c.pendingName=P},setModel:async P=>s.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 C=P.trim();if(C){if(C.startsWith("/")){let N=Ja(C);if(!N)continue;let I=Qa[N.name];if(!I){console.log($(`Unknown command: /${N.name}`)),console.log(f("Type /help for the list."));continue}let O=await I(N.args,b);if(O.kind==="exit")break;if(O.kind==="clear"){b.restartAgent();continue}if(O.kind==="allow-prod"){r=!0,b.restartAgent(),console.log(j("\u2713 Production writes authorized for this session.")),console.log("");continue}if(O.kind==="resume"){s.close(),s=bs({cwd:e,resume:O.uuid,profileName:n,allowProdWrites:r});let J=Zp(O.uuid);c={uuid:O.uuid,firstPrompt:J?.firstPrompt??null,titleFired:!0},rl(O.uuid),console.log(j(`\u2713 Resumed "${O.name}"`)),console.log("");continue}O.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=O.display??O.prompt),await ol(s,O.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=C),await ol(s,C,o,c,e)}}}finally{s.close(),p.close()}}function df(e,t){console.log(""),console.log(Kt("document360-writer")),console.log(f(` cwd: ${e}`));let n=rf(e);if(console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(pf(e,t)),!sf(e))console.log(M(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{try{Gn(e);for(let o of Yn(e))console.log(M(` ${o}`))}catch{}try{let o=Ut(Ot(e));o&&console.log(M(` \u{1F4CB} ${o} from the repo's coding agent \u2014 run /catch-up.`))}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function pf(e,t){try{let n=sl(e,t),o=n.production?M(" \u26A0 PRODUCTION"):"",r=lf(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...nl(r.idToken)??{},...nl(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return af(r)&&!r.refreshToken?M(` 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 ff(){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 mf(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;nf({uuid:t,name:r??tf(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function hf(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||of(o,t).then(r=>{r&&ef(n,r)}).catch(()=>{})}async function ol(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))gf(c,o,r,n,s)}function gf(e,t,n,o,r){switch(e.type){case"session":t.uuid||mf(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=fo(e.name,e.input);s&&(process.stdout.write(`
254
+
255
+ `),console.log(`${j("\u25CF")} ${Pe(s.title)}${s.arg!==null?se(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=ut(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=p=>p===1?"":"s";console.log(se(` \u23BF Added ${s.added} line${c(s.added)}, removed ${s.removed} line${c(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(f(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let c=mo(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?$:se;c.lines.forEach((g,k)=>console.log(p((k===0?" \u23BF ":" ")+g))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||uf(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
256
+ `),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&&(rl(t.uuid),t.titleFired||hf(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&ff();break}}import{render as jm}from"ink";import{resolveAuth as Am}from"document360-engine";import{useCallback as V,useEffect as Te,useMemo as Rs,useRef as Q,useState as H}from"react";import{Box as oe,Text as T,useApp as Nf,useInput as _f,useStdout as Mf}from"ink";import{existsSync as Xe,readFileSync as Ts,readdirSync as jo}from"node:fs";import{spawnSync as Lf}from"node:child_process";import{basename as pn,isAbsolute as Of,join as mt}from"node:path";import{createSession as Ml,classifyClaudeAuth as As,CLAUDE_CODE_SETUP_HINT as Uf,loginPkce as Wf,toStoredTokens as Ff,saveTokens as Hf,getAccessToken as qf,resolveActiveProfile as de,resolveProjectId as Bf,getArticle as Gf,decodeJwtClaims as Ft,isExpired as We,loadTokens as Ke,clearTokens as Yf,clearProfileProject as Vf,setTitle as zf,slugify as Xf,touchSession as Ss,upsertSession as Kf,generateTitle as Ll,findByName as Qf,listSessions as Jf,renameSession as Zf,suggestNextAction as em,readProjectConfig as Z,writeProjectConfig as Ol,resolveModelSetting as Es,loadProfileMap as Do,applyPull as tm,computeSyncStatus as Ul,countLocalAhead as nm,lintDocs as Wl,compareRemoteSources as om,planPull as rm,establishBaselines as sm,rebaselineServerMeta as im,inventoryRepo as am,knownEnvironments as lm,resolveEnvironment as cm,planPartitions as Ds,partitionEvenly as um,screenshotPlaceholderIds as dm,trackedArticlePaths as pm,runPartitioned as Ro,estimateBulkCost as Fl,resolveModelForOperation as To,readDocsPlan as Hl,checkForUpdate as fm,detectInstallKind as mm,isSelfUpdatable as hm,devHintsGuidePath as Is,toolFeedbackPath as gm,reconcileToolFeedback as wm,DEFAULT_DOCS_DIR as fn,setProfileProject as ym,writeCrashLog as km}from"document360-engine";ct();import{spawn as al}from"node:child_process";function wf(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function yf(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?al([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):al(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",c=>o(c===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function ll(e){for(let[t,n]of wf())if(await yf(t,n,e))return!0;return!1}var kf=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function xs(e,t){if(t.closed)return e;let n=e.split(`
257
+ `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){kf.test(s)&&(t.cueSeen=!0);continue}let c=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);c?(n[r]=`${c[1]}${++t.num}. ${c[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
258
+ `)}import{existsSync as bf,mkdirSync as xf,readFileSync as $f,writeFileSync as vf}from"node:fs";import{join as cl}from"node:path";import{writerDir as Cf}from"document360-engine";function ul(e){return cl(Cf(e),".sessions")}function dl(e,t){return cl(ul(e),`${t}.json`)}function pl(e,t,n){try{xf(ul(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");vf(dl(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function $s(e,t){try{let n=dl(e,t);if(!bf(n))return[];let o=JSON.parse($f(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Pf=e=>`\x1B]0;${e}\x07`,Rf=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function fl(e){process.stdout.isTTY&&process.stdout.write(e)}function Wt(e){fl(Pf(e))}function yo(e){fl(Rf(e))}var ko=["\xB7 "," \xB7"],bo="\u{1F7E3}";so();Xn();var xo=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path>] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Reports issues; --fix applies the corrections in place",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],ml={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function hl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(ml[n])return ml[n];let o=xo.find(r=>r.name===t);return o?o.desc:""}function gl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return xo.filter(n=>n.name.startsWith(t))}function wl(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as yl,Text as ie}from"ink";import{jsx as le,jsxs as $o}from"react/jsx-runtime";function Tf({row:e}){switch(e.t){case"head":return le(ie,{color:F,bold:!0,children:e.s});case"text":return le(ie,{children:e.s});case"dim":return le(ie,{dimColor:!0,children:e.s});case"sub":return le(ie,{bold:!0,dimColor:!0,children:e.s});case"good":return le(ie,{color:"green",children:e.s});case"step":return $o(ie,{children:[le(ie,{color:F,children:`${e.n}. `}),e.s]});case"cmd":return $o(ie,{children:[" ",le(ie,{color:F,children:e.name.padEnd(20)}),le(ie,{dimColor:!0,children:e.s})]});case"gap":return le(ie,{children:" "})}}function kl({tab:e,width:t}){let n=Re[e]??Re[0],o=6+Re.reduce((s,c)=>s+c.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return $o(yl,{flexDirection:"column",paddingX:1,children:[$o(ie,{children:[le(ie,{color:F,bold:!0,children:"Help "}),Re.map((s,c)=>c===e?le(ie,{color:"white",backgroundColor:F,bold:!0,children:` ${s.label} `},s.key):le(ie,{dimColor:!0,children:` ${s.label} `},s.key))]}),le(ie,{color:F,children:r}),le(yl,{flexDirection:"column",marginTop:1,children:n.rows.map((s,c)=>le(Tf,{row:s},c))}),le(ie,{dimColor:!0,children:`
259
+ \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var Sf=/^(?:\d+[.)]|[-*•])\s+/;function bl(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
260
+ `)){let c=s.trim().replace(Sf,""),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 k=`/${g[1].toLowerCase()}${g[2]?` ${g[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}W();function dn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Oe(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function xl(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Df=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function $l(e,t,n){if(!Df.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(s=>{let c=s.replace(/\\/g,"/");return r===c||r.endsWith(`/${c}`)})??null}function vs(e){return e.replace(/^[\w.-]+\//,"")}var vo=16,vl={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function ft(e){return typeof e=="string"?e:e.cmd}function Cl(e){return typeof e=="string"?void 0:e.desc}function Cs(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Pl(e,t){let n=Cs(t);return e.some(r=>ft(r).trim()===t.trim()||!!n&&Cs(ft(r))===n)?e.filter(r=>ft(r).trim()!==t.trim()&&!(n&&Cs(ft(r))===n)):[]}var jf='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function Af(e,t){switch(e){case"/write":return"finish the planned articles that aren\u2019t written yet";case"/catch-up":return"write up everything your builder flagged";case"/audit":return t?"also scan the code for other changes":"check the code for anything new or missing in the docs";case"/pull":return"pull edits + new articles from Document360";case"/publish":return"push your local changes up to Document360";default:return""}}function Ue(e){return e===1?"":"s"}function Ef(e){switch(e){case"/write":return"it finishes the articles already planned";case"/catch-up":return"it clears everything your builder queued";case"/audit":return"it shows what the latest code changes touch";case"/pull":return"it reconciles anything changed on Document360";case"/publish":return"it pushes your local edits up to Document360";default:return"it\u2019s the most useful next step"}}function Ps(e,t,n){let o=[];e.pendingWrites>0&&o.push(` \u2022 ${e.pendingWrites} planned article${Ue(e.pendingWrites)} still unwritten`),e.localAhead>0&&o.push(` \u2022 ${e.localAhead} article${Ue(e.localAhead)} changed locally \u2014 ready to publish`),e.pendingText&&o.push(` \u2022 your builder left ${e.pendingText}`),e.behind>0&&o.push(` \u2022 ${e.behind} code change${Ue(e.behind)} since your last docs check`);let r=o.length>0?["Welcome back \u2014 where your docs stand:",...o,`I\u2019d start with ${t[0]} \u2014 ${Ef(t[0])}.`]:[`Welcome back. Your ${e.tracked} tracked article${Ue(e.tracked)} are all in sync.`];return r.push("",...t.map((s,c)=>` ${c+1} ${s.padEnd(9)} ${Af(s,n)}`),"Or just tell me what to write or update."),r.join(`
261
+ `)}function Rl(e){if(!e.ready)return{kind:"idle"};let t=!!e.pendingText;if(!e.hasDocs)return{kind:"noDocs",note:jf,ghost:"write the docs for this repo",title:t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:null,options:t?["/catch-up","/audit"]:["/audit"]};if(e.pendingWrites>0){let r=t?["/write","/catch-up"]:["/write","/audit"],s=`\u{1F4DD} ${e.pendingWrites} planned article${Ue(e.pendingWrites)} not written yet \u2014 pick up where you left off:`;return{kind:"actions",note:Ps(e,r,t),title:s,options:r}}if(e.localAhead>0){let r=t?["/publish","/catch-up"]:["/publish","/audit"],s=`\u{1F4E4} ${e.localAhead} article${Ue(e.localAhead)} changed locally \u2014 ready to publish to Document360:`;return{kind:"actions",note:Ps(e,r,t),title:s,options:r}}if(!t&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${Ue(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`};let n=t?["/catch-up","/audit"]:["/audit","/pull"],o=t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:e.behind>0?`\u{1F4CB} ${e.behind} code change${Ue(e.behind)} since your last docs check \u2014 /audit to see what needs updating (or /audit --auto on to run it for you):`:`\u{1F4DA} ${e.tracked} article${Ue(e.tracked)} tracked for "${e.profileName}". What next?`;return{kind:"actions",note:Ps(e,n,t),title:o,options:n}}var If=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Tl(e){return e.replace(/\r\n?/g,`
262
+ `)}function Sl(e){return e.includes(`
263
+ `)||e.length>200}function Dl(e,t){let n=t.split(`
264
+ `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function jl(e,t){return e.replace(If,n=>t.get(n)??n)}function Al(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Co(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
265
+ `)){if(s.length===0)o.push({start:r,end:r});else for(let c=0;c<s.length;c+=n)o.push({start:r+c,end:r+Math.min(c+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function Po(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function El(e,t,n){let o=Po(e,t),r=o+n;if(r<0||r>=e.length)return t;let s=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+s,e[r].end)}function Il(e,t,n){let o=e[Po(e,t)];return n==="start"?o.start:o.end}function Nl(e,t,n){let o=Math.max(1,n),r=e.split(`
266
+ `),s=0;for(let c=r.length-1;c>=0;c--){let p=r[c];if(s+=Math.max(1,Math.ceil(p.length/o)),s>=t){let g=s-t;return{text:[g>0?p.slice(g*o):p,...r.slice(c+1)].join(`
267
+ `),truncated:c>0||g>0}}}return{text:e,truncated:!1}}function _l(e){let t=!1,n=0,o=0;for(let r of e.split(`
268
+ `)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as js,jsx as E,jsxs as G}from"react/jsx-runtime";var bm={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},ql=` 1. /init \u2014 pick your Document360 environment & scaffold config
269
269
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
270
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function bm(e,t,n,o){let r=Ss(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",u=Ds(e),p=Z(e),h=(p?.docsDir??dn).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${h}/ + config`,x={version:t,claude:s,model:u.model??"Claude Code default model",modelSource:km[u.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:k};if(p===null)return x;try{let D=de(e,o);x.profile=D.name,x.apiUrl=D.connection.apiUrl,x.prod=D.production,x.project=D.project.projectName??D.project.projectId??"(chosen at login)";let b=Ke(D.name);if(b){let P={...Ut(b.idToken)??{},...Ut(b.accessToken)??{}},C=P.email??P.preferred_username??"signed in";We(b)?b.refreshToken&&(x.who=C,x.loggedOut=!1,x.sessionHint="session expired \u2014 refreshing\u2026"):(x.who=C,x.loggedOut=!1,x.sessionHint=`session valid until ${new Date(b.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return x}function xm(e,t){try{let n=de(e,t),o=Ke(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Ut(o.idToken)??{},...Ut(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return We(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var Fl=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],So=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],$m="Ask me to write or update an article\u2026";function Po({ch:e,dim:t}){let[n,o]=H(!0);return Te(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),E(T,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var vm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Hl(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Cm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ql(e){try{return To(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Bl(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>ql(ft(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&ql(ft(e,o)))}function Gl(e,t){try{let n=Z(e);if(!n)return!1;let o=de(e,t),r=Ro(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=ft(e,(n.docsDir??dn).replace(/\/+$/,""));return!!(Xe(s)&&To(s).length>0||Xe(js(e)))}catch{return!1}}function Pm({startTime:e,chars:t}){let[n,o]=H(0);Te(()=>{let h=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(h)},[]);let r=So[n%So.length],s=Fl[Math.floor(n/16)%Fl.length],u=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return G(oe,{children:[E(T,{color:F,children:` ${r} ${s}\u2026 `}),E(T,{color:"gray",children:`(${tn(u)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var Rm=12e4;function Tm({p:e}){let[t,n]=H(0);Te(()=>{let I=setInterval(()=>n(O=>O+1),150);return()=>clearInterval(I)},[]);let o=So[t%So.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),u=Math.round(e.chars/4),p=Date.now()-e.lastAt>=Rm,h=e.verb??"Converting",k=e.unit??"article",x=e.rows.reduce((I,O)=>I+O.items,0),D=h.toLowerCase(),b=e.rows,P=0;if(b.length>bo){let I=b.findIndex(J=>J.status==="active"||J.status==="pending"),O=Math.max(0,Math.min(I-2,b.length-bo));P=b.slice(0,O).filter(J=>J.status==="done").length,b=b.slice(O,O+bo)}let C=Math.min(40,Math.max(...b.map(I=>bs(I.label).length),0)),N=I=>I==="failed"?"red":I==="active"?F:void 0;return G(oe,{flexDirection:"column",children:[G(oe,{children:[E(T,{color:F,children:` ${o} ${h} ${x} ${k}${x===1?"":"s"} `}),E(T,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${u} tokens \xB7 ${tn(r)} \xB7 esc to stop`})]}),P>0&&E(T,{dimColor:!0,children:` \u2714 +${P} done`}),b.map(I=>G(T,{color:N(I.status),dimColor:I.status==="done"||I.status==="pending",children:[` ${bl[I.status]} ${bs(I.label).padEnd(C)}`,I.status==="active"&&I.itemsDone!==void 0?` (${I.itemsDone}/${I.items} ${k}${I.items===1?"":"s"})`:I.status!=="pending"?` (${I.items} ${k}${I.items===1?"":"s"})`:"",I.status==="active"?` \u2190 ${D}\u2026`:""]},I.label)),p&&E(T,{color:"yellow",children:` \u26A0 no activity for ${tn(s)} \u2014 press esc to stop if it's wedged`})]})}var Sm=10800*1e3;function Yl({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=If(),[s,u]=H(n),[p,h]=H(null),[k,x]=H({text:"",pos:0}),D=k.text,b=V(l=>{x(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),P=V(l=>{x(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),C=V(()=>{x(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=Sl(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[N,I]=H(!1),[O,J]=H(!1),[pe,ne]=H(0),[De,ue]=H(null),[Qe,B]=H([]),mt=Q(0),[ec,pn]=H(!1),[tc,fn]=H(!1),[Do,Ns]=H(null),[nc,ht]=H(0),Je=Q(0),[Wt,gt]=H(0),[wt,mn]=H(null),_s=Q(new Map),oc=Q(0),yt=Q([]),be=Q(null);be.current===null&&(be.current=Il({cwd:e,profileName:s,allowProdWrites:!1}));let Ie=Q({uuid:null,firstPrompt:null,titleFired:!1}),hn=Q(new Map),kt=Q(!1),jo=Q([]),Fe=Q([]),Ao=Q(null),[Ms,Ze]=H(null),Eo=Q(null),[et,tt]=H(null),[Ne,bt]=H(null),[He,xt]=H(null),[fe,$t]=H(null),[xe,nt]=H(null),[ot,vt]=H(null),[Ls,je]=H(null),[$e,rt]=H(null),[he,Ct]=H(null),[Os,Io]=H([]),st=Q([]),Ft=Q(!1),ve=Q(null),[gn,ee]=H(null),wn=Q(!1),yn=Q(null),Ht=Q(null),[Ce,it]=H(null),[No,qt]=H(null),[Us,Pt]=H(0),[Ws,Rt]=H(0),[rc,Fs]=H(0),_o=vs(()=>{try{return Ds(e).model??"auto"}catch{return null}},[e,rc]),{stdout:Ae}=_f(),[,sc]=H(0),Hs=Q(`${Ae.columns??80}x${Ae.rows??24}`),qe=V(()=>Math.max(20,(Ae.columns??80)-1),[Ae]),d=V(l=>{yt.current.push(l),console.log(fr(l,qe()))},[qe]),[Mo,Lo]=H(null),Tt=V(l=>{Lo(l),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),Oo=Q(!1),Uo=V(async()=>{try{if(Oo.current||!mm(fm())||Z(e)?.mode==="engineer")return;let l=await pm({pkg:dt,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;Oo.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${dt} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),fn(!0),(await io().finally(()=>fn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),B(a=>a.includes("/exit")?a:[...a,"/exit"]),Ns(l.latest)):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${so}`})}catch{}},[e,o,d]),Wo=V(l=>{let i=Le(e,s);return i.ok?!0:(d({kind:"note",tone:"warn",text:i.reason}),Ht.current=l,B(["/login"]),!1)},[e,s,d]),[Fo,Ho]=H(null),Bt=Q(!0),kn=Q(0),Gt=Q(0);Te(()=>{let l=setInterval(()=>{if(Bt.current){kn.current=0,Gt.current=0;return}if(!N)try{if(!Xe(js(e)))return;if(Me(e).status==="current"){Bt.current=!0,kn.current=0,Gt.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."}),Lo(null),ue("write the docs for this repo");return}kn.current+=1;let i=kn.current;if((i===4||i%15===0)&&Gt.current<3){Gt.current+=1;let a=Gt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Jt(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${a}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${a}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,N,d]),Te(()=>{let l=Ms??un(e);if(!N){ho(0),Ot(`${wo} ${l}`);return}ho(3);let i=0;Ot(`${go[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%go.length,Ot(`${go[i]} ${l}`)},400);return()=>clearInterval(a)},[N,e,Ms]),Te(()=>()=>ho(0),[]);let qo=V(l=>{try{let i=Z(e);if(!i)return{kind:"idle"};let a=de(e,s),g=Ke(a.name),c=!!g&&(!We(g)||!!g.refreshToken),m=Gl(e,s)||!Bl(e,i.authoritativeSourceFiles),w=Ss(t).state==="missing",y=Ro(e,a.name),R=y?Object.keys(y.articles).length:0,S=ft(e,(i.docsDir??dn).replace(/\/+$/,"")),K=!1;try{K=Xe(S)&&To(S).length>0}catch{}let q=0;if(y?.lastAnalyzedCommit)try{let U=Mf("git",["rev-list","--count",`${y.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});U.status===0&&(q=parseInt((U.stdout||"").trim(),10)||0)}catch{}let L=0;try{let U=Ul(e);if(U.length>0){let X=(i.docsDir??dn).replace(/\/+$/,"");L=Ir(e,X,U.map(we=>we.path)).length}}catch{}let v=tm(e,s),A={ready:c&&m&&!w,hasDocs:K,tracked:R,pendingText:Lt(Mt(e)),behind:q,pendingWrites:L,localAhead:v,autoAudit:!!i.autoAudit,profileName:a.name,allowAutoAudit:l};return vl(A)}catch{return{kind:"idle"}}},[e,s,t]);Te(()=>{let l=performance.now(),i=[],a=(w,y)=>{let R=performance.now();try{return y()}finally{let S=Math.round(performance.now()-R);S>=80&&i.push(`${w}: ${S}ms`)}};d({kind:"banner",info:a("banner",()=>bm(e,o,t,s))});let g=Ss(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.
271
- ${Of}
270
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function xm(e,t,n,o){let r=As(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",c=Es(e),p=Z(e),g=(p?.docsDir??fn).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${g}/ + config`,x={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:bm[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:k};if(p===null)return x;try{let D=de(e,o);x.profile=D.name,x.apiUrl=D.connection.apiUrl,x.prod=D.production,x.project=D.project.projectName??D.project.projectId??"(chosen at login)";let b=Ke(D.name);if(b){let P={...Ft(b.idToken)??{},...Ft(b.accessToken)??{}},C=P.email??P.preferred_username??"signed in";We(b)?b.refreshToken&&(x.who=C,x.loggedOut=!1,x.sessionHint="session expired \u2014 refreshing\u2026"):(x.who=C,x.loggedOut=!1,x.sessionHint=`session valid until ${new Date(b.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return x}function $m(e,t){try{let n=de(e,t),o=Ke(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Ft(o.idToken)??{},...Ft(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return We(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var Bl=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Ao=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],vm="Ask me to write or update an article\u2026";function So({ch:e,dim:t}){let[n,o]=H(!0);return Te(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),E(T,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Cm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Gl(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Pm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Yl(e){try{return jo(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Vl(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Yl(mt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Yl(mt(e,o)))}function zl(e,t){try{let n=Z(e);if(!n)return!1;let o=de(e,t),r=Do(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=mt(e,(n.docsDir??fn).replace(/\/+$/,""));return!!(Xe(s)&&jo(s).length>0||Xe(Is(e)))}catch{return!1}}function Rm({startTime:e,chars:t}){let[n,o]=H(0);Te(()=>{let g=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(g)},[]);let r=Ao[n%Ao.length],s=Bl[Math.floor(n/16)%Bl.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return G(oe,{children:[E(T,{color:F,children:` ${r} ${s}\u2026 `}),E(T,{color:"gray",children:`(${on(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var Tm=12e4;function Sm({p:e}){let[t,n]=H(0);Te(()=>{let I=setInterval(()=>n(O=>O+1),150);return()=>clearInterval(I)},[]);let o=Ao[t%Ao.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),p=Date.now()-e.lastAt>=Tm,g=e.verb??"Converting",k=e.unit??"article",x=e.rows.reduce((I,O)=>I+O.items,0),D=g.toLowerCase(),b=e.rows,P=0;if(b.length>vo){let I=b.findIndex(J=>J.status==="active"||J.status==="pending"),O=Math.max(0,Math.min(I-2,b.length-vo));P=b.slice(0,O).filter(J=>J.status==="done").length,b=b.slice(O,O+vo)}let C=Math.min(40,Math.max(...b.map(I=>vs(I.label).length),0)),N=I=>I==="failed"?"red":I==="active"?F:void 0;return G(oe,{flexDirection:"column",children:[G(oe,{children:[E(T,{color:F,children:` ${o} ${g} ${x} ${k}${x===1?"":"s"} `}),E(T,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${on(r)} \xB7 esc to stop`})]}),P>0&&E(T,{dimColor:!0,children:` \u2714 +${P} done`}),b.map(I=>G(T,{color:N(I.status),dimColor:I.status==="done"||I.status==="pending",children:[` ${vl[I.status]} ${vs(I.label).padEnd(C)}`,I.status==="active"&&I.itemsDone!==void 0?` (${I.itemsDone}/${I.items} ${k}${I.items===1?"":"s"})`:I.status!=="pending"?` (${I.items} ${k}${I.items===1?"":"s"})`:"",I.status==="active"?` \u2190 ${D}\u2026`:""]},I.label)),p&&E(T,{color:"yellow",children:` \u26A0 no activity for ${on(s)} \u2014 press esc to stop if it's wedged`})]})}var Dm=10800*1e3;function Xl({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Nf(),[s,c]=H(n),[p,g]=H(null),[k,x]=H({text:"",pos:0}),D=k.text,b=V(l=>{x(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),P=V(l=>{x(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),C=V(()=>{x(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=Al(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[N,I]=H(!1),[O,J]=H(!1),[pe,ne]=H(0),[De,ue]=H(null),[Qe,q]=H([]),ht=Q(0),[oc,mn]=H(!1),[rc,hn]=H(!1),[Eo,Ls]=H(null),[sc,gt]=H(0),Je=Q(0),[Ht,wt]=H(0),[yt,gn]=H(null),Os=Q(new Map),ic=Q(0),kt=Q([]),be=Q(null);be.current===null&&(be.current=Ml({cwd:e,profileName:s,allowProdWrites:!1}));let Ie=Q({uuid:null,firstPrompt:null,titleFired:!1}),wn=Q(new Map),bt=Q(!1),Io=Q([]),Fe=Q([]),No=Q(null),[Us,Ze]=H(null),_o=Q(null),[et,tt]=H(null),[Ne,xt]=H(null),[He,$t]=H(null),[fe,vt]=H(null),[xe,nt]=H(null),[ot,Ct]=H(null),[Ws,he]=H(null),[$e,rt]=H(null),[ge,Pt]=H(null),[Fs,Mo]=H([]),st=Q([]),qt=Q(!1),ve=Q(null),[yn,ee]=H(null),kn=Q(!1),bn=Q(null),Bt=Q(null),[Ce,it]=H(null),[Lo,Gt]=H(null),[Hs,Rt]=H(0),[qs,Tt]=H(0),[ac,Bs]=H(0),Oo=Rs(()=>{try{return Es(e).model??"auto"}catch{return null}},[e,ac]),{stdout:je}=Mf(),[,lc]=H(0),Gs=Q(`${je.columns??80}x${je.rows??24}`),qe=V(()=>Math.max(20,(je.columns??80)-1),[je]),d=V(l=>{kt.current.push(l),console.log(gr(l,qe()))},[qe]),[Uo,Wo]=H(null),St=V(l=>{Wo(l),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),Fo=Q(!1),Ho=V(async()=>{try{if(Fo.current||!hm(mm())||Z(e)?.mode==="engineer")return;let l=await fm({pkg:pt,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;Fo.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${pt} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),hn(!0),(await co().finally(()=>hn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),q(a=>a.includes("/exit")?a:[...a,"/exit"]),Ls(l.latest)):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${lo}`})}catch{}},[e,o,d]),qo=V(l=>{let i=Le(e,s);return i.ok?!0:(d({kind:"note",tone:"warn",text:i.reason}),Bt.current=l,q(["/login"]),!1)},[e,s,d]),[Bo,Go]=H(null),Yt=Q(!0),xn=Q(0),Vt=Q(0);Te(()=>{let l=setInterval(()=>{if(Yt.current){xn.current=0,Vt.current=0;return}if(!N)try{if(!Xe(Is(e)))return;if(Me(e).status==="current"){Yt.current=!0,xn.current=0,Vt.current=0,d({kind:"note",tone:"ok",text:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs."}),Wo(null),ue("write the docs for this repo");return}xn.current+=1;let i=xn.current;if((i===4||i%15===0)&&Vt.current<3){Vt.current+=1;let a=Vt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:en(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${a}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${a}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,N,d]),Te(()=>{let l=Us??pn(e);if(!N){yo(0),Wt(`${bo} ${l}`);return}yo(3);let i=0;Wt(`${ko[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%ko.length,Wt(`${ko[i]} ${l}`)},400);return()=>clearInterval(a)},[N,e,Us]),Te(()=>()=>yo(0),[]);let Yo=V(l=>{try{let i=Z(e);if(!i)return{kind:"idle"};let a=de(e,s),h=Ke(a.name),u=!!h&&(!We(h)||!!h.refreshToken),m=zl(e,s)||!Vl(e,i.authoritativeSourceFiles),w=As(t).state==="missing",y=Do(e,a.name),R=y?Object.keys(y.articles).length:0,S=mt(e,(i.docsDir??fn).replace(/\/+$/,"")),K=!1;try{K=Xe(S)&&jo(S).length>0}catch{}let B=0;if(y?.lastAnalyzedCommit)try{let U=Lf("git",["rev-list","--count",`${y.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});U.status===0&&(B=parseInt((U.stdout||"").trim(),10)||0)}catch{}let L=0;try{let U=Hl(e);if(U.length>0){let X=(i.docsDir??fn).replace(/\/+$/,"");L=Mr(e,X,U.map(ye=>ye.path)).length}}catch{}let v=nm(e,s),A={ready:u&&m&&!w,hasDocs:K,tracked:R,pendingText:Ut(Ot(e)),behind:B,pendingWrites:L,localAhead:v,autoAudit:!!i.autoAudit,profileName:a.name,allowAutoAudit:l};return Rl(A)}catch{return{kind:"idle"}}},[e,s,t]);Te(()=>{let l=performance.now(),i=[],a=(w,y)=>{let R=performance.now();try{return y()}finally{let S=Math.round(performance.now()-R);S>=80&&i.push(`${w}: ${S}ms`)}};d({kind:"banner",info:a("banner",()=>xm(e,o,t,s))});let h=As(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.
271
+ ${Uf}
272
272
  Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!Z(e)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
273
- ${Wl}`}),B(g?["/doctor","/init"]:["/init"]);return}g&&B(["/doctor"]);try{let w=de(e,s),y=Ke(w.name);y&&We(y)&&y.refreshToken?Hf({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),ne(R=>R+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),B(["/login"])}):(!y||We(y))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),B(["/login"]))}catch{}try{let w=Z(e),y=de(e,s),R=Ke(y.name);w&&R&&!We(R)&&Bl(e,w.authoritativeSourceFiles)&&!Gl(e,s)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),B(["/scope"]))}catch{}try{if(a("reconcile-devhints",()=>Hn(e)),Me(e).status!=="current")if(Jt(e))d({kind:"note",tone:"info",text:`\u{1F514} A newer dev\u2194docs protocol (v${re}) is available \u2014 your builder can re-run /devhints when convenient. Your docs aren't blocked.`});else{let w=qn(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
274
- `)}),Tt(at()),Bt.current=!1)}}catch{}try{let w=a("reconcile-feedback",()=>gm(e));w.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}let c=a("ready-decision",()=>qo(!0));c.kind==="autoAudit"?(d({kind:"note",tone:"info",text:c.note}),rn().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&ae(w.prompt,{display:w.display,quietUser:!0})})):c.kind==="noDocs"?(d({kind:"note",tone:"info",text:c.note}),ue(c.ghost),B(c.options),c.title&&je(c.title)):c.kind==="actions"&&(d({kind:"note",tone:"info",text:c.note}),B(c.options),je(c.title));let m=Math.round(performance.now()-l);m>=800&&ym({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${m}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${i.length?i.join(`
273
+ ${ql}`}),q(h?["/doctor","/init"]:["/init"]);return}h&&q(["/doctor"]);try{let w=de(e,s),y=Ke(w.name);y&&We(y)&&y.refreshToken?qf({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),ne(R=>R+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),q(["/login"])}):(!y||We(y))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),q(["/login"]))}catch{}try{let w=Z(e),y=de(e,s),R=Ke(y.name);w&&R&&!We(R)&&Vl(e,w.authoritativeSourceFiles)&&!zl(e,s)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),q(["/scope"]))}catch{}try{if(a("reconcile-devhints",()=>Gn(e)),Me(e).status!=="current")if(en(e))d({kind:"note",tone:"info",text:`\u{1F514} A newer dev\u2194docs protocol (v${re}) is available \u2014 your builder can re-run /devhints when convenient. Your docs aren't blocked.`});else{let w=Yn(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
274
+ `)}),St(lt()),Yt.current=!1)}}catch{}try{let w=a("reconcile-feedback",()=>wm(e));w.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}let u=a("ready-decision",()=>Yo(!0));u.kind==="autoAudit"?(d({kind:"note",tone:"info",text:u.note}),an().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&ae(w.prompt,{display:w.display,quietUser:!0})})):u.kind==="noDocs"?(d({kind:"note",tone:"info",text:u.note}),ue(u.ghost),q(u.options),u.title&&he(u.title)):u.kind==="actions"&&(d({kind:"note",tone:"info",text:u.note}),q(u.options),he(u.title));let m=Math.round(performance.now()-l);m>=800&&km({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${m}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${i.length?i.join(`
275
275
  `):"no single phase \u226580ms"}
276
- cwd: ${e}`}),Uo()},[]),Te(()=>{let l=setInterval(()=>{Uo()},Sm);return()=>clearInterval(l)},[Uo]),Te(()=>{if(N||Qe.length>0)return;let l=qo(!1);(l.kind==="actions"||l.kind==="noDocs")&&(B(l.options),je(l.title??null))},[N,Qe,pe,qo]),Te(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${Ae.columns??80}x${Ae.rows??24}`;g!==Hs.current&&(Hs.current=g,sc(c=>c+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Bi(yt.current,qe())+"\x1B[?2026l")},80))},400)};return Ae.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),Ae.off("resize",a)}},[Ae,qe]);let _e=Math.max(20,(Ae.columns??80)-1),qs=vs(()=>xm(e,s),[e,s,pe]),Bo=(()=>{if(tc)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Do!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Do?` v${Do}`:""}\u2026`,isSetup:!0};let l=Z(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=ft(e,(l.docsDir??dn).replace(/\/+$/,"")),a=(()=>{try{return Xe(i)&&To(i).length>0}catch{return!1}})();try{let g=de(e,s),c=Ke(g.name);if(!(!!c&&!(We(c)&&!c.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${g.name}")\u2026`,isSetup:!0};if(!g.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!g.project.workspaceId&&!a)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return a?{text:$m,isSetup:!1}:Mo?{text:"Press c to copy the prompt above, run it in your coding agent \u2014 then ask me to write the docs",isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Yt=fl(D),Bs=Yt.length>0&&!N,Go=p!==null?Al(p,8,_e):null,bn=$e?$e.paths.filter(l=>!$e.query||l.toLowerCase().includes($e.query.toLowerCase())).slice(0,8):[],xn=Ce?Ce.sessions.filter(l=>{let i=Ce.query.toLowerCase();return!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],ge=V((l,i)=>{be.current?.close(),be.current=Il({cwd:e,resume:l,profileName:i??s,allowProdWrites:kt.current}),l||(Ie.current={uuid:null,firstPrompt:null,titleFired:!1},Ze(null)),Pt(0),Rt(0)},[e,s]),Gs=V((l,i,a)=>{if(vm.test(l))try{let g=de(e,s),c=typeof i.project_id=="string"&&i.project_id||g.project.projectId,m=fo(i,a),w=[],y=mo(a);l.endsWith("publish_article")&&y&&w.push(`Live: ${y}`),m&&c&&w.push(`Preview: ${po(g.connection.portalUrl,c,m,g.project.languageCode??"en")}`),w.length>0&&d({kind:"link",lines:w})}catch{}},[e,s,d]),ae=V(async(l,i)=>{pn(!0),ue(null),B([]),je(null),Lo(null),Ho(null);let a=++mt.current;i?.quietUser||d({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let g=Ie.current;g.firstPrompt||(g.firstPrompt=i?.display??l),Je.current=Date.now(),ht(0),I(!0),hn.current.clear();let c="",m=!1,w=!1,y="",R={num:0,closed:!1,cueSeen:!1},S=null,K=()=>{S||(S=setTimeout(()=>{S=null,h(y.length>0?y:null)},60))},q=()=>{S&&clearTimeout(S),S=null,h(null)},L=()=>{if(y.trim()){let v=ys(y.trimEnd(),R);d({kind:"assistant",text:v})}y="",q()};try{for await(let v of be.current.send(l))if(v.type==="session"){if(!g.uuid){g.uuid=v.sessionId;let A=new Date().toISOString(),U=Eo.current,X=U??zf(g.firstPrompt??"session");Xf({uuid:v.sessionId,name:X,renamed:!!U,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:A,updatedAt:A}),Ze(X),Eo.current=null}}else if(v.type==="text"){y+=v.delta,c+=v.delta;let A=El(y);if(A>0){let U=y.slice(0,A).trimEnd();U&&d({kind:"assistant",text:ys(U,R)}),y=y.slice(A)}K(),ht(U=>U+v.delta.length)}else if(v.type==="tool"){m=!0;let A=co(v.name,v.input);A&&(L(),d({kind:"tool",title:A.title,sep:A.sep,arg:A.arg}),hn.current.set(v.id,{name:v.name,input:v.input}))}else if(v.type==="article_diff"){let A=ct(v.oldContent,v.newContent,qe());A&&(L(),d({kind:"diff",added:A.added,removed:A.removed,lines:A.lines,hidden:A.hidden}))}else if(v.type==="tool_result"){v.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(v.output)&&(wn.current=!0);let A=hn.current.get(v.id);if(A){hn.current.delete(v.id),L();let U=uo(v.output,4,v.isError?void 0:A.name,A.input);d({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:v.isError}),v.isError||Gs(A.name,A.input,v.output)}}else if(v.type==="result"){if(L(),Pt(U=>U+v.outputTokens),Rt(U=>U+v.costUsd),d({kind:"done",seconds:Math.round((Date.now()-Je.current)/1e3),tokens:v.outputTokens,costUsd:v.costUsd,ok:v.ok}),!w&&!m&&!c.trim()&&!Ft.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),v.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(c))try{let U=hm(e);if(Xe(U)){let X=Cs(U,"utf8").trim();X&&(Ho(X),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}let A=v.ok?wl(c,yo.map(U=>U.name)):[];if(A.length>0?B(A):v.ok&&c.trim()&&Zf(l,c,e).then(U=>{U&&mt.current===a&&ue(U)}).catch(()=>{}),g.uuid&&(Ps(g.uuid),!g.titleFired)){g.titleFired=!0;let U=g.uuid,X=g.firstPrompt;X&&Nl(X,e).then(we=>{we&&(Vf(U,we),Ze(we))}).catch(()=>{})}}else v.type==="error"&&(L(),w=!0,v.kind==="auth"&&(wn.current=!0),d({kind:"note",text:`agent error: ${v.message}`,tone:"error"}))}finally{I(!1),q(),ne(v=>v+1),Ie.current.uuid&&cl(e,Ie.current.uuid,yt.current),wn.current&&(wn.current=!1,yn.current=i?.display??l,B(["/login"])),Ft.current&&(Ft.current=!1,st.current.length>0&&(d({kind:"note",tone:"info",text:`(${st.current.length} queued message(s) discarded)`}),st.current=[],Io([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Gs,qe]),$n=V(async l=>{let i=Rs(l),a=Co(e,"standard");Je.current=Date.now(),ht(0),I(!0);let g=new AbortController;ve.current=g,ee({verb:"Publishing",total:i.length,done:0,active:[],rows:cn(i),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${nn} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let c of vo({cwd:e,partitions:i,promptFor:m=>Xn(m.paths),concurrency:nn,profileName:s,allowProdWrites:kt.current,model:a.model,signal:g.signal}))if(c.type==="partition_status")c.status==="running"?ee(m=>m&&{...m,active:[...m.active,c.label],rows:Oe(m.rows,c.label,"active"),lastAt:Date.now()}):ee(m=>m&&{...m,active:m.active.filter(w=>w!==c.label),done:m.done+1,rows:Oe(m.rows,c.label,c.status==="done"?"done":"failed"),lastAt:Date.now()});else if(c.type==="partition_event")ee(m=>{if(!m)return m;let w={...m,lastAt:Date.now()};return c.event.type==="tool"?w.tools=m.tools+1:c.event.type==="text"&&(w.chars=m.chars+c.event.delta.length),w});else if(c.type==="run_done"){Rt(R=>R+c.totalCostUsd),Pt(R=>R+c.results.reduce((S,K)=>S+K.outputTokens,0));let m=c.aborted?"Stopped. ":"",w=t.kind==="api"?"api":"subscription";d({kind:"note",tone:c.aborted?"warn":c.ok?"ok":"warn",text:m+yr(c.results,i,w).join(`
277
- `)});let y=wr(e,s);y&&d({kind:"note",tone:"info",text:y})}}catch(c){d({kind:"note",tone:"error",text:`Publish run failed: ${c.message}`})}finally{ve.current=null,ee(null),I(!1),ne(c=>c+1)}},[e,s,d,t]),Yo=V(async l=>{await ae(gr(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await Kn(e,s,l.replace(/\\/g,"/"));i.length>0&&(je(`Related articles not yet published (${i.length}):`),B([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ae]),Vo=V(l=>{let i=Ke(l);if(!i||We(i)&&!i.refreshToken)return null;let a={...Ut(i.idToken)??{},...Ut(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),zo=V((l,i)=>{if(i){let a=Z(e);a&&(a.defaultProfile=l,_l(a,e))}u(l),ge(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Vo(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),B(["/login"])),ne(a=>a+1)},[e,d,ge,Vo]),vn=V((l,i,a)=>{jn(e,l,i,a.id,a.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),ge(),Ro(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:It(Et(e)).join(`
278
- `)}),Tt(at()),Bt.current=Me(e).status==="current"||Jt(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,ge,Tt]),Cn=V(async l=>{let i;try{i=await Xt(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),B(["/workspace"]);return}if(i.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(c=>(c.workspace_type??"").toLowerCase()!=="apidocumentation"),g=a.length>0?a:i.workspaces;if(g.length===1){let c=g[0],m=i.workspaces.length-g.length;d({kind:"note",tone:"ok",text:`Selected the "${c.name??c.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),vn(i.profile,i.projectId,c);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),B(["/workspace"])},[e,d,vn]),Pn=V((l,i)=>{An(e,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),ge(),Cn(l)},[e,d,ge,Cn]),Ys=V(async l=>{let i;try{i=de(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await Ge(e,i.name),g=a.find(c=>c.id===i.project.projectId);g?.name&&wm(e,i.name,{projectName:g.name})}catch{}await Cn(i.name);return}try{let{projects:a}=await Ge(e,i.name);if(a.length===1){let g=a[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),Pn(i.name,{id:g.id,name:g.name});return}if(a.length>1){let g=a.map(c=>({id:c.id,name:c.name??c.id,sub:c.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),nt({cursor:0,current:-1,rows:g,profile:i.name,environment:i.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),B(["/project"])}},[e,d,Cn,Pn]),Rn=V(()=>{let l=Fe.current[0];if(!l)return;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let a of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${a}`});l.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let i=ct(l.oldContent,l.newContent,qe());d(i?{kind:"diff",added:i.added,removed:i.removed,lines:i.lines,hidden:i.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,qe]),Vs=V(l=>{if(Fe.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Fe.current.shift();try{em({cwd:e,profileName:s},a),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Fe.current.length===0&&B(g=>g.length>0?g:["/pull"])}catch(g){d({kind:"note",tone:"error",text:`Pull failed: ${g.message}`})}}else if(i==="n"||i==="no"){let a=Fe.current.shift();d({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Fe.current.length;return Fe.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return Rn(),!0},[e,s,Rn,d]),zs=V(l=>{let i=Ao.current;if(!i)return!1;if(Ao.current=null,ue(null),mt.current++,l.trim()!==i.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:g}=ds(e,i.targets);d({kind:"note",tone:g.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let c of g)d({kind:"note",tone:"error",text:` \u2717 ${c.path}: ${c.error}`});return i.hadDevhints&&(d({kind:"note",tone:"warn",text:Bn().join(`
279
- `)}),Tt(or())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
280
- ${Wl}`}),B(["/init"]),pn(!1),!0},[e,d,Tt]),Xs=V(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),g=i.slice(1);switch(pn(!0),a){case"help":qt({tab:0});return;case"exit":case"quit":be.current?.close(),r();return;case"clear":ge(),yt.current=[],pn(!1),ue(null),mt.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let c;try{c=de(e,s)}catch(m){d({kind:"note",tone:"error",text:m.message});return}d({kind:"note",tone:"info",text:`Profile "${c.name}" \u2192 ${c.connection.name} (${c.connection.apiUrl})${c.production?" \u26A0 PRODUCTION":""}`}),J(!0);try{let m=await Uf(c.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},y=>d({kind:"note",tone:"info",text:y})),w=Wf(c.name,m);if(Ff(w),await Jo(w,c.name,y=>d({kind:"note",tone:"info",text:y})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${c.name}" as ${Nn(w)}`}),await Ys(s),Ht.current){let y=Ht.current;Ht.current=null;let R=Le(e,s);R.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${y}.`}),B([y])):(d({kind:"note",tone:"warn",text:`${R.reason} (then ${y}.)`}),B(["/login"]),Ht.current=y)}else yn.current&&(ue(yn.current),yn.current=null,d({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(m){d({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{J(!1),ne(m=>m+1)}return}case"allow-prod":{let c=!1;try{c=de(e,s).production}catch{}if(!c){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}kt.current=!0,ge(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let c=Vr(g.join(" ")),m=Ie.current.uuid;if(!m){if(!c){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Eo.current=c,Ze(c),Ot(`${wo} ${c}`),d({kind:"note",tone:"ok",text:`Session will be named "${c}" once it starts.`});return}if(!c){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Ie.current.firstPrompt??"";Nl(w,e).then(y=>{y?(ue(`/rename ${y}`),d({kind:"note",tone:"info",text:`Suggestion: "${y}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Jf(m,c),Ze(c),Ot(`${wo} ${c}`),d({kind:"note",tone:"ok",text:`Session renamed to "${c}".`});return}case"profile":{let c=g[0],m=Z(e);if(!c){let w=Object.entries(m?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let y=w.map(([K,q])=>({name:K,env:q.connection?.environment??"custom",prod:q.production===!0,who:Vo(K)})),R=s??m?.defaultProfile,S=Math.max(0,y.findIndex(K=>K.name===R));bt({cursor:S,current:S,rows:y});return}if(c==="add"){let w=zr(e,g[1],g[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),zo(g[1],!1);return}if(!m?.profiles?.[c]){d({kind:"note",tone:"error",text:`Unknown profile "${c}". Create it: /profile add ${c} <environment>`});return}zo(c,!0);return}case"doctor":await an(g,{cwd:e});return;case"mcp":await Vn(g);return;case"init":{if(Z(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let c=am().map(m=>({name:m,apiUrl:lm(m).apiUrl}));xt({cursor:0,rows:c});return}case"resume":{let c=g.join(" ").trim(),m=Qf(e).filter(R=>R.uuid!==Ie.current.uuid);if(!c){if(!m.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}it({query:"",cursor:0,sessions:m});return}let w=Kf(e,c);if(!w){d({kind:"note",tone:"error",text:`No session matches "${c}".`});return}ge(w.uuid),Ie.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},Ze(w.name),Ps(w.uuid),yt.current=[];let y=ks(e,w.uuid);for(let R of y)d(R);d({kind:"note",tone:"ok",text:y.length?`Resumed "${w.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let c=g.join(" ").trim(),m;try{m=await Xt(e,s)}catch(y){d({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!c){let y=m.workspaces.map(S=>({id:S.id,name:S.name??S.id,type:S.workspace_type}));if(y.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let R=Math.max(0,y.findIndex(S=>S.id===m.current));$t({cursor:R,current:R,rows:y,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let w=Ko(m.workspaces,c);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${c}".`});return}vn(m.profile,m.projectId,w);return}case"project":{let c=g.join(" ").trim(),m;try{m=await Ge(e,s)}catch(y){d({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!c){let y=m.projects.map(S=>({id:S.id,name:S.name??S.id,sub:S.sub_domain}));if(y.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let R=y.findIndex(S=>S.id===m.current);nt({cursor:Math.max(0,R),current:R,rows:y,profile:m.profile,environment:m.environment});return}let w=Qo(m.projects,c);if(!w){d({kind:"note",tone:"error",text:`No project matches "${c}". Available: ${m.projects.map(y=>y.name??y.id).join(", ")}`});return}Pn(m.profile,w);return}case"logout":{let c;try{c=de(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let m=Gf(c);Yf(e,c),ge(),ne(w=>w+1),d({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${c}" and cleared its project/workspace selection.`:`Profile "${c}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),B(["/login"]);return}case"publish":{if(!Wo(l.trim()))return;if(g[0]==="--related"&&g[1]){let m=await Kn(e,s,g[1].replace(/\\/g,"/"));if(m.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await $n(m);return}if(g[0]&&g[0]!=="--all"){await Yo(g[0]);return}let c=g[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Ml({cwd:e,profileName:s}),w=on(m.entries),y=zn(m.entries);if(y>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${y} article${y===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),w.length===0){d({kind:"note",tone:"ok",text:y>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let R=m.counts["unknown-base"]??0;R>0&&d({kind:"note",tone:"info",text:`(${R} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(c){await $n(w.map(R=>R.path));return}vt({cursor:0,rows:Vi(w)})}catch(m){d({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let c=g.join(" ").trim();if(!c){let w=[];try{w=Object.keys(Ro(e,de(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}rt({query:"",cursor:0,paths:w});return}let m=Lf(c)?c:ft(e,c);if(Xe(m)){try{d({kind:"preview",name:un(m),text:Hl(Cs(m,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${m}: ${w.message}`})}return}if(Cm.test(c)){try{let w=de(e,s),y={profile:w.name,connection:w.connection},R=w.project.projectId??qf(y),S=await Bf(y,R,c);d({kind:"preview",name:S.title??c,text:S.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${c}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let c=g[0]?.trim();if(!c){let R=to(Ds(e));tt({cursor:R,current:R});return}let{lines:m,changed:w,effective:y}=sn(e,c);for(let R of m)d({kind:"note",tone:R.startsWith("\u26A0")?"warn":R.startsWith("\u2713")?"ok":"info",text:R});w&&(Fs(R=>R+1),be.current?.setModel(y));return}case"convert":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:c,run:m}=Pr(g),w=dm(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let y=Rr(w,c);if(y.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${c}". (${w.length} are tracked overall.)`});return}let R=Rs(y),S=3,K=`/convert${c?` --scope ${c}`:""} --run`,q=Co(e,"light");if(!m){let v=Ol({files:Tr(e,y),op:"convert",model:q.model}),A=c?`Scope: ${c} (${y.length} of ${w.length} tracked)
276
+ cwd: ${e}`}),Ho()},[]),Te(()=>{let l=setInterval(()=>{Ho()},Dm);return()=>clearInterval(l)},[Ho]),Te(()=>{if(N||Qe.length>0)return;let l=Yo(!1);(l.kind==="actions"||l.kind==="noDocs")&&(q(l.options),he(l.title??null))},[N,Qe,pe,Yo]),Te(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let h=`${je.columns??80}x${je.rows??24}`;h!==Gs.current&&(Gs.current=h,lc(u=>u+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Vi(kt.current,qe())+"\x1B[?2026l")},80))},400)};return je.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),je.off("resize",a)}},[je,qe]);let _e=Math.max(20,(je.columns??80)-1),Ys=Rs(()=>$m(e,s),[e,s,pe]),Vo=(()=>{if(rc)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Eo!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Eo?` v${Eo}`:""}\u2026`,isSetup:!0};let l=Z(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=mt(e,(l.docsDir??fn).replace(/\/+$/,"")),a=(()=>{try{return Xe(i)&&jo(i).length>0}catch{return!1}})();try{let h=de(e,s),u=Ke(h.name);if(!(!!u&&!(We(u)&&!u.refreshToken)))return{text:`Press 1 to sign in to Document360 (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&&!a)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return a?{text:vm,isSetup:!1}:Uo?{text:"Press c to copy the prompt above, run it in your coding agent \u2014 then ask me to write the docs",isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),zt=gl(D),Vs=zt.length>0&&!N,zo=p!==null?Nl(p,8,_e):null,$n=$e?$e.paths.filter(l=>!$e.query||l.toLowerCase().includes($e.query.toLowerCase())).slice(0,8):[],vn=Ce?Ce.sessions.filter(l=>{let i=Ce.query.toLowerCase();return!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],we=V((l,i)=>{be.current?.close(),be.current=Ml({cwd:e,resume:l,profileName:i??s,allowProdWrites:bt.current}),l||(Ie.current={uuid:null,firstPrompt:null,titleFired:!1},Ze(null)),Rt(0),Tt(0)},[e,s]),zs=V((l,i,a)=>{if(Cm.test(l))try{let h=de(e,s),u=typeof i.project_id=="string"&&i.project_id||h.project.projectId,m=go(i,a),w=[],y=wo(a);l.endsWith("publish_article")&&y&&w.push(`Live: ${y}`),m&&u&&w.push(`Preview: ${ho(h.connection.portalUrl,u,m,h.project.languageCode??"en")}`),w.length>0&&d({kind:"link",lines:w})}catch{}},[e,s,d]),ae=V(async(l,i)=>{mn(!0),ue(null),q([]),he(null),Wo(null),Go(null);let a=++ht.current;i?.quietUser||d({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let h=Ie.current;h.firstPrompt||(h.firstPrompt=i?.display??l),Je.current=Date.now(),gt(0),I(!0),wn.current.clear();let u="",m=!1,w=!1,y="",R={num:0,closed:!1,cueSeen:!1},S=null,K=()=>{S||(S=setTimeout(()=>{S=null,g(y.length>0?y:null)},60))},B=()=>{S&&clearTimeout(S),S=null,g(null)},L=()=>{if(y.trim()){let v=xs(y.trimEnd(),R);d({kind:"assistant",text:v})}y="",B()};try{for await(let v of be.current.send(l))if(v.type==="session"){if(!h.uuid){h.uuid=v.sessionId;let A=new Date().toISOString(),U=_o.current,X=U??Xf(h.firstPrompt??"session");Kf({uuid:v.sessionId,name:X,renamed:!!U,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:A,updatedAt:A}),Ze(X),_o.current=null}}else if(v.type==="text"){y+=v.delta,u+=v.delta;let A=_l(y);if(A>0){let U=y.slice(0,A).trimEnd();U&&d({kind:"assistant",text:xs(U,R)}),y=y.slice(A)}K(),gt(U=>U+v.delta.length)}else if(v.type==="tool"){m=!0;let A=fo(v.name,v.input);A&&(L(),d({kind:"tool",title:A.title,sep:A.sep,arg:A.arg}),wn.current.set(v.id,{name:v.name,input:v.input}))}else if(v.type==="article_diff"){let A=ut(v.oldContent,v.newContent,qe());A&&(L(),d({kind:"diff",added:A.added,removed:A.removed,lines:A.lines,hidden:A.hidden}))}else if(v.type==="tool_result"){v.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(v.output)&&(kn.current=!0);let A=wn.current.get(v.id);if(A){wn.current.delete(v.id),L();let U=mo(v.output,4,v.isError?void 0:A.name,A.input);d({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:v.isError}),v.isError||zs(A.name,A.input,v.output)}}else if(v.type==="result"){if(L(),Rt(U=>U+v.outputTokens),Tt(U=>U+v.costUsd),d({kind:"done",seconds:Math.round((Date.now()-Je.current)/1e3),tokens:v.outputTokens,costUsd:v.costUsd,ok:v.ok}),!w&&!m&&!u.trim()&&!qt.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),v.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let U=gm(e);if(Xe(U)){let X=Ts(U,"utf8").trim();X&&(Go(X),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}let A=v.ok?bl(u,xo.map(U=>U.name)):[];if(A.length>0?q(A):v.ok&&u.trim()&&em(l,u,e).then(U=>{U&&ht.current===a&&ue(U)}).catch(()=>{}),h.uuid&&(Ss(h.uuid),!h.titleFired)){h.titleFired=!0;let U=h.uuid,X=h.firstPrompt;X&&Ll(X,e).then(ye=>{ye&&(zf(U,ye),Ze(ye))}).catch(()=>{})}}else v.type==="error"&&(L(),w=!0,v.kind==="auth"&&(kn.current=!0),d({kind:"note",text:`agent error: ${v.message}`,tone:"error"}))}finally{I(!1),B(),ne(v=>v+1),Ie.current.uuid&&pl(e,Ie.current.uuid,kt.current),kn.current&&(kn.current=!1,bn.current=i?.display??l,q(["/login"])),qt.current&&(qt.current=!1,st.current.length>0&&(d({kind:"note",tone:"info",text:`(${st.current.length} queued message(s) discarded)`}),st.current=[],Mo([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,zs,qe]),Cn=V(async l=>{let i=Ds(l),a=To(e,"standard");Je.current=Date.now(),gt(0),I(!0);let h=new AbortController;ve.current=h,ee({verb:"Publishing",total:i.length,done:0,active:[],rows:dn(i),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${rn} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let u of Ro({cwd:e,partitions:i,promptFor:m=>Jn(m.paths),concurrency:rn,profileName:s,allowProdWrites:bt.current,model:a.model,signal:h.signal}))if(u.type==="partition_status")u.status==="running"?ee(m=>m&&{...m,active:[...m.active,u.label],rows:Oe(m.rows,u.label,"active"),lastAt:Date.now()}):ee(m=>m&&{...m,active:m.active.filter(w=>w!==u.label),done:m.done+1,rows:Oe(m.rows,u.label,u.status==="done"?"done":"failed"),lastAt:Date.now()});else if(u.type==="partition_event")ee(m=>{if(!m)return m;let w={...m,lastAt:Date.now()};return u.event.type==="tool"?w.tools=m.tools+1:u.event.type==="text"&&(w.chars=m.chars+u.event.delta.length),w});else if(u.type==="run_done"){Tt(R=>R+u.totalCostUsd),Rt(R=>R+u.results.reduce((S,K)=>S+K.outputTokens,0));let m=u.aborted?"Stopped. ":"",w=t.kind==="api"?"api":"subscription";d({kind:"note",tone:u.aborted?"warn":u.ok?"ok":"warn",text:m+xr(u.results,i,w).join(`
277
+ `)});let y=br(e,s);y&&d({kind:"note",tone:"info",text:y})}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{ve.current=null,ee(null),I(!1),ne(u=>u+1)}},[e,s,d,t]),Xo=V(async l=>{await ae(kr(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await Zn(e,s,l.replace(/\\/g,"/"));i.length>0&&(he(`Related articles not yet published (${i.length}):`),q([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ae]),Ko=V(l=>{let i=Ke(l);if(!i||We(i)&&!i.refreshToken)return null;let a={...Ft(i.idToken)??{},...Ft(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),Qo=V((l,i)=>{if(i){let a=Z(e);a&&(a.defaultProfile=l,Ol(a,e))}c(l),we(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Ko(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),q(["/login"])),ne(a=>a+1)},[e,d,we,Ko]),Pn=V((l,i,a)=>{In(e,l,i,a.id,a.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),we(),Do(e,l)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:_t(Nt(e)).join(`
278
+ `)}),St(lt()),Yt.current=Me(e).status==="current"||en(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,we,St]),Rn=V(async l=>{let i;try{i=await Qt(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),q(["/workspace"]);return}if(i.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),h=a.length>0?a:i.workspaces;if(h.length===1){let u=h[0],m=i.workspaces.length-h.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),Pn(i.profile,i.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),q(["/workspace"])},[e,d,Pn]),Tn=V((l,i)=>{Nn(e,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),we(),Rn(l)},[e,d,we,Rn]),Xs=V(async l=>{let i;try{i=de(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await Ge(e,i.name),h=a.find(u=>u.id===i.project.projectId);h?.name&&ym(e,i.name,{projectName:h.name})}catch{}await Rn(i.name);return}try{let{projects:a}=await Ge(e,i.name);if(a.length===1){let h=a[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${h.name??h.id}".`}),Tn(i.name,{id:h.id,name:h.name});return}if(a.length>1){let h=a.map(u=>({id:u.id,name:u.name??u.id,sub:u.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),nt({cursor:0,current:-1,rows:h,profile:i.name,environment:i.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),q(["/project"])}},[e,d,Rn,Tn]),Sn=V(()=>{let l=Fe.current[0];if(!l)return;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let a of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${a}`});l.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let i=ut(l.oldContent,l.newContent,qe());d(i?{kind:"diff",added:i.added,removed:i.removed,lines:i.lines,hidden:i.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,qe]),Ks=V(l=>{if(Fe.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Fe.current.shift();try{tm({cwd:e,profileName:s},a),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Fe.current.length===0&&q(h=>h.length>0?h:["/pull"])}catch(h){d({kind:"note",tone:"error",text:`Pull failed: ${h.message}`})}}else if(i==="n"||i==="no"){let a=Fe.current.shift();d({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Fe.current.length;return Fe.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return Sn(),!0},[e,s,Sn,d]),Qs=V(l=>{let i=No.current;if(!i)return!1;if(No.current=null,ue(null),ht.current++,l.trim()!==i.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:h}=ms(e,i.targets);d({kind:"note",tone:h.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let u of h)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return i.hadDevhints&&(d({kind:"note",tone:"warn",text:Vn().join(`
279
+ `)}),St(ir())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
280
+ ${ql}`}),q(["/init"]),mn(!1),!0},[e,d,St]),Js=V(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),h=i.slice(1);switch(mn(!0),a){case"help":Gt({tab:0});return;case"exit":case"quit":be.current?.close(),r();return;case"clear":we(),kt.current=[],mn(!1),ue(null),ht.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=de(e,s)}catch(m){d({kind:"note",tone:"error",text:m.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),J(!0);try{let m=await Wf(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},y=>d({kind:"note",tone:"info",text:y})),w=Ff(u.name,m);if(Hf(w),await tr(w,u.name,y=>d({kind:"note",tone:"info",text:y})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${Ln(w)}`}),await Xs(s),Bt.current){let y=Bt.current;Bt.current=null;let R=Le(e,s);R.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${y}.`}),q([y])):(d({kind:"note",tone:"warn",text:`${R.reason} (then ${y}.)`}),q(["/login"]),Bt.current=y)}else bn.current&&(ue(bn.current),bn.current=null,d({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(m){d({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{J(!1),ne(m=>m+1)}return}case"allow-prod":{let u=!1;try{u=de(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}bt.current=!0,we(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Kr(h.join(" ")),m=Ie.current.uuid;if(!m){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}_o.current=u,Ze(u),Wt(`${bo} ${u}`),d({kind:"note",tone:"ok",text:`Session will be named "${u}" once it starts.`});return}if(!u){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Ie.current.firstPrompt??"";Ll(w,e).then(y=>{y?(ue(`/rename ${y}`),d({kind:"note",tone:"info",text:`Suggestion: "${y}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Zf(m,u),Ze(u),Wt(`${bo} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=h[0],m=Z(e);if(!u){let w=Object.entries(m?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let y=w.map(([K,B])=>({name:K,env:B.connection?.environment??"custom",prod:B.production===!0,who:Ko(K)})),R=s??m?.defaultProfile,S=Math.max(0,y.findIndex(K=>K.name===R));xt({cursor:S,current:S,rows:y});return}if(u==="add"){let w=Qr(e,h[1],h[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),Qo(h[1],!1);return}if(!m?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}Qo(u,!0);return}case"doctor":await cn(h,{cwd:e});return;case"mcp":await Kn(h);return;case"init":{if(Z(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let u=lm().map(m=>({name:m,apiUrl:cm(m).apiUrl}));$t({cursor:0,rows:u});return}case"resume":{let u=h.join(" ").trim(),m=Jf(e).filter(R=>R.uuid!==Ie.current.uuid);if(!u){if(!m.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}it({query:"",cursor:0,sessions:m});return}let w=Qf(e,u);if(!w){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}we(w.uuid),Ie.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},Ze(w.name),Ss(w.uuid),kt.current=[];let y=$s(e,w.uuid);for(let R of y)d(R);d({kind:"note",tone:"ok",text:y.length?`Resumed "${w.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=h.join(" ").trim(),m;try{m=await Qt(e,s)}catch(y){d({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!u){let y=m.workspaces.map(S=>({id:S.id,name:S.name??S.id,type:S.workspace_type}));if(y.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let R=Math.max(0,y.findIndex(S=>S.id===m.current));vt({cursor:R,current:R,rows:y,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let w=Zo(m.workspaces,u);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}Pn(m.profile,m.projectId,w);return}case"project":{let u=h.join(" ").trim(),m;try{m=await Ge(e,s)}catch(y){d({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!u){let y=m.projects.map(S=>({id:S.id,name:S.name??S.id,sub:S.sub_domain}));if(y.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let R=y.findIndex(S=>S.id===m.current);nt({cursor:Math.max(0,R),current:R,rows:y,profile:m.profile,environment:m.environment});return}let w=er(m.projects,u);if(!w){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${m.projects.map(y=>y.name??y.id).join(", ")}`});return}Tn(m.profile,w);return}case"logout":{let u;try{u=de(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let m=Yf(u);Vf(e,u),we(),ne(w=>w+1),d({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${u}" and cleared its project/workspace selection.`:`Profile "${u}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),q(["/login"]);return}case"publish":{if(!qo(l.trim()))return;if(h[0]==="--related"&&h[1]){let m=await Zn(e,s,h[1].replace(/\\/g,"/"));if(m.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Cn(m);return}if(h[0]&&h[0]!=="--all"){await Xo(h[0]);return}let u=h[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Ul({cwd:e,profileName:s}),w=sn(m.entries),y=Qn(m.entries);if(y>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${y} article${y===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),w.length===0){d({kind:"note",tone:"ok",text:y>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let R=m.counts["unknown-base"]??0;R>0&&d({kind:"note",tone:"info",text:`(${R} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(u){await Cn(w.map(R=>R.path));return}Ct({cursor:0,rows:Ki(w)})}catch(m){d({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let u=h.join(" ").trim();if(!u){let w=[];try{w=Object.keys(Do(e,de(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}rt({query:"",cursor:0,paths:w});return}let m=Of(u)?u:mt(e,u);if(Xe(m)){try{d({kind:"preview",name:pn(m),text:Gl(Ts(m,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${m}: ${w.message}`})}return}if(Pm.test(u)){try{let w=de(e,s),y={profile:w.name,connection:w.connection},R=w.project.projectId??Bf(y),S=await Gf(y,R,u);d({kind:"preview",name:S.title??u,text:S.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${u}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let u=h[0]?.trim();if(!u){let R=ro(Es(e));tt({cursor:R,current:R});return}let{lines:m,changed:w,effective:y}=ln(e,u);for(let R of m)d({kind:"note",tone:R.startsWith("\u26A0")?"warn":R.startsWith("\u2713")?"ok":"info",text:R});w&&(Bs(R=>R+1),be.current?.setModel(y));return}case"convert":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:m}=Sr(h),w=pm(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let y=Dr(w,u);if(y.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${w.length} are tracked overall.)`});return}let R=Ds(y),S=3,K=`/convert${u?` --scope ${u}`:""} --run`,B=To(e,"light");if(!m){let v=Fl({files:jr(e,y),op:"convert",model:B.model}),A=u?`Scope: ${u} (${y.length} of ${w.length} tracked)
281
281
  `:"",U=`
282
- Model: ${q.model}${q.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:A+Dr(R,v,S).join(`
283
- `)+U}),B([K]);return}Je.current=Date.now(),ht(0),I(!0);let L=new AbortController;ve.current=L,ee({verb:"Converting",total:R.length,done:0,active:[],rows:cn(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${y.length} articles across ${R.length} partitions (\u2264${S} agents at once) on ${q.model}\u2026 (esc to stop)`});try{for await(let v of vo({cwd:e,partitions:R,promptFor:Sr,concurrency:S,profileName:s,allowProdWrites:kt.current,model:q.model,signal:L.signal}))if(v.type==="partition_status")v.status==="running"?ee(A=>A&&{...A,active:[...A.active,v.label],rows:Oe(A.rows,v.label,"active"),lastAt:Date.now()}):ee(A=>A&&{...A,active:A.active.filter(U=>U!==v.label),done:A.done+1,rows:Oe(A.rows,v.label,v.status==="done"?"done":"failed"),lastAt:Date.now()});else if(v.type==="partition_event")ee(A=>{if(!A)return A;let U={...A,lastAt:Date.now()};return v.event.type==="tool"?U.tools=A.tools+1:v.event.type==="text"&&(U.chars=A.chars+v.event.delta.length),U});else if(v.type==="run_done"){Rt(X=>X+v.totalCostUsd),Pt(X=>X+v.results.reduce((we,Dt)=>we+Dt.outputTokens,0));let A=v.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";d({kind:"note",tone:v.aborted?"warn":v.ok?"ok":"warn",text:A+jr(v.results,R,U).join(`
284
- `)})}}catch(v){d({kind:"note",tone:"error",text:`Convert run failed: ${v.message}`})}finally{ve.current=null,ee(null),I(!1),ne(v=>v+1)}return}case"write":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let c=Ul(e);if(c.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:w,preview:y,concurrency:R,rewrite:S}=Er(g),{docsDir:K,targets:q,reason:L,rewriting:v}=Ur(e,c,{scope:m,path:w,rewrite:S});if(q.length===0){d({kind:"note",tone:"warn",text:L??"Nothing to write."});return}v&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${q.length} already-written article${q.length===1?"":"s"} (overwrites them; git has your baseline).`});let A=Rs(q),U=Ar(R),X=Co(e,"standard"),we=!!w;if(y&&!we){let Y=Ol({files:Nr(e,c,q),op:"write",model:X.model}),te=m?`Scope: ${m} (${q.length} pending)
282
+ Model: ${B.model}${B.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:A+Er(R,v,S).join(`
283
+ `)+U}),q([K]);return}Je.current=Date.now(),gt(0),I(!0);let L=new AbortController;ve.current=L,ee({verb:"Converting",total:R.length,done:0,active:[],rows:dn(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${y.length} articles across ${R.length} partitions (\u2264${S} agents at once) on ${B.model}\u2026 (esc to stop)`});try{for await(let v of Ro({cwd:e,partitions:R,promptFor:Ar,concurrency:S,profileName:s,allowProdWrites:bt.current,model:B.model,signal:L.signal}))if(v.type==="partition_status")v.status==="running"?ee(A=>A&&{...A,active:[...A.active,v.label],rows:Oe(A.rows,v.label,"active"),lastAt:Date.now()}):ee(A=>A&&{...A,active:A.active.filter(U=>U!==v.label),done:A.done+1,rows:Oe(A.rows,v.label,v.status==="done"?"done":"failed"),lastAt:Date.now()});else if(v.type==="partition_event")ee(A=>{if(!A)return A;let U={...A,lastAt:Date.now()};return v.event.type==="tool"?U.tools=A.tools+1:v.event.type==="text"&&(U.chars=A.chars+v.event.delta.length),U});else if(v.type==="run_done"){Tt(X=>X+v.totalCostUsd),Rt(X=>X+v.results.reduce((ye,jt)=>ye+jt.outputTokens,0));let A=v.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";d({kind:"note",tone:v.aborted?"warn":v.ok?"ok":"warn",text:A+Ir(v.results,R,U).join(`
284
+ `)})}}catch(v){d({kind:"note",tone:"error",text:`Convert run failed: ${v.message}`})}finally{ve.current=null,ee(null),I(!1),ne(v=>v+1)}return}case"write":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Hl(e);if(u.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:w,preview:y,concurrency:R,rewrite:S}=_r(h),{docsDir:K,targets:B,reason:L,rewriting:v}=Hr(e,u,{scope:m,path:w,rewrite:S});if(B.length===0){d({kind:"note",tone:"warn",text:L??"Nothing to write."});return}v&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${B.length} already-written article${B.length===1?"":"s"} (overwrites them; git has your baseline).`});let A=Ds(B),U=Nr(R),X=To(e,"standard"),ye=!!w;if(y&&!ye){let Y=Fl({files:Lr(e,u,B),op:"write",model:X.model}),te=m?`Scope: ${m} (${B.length} pending)
285
285
  `:"",ce=`
286
- Model: ${X.model}${X.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:te+Mr(A,Y,U).join(`
287
- `)+ce}),B([`/write${m?` --scope ${m}`:""}`]);return}Je.current=Date.now(),ht(0),I(!0);let Dt=new AbortController;ve.current=Dt,ee({verb:"Writing",total:A.length,done:0,active:[],rows:cn(A),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${q.length} article${q.length===1?"":"s"} across ${A.length} partition${A.length===1?"":"s"} (\u2264${U} agents at once) on ${X.model}${X.forced?" (forced)":""}\u2026 (esc to stop)`});let Zs=new Set;try{for await(let Y of vo({cwd:e,partitions:A,promptFor:te=>_r(te,K,{rewrite:v||we}),concurrency:U,profileName:s,allowProdWrites:kt.current,model:X.model,signal:Dt.signal}))if(Y.type==="partition_status")Y.status==="running"?ee(te=>te&&{...te,active:[...te.active,Y.label],rows:Oe(te.rows,Y.label,"active"),lastAt:Date.now()}):ee(te=>te&&{...te,active:te.active.filter(ce=>ce!==Y.label),done:te.done+1,rows:Oe(te.rows,Y.label,Y.status==="done"?"done":"failed"),lastAt:Date.now()});else if(Y.type==="partition_event"){let te=null;if(Y.event.type==="tool"){let ce=kl(Y.event.name,Y.event.input,A[Y.index]?.paths??[]);ce&&!Zs.has(ce)&&(Zs.add(ce),te=Y.label)}ee(ce=>{if(!ce)return ce;let ye={...ce,lastAt:Date.now()};return Y.event.type==="tool"?ye.tools=ce.tools+1:Y.event.type==="text"&&(ye.chars=ce.chars+Y.event.delta.length),te&&(ye.rows=yl(ye.rows,te)),ye})}else if(Y.type==="run_done"){Rt(ye=>ye+Y.totalCostUsd),Pt(ye=>ye+Y.results.reduce((lc,cc)=>lc+cc.outputTokens,0));let te=Y.aborted?"Stopped. ":"",ce=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:Y.aborted?"warn":Y.ok?"ok":"warn",text:te+Lr(Y.results,A,ce).join(`
288
- `)}),!Y.aborted){let ye=Or(e,K,q);ye&&d({kind:"note",tone:"warn",text:ye})}!Y.aborted&&Y.ok&&B(["/publish --all","/screenshot --all"])}}catch(Y){d({kind:"note",tone:"error",text:`Write run failed: ${Y.message}`})}finally{ve.current=null,ee(null),I(!1),ne(Y=>Y+1)}return}case"draft":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:c,looseDocs:m}=Wr(e);if(c.length===0&&m===0){d({kind:"note",tone:"info",text:Hr});return}let w=g.join(" ").trim();if(!w&&c.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
289
- ${c.map(S=>` \u2022 ${S.name} (${S.docCount} doc${S.docCount===1?"":"s"})`).join(`
290
- `)}`}),B(c.map(S=>`/draft ${S.name}`));return}let y="",R;if(w){let S=Fr(c,w);S?y=S:R=w}else y=c[0]?.name??"";await ae(eo(y,R),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!Wo(l.trim()))return;let c=g.find(m=>m.startsWith("--"));try{if(c==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let y=Date.now(),R=await Ml({cwd:e,profileName:s});d({kind:"note",tone:"info",text:Jn(R,Date.now()-y).join(`
291
- `)});return}if(c==="--baseline"){let y=g.find(q=>!q.startsWith("--")),R=y?y.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:R?`Setting the sync baseline for ${R}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let S=await rm({cwd:e,profileName:s,relPaths:R?[R]:void 0}),K=R?{rebaselined:[],skipped:[]}:await sm({cwd:e,profileName:s});if(S.baselined.length===0&&S.skipped.length===0&&K.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}S.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${S.baselined.length} article${S.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),K.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${K.rebaselined.length} article${K.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),S.skipped.length>0&&d({kind:"note",tone:"warn",text:`${S.skipped.length} skipped:
292
- ${S.skipped.map(q=>` - ${q.path} (${q.reason})`).join(`
293
- `)}`}),ne(q=>q+1);return}if(c==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let y=await nm({cwd:e,profileName:s}),R=y.onlyInLegacy.length===0&&y.onlyInManifest.length===0&&y.mappedMissingFromManifest.length===0,S=[`Legacy listing: ${y.legacyCount} \xB7 Manifest: ${y.manifestCount} \xB7 in both: ${y.inBoth}`];R?S.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(y.mappedMissingFromManifest.length&&S.push(`\u2717 ${y.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${y.mappedMissingFromManifest.slice(0,5).join(", ")}`),y.onlyInLegacy.length&&S.push(`\u26A0 ${y.onlyInLegacy.length} only in the legacy listing: ${y.onlyInLegacy.slice(0,5).join(", ")}`),y.onlyInManifest.length&&S.push(`\u26A0 ${y.onlyInManifest.length} only in the manifest: ${y.onlyInManifest.slice(0,5).join(", ")}`),S.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:R?"ok":"warn",text:S.join(`
294
- `)});return}if(c){d({kind:"note",tone:"error",text:`Unknown option: ${c} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=g[0];if(m){let y=await om({cwd:e,profileName:s,relPath:m.replace(/\\/g,"/")});Fe.current=[y],Rn();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let w=await $r({cwd:e,profileName:s});for(let y of vr(w))d({kind:"note",tone:y.tone,text:y.text});ne(y=>y+1)}catch(m){d({kind:"note",tone:"error",text:`Pull failed: ${m.message}`})}return}case"scope":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let c=im(e);if(c.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Ct({cursor:0,rows:c.map(m=>({...m,checked:m.recommended}))});return}case"audit":{if(g[0]==="--auto"){let m=Z(e);if(!m){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=g[1]!=="off";_l({...m,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let c=await rn();c.kind==="forward-to-agent"&&c.prompt&&await ae(c.prompt,{display:c.display,quietUser:!0});return}case"check":{let c=Ll({cwd:e});if(g.includes("--fix")){if(c.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 ${c.length} doc issue${c.length===1?"":"s"}\u2026`}),await ae(fs(c),{display:"/check --fix",quietUser:!0});let m=Ll({cwd:e});d({kind:"note",tone:m.length===0?"ok":"warn",text:m.length===0?"\u2713 Doc-checker: all issues resolved.":lo(m).join(`
295
- `)});return}d({kind:"note",tone:c.length===0?"ok":"warn",text:lo(c).join(`
296
- `)}),c.length>0&&(B([{cmd:"/check --fix",desc:"have the agent fix these in place"},{cmd:"/review",desc:"also run the editorial review (style, grammar, structure)"},{cmd:"/publish --all",desc:"skip fixing \u2014 publish the docs as-is"}]),je(`Found ${c.length} doc issue${c.length===1?"":"s"} above \u2014 fix them, or publish as-is:`));return}case"review":{let c=ms(e,g);if(!c){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=g.includes("--fix");if(await ae(c.prompt,{display:c.display,quietUser:!0}),m)B([{cmd:"/publish --all",desc:"publish the corrected docs to Document360"},{cmd:"/check",desc:"optional: instant re-scan for leaks/bad commands (no tokens)"}]),je("\u2713 Editor applied its fixes \u2014 your docs are corrected. Publish them, or re-scan first:");else{let w=g.filter(y=>y!=="--fix").join(" ");B([{cmd:`/review${w?` ${w}`:""} --fix`,desc:"let the editor apply all the fixes it listed above"},{cmd:"/check --fix",desc:"fix just the deterministic issues (leaks, bad commands)"},{cmd:"/publish --all",desc:"skip fixing \u2014 publish the docs as-is"}]),je("The review listed issues above. Apply the fixes, or publish as-is:")}return}case"capture-setup":{let c=await ln();c.kind==="forward-to-agent"&&c.prompt&&await ae(c.prompt,{display:c.display,quietUser:!0});let m=es(e);m&&d({kind:"note",tone:"info",text:m.join(`
297
- `)});return}case"devhints":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:It(Et(e)).join(`
298
- `)}),Tt(at()),Bt.current=Me(e).status==="current"||Jt(e);return}case"inbox":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(ts(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 ae(ns(),{display:"/inbox",quietUser:!0});return}case"document":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:c,what:m}=Br(g);if(!m&&qr(e)===0){d({kind:"note",tone:"info",text:Yr});return}let w=`/document${m?` ${m}`:""}${c?" --publish":""}`;await ae(Gr(m,c),{display:w,quietUser:!0});return}case"catch-up":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Wo(l.trim()))return;let{publish:c}=rs(g);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let m=await is({cwd:e,profileName:s});for(let y of as(m))d({kind:"note",tone:y.startsWith("\u2713")?"ok":y.startsWith("\u2139")?"info":"warn",text:y});let w=Lt(Mt(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ae(ss({publish:c}),{display:`/catch-up${c?" --publish":""}`,quietUser:!0});return}case"update":{Oo.current=!0,d({kind:"note",tone:"info",text:`Updating ${dt}\u2026 (don\u2019t close this window)`}),fn(!0),(await io().finally(()=>fn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),B(m=>m.includes("/exit")?m:[...m,"/exit"]),Ns("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${so}`});return}case"screenshot":{let c=Qr(g);if(c.mode==="list"){if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Zr(Jr(e,c.scope),c.scope).join(`
299
- `)});return}if(c.mode==="single"){let L=await oo(g);L.kind==="forward-to-agent"&&L.prompt&&await ae(L.prompt,{display:L.display,quietUser:!0});return}if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=c.mode==="scope"?c.scope:void 0,w=um(e,{scope:m}).map(L=>L.id);if(w.length===0){d({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let y=6,R=cm(w,3),S=Co(e,"standard");Je.current=Date.now(),ht(0),I(!0);let K=new AbortController;ve.current=K,ee({verb:"Authoring",unit:"spec",total:R.length,done:0,active:[],rows:cn(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${w.length} screenshot spec${w.length===1?"":"s"} across ${R.length} partition${R.length===1?"":"s"} (\u2264${y} agents at once) on ${S.model}${S.forced?" (forced)":""}\u2026 (esc to stop)`});let q=!1;try{for await(let L of vo({cwd:e,partitions:R,promptFor:Ma,concurrency:y,profileName:s,allowProdWrites:kt.current,model:S.model,signal:K.signal}))if(L.type==="partition_status")L.status==="running"?ee(v=>v&&{...v,active:[...v.active,L.label],rows:Oe(v.rows,L.label,"active"),lastAt:Date.now()}):ee(v=>v&&{...v,active:v.active.filter(A=>A!==L.label),done:v.done+1,rows:Oe(v.rows,L.label,L.status==="done"?"done":"failed"),lastAt:Date.now()});else if(L.type==="partition_event")ee(v=>{if(!v)return v;let A={...v,lastAt:Date.now()};return L.event.type==="tool"?A.tools=v.tools+1:L.event.type==="text"&&(A.chars=v.chars+L.event.delta.length),A});else if(L.type==="run_done"){Rt(X=>X+L.totalCostUsd),Pt(X=>X+L.results.reduce((we,Dt)=>we+Dt.outputTokens,0));let v=L.results.filter(X=>X.ok).length,A=L.aborted?"Stopped. ":"";q=!L.aborted&&c.setup;let U=L.aborted?"":q?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:L.aborted?"warn":L.ok?"ok":"warn",text:`${A}Authored specs \u2014 ${v}/${L.results.length} batches ok.${U}`})}}catch(L){d({kind:"note",tone:"error",text:`Spec authoring failed: ${L.message}`})}finally{ve.current=null,ee(null),I(!1),ne(L=>L+1)}if(q){let L=await ln();L.kind==="forward-to-agent"&&L.prompt&&await ae(L.prompt,{display:L.display,quietUser:!0});let v=es(e);v&&d({kind:"note",tone:"info",text:v.join(`
300
- `)})}return}case"reset":{let c=us(e);if(c.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Ao.current={repoName:un(e),targets:c,hadDevhints:Xe(js(e))},d({kind:"note",tone:"warn",text:ps(e,c).join(`
301
- `)}),ue(un(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,Rn,d,ge,ae,$n,Yo,Ys]),Tn=V(l=>{let i=(l??D).trim();if(b(""),mn(null),gt(0),i.startsWith("/")&&(ue(null),mt.current++,je(null),B(g=>$l(g,i))),!i||zs(i)||Vs(i))return;jo.current.push(i);let a=Tl(i,_s.current);i.startsWith("/")?(d({kind:"user",text:i}),Xs(a)):ae(a,{display:i})},[D,zs,Vs,Xs,ae]),Ks=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=Cl(l);if(Pl(i)){let a=Rl(++oc.current,i);_s.current.set(a,i),P(a)}else P(i);return}P(l)},[P]),St=Math.max(10,_e-6),Qs=vs(()=>xo(k.text,St),[k.text,St]),Xo=V(l=>x(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),Sn=V(l=>x(i=>({...i,pos:Dl(xo(i.text,St),i.pos,l)})),[St]),Vt=V(l=>x(i=>({...i,pos:jl(xo(i.text,St),i.pos,l)})),[St]),ic=["\x1B[H","\x1B[1~","\x1BOH"],ac=["\x1B[F","\x1B[4~","\x1BOF"],Js=V((l,i)=>i.leftArrow?(Xo(-1),!0):i.rightArrow?(Xo(1),!0):l&&ic.includes(l)?(Vt("start"),!0):l&&ac.includes(l)?(Vt("end"),!0):i.ctrl&&l==="a"?(Vt("start"),!0):i.ctrl&&l==="e"?(Vt("end"),!0):!1,[Xo,Vt]);return Nf((l,i)=>{if(i.ctrl&&l==="c"){be.current?.close(),r();return}if(!O){if(N){if(i.escape){if(ve.current){if(!ve.current.signal.aborted){let a=(gn?.verb??"work").toLowerCase(),g=gn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${g}s)\u2026`}),ve.current.abort()}return}Ft.current||(Ft.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),be.current?.interrupt());return}if(i.return){let a=D.trim();if(!a)return;st.current.push(a),Io([...st.current]),b("");return}if(Js(l,i))return;if(i.upArrow){Sn(-1);return}if(i.downArrow){Sn(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&Ks(l);return}if(et){if(i.upArrow){tt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){tt(a=>a&&{...a,cursor:Math.min(Ee.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ee.length){tt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Ee[et.cursor];tt(null);let{lines:g,changed:c,effective:m}=sn(e,a.value??"default");for(let w of g)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});c&&(Fs(w=>w+1),be.current?.setModel(m));return}if(l==="s"){let a=Ee[et.cursor];tt(null),be.current?.setModel(a.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){tt(null);return}return}if(Ne){if(i.upArrow){bt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){bt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ne.rows.length){bt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=Ne.rows[Ne.cursor];bt(null),zo(a.name,i.return===!0);return}if(i.escape){bt(null);return}return}if(No){if(i.escape){qt(null);return}if(i.leftArrow||i.tab&&i.shift){qt(a=>a&&{tab:(a.tab-1+Re.length)%Re.length});return}if(i.rightArrow||i.tab){qt(a=>a&&{tab:(a.tab+1)%Re.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.length){qt({tab:Number(l)-1});return}return}if(He){if(i.upArrow){xt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){xt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=He.rows.length){xt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=He.rows[He.cursor].name;if(xt(null),!rr(e,a).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${a}").`});let c=!1;try{let m=Ke(a);c=!!m&&!(We(m)&&!m.refreshToken)}catch{c=!1}d({kind:"note",tone:"info",text:c?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),B(["/login"]),ne(m=>m+1);return}if(i.escape){xt(null);return}return}if(fe){if(i.upArrow){$t(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){$t(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=fe.rows.length){$t(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=fe.rows[fe.cursor],{profile:g,projectId:c}=fe;$t(null),vn(g,c,a);return}if(i.escape){$t(null);return}return}if(xe){if(i.upArrow){nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){nt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=xe.rows.length){nt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=xe.rows[xe.cursor],{profile:g}=xe;nt(null),Pn(g,a);return}if(i.escape){nt(null);return}return}if(he){if(i.upArrow){Ct(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ct(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){Ct(a=>a&&{...a,rows:a.rows.map((g,c)=>c===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=he.rows.filter(g=>g.checked).map(g=>g.path);if(Ct(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}kr(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let g of a)d({kind:"note",tone:"info",text:` ${g}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){Ct(null);return}return}if(ot){if(i.upArrow){vt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){vt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ot.rows.length){vt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ot.rows[ot.cursor];vt(null),a.kind==="article"?Yo(a.paths[0]):$n(a.paths);return}if(i.escape){vt(null);return}return}if($e){if(i.escape){rt(null);return}if(i.upArrow){rt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){rt(a=>a&&{...a,cursor:Math.min(Math.max(0,bn.length-1),a.cursor+1)});return}if(i.return){let a=bn[$e.cursor];if(a){rt(null);try{d({kind:"preview",name:un(a),text:Hl(Cs(ft(e,a),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){rt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){rt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(Ce){if(i.escape){it(null);return}if(i.upArrow){it(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){it(a=>a&&{...a,cursor:Math.min(Math.max(0,xn.length-1),a.cursor+1)});return}if(i.return){let a=xn[Ce.cursor];if(a){it(null),ge(a.uuid),Ie.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Ze(a.name),Ps(a.uuid),yt.current=[];let g=ks(e,a.uuid);for(let c of g)d(c);d({kind:"note",tone:"ok",text:g.length?`Resumed "${a.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){it(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){it(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!D&&De){b(De),ue(null),mt.current++;return}if(!D&&Qe.length>0&&l&&/^[1-9]$/.test(l)){let a=Qe[Number(l)-1];if(a){b(pt(a));return}}if(!D&&(Fo||Mo)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=Fo!=null;sl(Fo??Mo).then(c=>{d({kind:"note",tone:c?"ok":"warn",text:c?a?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),c&&a&&Ho(null)});return}if(!Js(l,i)){if(Bs){if(i.upArrow){gt(a=>Math.max(0,a-1));return}if(i.downArrow){gt(a=>Math.min(Yt.length-1,a+1));return}if(i.tab){b("/"+(Yt[Wt]?.name??"")+" "),gt(0);return}if(i.return){let a=Yt[Wt];if(a){let g=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(ml(a.usage)&&!g){b("/"+a.name+" "),gt(0);return}Tn("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(D!==""&&wt===null){Sn(-1);return}let a=jo.current;if(!a.length)return;let g=wt===null?a.length-1:Math.max(0,wt-1);mn(g),b(a[g]??"");return}if(i.downArrow){if(D!==""&&wt===null){Sn(1);return}let a=jo.current;if(wt===null)return;let g=wt+1;g>=a.length?(mn(null),b("")):(mn(g),b(a[g]??""));return}}if(i.return){Tn();return}if(i.backspace||i.delete){C();return}if(i.escape){b(""),gt(0),ue(null),B([]),je(null);return}l&&!i.ctrl&&!i.meta&&Ks(l)}}}),Te(()=>{if(N||O)return;let l=st.current.shift();l!==void 0&&(Io([...st.current]),Tn(l))},[N,O,Tn]),G(oe,{flexDirection:"column",width:_e,children:[Go!==null&&G(oe,{marginTop:1,flexDirection:"column",children:[Go.truncated&&E(T,{dimColor:!0,children:"\u2026"}),E(T,{children:Go.text})]}),N&&(gn?E(Tm,{p:gn}):E(Pm,{startTime:Je.current,chars:nc})),E(oe,{borderStyle:"round",borderColor:qs.prod?"yellow":F,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?Qs.map((l,i)=>{let a=k.text.slice(l.start,l.end),g=i===$o(Qs,k.pos),c=Math.min(k.pos,l.end)-l.start;return G(T,{children:[E(T,{color:F,children:i===0?"> ":" "}),g?G(Ts,{children:[a.slice(0,c),E(Po,{ch:a[c]??" "}),a.slice(c+1)]}):a||" "]},`${i}-${l.start}`)}):G(T,{children:[E(T,{color:F,children:"> "}),De&&!N?G(Ts,{children:[E(Po,{ch:De[0],dim:!0}),E(T,{color:"gray",children:De.slice(1)}),E(T,{dimColor:!0,children:" (tab)"})]}):(Bo.isSetup||!ec)&&!N?G(Ts,{children:[E(Po,{ch:Bo.text[0],dim:!0}),E(T,{color:"gray",children:Bo.text.slice(1)})]}):E(Po,{ch:" "})]})}),Os.length>0&&E(oe,{flexDirection:"column",paddingX:1,children:Os.map((l,i)=>E(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),No?E(gl,{tab:No.tab,width:_e}):et?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Select model"}),E(T,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ee.map((l,i)=>G(T,{color:i===et.cursor?F:void 0,children:[i===et.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===et.current?" \u2714":""}`.padEnd(16),E(T,{color:"gray",children:l.desc})]},l.label)),E(T,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Ne?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Switch connection profile"}),Ne.rows.map((l,i)=>G(T,{color:i===Ne.cursor?F:void 0,children:[i===Ne.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===Ne.current?" \u2714":""}`.padEnd(20),E(T,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?E(T,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),E(T,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):He?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Pick your Document360 environment"}),He.rows.map((l,i)=>G(T,{color:i===He.cursor?F:void 0,children:[i===He.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),E(T,{color:"gray",children:l.apiUrl})]},l.name)),E(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Switch workspace"}),E(T,{dimColor:!0,children:`environment ${fe.environment} \xB7 project ${fe.projectName??`${fe.projectId.slice(0,8)}\u2026`}`}),fe.rows.map((l,i)=>G(T,{color:i===fe.cursor?F:void 0,children:[i===fe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===fe.current?" \u2714":""}`.padEnd(30),E(T,{color:"gray",children:l.type??""})]},l.id)),E(T,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):xe?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Choose project"}),E(T,{dimColor:!0,children:`environment ${xe.environment}`}),xe.rows.map((l,i)=>G(T,{color:i===xe.cursor?F:void 0,children:[i===xe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===xe.current?" \u2714":""}`.padEnd(30),E(T,{color:"gray",children:l.sub??""})]},l.id)),E(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):he?(()=>{let i=Math.min(Math.max(0,he.cursor-Math.floor(7)),Math.max(0,he.rows.length-14)),a=he.rows.slice(i,i+14),g=he.rows.filter(c=>c.checked).length;return G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Which folders back the user docs? (${g} selected of ${he.rows.length})`}),i>0?E(T,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((c,m)=>{let w=i+m;return G(T,{color:w===he.cursor?F:void 0,children:[w===he.cursor?"\u276F ":" ",c.checked?"\u25C9 ":"\u25CB ",c.path.padEnd(Math.min(48,_e-34)),E(T,{color:"gray",children:Qn(c)})]},c.path)}),i+14<he.rows.length?E(T,{dimColor:!0,children:` \u2193 ${he.rows.length-i-14} more`}):null,E(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():ot?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),ot.rows.map((l,i)=>{let a=i===ot.cursor,g=l.indent?" ":" ",c=`${i+1}.`.padEnd(3);return G(T,{color:a?F:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${c} ${l.label}`.padEnd(Math.min(56,_e-24)),l.note?E(T,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),E(T,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):$e?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Preview article${$e.query?` \u2014 filter: ${$e.query}`:" (type to filter)"}`}),bn.length===0?E(T,{color:"gray",children:"no articles match"}):bn.map((l,i)=>G(T,{color:i===$e.cursor?F:void 0,children:[i===$e.cursor?"\u276F ":" ",l]},l)),E(T,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ce?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Resume session${Ce.query?` \u2014 filter: ${Ce.query}`:" (type to filter)"}`}),xn.length===0?E(T,{color:"gray",children:"no sessions match"}):xn.map((l,i)=>G(T,{color:i===Ce.cursor?F:void 0,children:[i===Ce.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),E(T,{color:i===Ce.cursor?F:"gray",children:l.firstPrompt.slice(0,Math.max(10,_e-40))})]},l.uuid)),E(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Bs?G(oe,{flexDirection:"column",children:[Yt.map((l,i)=>G(T,{color:i===Wt?F:void 0,children:[i===Wt?"\u276F ":" ",l.usage.padEnd(22)," ",E(T,{color:i===Wt?F:"gray",children:l.name==="model"&&_o?`${l.desc} (currently ${_o})`:l.desc})]},l.name)),E(T,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!D&&Qe.length>0?G(oe,{flexDirection:"column",paddingX:1,children:[Ls?E(T,{color:F,children:Ls}):null,Qe.map((l,i)=>{let a=pt(l),g=a.slice(0,Math.max(20,_e-5)),c=_e-g.length-7,m=c>=12?(xl(l)??pl(a)).slice(0,c):"";return G(T,{children:[E(T,{color:F,children:i+1})," ",g,m?E(T,{dimColor:!0,children:` \u2014 ${m}`}):null]},a)}),E(T,{dimColor:!0,children:`press 1-${Qe.length} to fill the command \xB7 esc dismiss`})]}):E(oe,{paddingX:1,children:G(T,{color:"gray",children:[qs.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${_o??"model n/a"}${t.kind==="api"?Ws>0?` \xB7 ${me(Ws)}`:"":Us>0?` \xB7 ${Ve(Us)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Am}from"react/jsx-runtime";async function Vl(e=process.cwd(),t="auto",n,o="0.0.0"){let r=jm(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Dm(Am(Yl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
302
- `),process.exit(0)}W();import{writeCrashLog as zl,isBenignTransportError as Em}from"document360-engine";var Xl=!1;function As(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Kl(e){if(Xl)return;Xl=!0;let t=(n,o)=>{if(Em(o)){zl({kind:n,level:"transport",message:As(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=zl({kind:n,level:"fatal",message:As(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
303
- `+$(`\u2717 d360-writer crashed: ${As(o)}`)+`
286
+ Model: ${X.model}${X.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:te+Ur(A,Y,U).join(`
287
+ `)+ce}),q([`/write${m?` --scope ${m}`:""}`]);return}Je.current=Date.now(),gt(0),I(!0);let jt=new AbortController;ve.current=jt,ee({verb:"Writing",total:A.length,done:0,active:[],rows:dn(A),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${B.length} article${B.length===1?"":"s"} across ${A.length} partition${A.length===1?"":"s"} (\u2264${U} agents at once) on ${X.model}${X.forced?" (forced)":""}\u2026 (esc to stop)`});let ni=new Set;try{for await(let Y of Ro({cwd:e,partitions:A,promptFor:te=>Or(te,K,{rewrite:v||ye}),concurrency:U,profileName:s,allowProdWrites:bt.current,model:X.model,signal:jt.signal}))if(Y.type==="partition_status")Y.status==="running"?ee(te=>te&&{...te,active:[...te.active,Y.label],rows:Oe(te.rows,Y.label,"active"),lastAt:Date.now()}):ee(te=>te&&{...te,active:te.active.filter(ce=>ce!==Y.label),done:te.done+1,rows:Oe(te.rows,Y.label,Y.status==="done"?"done":"failed"),lastAt:Date.now()});else if(Y.type==="partition_event"){let te=null;if(Y.event.type==="tool"){let ce=$l(Y.event.name,Y.event.input,A[Y.index]?.paths??[]);ce&&!ni.has(ce)&&(ni.add(ce),te=Y.label)}ee(ce=>{if(!ce)return ce;let Ae={...ce,lastAt:Date.now()};return Y.event.type==="tool"?Ae.tools=ce.tools+1:Y.event.type==="text"&&(Ae.chars=ce.chars+Y.event.delta.length),te&&(Ae.rows=xl(Ae.rows,te)),Ae})}else if(Y.type==="run_done"){Tt(At=>At+Y.totalCostUsd),Rt(At=>At+Y.results.reduce((An,at)=>An+at.outputTokens,0));let te=Y.aborted?"Stopped. ":"",ce=t.kind==="api"?"api":"subscription";d({kind:"note",tone:Y.aborted?"warn":Y.ok?"ok":"warn",text:te+Wr(Y.results,A,ce).join(`
288
+ `)});let Ae=Y.aborted?null:Fr(e,K,B);if(Ae&&d({kind:"note",tone:"warn",text:Ae}),!Y.aborted&&Y.ok){let At=m??w??"",An=At?` ${At}`:"",at=[];Ae&&at.push({cmd:`/check${An} --fix`,desc:"fix the issues the checker just flagged"}),at.push({cmd:`/review${An} --fix`,desc:"editorial review + apply fixes (style, grammar, structure)"}),at.push({cmd:"/publish --all",desc:"publish the drafts to Document360"}),at.push({cmd:"/screenshot --all",desc:"add screenshots first (optional)"}),q(at),he(Ae?"Written \u2014 but the checker flagged issues. Fix, review, then publish:":"Written. Review for quality, then publish:")}}}catch(Y){d({kind:"note",tone:"error",text:`Write run failed: ${Y.message}`})}finally{ve.current=null,ee(null),I(!1),ne(Y=>Y+1)}return}case"draft":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:m}=qr(e);if(u.length===0&&m===0){d({kind:"note",tone:"info",text:Gr});return}let w=h.join(" ").trim();if(!w&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
289
+ ${u.map(S=>` \u2022 ${S.name} (${S.docCount} doc${S.docCount===1?"":"s"})`).join(`
290
+ `)}`}),q(u.map(S=>`/draft ${S.name}`));return}let y="",R;if(w){let S=Br(u,w);S?y=S:R=w}else y=u[0]?.name??"";await ae(oo(y,R),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!qo(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(),R=await Ul({cwd:e,profileName:s});d({kind:"note",tone:"info",text:to(R,Date.now()-y).join(`
291
+ `)});return}if(u==="--baseline"){let y=h.find(B=>!B.startsWith("--")),R=y?y.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:R?`Setting the sync baseline for ${R}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let S=await sm({cwd:e,profileName:s,relPaths:R?[R]:void 0}),K=R?{rebaselined:[],skipped:[]}:await im({cwd:e,profileName:s});if(S.baselined.length===0&&S.skipped.length===0&&K.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}S.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${S.baselined.length} article${S.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),K.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${K.rebaselined.length} article${K.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),S.skipped.length>0&&d({kind:"note",tone:"warn",text:`${S.skipped.length} skipped:
292
+ ${S.skipped.map(B=>` - ${B.path} (${B.reason})`).join(`
293
+ `)}`}),ne(B=>B+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 om({cwd:e,profileName:s}),R=y.onlyInLegacy.length===0&&y.onlyInManifest.length===0&&y.mappedMissingFromManifest.length===0,S=[`Legacy listing: ${y.legacyCount} \xB7 Manifest: ${y.manifestCount} \xB7 in both: ${y.inBoth}`];R?S.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(y.mappedMissingFromManifest.length&&S.push(`\u2717 ${y.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${y.mappedMissingFromManifest.slice(0,5).join(", ")}`),y.onlyInLegacy.length&&S.push(`\u26A0 ${y.onlyInLegacy.length} only in the legacy listing: ${y.onlyInLegacy.slice(0,5).join(", ")}`),y.onlyInManifest.length&&S.push(`\u26A0 ${y.onlyInManifest.length} only in the manifest: ${y.onlyInManifest.slice(0,5).join(", ")}`),S.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:R?"ok":"warn",text:S.join(`
294
+ `)});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 rm({cwd:e,profileName:s,relPath:m.replace(/\\/g,"/")});Fe.current=[y],Sn();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let w=await Pr({cwd:e,profileName:s});for(let y of Rr(w))d({kind:"note",tone:y.tone,text:y.text});ne(y=>y+1)}catch(m){d({kind:"note",tone:"error",text:`Pull failed: ${m.message}`})}return}case"scope":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=am(e);if(u.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Pt({cursor:0,rows:u.map(m=>({...m,checked:m.recommended}))});return}case"audit":{if(h[0]==="--auto"){let m=Z(e);if(!m){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=h[1]!=="off";Ol({...m,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let u=await an();u.kind==="forward-to-agent"&&u.prompt&&await ae(u.prompt,{display:u.display,quietUser:!0});return}case"check":{let u=h.find(y=>!y.startsWith("--")),m=u?` ${u}`:"",w=Wl({cwd:e,scope:u});if(h.includes("--fix")){if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}d({kind:"note",tone:"info",text:`Fixing ${w.length} doc issue${w.length===1?"":"s"}\u2026`}),await ae(gs(w),{display:`/check${m} --fix`,quietUser:!0});let y=Wl({cwd:e,scope:u});d({kind:"note",tone:y.length===0?"ok":"warn",text:y.length===0?"\u2713 Doc-checker: all issues resolved.":po(y).join(`
295
+ `)}),q([{cmd:`/review${m} --fix`,desc:"editorial review + apply fixes (style, grammar, structure)"},{cmd:"/publish --all",desc:"publish the corrected docs to Document360"}]),he(y.length===0?"Deterministic issues fixed. Review for quality, then publish:":"Some issues remain \u2014 review, then publish:");return}d({kind:"note",tone:w.length===0?"ok":"warn",text:po(w).join(`
296
+ `)}),w.length>0&&(q([{cmd:`/check${m} --fix`,desc:"have the agent fix these in place"},{cmd:`/review${m} --fix`,desc:"also run the editorial review (style, grammar, structure)"},{cmd:"/publish --all",desc:"skip fixing \u2014 publish the docs as-is"}]),he(`Found ${w.length} doc issue${w.length===1?"":"s"} above \u2014 fix them, or publish as-is:`));return}case"review":{let u=ws(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=h.includes("--fix");if(await ae(u.prompt,{display:u.display,quietUser:!0}),m)q([{cmd:"/publish --all",desc:"publish the corrected docs to Document360"},{cmd:"/check",desc:"optional: instant re-scan for leaks/bad commands (no tokens)"}]),he("\u2713 Editor applied its fixes \u2014 your docs are corrected. Publish them, or re-scan first:");else{let w=h.filter(y=>y!=="--fix").join(" ");q([{cmd:`/review${w?` ${w}`:""} --fix`,desc:"let the editor apply all the fixes it listed above"},{cmd:"/check --fix",desc:"fix just the deterministic issues (leaks, bad commands)"},{cmd:"/publish --all",desc:"skip fixing \u2014 publish the docs as-is"}]),he("The review listed issues above. Apply the fixes, or publish as-is:")}return}case"capture-setup":{let u=await un();u.kind==="forward-to-agent"&&u.prompt&&await ae(u.prompt,{display:u.display,quietUser:!0});let m=os(e);m&&d({kind:"note",tone:"info",text:m.join(`
297
+ `)});return}case"devhints":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:_t(Nt(e)).join(`
298
+ `)}),St(lt()),Yt.current=Me(e).status==="current"||en(e);return}case"inbox":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(rs(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await ae(ss(),{display:"/inbox",quietUser:!0});return}case"document":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:m}=Vr(h);if(!m&&Yr(e)===0){d({kind:"note",tone:"info",text:Xr});return}let w=`/document${m?` ${m}`:""}${u?" --publish":""}`;await ae(zr(m,u),{display:w,quietUser:!0});return}case"catch-up":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!qo(l.trim()))return;let{publish:u}=as(h);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let m=await cs({cwd:e,profileName:s});for(let y of us(m))d({kind:"note",tone:y.startsWith("\u2713")?"ok":y.startsWith("\u2139")?"info":"warn",text:y});let w=Ut(Ot(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ae(ls({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{Fo.current=!0,d({kind:"note",tone:"info",text:`Updating ${pt}\u2026 (don\u2019t close this window)`}),hn(!0),(await co().finally(()=>hn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),q(m=>m.includes("/exit")?m:[...m,"/exit"]),Ls("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${lo}`});return}case"screenshot":{let u=es(h);if(u.mode==="list"){if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:ns(ts(e,u.scope),u.scope).join(`
299
+ `)});return}if(u.mode==="single"){let L=await io(h);L.kind==="forward-to-agent"&&L.prompt&&await ae(L.prompt,{display:L.display,quietUser:!0});return}if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=u.mode==="scope"?u.scope:void 0,w=dm(e,{scope:m}).map(L=>L.id);if(w.length===0){d({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let y=6,R=um(w,3),S=To(e,"standard");Je.current=Date.now(),gt(0),I(!0);let K=new AbortController;ve.current=K,ee({verb:"Authoring",unit:"spec",total:R.length,done:0,active:[],rows:dn(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${w.length} screenshot spec${w.length===1?"":"s"} across ${R.length} partition${R.length===1?"":"s"} (\u2264${y} agents at once) on ${S.model}${S.forced?" (forced)":""}\u2026 (esc to stop)`});let B=!1;try{for await(let L of Ro({cwd:e,partitions:R,promptFor:Ua,concurrency:y,profileName:s,allowProdWrites:bt.current,model:S.model,signal:K.signal}))if(L.type==="partition_status")L.status==="running"?ee(v=>v&&{...v,active:[...v.active,L.label],rows:Oe(v.rows,L.label,"active"),lastAt:Date.now()}):ee(v=>v&&{...v,active:v.active.filter(A=>A!==L.label),done:v.done+1,rows:Oe(v.rows,L.label,L.status==="done"?"done":"failed"),lastAt:Date.now()});else if(L.type==="partition_event")ee(v=>{if(!v)return v;let A={...v,lastAt:Date.now()};return L.event.type==="tool"?A.tools=v.tools+1:L.event.type==="text"&&(A.chars=v.chars+L.event.delta.length),A});else if(L.type==="run_done"){Tt(X=>X+L.totalCostUsd),Rt(X=>X+L.results.reduce((ye,jt)=>ye+jt.outputTokens,0));let v=L.results.filter(X=>X.ok).length,A=L.aborted?"Stopped. ":"";B=!L.aborted&&u.setup;let U=L.aborted?"":B?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:L.aborted?"warn":L.ok?"ok":"warn",text:`${A}Authored specs \u2014 ${v}/${L.results.length} batches ok.${U}`})}}catch(L){d({kind:"note",tone:"error",text:`Spec authoring failed: ${L.message}`})}finally{ve.current=null,ee(null),I(!1),ne(L=>L+1)}if(B){let L=await un();L.kind==="forward-to-agent"&&L.prompt&&await ae(L.prompt,{display:L.display,quietUser:!0});let v=os(e);v&&d({kind:"note",tone:"info",text:v.join(`
300
+ `)})}return}case"reset":{let u=fs(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}No.current={repoName:pn(e),targets:u,hadDevhints:Xe(Is(e))},d({kind:"note",tone:"warn",text:hs(e,u).join(`
301
+ `)}),ue(pn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,Sn,d,we,ae,Cn,Xo,Xs]),Dn=V(l=>{let i=(l??D).trim();if(b(""),gn(null),wt(0),i.startsWith("/")&&(ue(null),ht.current++,he(null),q(h=>Pl(h,i))),!i||Qs(i)||Ks(i))return;Io.current.push(i);let a=jl(i,Os.current);i.startsWith("/")?(d({kind:"user",text:i}),Js(a)):ae(a,{display:i})},[D,Qs,Ks,Js,ae]),Zs=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=Tl(l);if(Sl(i)){let a=Dl(++ic.current,i);Os.current.set(a,i),P(a)}else P(i);return}P(l)},[P]),Dt=Math.max(10,_e-6),ei=Rs(()=>Co(k.text,Dt),[k.text,Dt]),Jo=V(l=>x(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),jn=V(l=>x(i=>({...i,pos:El(Co(i.text,Dt),i.pos,l)})),[Dt]),Xt=V(l=>x(i=>({...i,pos:Il(Co(i.text,Dt),i.pos,l)})),[Dt]),cc=["\x1B[H","\x1B[1~","\x1BOH"],uc=["\x1B[F","\x1B[4~","\x1BOF"],ti=V((l,i)=>i.leftArrow?(Jo(-1),!0):i.rightArrow?(Jo(1),!0):l&&cc.includes(l)?(Xt("start"),!0):l&&uc.includes(l)?(Xt("end"),!0):i.ctrl&&l==="a"?(Xt("start"),!0):i.ctrl&&l==="e"?(Xt("end"),!0):!1,[Jo,Xt]);return _f((l,i)=>{if(i.ctrl&&l==="c"){be.current?.close(),r();return}if(!O){if(N){if(i.escape){if(ve.current){if(!ve.current.signal.aborted){let a=(yn?.verb??"work").toLowerCase(),h=yn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${h}s)\u2026`}),ve.current.abort()}return}qt.current||(qt.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),be.current?.interrupt());return}if(i.return){let a=D.trim();if(!a)return;st.current.push(a),Mo([...st.current]),b("");return}if(ti(l,i))return;if(i.upArrow){jn(-1);return}if(i.downArrow){jn(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&Zs(l);return}if(et){if(i.upArrow){tt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){tt(a=>a&&{...a,cursor:Math.min(Ee.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ee.length){tt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Ee[et.cursor];tt(null);let{lines:h,changed:u,effective:m}=ln(e,a.value??"default");for(let w of h)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});u&&(Bs(w=>w+1),be.current?.setModel(m));return}if(l==="s"){let a=Ee[et.cursor];tt(null),be.current?.setModel(a.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){tt(null);return}return}if(Ne){if(i.upArrow){xt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){xt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ne.rows.length){xt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=Ne.rows[Ne.cursor];xt(null),Qo(a.name,i.return===!0);return}if(i.escape){xt(null);return}return}if(Lo){if(i.escape){Gt(null);return}if(i.leftArrow||i.tab&&i.shift){Gt(a=>a&&{tab:(a.tab-1+Re.length)%Re.length});return}if(i.rightArrow||i.tab){Gt(a=>a&&{tab:(a.tab+1)%Re.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.length){Gt({tab:Number(l)-1});return}return}if(He){if(i.upArrow){$t(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){$t(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=He.rows.length){$t(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=He.rows[He.cursor].name;if($t(null),!ar(e,a).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${a}").`});let u=!1;try{let m=Ke(a);u=!!m&&!(We(m)&&!m.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),q(["/login"]),ne(m=>m+1);return}if(i.escape){$t(null);return}return}if(fe){if(i.upArrow){vt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){vt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=fe.rows.length){vt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=fe.rows[fe.cursor],{profile:h,projectId:u}=fe;vt(null),Pn(h,u,a);return}if(i.escape){vt(null);return}return}if(xe){if(i.upArrow){nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){nt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=xe.rows.length){nt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=xe.rows[xe.cursor],{profile:h}=xe;nt(null),Tn(h,a);return}if(i.escape){nt(null);return}return}if(ge){if(i.upArrow){Pt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Pt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){Pt(a=>a&&{...a,rows:a.rows.map((h,u)=>u===a.cursor?{...h,checked:!h.checked}:h)});return}if(i.return){let a=ge.rows.filter(h=>h.checked).map(h=>h.path);if(Pt(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}$r(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of a)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(i.escape){Pt(null);return}return}if(ot){if(i.upArrow){Ct(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ct(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ot.rows.length){Ct(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ot.rows[ot.cursor];Ct(null),a.kind==="article"?Xo(a.paths[0]):Cn(a.paths);return}if(i.escape){Ct(null);return}return}if($e){if(i.escape){rt(null);return}if(i.upArrow){rt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){rt(a=>a&&{...a,cursor:Math.min(Math.max(0,$n.length-1),a.cursor+1)});return}if(i.return){let a=$n[$e.cursor];if(a){rt(null);try{d({kind:"preview",name:pn(a),text:Gl(Ts(mt(e,a),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${a}: ${h.message}`})}}return}if(i.backspace||i.delete){rt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){rt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(Ce){if(i.escape){it(null);return}if(i.upArrow){it(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){it(a=>a&&{...a,cursor:Math.min(Math.max(0,vn.length-1),a.cursor+1)});return}if(i.return){let a=vn[Ce.cursor];if(a){it(null),we(a.uuid),Ie.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Ze(a.name),Ss(a.uuid),kt.current=[];let h=$s(e,a.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${a.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){it(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){it(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!D&&De){b(De),ue(null),ht.current++;return}if(!D&&Qe.length>0&&l&&/^[1-9]$/.test(l)){let a=Qe[Number(l)-1];if(a){b(ft(a));return}}if(!D&&(Bo||Uo)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=Bo!=null;ll(Bo??Uo).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?a?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&a&&Go(null)});return}if(!ti(l,i)){if(Vs){if(i.upArrow){wt(a=>Math.max(0,a-1));return}if(i.downArrow){wt(a=>Math.min(zt.length-1,a+1));return}if(i.tab){b("/"+(zt[Ht]?.name??"")+" "),wt(0);return}if(i.return){let a=zt[Ht];if(a){let h=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(wl(a.usage)&&!h){b("/"+a.name+" "),wt(0);return}Dn("/"+a.name+(h?" "+h:""));return}}}else{if(i.upArrow){if(D!==""&&yt===null){jn(-1);return}let a=Io.current;if(!a.length)return;let h=yt===null?a.length-1:Math.max(0,yt-1);gn(h),b(a[h]??"");return}if(i.downArrow){if(D!==""&&yt===null){jn(1);return}let a=Io.current;if(yt===null)return;let h=yt+1;h>=a.length?(gn(null),b("")):(gn(h),b(a[h]??""));return}}if(i.return){Dn();return}if(i.backspace||i.delete){C();return}if(i.escape){b(""),wt(0),ue(null),q([]),he(null);return}l&&!i.ctrl&&!i.meta&&Zs(l)}}}),Te(()=>{if(N||O)return;let l=st.current.shift();l!==void 0&&(Mo([...st.current]),Dn(l))},[N,O,Dn]),G(oe,{flexDirection:"column",width:_e,children:[zo!==null&&G(oe,{marginTop:1,flexDirection:"column",children:[zo.truncated&&E(T,{dimColor:!0,children:"\u2026"}),E(T,{children:zo.text})]}),N&&(yn?E(Sm,{p:yn}):E(Rm,{startTime:Je.current,chars:sc})),E(oe,{borderStyle:"round",borderColor:Ys.prod?"yellow":F,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?ei.map((l,i)=>{let a=k.text.slice(l.start,l.end),h=i===Po(ei,k.pos),u=Math.min(k.pos,l.end)-l.start;return G(T,{children:[E(T,{color:F,children:i===0?"> ":" "}),h?G(js,{children:[a.slice(0,u),E(So,{ch:a[u]??" "}),a.slice(u+1)]}):a||" "]},`${i}-${l.start}`)}):G(T,{children:[E(T,{color:F,children:"> "}),De&&!N?G(js,{children:[E(So,{ch:De[0],dim:!0}),E(T,{color:"gray",children:De.slice(1)}),E(T,{dimColor:!0,children:" (tab)"})]}):(Vo.isSetup||!oc)&&!N?G(js,{children:[E(So,{ch:Vo.text[0],dim:!0}),E(T,{color:"gray",children:Vo.text.slice(1)})]}):E(So,{ch:" "})]})}),Fs.length>0&&E(oe,{flexDirection:"column",paddingX:1,children:Fs.map((l,i)=>E(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Lo?E(kl,{tab:Lo.tab,width:_e}):et?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Select model"}),E(T,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ee.map((l,i)=>G(T,{color:i===et.cursor?F:void 0,children:[i===et.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===et.current?" \u2714":""}`.padEnd(16),E(T,{color:"gray",children:l.desc})]},l.label)),E(T,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Ne?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Switch connection profile"}),Ne.rows.map((l,i)=>G(T,{color:i===Ne.cursor?F:void 0,children:[i===Ne.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===Ne.current?" \u2714":""}`.padEnd(20),E(T,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?E(T,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),E(T,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):He?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Pick your Document360 environment"}),He.rows.map((l,i)=>G(T,{color:i===He.cursor?F:void 0,children:[i===He.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),E(T,{color:"gray",children:l.apiUrl})]},l.name)),E(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Switch workspace"}),E(T,{dimColor:!0,children:`environment ${fe.environment} \xB7 project ${fe.projectName??`${fe.projectId.slice(0,8)}\u2026`}`}),fe.rows.map((l,i)=>G(T,{color:i===fe.cursor?F:void 0,children:[i===fe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===fe.current?" \u2714":""}`.padEnd(30),E(T,{color:"gray",children:l.type??""})]},l.id)),E(T,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):xe?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Choose project"}),E(T,{dimColor:!0,children:`environment ${xe.environment}`}),xe.rows.map((l,i)=>G(T,{color:i===xe.cursor?F:void 0,children:[i===xe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===xe.current?" \u2714":""}`.padEnd(30),E(T,{color:"gray",children:l.sub??""})]},l.id)),E(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ge?(()=>{let i=Math.min(Math.max(0,ge.cursor-Math.floor(7)),Math.max(0,ge.rows.length-14)),a=ge.rows.slice(i,i+14),h=ge.rows.filter(u=>u.checked).length;return G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Which folders back the user docs? (${h} selected of ${ge.rows.length})`}),i>0?E(T,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((u,m)=>{let w=i+m;return G(T,{color:w===ge.cursor?F:void 0,children:[w===ge.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,_e-34)),E(T,{color:"gray",children:eo(u)})]},u.path)}),i+14<ge.rows.length?E(T,{dimColor:!0,children:` \u2193 ${ge.rows.length-i-14} more`}):null,E(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():ot?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),ot.rows.map((l,i)=>{let a=i===ot.cursor,h=l.indent?" ":" ",u=`${i+1}.`.padEnd(3);return G(T,{color:a?F:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${h}${u} ${l.label}`.padEnd(Math.min(56,_e-24)),l.note?E(T,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),E(T,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):$e?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Preview article${$e.query?` \u2014 filter: ${$e.query}`:" (type to filter)"}`}),$n.length===0?E(T,{color:"gray",children:"no articles match"}):$n.map((l,i)=>G(T,{color:i===$e.cursor?F:void 0,children:[i===$e.cursor?"\u276F ":" ",l]},l)),E(T,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ce?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Resume session${Ce.query?` \u2014 filter: ${Ce.query}`:" (type to filter)"}`}),vn.length===0?E(T,{color:"gray",children:"no sessions match"}):vn.map((l,i)=>G(T,{color:i===Ce.cursor?F:void 0,children:[i===Ce.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),E(T,{color:i===Ce.cursor?F:"gray",children:l.firstPrompt.slice(0,Math.max(10,_e-40))})]},l.uuid)),E(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Vs?G(oe,{flexDirection:"column",children:[zt.map((l,i)=>G(T,{color:i===Ht?F:void 0,children:[i===Ht?"\u276F ":" ",l.usage.padEnd(22)," ",E(T,{color:i===Ht?F:"gray",children:l.name==="model"&&Oo?`${l.desc} (currently ${Oo})`:l.desc})]},l.name)),E(T,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!D&&Qe.length>0?G(oe,{flexDirection:"column",paddingX:1,children:[Ws?E(T,{color:F,children:Ws}):null,Qe.map((l,i)=>{let a=ft(l),h=a.slice(0,Math.max(20,_e-5)),u=_e-h.length-7,m=u>=12?(Cl(l)??hl(a)).slice(0,u):"";return G(T,{children:[E(T,{color:F,children:i+1})," ",h,m?E(T,{dimColor:!0,children:` \u2014 ${m}`}):null]},a)}),E(T,{dimColor:!0,children:`press 1-${Qe.length} to fill the command \xB7 esc dismiss`})]}):E(oe,{paddingX:1,children:G(T,{color:"gray",children:[Ys.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Oo??"model n/a"}${t.kind==="api"?qs>0?` \xB7 ${me(qs)}`:"":Hs>0?` \xB7 ${Ve(Hs)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Em}from"react/jsx-runtime";async function Kl(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Am(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=jm(Em(Xl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
302
+ `),process.exit(0)}W();import{writeCrashLog as Ql,isBenignTransportError as Im}from"document360-engine";var Jl=!1;function Ns(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Zl(e){if(Jl)return;Jl=!0;let t=(n,o)=>{if(Im(o)){Ql({kind:n,level:"transport",message:Ns(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=Ql({kind:n,level:"fatal",message:Ns(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
303
+ `+$(`\u2717 d360-writer crashed: ${Ns(o)}`)+`
304
304
  `),r&&process.stderr.write(f(` Crash details: ${r}`)+`
305
305
  `+f(" Run: d360-writer logs")+`
306
- `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Mm=Nm(import.meta.url),Ql=Mm("../package.json");Kl("d360-writer");var Se=new Im;function Es(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Se.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{Es(e),await _n({profile:e.profile,manual:e.manual})});Se.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Es(e),await di({profile:e.profile})});Se.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Es(e),await ui({profile:e.profile})});var Is=Se.command("profile").description("Manage connection profiles for the current repo");Is.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Mn(process.cwd()));Is.command("use <name>").description("Set the default profile for this repo").action(e=>Ln(process.cwd(),e));Is.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>On(process.cwd(),e));var Jl=Se.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Jl.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>jt(process.cwd(),e.profile));Jl.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await oi(process.cwd(),e,t.profile)});var Zl=Se.command("project").description("Choose the Document360 project for this repo (active profile's identity)");Zl.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>En(process.cwd(),e.profile));Zl.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await si(process.cwd(),e,t.profile)});Se.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Yn(),Mi));await e()});Se.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>hi());Se.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(no(),Sa)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Se.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Ql.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(_m.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 gi(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 ol(e.cwd,e.auth,e.profile):await Vl(e.cwd,e.auth,e.profile,Ql.version)});Se.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
306
+ `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Lm=_m(import.meta.url),ec=Lm("../package.json");Zl("d360-writer");var Se=new Nm;function _s(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Se.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{_s(e),await On({profile:e.profile,manual:e.manual})});Se.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{_s(e),await mi({profile:e.profile})});Se.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{_s(e),await fi({profile:e.profile})});var Ms=Se.command("profile").description("Manage connection profiles for the current repo");Ms.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Un(process.cwd()));Ms.command("use <name>").description("Set the default profile for this repo").action(e=>Wn(process.cwd(),e));Ms.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Fn(process.cwd(),e));var tc=Se.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");tc.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Et(process.cwd(),e.profile));tc.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await ii(process.cwd(),e,t.profile)});var nc=Se.command("project").description("Choose the Document360 project for this repo (active profile's identity)");nc.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>_n(process.cwd(),e.profile));nc.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await li(process.cwd(),e,t.profile)});Se.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Xn(),Ui));await e()});Se.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>yi());Se.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(so(),Aa)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Se.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(ec.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(Mm.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 ki(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 il(e.cwd,e.auth,e.profile):await Kl(e.cwd,e.auth,e.profile,ec.version)});Se.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});