document360-writer 0.4.81 → 0.4.83

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 +82 -82
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var el=Object.defineProperty;var yo=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var tl=(e,t)=>{for(var n in t)el(e,n,{get:t[n],enumerable:!0})};import Ee from"picocolors";var q,nl,ol,rl,as,At,f,x,L,j,A,te,Te,M=yo(()=>{"use strict";q="#7f56d9",[nl,ol,rl]=[127,86,217],as=e=>Ee.isColorSupported?`\x1B[38;2;${nl};${ol};${rl}m${e}\x1B[39m`:e,At=e=>Ee.bold(as(e)),f=e=>Ee.dim(e),x=e=>Ee.red(e),L=e=>Ee.yellow(e),j=e=>Ee.green(e),A=as,te=e=>Ee.gray(e),Te=e=>Ee.bold(e)});import{existsSync as bn,writeFileSync as _t,readFileSync as Bl,readdirSync as Gl}from"node:fs";import{join as Vl}from"node:path";import{devHintsGuidePath as xn,hintsDir as Ps,architectureDir as Rs,messagesDir as Co,creatorNotesPath as Ts,devhintsStatePath as Ds,ensureDir as kn,writeMessage as Yl,listOpenForDev as zl}from"document360-engine";function js(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var tl=Object.defineProperty;var ko=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var nl=(e,t)=>{for(var n in t)tl(e,n,{get:t[n],enumerable:!0})};import Ie from"picocolors";var q,ol,rl,sl,ls,Et,f,x,L,j,E,te,Te,M=ko(()=>{"use strict";q="#7f56d9",[ol,rl,sl]=[127,86,217],ls=e=>Ie.isColorSupported?`\x1B[38;2;${ol};${rl};${sl}m${e}\x1B[39m`:e,Et=e=>Ie.bold(ls(e)),f=e=>Ie.dim(e),x=e=>Ie.red(e),L=e=>Ie.yellow(e),j=e=>Ie.green(e),E=ls,te=e=>Ie.gray(e),Te=e=>Ie.bold(e)});import{existsSync as xn,writeFileSync as Ut,readFileSync as Gl,readdirSync as Vl}from"node:fs";import{join as Yl}from"node:path";import{devHintsGuidePath as $n,hintsDir as Ts,architectureDir as Ds,messagesDir as Po,creatorNotesPath as Ss,devhintsStatePath as js,ensureDir as bn,writeMessage as zl,listOpenForDev as Xl}from"document360-engine";function As(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
3
3
 
4
4
  <!-- devhints script v${ne} \xB7 maintained by document360-writer (/devhints). -->
5
5
 
@@ -141,7 +141,7 @@ output shape; the writer judges it like a technical writer would. Two ways:
141
141
  \`--yes\` if the target profile is production.
142
142
  - **Queued (async)** \u2014 drop a \`request\` message (Part 3); the writer documents it on its next session or
143
143
  via CI. Use this when a human should review before publishing.
144
- `}function Xl(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
144
+ `}function Kl(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
145
145
 
146
146
  <!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
147
147
  The builder agent reads this FIRST and treats it as authoritative when writing the architecture
@@ -155,60 +155,60 @@ Anything only a human knows that would help document this product. For example:
155
155
  - Gotchas or non-obvious behavior.
156
156
 
157
157
  (Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
158
- `}function yt(e){kn(Ps(e)),kn(Rs(e)),kn(Co(e));for(let n of[Ps(e),Co(e)]){let o=Vl(n,".gitkeep");bn(o)||_t(o,`# Keeps this document360-writer inbox tracked in git even when empty.
159
- `)}bn(Ts(e))||_t(Ts(e),Xl()),_t(xn(e),js());let t=Ie(e);return Es(e,new Date().toISOString()),t}async function As(e,t){for(let n of kt(yt(t.cwd)))console.log(n);return{kind:"continue"}}function Ye(){return[`This is document360-writer's dev hand-off setup (v${ne}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20134). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current; AND each session, check"," `.d360-writer/messages/` for open questions from the docs agent and answer them \u2014 all per"," `.d360-writer/DEV-HINTS-GUIDE.md`. If that section is already there, leave it (refine in place only if"," wrong) \u2014 do NOT add a duplicate. Then commit `.d360-writer/` and the memory-file change ONLY if"," something actually changed.","4. Two-way messages (Part 3): check `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each \u2014 fold durable facts into the architecture brief and/or drop"," a reply (`from: dev`, `kind: answer`, `re: <id>`) \u2014 then set the question's frontmatter `status: done`."," If there are none, continue.",'5. Then ask me: "Any tribal knowledge that would help document this product? (folder map, terminology,',` what to prioritize or skip, gotchas \u2014 or say 'none')". 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).",`6. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${ne},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","7. When everything is done, print exactly ONE of:",' \u2022 first-time setup: "\u2705 Setup complete \u2014 go back to document360-writer and run: write the docs for this repo"',' \u2022 a refresh (brief/notes already existed): "\u2705 Hand-off refreshed \u2014 back in document360-writer, run: write the docs for this repo"'].join(`
160
- `)}function Po(e){try{let t=Bl(Ds(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Es(e,t){let o={...Po(e)??{},emittedVersion:ne,emittedAt:t};_t(Ds(e),`${JSON.stringify(o,null,2)}
161
- `)}function Is(e){try{return Gl(Rs(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ie(e){let n=Po(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ne?"stale":"current",completedVersion:n}}function $n(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ne};try{if(!bn(xn(e)))return n;let o=Po(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;ne>r&&(kn(Co(e)),_t(xn(e),js()),Es(e,t),n.guideRefreshed=!0),ne>s&&(zl(e).some(p=>p.kind==="request"&&p.subject.startsWith(Ss))||(Yl(e,{id:`onb${ne}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Ss}${ne})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${ne}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",Ye()].join(`
162
- `)}),n.notifiedBuilder=!0))}catch{}return n}function vn(e){if(!bn(xn(e)))return[];let t=Ie(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${ne}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,wt,Ye(),wt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function To(){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(`
163
- `)}function Cn(){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):",wt,To(),wt]}function kt(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${ne}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",wt,Ye(),wt,"","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 here and run: write the docs for this repo"]}var wt,ne,Ss,ze=yo(()=>{"use strict";wt="-".repeat(64),ne=4;Ss="Re-run dev\u2194docs onboarding (protocol v"});var Oi={};tl(Oi,{doctorCommand:()=>Ht,renderDoctorChecks:()=>Ui,runDoctorChecks:()=>_i});import{existsSync as Ei}from"node:fs";import{d360GetAll as wu,getAccessToken as yu,isExpired as dr,loadProfileMap as ku,loadTokens as bu,packageSkillsDir as Ii,projectConfigPath as xu,readProjectConfig as $u,DEFAULT_DOCS_DIR as vu,resolveActiveProfile as Cu,classifyClaudeAuth as Pu,CLAUDE_CODE_SETUP_HINT as Ni,resolveModelSetting as Tu,devHintsGuidePath as Su}from"document360-engine";async function _i(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=Pu();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. ${Ni}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Ni});let r=Tu(e);t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`});let s=$u(e);if(!s)return t.push({level:"fail",label:`No ${xu(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??vu).replace(/\/+$/,"");t.push(s.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let h;try{h=Cu(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(w){return t.push({level:"fail",label:`Profile config: ${w.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let b=bu(h.name);b?dr(b)&&!b.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):dr(b)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(b.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${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 k=ku(e,h.name);k?k.projectId&&h.project.projectId&&k.projectId!==h.project.projectId?t.push({level:"fail",label:`Category map projectId (${k.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(k.articles).length} articles, ${Object.keys(k.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${h.name}" (created on first /publish)`}),t.push(Ei(Ii())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Ii()}`,fix:"Reinstall document360-writer (broken install)"});let D=Ie(e);if((Ei(Su(e))||D.status!=="unset")&&(D.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ne})`}):D.status==="stale"?t.push({level:"warn",label:`Dev hand-off: builder on devhints v${D.completedVersion}, current is v${ne}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}):t.push({level:"warn",label:"Dev hand-off: guide emitted but the builder hasn't completed it",fix:"Have the repo's coding agent run the /devhints prompt (sets up the two-way channel)"})),b&&(!dr(b)||b.refreshToken)){let w={profile:h.name,connection:h.connection};try{await yu(w);let v=await wu(w,"/v3/projects");t.push({level:"ok",label:`API reachable (${h.connection.apiUrl}) \u2014 ${v.length} project(s) visible`})}catch(v){t.push({level:"fail",label:`API call failed: ${v.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}}return t}function Ui(e){let t=[""];for(let r of e){let s=r.level==="ok"?j("\u2713"):r.level==="warn"?L("\u26A0"):x("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${A(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"})`}`):x(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Ht(e,t){console.log(f("Running checks\u2026"));for(let n of Ui(await _i(t.cwd)))console.log(n);return{kind:"continue"}}var Nn=yo(()=>{"use strict";ze();M()});import{Command as Hp}from"commander";import{createRequire as qp}from"node:module";import{AUTH_MODES as Bp}from"document360-engine";import{input as yl}from"@inquirer/prompts";import{loginPkce as kl,refreshTokens as bl,toStoredTokens as ms,clearTokens as xl,decodeJwtClaims as fs,isExpired as $l,loadTokens as vl,saveTokens as hs,resolveActiveProfile as pn,setProfileProject as Cl,readProjectConfig as Pl}from"document360-engine";M();import{select as sl}from"@inquirer/prompts";import{resolveActiveProfile as il,setProfileProject as al,resolveProjectId as ll,listWorkspaces as cl}from"document360-engine";async function Et(e,t){let n=il(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??ll(o);return{workspaces:await cl(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var ls=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 dn(e,t,n,o,r){al(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function cs(e,t,n){let o;try{o=await Et(e,n)}catch(s){return console.log(x(`Could not list workspaces: ${s.message}`)),1}let r=ko(o.workspaces,t);return r?(dn(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(x(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function ht(e,t){let n;try{n=await Et(e,t)}catch(b){console.log(x(`Could not list workspaces: ${b.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 b of o)console.log(` ${b.id===c?A("\u25CF"):" "} ${ls(b)} ${f(b.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await sl({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${ls(b)}${b.id===c?" (current)":""}`,value:b.id}))}),h=o.find(b=>b.id===p);dn(e,s,r,p,h?.name),console.log(j(`\u2713 Workspace set to "${h?.name??p}" for profile "${s}".`))}M();import{select as ul}from"@inquirer/prompts";import{resolveActiveProfile as dl,setProfileProject as pl,listProjects as fl}from"document360-engine";async function gt(e,t){let n=dl(e,t),o={profile:n.name,connection:n.connection};return{projects:await fl(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var us=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function ds(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 bo(e,t,n,o){pl(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function ps(e,t){let n;try{n=await gt(e,t)}catch(h){console.log(x(`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?A("\u25CF"):" "} ${us(h)} ${f(h.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await ul({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${us(h)}${h.id===s?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===c);bo(e,r,c,p?.name),console.log(j(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}M();import ml from"picocolors";function hl(e=process.env){return e.FORCE_HYPERLINK==="0"||!ml.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 gl(e,t=e,n){return hl(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var wl=/https?:\/\/[^\s\x1b]+/g;function It(e,t){return e.replace(wl,n=>gl(n,n,t))}function gs(e){return{...fs(e.idToken)??{},...fs(e.accessToken)??{}}}function fn(e){let t=gs(e),n=t.email??t.preferred_username??t.sub??"unknown",o=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${n}${o}`}async function mn(e){let t=pn(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 kl(n,{manual:e.manual,promptForRedirect:s=>yl({message:s})},s=>console.log(It(s))),r=ms(t.name,o);if(hs(r),await xo(r,t.name,s=>console.log(f(s))),console.log(""),console.log(j(`\u2713 Logged in to "${t.name}" as ${fn(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{Pl(process.cwd())?.profiles?.[t.name]&&(console.log(""),await ht(process.cwd(),t.name))}catch{}}async function xo(e,t,n){let r=gs(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(pn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await gt(process.cwd(),t);c=p.find(h=>h.id===r)?.name}catch{}Cl(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function ws(e){let t=pn(process.cwd(),e.profile),n=t.connection,o=vl(t.name);if(!o){console.log(x(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${A(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${fn(o)}`),$l(o))if(o.refreshToken)try{let r=ms(t.name,await bl(n,o.refreshToken));hs(r),console.log(j(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(L("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function ys(e){let t=pn(process.cwd(),e.profile);xl(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.`))}M();import{readProjectConfig as ks,writeProjectConfig as Tl,resolveActiveProfile as Sl,loadTokens as Rl,isExpired as Dl}from"document360-engine";function hn(e){let t=ks(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(x("No profiles in .d360-writer.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?A("\u25CF "):" ",s=o.production?L(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Rl(n),h=p?Dl(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${A(n)} \u2192 ${c}${s} [${h}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function gn(e,t){let n=ks(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(x(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Tl(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(j(`\u2713 Default profile is now "${t}"${o}`))}function wn(e,t){try{let n=Sl(e,t);console.log(""),console.log(`Profile ${A(n.name)}${n.production?L(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(x(n.message)),process.exitCode=1}}M();import{existsSync as jl,readdirSync as Al,statSync as El}from"node:fs";import{join as Il}from"node:path";import{apiLogDir as Nl}from"document360-engine";function bs(){let e=Nl();if(console.log(""),console.log(`Document360 API logs: ${A(e)}`),!jl(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Al(e).filter(n=>n.endsWith(".jsonl")).sort().reverse();t.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let n of t.slice(0,14)){let o=(El(Il(e,n)).size/1024).toFixed(1);console.log(` ${n} ${f(`${o} 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("")}M();import{createSession as _l,resolveAuth as Ul,findByName as Ol,slugify as Ll,touchSession as Ml,upsertSession as Wl,resolveActiveProfile as Fl}from"document360-engine";async function xs(e,t,n,o,r,s){let c=Ul(n);c.kind==="none"&&(console.error(""),console.error(x("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${A("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${A("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=Fl(e,r)}catch(w){console.error(x(`Document360 profile error: ${w.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(x("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let h;if(o){let w=Ol(e,o);w||(console.error(x(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),h=w.uuid,console.error(f(`Resuming "${w.name}"`))}let b=_l({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),k=h??null,D=1;for await(let w of b.send(t))switch(w.type){case"session":if(!k){k=w.sessionId;let v=new Date().toISOString();Wl({uuid:k,name:Ll(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:v,updatedAt:v})}break;case"text":process.stdout.write(w.delta);break;case"tool":console.error(te(` \u2699 ${w.name}`));break;case"result":D=w.ok?0:1,console.error(f(`(${w.inputTokens}\u2192${w.outputTokens} tokens`+(w.costUsd>0?`, $${w.costUsd<.01?w.costUsd.toFixed(4):w.costUsd.toFixed(2)}`:"")+")")),w.ok||console.error(x("agent finished with an error result"));break;case"error":console.error(""),console.error(x(`agent error: ${w.message}`)),process.exit(1)}k&&Ml(k),process.stdout.write(`
164
- `),process.exit(D)}import{createInterface as gd}from"node:readline/promises";import{createSession as Sr,resolveAuth as wd,getSession as yd,setTitle as kd,slugify as bd,touchSession as la,upsertSession as xd,generateTitle as $d,resolveActiveProfile as ca,resolveModelSetting as vd,readProjectConfig as Cd,decodeJwtClaims as ia,isExpired as Pd,loadTokens as Td}from"document360-engine";var Nt=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--all|--scope <cat>|<path>] [--run]",desc:"Author the planned articles in parallel (bare = preview + cost; --run starts)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"audit",usage:"/audit",desc:"Gap analysis: code vs docs vs Document360 (what changed)",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"sync",usage:"/sync [pull <path>|--all]",desc:"Drift report local vs Document360; pull portal edits",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"}],Hl=[{key:"start",label:"Start here"},{key:"docs",label:"Write & screenshots"},{key:"publish",label:"Publish & keep in sync"},{key:"setup",label:"Setup & health"},{key:"session",label:"Session"}];function yn(){let e=Math.max(...Nt.map(n=>n.usage.length))+2,t=["document360-writer \u2014 commands","","New here? Four steps from a fresh repo to published docs:"," 1. /init \u2192 connect, scaffold config, AND print a one-paste hand-off prompt for your source repo"," 2. run that prompt in your repo's coding agent (Claude Code / Codex / Cursor)",' 3. "write the docs for this repo" \u2192 back here, the agent authors the articles'," 4. /publish \u2192 dual-publish to Document360",""," Screenshots are optional \u2014 add them anytime:"," /screenshot --all \u2192 d360-capture capture \u2192 re-/publish"];for(let{key:n,label:o}of Hl){t.push("",o);for(let r of Nt.filter(s=>s.group===n))t.push(` ${r.usage.padEnd(e)}${r.desc}`)}return t.push("","Tip: anything not starting with / is sent to the agent."),t}function $s(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Nt.filter(n=>n.name.startsWith(t))}function vs(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}async function $o(){console.log("");for(let e of yn())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}M();import{getSession as ql}from"document360-engine";async function Cs(e,t){let n=t.currentUuid(),o=n?ql(n):void 0;return console.log(o?f(`
158
+ `}function yt(e){bn(Ts(e)),bn(Ds(e)),bn(Po(e));for(let n of[Ts(e),Po(e)]){let o=Yl(n,".gitkeep");xn(o)||Ut(o,`# Keeps this document360-writer inbox tracked in git even when empty.
159
+ `)}xn(Ss(e))||Ut(Ss(e),Kl()),Ut($n(e),As());let t=Ne(e);return Is(e,new Date().toISOString()),t}async function Es(e,t){for(let n of kt(yt(t.cwd)))console.log(n);return{kind:"continue"}}function Ye(){return[`This is document360-writer's dev hand-off setup (v${ne}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20134). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current; AND each session, check"," `.d360-writer/messages/` for open questions from the docs agent and answer them \u2014 all per"," `.d360-writer/DEV-HINTS-GUIDE.md`. If that section is already there, leave it (refine in place only if"," wrong) \u2014 do NOT add a duplicate. Then commit `.d360-writer/` and the memory-file change ONLY if"," something actually changed.","4. Two-way messages (Part 3): check `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each \u2014 fold durable facts into the architecture brief and/or drop"," a reply (`from: dev`, `kind: answer`, `re: <id>`) \u2014 then set the question's frontmatter `status: done`."," If there are none, continue.",'5. Then ask me: "Any tribal knowledge that would help document this product? (folder map, terminology,',` what to prioritize or skip, gotchas \u2014 or say 'none')". 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).",`6. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${ne},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","7. When everything is done, print exactly ONE of:",' \u2022 first-time setup: "\u2705 Setup complete \u2014 go back to document360-writer and run: write the docs for this repo"',' \u2022 a refresh (brief/notes already existed): "\u2705 Hand-off refreshed \u2014 back in document360-writer, run: write the docs for this repo"'].join(`
160
+ `)}function To(e){try{let t=Gl(js(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Is(e,t){let o={...To(e)??{},emittedVersion:ne,emittedAt:t};Ut(js(e),`${JSON.stringify(o,null,2)}
161
+ `)}function Ns(e){try{return Vl(Ds(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ne(e){let n=To(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ne?"stale":"current",completedVersion:n}}function vn(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ne};try{if(!xn($n(e)))return n;let o=To(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;ne>r&&(bn(Po(e)),Ut($n(e),As()),Is(e,t),n.guideRefreshed=!0),ne>s&&(Xl(e).some(p=>p.kind==="request"&&p.subject.startsWith(Rs))||(zl(e,{id:`onb${ne}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Rs}${ne})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${ne}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",Ye()].join(`
162
+ `)}),n.notifiedBuilder=!0))}catch{}return n}function Cn(e){if(!xn($n(e)))return[];let t=Ne(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${ne}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,wt,Ye(),wt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function So(){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(`
163
+ `)}function Pn(){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):",wt,So(),wt]}function kt(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${ne}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",wt,Ye(),wt,"","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 here and run: write the docs for this repo"]}var wt,ne,Rs,ze=ko(()=>{"use strict";wt="-".repeat(64),ne=4;Rs="Re-run dev\u2194docs onboarding (protocol v"});var Li={};nl(Li,{doctorCommand:()=>qt,renderDoctorChecks:()=>Oi,runDoctorChecks:()=>Ui});import{existsSync as Ii}from"node:fs";import{d360GetAll as yu,getAccessToken as ku,isExpired as pr,loadProfileMap as bu,loadTokens as xu,packageSkillsDir as Ni,projectConfigPath as $u,readProjectConfig as vu,DEFAULT_DOCS_DIR as Cu,resolveActiveProfile as Pu,classifyClaudeAuth as Tu,CLAUDE_CODE_SETUP_HINT as _i,resolveModelSetting as Su,devHintsGuidePath as Ru}from"document360-engine";async function Ui(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=Tu();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. ${_i}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:_i});let r=Su(e);t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`});let s=vu(e);if(!s)return t.push({level:"fail",label:`No ${$u(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??Cu).replace(/\/+$/,"");t.push(s.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let h;try{h=Pu(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(w){return t.push({level:"fail",label:`Profile config: ${w.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let b=xu(h.name);b?pr(b)&&!b.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):pr(b)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(b.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${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 k=bu(e,h.name);k?k.projectId&&h.project.projectId&&k.projectId!==h.project.projectId?t.push({level:"fail",label:`Category map projectId (${k.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(k.articles).length} articles, ${Object.keys(k.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${h.name}" (created on first /publish)`}),t.push(Ii(Ni())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Ni()}`,fix:"Reinstall document360-writer (broken install)"});let D=Ne(e);if((Ii(Ru(e))||D.status!=="unset")&&(D.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ne})`}):D.status==="stale"?t.push({level:"warn",label:`Dev hand-off: builder on devhints v${D.completedVersion}, current is v${ne}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}):t.push({level:"warn",label:"Dev hand-off: guide emitted but the builder hasn't completed it",fix:"Have the repo's coding agent run the /devhints prompt (sets up the two-way channel)"})),b&&(!pr(b)||b.refreshToken)){let w={profile:h.name,connection:h.connection};try{await ku(w);let v=await yu(w,"/v3/projects");t.push({level:"ok",label:`API reachable (${h.connection.apiUrl}) \u2014 ${v.length} project(s) visible`})}catch(v){t.push({level:"fail",label:`API call failed: ${v.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}}return t}function Oi(e){let t=[""];for(let r of e){let s=r.level==="ok"?j("\u2713"):r.level==="warn"?L("\u26A0"):x("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${E(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"})`}`):x(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function qt(e,t){console.log(f("Running checks\u2026"));for(let n of Oi(await Ui(t.cwd)))console.log(n);return{kind:"continue"}}var _n=ko(()=>{"use strict";ze();M()});import{Command as qp}from"commander";import{createRequire as Bp}from"node:module";import{AUTH_MODES as Gp}from"document360-engine";import{input as kl}from"@inquirer/prompts";import{loginPkce as bl,refreshTokens as xl,toStoredTokens as hs,clearTokens as $l,decodeJwtClaims as ms,isExpired as vl,loadTokens as Cl,saveTokens as gs,resolveActiveProfile as fn,setProfileProject as Pl,readProjectConfig as Tl}from"document360-engine";M();import{select as il}from"@inquirer/prompts";import{resolveActiveProfile as al,setProfileProject as ll,resolveProjectId as cl,listWorkspaces as ul}from"document360-engine";async function It(e,t){let n=al(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??cl(o);return{workspaces:await ul(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var cs=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function bo(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 pn(e,t,n,o,r){ll(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function us(e,t,n){let o;try{o=await It(e,n)}catch(s){return console.log(x(`Could not list workspaces: ${s.message}`)),1}let r=bo(o.workspaces,t);return r?(pn(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(x(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function ht(e,t){let n;try{n=await It(e,t)}catch(b){console.log(x(`Could not list workspaces: ${b.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 b of o)console.log(` ${b.id===c?E("\u25CF"):" "} ${cs(b)} ${f(b.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await il({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${cs(b)}${b.id===c?" (current)":""}`,value:b.id}))}),h=o.find(b=>b.id===p);pn(e,s,r,p,h?.name),console.log(j(`\u2713 Workspace set to "${h?.name??p}" for profile "${s}".`))}M();import{select as dl}from"@inquirer/prompts";import{resolveActiveProfile as pl,setProfileProject as fl,listProjects as ml}from"document360-engine";async function gt(e,t){let n=pl(e,t),o={profile:n.name,connection:n.connection};return{projects:await ml(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ds=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function ps(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 xo(e,t,n,o){fl(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function fs(e,t){let n;try{n=await gt(e,t)}catch(h){console.log(x(`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?E("\u25CF"):" "} ${ds(h)} ${f(h.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await dl({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${ds(h)}${h.id===s?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===c);xo(e,r,c,p?.name),console.log(j(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}M();import hl from"picocolors";function gl(e=process.env){return e.FORCE_HYPERLINK==="0"||!hl.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 wl(e,t=e,n){return gl(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var yl=/https?:\/\/[^\s\x1b]+/g;function Nt(e,t){return e.replace(yl,n=>wl(n,n,t))}function ws(e){return{...ms(e.idToken)??{},...ms(e.accessToken)??{}}}function mn(e){let t=ws(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 hn(e){let t=fn(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 bl(n,{manual:e.manual,promptForRedirect:s=>kl({message:s})},s=>console.log(Nt(s))),r=hs(t.name,o);if(gs(r),await $o(r,t.name,s=>console.log(f(s))),console.log(""),console.log(j(`\u2713 Logged in to "${t.name}" as ${mn(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Tl(process.cwd())?.profiles?.[t.name]&&(console.log(""),await ht(process.cwd(),t.name))}catch{}}async function $o(e,t,n){let r=ws(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(fn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await gt(process.cwd(),t);c=p.find(h=>h.id===r)?.name}catch{}Pl(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function ys(e){let t=fn(process.cwd(),e.profile),n=t.connection,o=Cl(t.name);if(!o){console.log(x(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${E(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${mn(o)}`),vl(o))if(o.refreshToken)try{let r=hs(t.name,await xl(n,o.refreshToken));gs(r),console.log(j(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(L("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function ks(e){let t=fn(process.cwd(),e.profile);$l(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.`))}M();import{readProjectConfig as bs,writeProjectConfig as Sl,resolveActiveProfile as Rl,loadTokens as Dl,isExpired as jl}from"document360-engine";function gn(e){let t=bs(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(x("No profiles in .d360-writer.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?E("\u25CF "):" ",s=o.production?L(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Dl(n),h=p?jl(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${E(n)} \u2192 ${c}${s} [${h}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function wn(e,t){let n=bs(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(x(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Sl(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(j(`\u2713 Default profile is now "${t}"${o}`))}function yn(e,t){try{let n=Rl(e,t);console.log(""),console.log(`Profile ${E(n.name)}${n.production?L(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(x(n.message)),process.exitCode=1}}M();import{existsSync as Al,readdirSync as El,statSync as Il}from"node:fs";import{join as Nl}from"node:path";import{apiLogDir as _l}from"document360-engine";function xs(){let e=_l();if(console.log(""),console.log(`Document360 API logs: ${E(e)}`),!Al(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=El(e).filter(n=>n.endsWith(".jsonl")).sort().reverse();t.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let n of t.slice(0,14)){let o=(Il(Nl(e,n)).size/1024).toFixed(1);console.log(` ${n} ${f(`${o} 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("")}M();import{createSession as Ul,resolveAuth as Ol,findByName as Ll,slugify as Ml,touchSession as Wl,upsertSession as Fl,resolveActiveProfile as Hl}from"document360-engine";async function $s(e,t,n,o,r,s){let c=Ol(n);c.kind==="none"&&(console.error(""),console.error(x("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${E("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${E("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=Hl(e,r)}catch(w){console.error(x(`Document360 profile error: ${w.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(x("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let h;if(o){let w=Ll(e,o);w||(console.error(x(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),h=w.uuid,console.error(f(`Resuming "${w.name}"`))}let b=Ul({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),k=h??null,D=1;for await(let w of b.send(t))switch(w.type){case"session":if(!k){k=w.sessionId;let v=new Date().toISOString();Fl({uuid:k,name:Ml(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:v,updatedAt:v})}break;case"text":process.stdout.write(w.delta);break;case"tool":console.error(te(` \u2699 ${w.name}`));break;case"result":D=w.ok?0:1,console.error(f(`(${w.inputTokens}\u2192${w.outputTokens} tokens`+(w.costUsd>0?`, $${w.costUsd<.01?w.costUsd.toFixed(4):w.costUsd.toFixed(2)}`:"")+")")),w.ok||console.error(x("agent finished with an error result"));break;case"error":console.error(""),console.error(x(`agent error: ${w.message}`)),process.exit(1)}k&&Wl(k),process.stdout.write(`
164
+ `),process.exit(D)}import{createInterface as wd}from"node:readline/promises";import{createSession as Rr,resolveAuth as yd,getSession as kd,setTitle as bd,slugify as xd,touchSession as ca,upsertSession as $d,generateTitle as vd,resolveActiveProfile as ua,resolveModelSetting as Cd,readProjectConfig as Pd,decodeJwtClaims as aa,isExpired as Td,loadTokens as Sd}from"document360-engine";var _t=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--all|--scope <cat>|<path>] [--run]",desc:"Author the planned articles in parallel (bare = preview + cost; --run starts)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"audit",usage:"/audit",desc:"Gap analysis: code vs docs vs Document360 (what changed)",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"sync",usage:"/sync [pull <path>|--all]",desc:"Drift report local vs Document360; pull portal edits",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"}],ql=[{key:"start",label:"Start here"},{key:"docs",label:"Write & screenshots"},{key:"publish",label:"Publish & keep in sync"},{key:"setup",label:"Setup & health"},{key:"session",label:"Session"}];function kn(){let e=Math.max(..._t.map(n=>n.usage.length))+2,t=["document360-writer \u2014 commands","","New here? Four steps from a fresh repo to published docs:"," 1. /init \u2192 connect, scaffold config, AND print a one-paste hand-off prompt for your source repo"," 2. run that prompt in your repo's coding agent (Claude Code / Codex / Cursor)",' 3. "write the docs for this repo" \u2192 back here, the agent authors the articles'," 4. /publish \u2192 dual-publish to Document360",""," Screenshots are optional \u2014 add them anytime:"," /screenshot --all \u2192 d360-capture capture \u2192 re-/publish"];for(let{key:n,label:o}of ql){t.push("",o);for(let r of _t.filter(s=>s.group===n))t.push(` ${r.usage.padEnd(e)}${r.desc}`)}return t.push("","Tip: anything not starting with / is sent to the agent."),t}function vs(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return _t.filter(n=>n.name.startsWith(t))}function Cs(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}async function vo(){console.log("");for(let e of kn())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}M();import{getSession as Bl}from"document360-engine";async function Ps(e,t){let n=t.currentUuid(),o=n?Bl(n):void 0;return console.log(o?f(`
165
165
  (conversation reset \u2014 "${o.name}" is still available via /resume)
166
166
  `):f(`
167
167
  (conversation reset \u2014 agent will start fresh on the next prompt)
168
- `)),{kind:"clear"}}async function vo(){return{kind:"exit"}}M();ze();import{input as Ut,confirm as Kl}from"@inquirer/prompts";import{basename as Ns,join as Pn}from"node:path";import{existsSync as bt,readFileSync as Jl,readdirSync as Ql,writeFileSync as Zl}from"node:fs";import{writeProjectConfig as _s,readProjectConfig as ec,projectConfigPath as Us,writerDir as tc,DEFAULT_DOCS_DIR as Os,DEFAULT_CAPTURE_DIR as Ls,DEFAULT_OUTPUT_DIR as Ms}from"document360-engine";function Ws(e,t="berlin"){let n=Us(e);if(bt(n))return{created:!1,path:n,profileName:""};let o={projectId:qs(e)??Ns(e),docsDir:Os,captureDir:Ls,outputDir:Ms,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Bs(e)};return _s(o,e),Fs(e),{created:!0,path:n,profileName:t}}function Fs(e){let t=Pn(tc(e),".gitignore");bt(t)||Zl(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
169
- `),"utf8")}async function Hs(){let e=process.cwd(),t=Us(e);if(bt(t)&&!await Kl({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=qs(e)??Ns(e),o=await Ut({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Ut({message:"Capture directory (where document360-capture .spec.ts files live):",default:Ls}),s=await Ut({message:"Screenshot output directory:",default:Ms}),c=await Ut({message:"Default connection profile name:",default:"berlin"}),p=await Ut({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),h={projectId:o,docsDir:Os,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Bs(e)},b=ec(e);b?.terminologyGlossary&&(h.terminologyGlossary=b.terminologyGlossary),_s(h,e),Fs(e);let k=yt(e);console.log(""),console.log(j(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${A(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of kt(k))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${A('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function qs(e){let t=Pn(e,"package.json");if(!bt(t))return null;try{return JSON.parse(Jl(t,"utf8")).name??null}catch{return null}}function Bs(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])bt(Pn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Pn(e,n);bt(o)&&!nc(o)&&t.push(n)}return t}function nc(e){try{return Ql(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}M();import{readMcpConfig as So,writeMcpConfig as Gs}from"document360-engine";async function Tn(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(oc(),{kind:"continue"}):t==="add"?(rc(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(sc(e.slice(1)),{kind:"continue"}):(console.log(x(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function oc(){let e=So(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
168
+ `)),{kind:"clear"}}async function Co(){return{kind:"exit"}}M();ze();import{input as Ot,confirm as Jl}from"@inquirer/prompts";import{basename as _s,join as Tn}from"node:path";import{existsSync as bt,readFileSync as Ql,readdirSync as Zl,writeFileSync as ec}from"node:fs";import{writeProjectConfig as Us,readProjectConfig as tc,projectConfigPath as Os,writerDir as nc,DEFAULT_DOCS_DIR as Ls,DEFAULT_CAPTURE_DIR as Ms,DEFAULT_OUTPUT_DIR as Ws}from"document360-engine";function Fs(e,t="berlin"){let n=Os(e);if(bt(n))return{created:!1,path:n,profileName:""};let o={projectId:Bs(e)??_s(e),docsDir:Ls,captureDir:Ms,outputDir:Ws,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Gs(e)};return Us(o,e),Hs(e),{created:!0,path:n,profileName:t}}function Hs(e){let t=Tn(nc(e),".gitignore");bt(t)||ec(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
169
+ `),"utf8")}async function qs(){let e=process.cwd(),t=Os(e);if(bt(t)&&!await Jl({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Bs(e)??_s(e),o=await Ot({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Ot({message:"Capture directory (where document360-capture .spec.ts files live):",default:Ms}),s=await Ot({message:"Screenshot output directory:",default:Ws}),c=await Ot({message:"Default connection profile name:",default:"berlin"}),p=await Ot({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),h={projectId:o,docsDir:Ls,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Gs(e)},b=tc(e);b?.terminologyGlossary&&(h.terminologyGlossary=b.terminologyGlossary),Us(h,e),Hs(e);let k=yt(e);console.log(""),console.log(j(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${E(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of kt(k))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${E('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Bs(e){let t=Tn(e,"package.json");if(!bt(t))return null;try{return JSON.parse(Ql(t,"utf8")).name??null}catch{return null}}function Gs(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])bt(Tn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Tn(e,n);bt(o)&&!oc(o)&&t.push(n)}return t}function oc(e){try{return Zl(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}M();import{readMcpConfig as Ro,writeMcpConfig as Vs}from"document360-engine";async function Sn(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(rc(),{kind:"continue"}):t==="add"?(sc(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(ic(e.slice(1)),{kind:"continue"}):(console.log(x(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function rc(){let e=Ro(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
170
170
  No MCP servers registered. Add one with /mcp add <name> <type> <ref>
171
- `));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(` ${A(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(` ${A(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function rc(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(x("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(x(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=So(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let h=o[++p],b=h?.match(/^([^:=]+)[:=](.+)$/);if(!b){console.log(x(`-H expects key:value (no spaces). Got: ${h??"(nothing)"}`));return}c[b[1].trim()]=b[2].trim()}else{console.log(x(`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,Gs(r),console.log(""),console.log(j(`\u2713 Registered "${t}" (${n})`)),console.log(L(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function sc(e){let t=e[0];if(!t){console.log(x("Usage: /mcp remove <name>"));return}let n=So();if(!n.servers[t]){console.log(x(`No server named "${t}".`));return}delete n.servers[t],Gs(n),console.log(j(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}M();import{select as bc}from"@inquirer/prompts";import{computeSyncStatus as Uo,planPartitions as xc,relatedArticlePaths as $c,resolveModelForOperation as vc,runPartitioned as Cc}from"document360-engine";import G from"picocolors";import Js from"wrap-ansi";import Io from"string-width";M();import Ne from"picocolors";import Ro from"wrap-ansi";import Do from"string-width";var Vs=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Ys=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),zs=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function ic(e){let t=e.replace(/\r/g,"").split(`
172
- `),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(Vs(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Ys(t[o+1])){let p=zs(r);o+=2;let h=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)h.push(zs(t[o++]));n.push({kind:"table",header:p,rows:h});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);)p.push(t[o++].replace(/^\s*([-*]|\d+\.)\s+/,""));n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Vs(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Ys(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function jo(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ne.bold(t.slice(2,-2)):t.startsWith("`")?A(t.slice(1,-1)):Ne.italic(t.slice(1,-1)))}var ac=(e,t)=>e+" ".repeat(Math.max(0,t-Do(e)));function lc(e,t,n){let o=e.length,r=e.map((C,I)=>Math.max(Do(C),...t.map(U=>Do(U[I]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],h=()=>p.reduce((C,I)=>C+I,0)+c,b=0;for(;h()>s&&b++<1e4;){let C=-1,I=6;for(let U=0;U<o;U++)p[U]>I&&(I=p[U],C=U);if(C===-1)break;p[C]-=1}let k=(C,I,U)=>Ne.gray(C+p.map(H=>"\u2500".repeat(H+2)).join(I)+U),D=Ne.gray("\u2502"),w=(C,I)=>{let U=p.map((ve,oe)=>{let ke=C[oe]??"",se=I?Ne.bold(ke):jo(ke);return Ro(se,ve,{hard:!0}).split(`
173
- `)}),H=Math.max(...U.map(ve=>ve.length)),ee=[];for(let ve=0;ve<H;ve++)ee.push(p.map((oe,ke)=>`${D} ${ac(U[ke][ve]??"",oe)} `).join("")+D);return ee.join(`
174
- `)},v=[k("\u250C","\u252C","\u2510"),w(e,!0)];return v.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((C,I)=>{v.push(w(C,!1)),v.push(I===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),v.join(`
175
- `)}function cc(e,t){switch(e.kind){case"heading":return Ne.bold(e.text);case"hr":return Ne.gray("\u2500".repeat(t));case"para":return Ro(jo(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=Ro(jo(n),Math.max(10,t-4)).split(`
171
+ `));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(` ${E(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(` ${E(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function sc(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(x("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(x(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Ro(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let h=o[++p],b=h?.match(/^([^:=]+)[:=](.+)$/);if(!b){console.log(x(`-H expects key:value (no spaces). Got: ${h??"(nothing)"}`));return}c[b[1].trim()]=b[2].trim()}else{console.log(x(`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,Vs(r),console.log(""),console.log(j(`\u2713 Registered "${t}" (${n})`)),console.log(L(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function ic(e){let t=e[0];if(!t){console.log(x("Usage: /mcp remove <name>"));return}let n=Ro();if(!n.servers[t]){console.log(x(`No server named "${t}".`));return}delete n.servers[t],Vs(n),console.log(j(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}M();import{select as xc}from"@inquirer/prompts";import{computeSyncStatus as Oo,planPartitions as $c,relatedArticlePaths as vc,resolveModelForOperation as Cc,runPartitioned as Pc}from"document360-engine";import V from"picocolors";import Qs from"wrap-ansi";import No from"string-width";M();import _e from"picocolors";import Do from"wrap-ansi";import jo from"string-width";var Ys=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),zs=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Xs=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function ac(e){let t=e.replace(/\r/g,"").split(`
172
+ `),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(Ys(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&zs(t[o+1])){let p=Xs(r);o+=2;let h=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)h.push(Xs(t[o++]));n.push({kind:"table",header:p,rows:h});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);)p.push(t[o++].replace(/^\s*([-*]|\d+\.)\s+/,""));n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Ys(t[o])&&!(t[o].includes("|")&&o+1<t.length&&zs(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function Ao(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?_e.bold(t.slice(2,-2)):t.startsWith("`")?E(t.slice(1,-1)):_e.italic(t.slice(1,-1)))}var lc=(e,t)=>e+" ".repeat(Math.max(0,t-jo(e)));function cc(e,t,n){let o=e.length,r=e.map((C,N)=>Math.max(jo(C),...t.map(U=>jo(U[N]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],h=()=>p.reduce((C,N)=>C+N,0)+c,b=0;for(;h()>s&&b++<1e4;){let C=-1,N=6;for(let U=0;U<o;U++)p[U]>N&&(N=p[U],C=U);if(C===-1)break;p[C]-=1}let k=(C,N,U)=>_e.gray(C+p.map(H=>"\u2500".repeat(H+2)).join(N)+U),D=_e.gray("\u2502"),w=(C,N)=>{let U=p.map((ve,oe)=>{let ke=C[oe]??"",se=N?_e.bold(ke):Ao(ke);return Do(se,ve,{hard:!0}).split(`
173
+ `)}),H=Math.max(...U.map(ve=>ve.length)),ee=[];for(let ve=0;ve<H;ve++)ee.push(p.map((oe,ke)=>`${D} ${lc(U[ke][ve]??"",oe)} `).join("")+D);return ee.join(`
174
+ `)},v=[k("\u250C","\u252C","\u2510"),w(e,!0)];return v.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((C,N)=>{v.push(w(C,!1)),v.push(N===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),v.join(`
175
+ `)}function uc(e,t){switch(e.kind){case"heading":return _e.bold(e.text);case"hr":return _e.gray("\u2500".repeat(t));case"para":return Do(Ao(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=Do(Ao(n),Math.max(10,t-4)).split(`
176
176
  `);return" \u2022 "+o+r.map(s=>`
177
177
  `+s).join("")}).join(`
178
- `);case"code":return e.lines.map(n=>Ne.gray(" "+n)).join(`
179
- `);case"table":return lc(e.header,e.rows,t)}}function Ao(e,t){let n=Math.max(20,t);return ic(e).map(o=>cc(o,n)).join(`
178
+ `);case"code":return e.lines.map(n=>_e.gray(" "+n)).join(`
179
+ `);case"table":return cc(e.header,e.rows,t)}}function Eo(e,t){let n=Math.max(20,t);return ac(e).map(o=>uc(o,n)).join(`
180
180
 
181
- `)}M();import uc from"picocolors";var dc=[127,86,217],pc=[22,38,43],Xs={T:dc,E:pc},Ot=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Eo=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,fc=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Ks(){if(!uc.isColorSupported)return[];let e=Ot[0].length,t=[];for(let n=0;n<Ot.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Xs[Ot[n][r]],c=n+1<Ot.length?Xs[Ot[n+1][r]]:void 0;s&&c?o+=`${Eo(s)}${fc(c)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Eo(s)}\u2580\x1B[39m`:c?o+=`${Eo(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Lt(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function le(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function _e(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var xt=(e,t)=>` ${e.padEnd(13)}${t}`;function mc(e,t){let n=[At("\u270E document360-writer")+G.gray(` v${e.version}`),G.gray(" Reads your code, writes your docs."),"",xt("Claude:",`${e.claude}${G.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),xt("Document360:",e.configured?e.loggedOut?G.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?G.gray(` (${e.sessionHint})`):""}`:G.yellow("not set up \u2014 run /init")),xt("Profile:",e.configured?`${e.profile}${G.gray(` (${e.apiUrl})`)}${e.prod?G.bold(G.yellow(" \u26A0 PRODUCTION")):""}`:G.gray("\u2014 (run /init)")),xt("Project:",e.project),xt("Mode:",G.gray(e.mode)),xt("cwd:",G.gray(e.cwd))],o=Ks();if(o.length===0)return n.join(`
182
- `);let r=2,s=3,c=Io(o[0]);if(!(t>=r+c+s+Math.max(...n.map(k=>Io(k)))))return[...o.map(k=>" "+k),...n].join(`
181
+ `)}M();import dc from"picocolors";var pc=[127,86,217],fc=[22,38,43],Ks={T:pc,E:fc},Lt=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Io=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,mc=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Js(){if(!dc.isColorSupported)return[];let e=Lt[0].length,t=[];for(let n=0;n<Lt.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Ks[Lt[n][r]],c=n+1<Lt.length?Ks[Lt[n+1][r]]:void 0;s&&c?o+=`${Io(s)}${mc(c)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Io(s)}\u2580\x1B[39m`:c?o+=`${Io(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Mt(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function le(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Ue(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var xt=(e,t)=>` ${e.padEnd(13)}${t}`;function hc(e,t){let n=[Et("\u270E document360-writer")+V.gray(` v${e.version}`),V.gray(" Reads your code, writes your docs."),"",xt("Claude:",`${e.claude}${V.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),xt("Document360:",e.configured?e.loggedOut?V.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?V.gray(` (${e.sessionHint})`):""}`:V.yellow("not set up \u2014 run /init")),xt("Profile:",e.configured?`${e.profile}${V.gray(` (${e.apiUrl})`)}${e.prod?V.bold(V.yellow(" \u26A0 PRODUCTION")):""}`:V.gray("\u2014 (run /init)")),xt("Project:",e.project),xt("Mode:",V.gray(e.mode)),xt("cwd:",V.gray(e.cwd))],o=Js();if(o.length===0)return n.join(`
182
+ `);let r=2,s=3,c=No(o[0]);if(!(t>=r+c+s+Math.max(...n.map(k=>No(k)))))return[...o.map(k=>" "+k),...n].join(`
183
183
  `);let h=Math.max(0,Math.floor((n.length-o.length)/2)),b=[];for(let k=0;k<Math.max(o.length+h,n.length);k++){let D=o[k-h]??" ".repeat(c);b.push((" ".repeat(r)+D+" ".repeat(s)+(n[k]??"")).trimEnd())}return b.join(`
184
- `)}var hc={error:G.red,warn:G.yellow,ok:G.green,info:G.gray};function No(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return mc(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(`
185
- `).flatMap(b=>Js(b,s,{hard:!0}).split(`
186
- `)),h=Math.max(0,p.length-c);return h>0&&(p=[...p.slice(0,c),G.dim(`\u2026 +${h} more lines`)]),`
187
- `+p.map((b,k)=>o+(k===0?A(" \u276F "):" ")+b+" ".repeat(Math.max(0,s-Io(b))+1)+r).join(`
184
+ `)}var gc={error:V.red,warn:V.yellow,ok:V.green,info:V.gray};function _o(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return hc(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(`
185
+ `).flatMap(b=>Qs(b,s,{hard:!0}).split(`
186
+ `)),h=Math.max(0,p.length-c);return h>0&&(p=[...p.slice(0,c),V.dim(`\u2026 +${h} more lines`)]),`
187
+ `+p.map((b,k)=>o+(k===0?E(" \u276F "):" ")+b+" ".repeat(Math.max(0,s-No(b))+1)+r).join(`
188
188
  `)}case"assistant":return`
189
- `+Ao(e.text,n);case"tool":{let o=e.arg!==null?G.gray(`${e.sep}(${e.arg})`):"";return`
190
- `+Js(G.green("\u25CF ")+G.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?G.red:G.gray,r=e.lines.map((s,c)=>o((c===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(G.dim(` \u2026 +${e.hidden} lines`)),r.join(`
191
- `)}case"diff":{let o=c=>c===1?"":"s",s=[G.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(G.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
192
- `)}case"link":return e.lines.map(o=>A(It(` \u2B95 ${o}`))).join(`
189
+ `+Eo(e.text,n);case"tool":{let o=e.arg!==null?V.gray(`${e.sep}(${e.arg})`):"";return`
190
+ `+Qs(V.green("\u25CF ")+V.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?V.red:V.gray,r=e.lines.map((s,c)=>o((c===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(V.dim(` \u2026 +${e.hidden} lines`)),r.join(`
191
+ `)}case"diff":{let o=c=>c===1?"":"s",s=[V.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(V.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
192
+ `)}case"link":return e.lines.map(o=>E(Nt(` \u2B95 ${o}`))).join(`
193
193
  `);case"preview":return`
194
- `+At(`\u25A3 Preview \u2014 ${e.name}`)+`
195
-
196
- `+Ao(e.text,n);case"note":return`
197
- `+hc[e.tone](It(e.text));case"done":return`
198
- `+(e.ok?G.magenta("\u2736 "):G.red("\u2736 "))+G.gray(`Cooked for ${Lt(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${le(e.costUsd)}`:""))}}function Qs(e,t){return e.map(n=>No(n,t)).join(`
199
- `)}import{resolveActiveProfile as gc,loadTokens as wc,isExpired as yc,decodeJwtClaims as Zs}from"document360-engine";function kc(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ue(e,t){try{let n=gc(e,t),o=wc(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(yc(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={...Zs(o.idToken)??{},...Zs(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 ${kc(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var Mt=3;function Oo(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(`
200
- `)}var ei={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Wt(e){return e.filter(t=>t.path!==null&&t.status in ei).map(t=>({path:t.path,label:ei[t.status]}))}function Pc(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 ti(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:`${Pc(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 Sn(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(`
201
- `)}function Lo(e,t,n){let o=w=>t[w.index]?.paths.length??0,r=e.filter(w=>w.ok),s=e.filter(w=>!w.ok),c=e.reduce((w,v)=>w+o(v),0),p=r.reduce((w,v)=>w+o(v),0),h=n==="api"?`${le(e.reduce((w,v)=>w+v.costUsd,0))} total`:_e(e.reduce((w,v)=>w+v.outputTokens,0)),b=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,k=w=>`${w} article${w===1?"":"s"}`,D=[];if(s.length===0)D.push(`Published ${k(c)} (${b}) successfully \xB7 ${h}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${k(c)} (${b}) \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 w of s)D.push(` \u2717 ${w.label}${w.error?` \u2014 ${w.error}`:""}`)}return D}async function _o(e,t){let n=xc(t),{model:o}=vc(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${Mt} 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 Cc({cwd:e.cwd,partitions:n,promptFor:s=>Sn(s.paths),concurrency:Mt,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(x(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let s=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let c of Lo(r.results,n,s))console.log(r.ok?j(c):L(c))}}catch(r){console.log(x(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Rn(e,t,n){let o=$c(e,n);if(o.length===0)return[];let r=new Set(Wt((await Uo({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function ni(e,t){let n=Ue(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(x(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Rn(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 _o(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=Wt((await Uo({cwd:t?.cwd??process.cwd()})).entries);return r.length===0?(console.log(j("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):t?await _o(t,r.map(s=>s.path)):{kind:"forward-to-agent",prompt:Sn(r.map(s=>s.path)),display:"/publish --all"}}catch(r){return console.log(x(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let r;try{r=Wt((await Uo({cwd:t?.cwd??process.cwd()})).entries)}catch(s){return console.log(x(`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(()=>bc({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 _o(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Oo(o),display:`/publish ${o}`}}async function Dn(){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 | adopt) | 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(`
202
- `),display:"/audit"}}M();import{checkbox as Tc}from"@inquirer/prompts";import{inventoryRepo as Sc,readProjectConfig as oi,writeProjectConfig as Rc}from"document360-engine";function Mo(e,t){let n=oi(e);n&&(n.authoritativeSourceFiles=t,Rc(n,e))}function jn(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 ri(e,t){let n=t?.cwd??process.cwd();if(!oi(n))return console.log(x("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=Sc(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(A("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(jn(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Tc({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${jn(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"};Mo(n,r),console.log(j(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}M();import{confirm as Ic}from"@inquirer/prompts";import{applyPull as ci,computeSyncStatus as ui,planPull as Nc,D360AuthError as _c}from"document360-engine";M();var si=[{status:"conflict",header:"Conflicts \u2014 both sides changed; pick a direction (/sync pull <path> or /publish <path>):",paint:x,mark:"!"},{status:"local-ahead",header:"Local ahead \u2014 push with /publish <path>:",paint:L,mark:"M"},{status:"remote-ahead",header:"Remote ahead \u2014 pull with /sync pull <path>:",paint:A,mark:"M"},{status:"deleted-local",header:"Deleted locally \u2014 still on Document360 (pull to restore, or remove from the map):",paint:x,mark:"D"},{status:"deleted-remote",header:"Deleted on Document360 \u2014 still local (publish to recreate, or delete the file):",paint:x,mark:"D"},{status:"orphaned",header:"Orphaned map entries \u2014 gone on both sides (remove from d360-category-map.json):",paint:te,mark:"X"},{status:"untracked-local",header:"Untracked local articles \u2014 publish to start tracking:",paint:f,mark:"?"},{status:"untracked-remote",header:"Untracked Document360 articles \u2014 no local file maps to them:",paint:f,mark:"?"},{status:"unknown-base",header:"No sync base recorded yet \u2014 the next /publish or /sync pull of each records one:",paint:te,mark:"\xB7"}];function Dc(e){return e.path?e.path:`${e.title??"(untitled)"} ${te(`[${e.articleId}]`)}`}function An(e){let t=[];for(let c of si){let p=e.entries.filter(h=>h.status===c.status);if(p.length!==0){t.push(""),t.push(Te(c.header));for(let h of p)t.push(` ${c.paint(c.mark)} ${c.paint(Dc(h))}${h.detail?te(` (${h.detail})`):""}`)}}let n=e.counts["in-sync"]??0,o=e.entries.length;t.push("");let r={"in-sync":"in sync","local-ahead":"local ahead","remote-ahead":"remote ahead",conflict:"conflicts","untracked-local":"untracked local","untracked-remote":"untracked remote","deleted-local":"deleted locally","deleted-remote":"deleted on D360",orphaned:"orphaned","unknown-base":"no base yet"},s=o===n?j("\u2713 everything in sync"):[n>0?j(`\u2713 ${n} in sync`):null,...si.map(c=>{let p=e.counts[c.status]??0;return p>0?`${p} ${r[c.status]}`:null})].filter(Boolean).join(te(" \xB7 "));return t.push(s+te(` \xB7 ${o} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/`)),t}import{structuredPatch as jc}from"diff";import ii from"picocolors";var ai=80,Ac="\x1B[48;2;74;28;28m",Ec="\x1B[48;2;24;66;24m",li="\x1B[49m",Wo=e=>String(e).padStart(5);function Xe(e,t,n){let o=w=>{let v=w.replace(/\r\n/g,`
194
+ `+Et(`\u25A3 Preview \u2014 ${e.name}`)+`
195
+
196
+ `+Eo(e.text,n);case"note":return`
197
+ `+gc[e.tone](Nt(e.text));case"done":return`
198
+ `+(e.ok?V.magenta("\u2736 "):V.red("\u2736 "))+V.gray(`Cooked for ${Mt(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${le(e.costUsd)}`:""))}}function Zs(e,t){return e.map(n=>_o(n,t)).join(`
199
+ `)}import{resolveActiveProfile as wc,loadTokens as yc,isExpired as kc,decodeJwtClaims as ei}from"document360-engine";function bc(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Se(e,t){try{let n=wc(e,t),o=yc(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(kc(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let c={...ei(o.idToken)??{},...ei(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 ${bc(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var Wt=3;function Lo(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(`
200
+ `)}var ti={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Ft(e){return e.filter(t=>t.path!==null&&t.status in ti).map(t=>({path:t.path,label:ti[t.status]}))}function Tc(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 ni(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:`${Tc(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 Rn(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(`
201
+ `)}function Mo(e,t,n){let o=w=>t[w.index]?.paths.length??0,r=e.filter(w=>w.ok),s=e.filter(w=>!w.ok),c=e.reduce((w,v)=>w+o(v),0),p=r.reduce((w,v)=>w+o(v),0),h=n==="api"?`${le(e.reduce((w,v)=>w+v.costUsd,0))} total`:Ue(e.reduce((w,v)=>w+v.outputTokens,0)),b=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,k=w=>`${w} article${w===1?"":"s"}`,D=[];if(s.length===0)D.push(`Published ${k(c)} (${b}) successfully \xB7 ${h}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${k(c)} (${b}) \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 w of s)D.push(` \u2717 ${w.label}${w.error?` \u2014 ${w.error}`:""}`)}return D}async function Uo(e,t){let n=$c(t),{model:o}=Cc(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${Wt} 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 Pc({cwd:e.cwd,partitions:n,promptFor:s=>Rn(s.paths),concurrency:Wt,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(x(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let s=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let c of Mo(r.results,n,s))console.log(r.ok?j(c):L(c))}}catch(r){console.log(x(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Dn(e,t,n){let o=vc(e,n);if(o.length===0)return[];let r=new Set(Ft((await Oo({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function oi(e,t){let n=Se(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(x(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Dn(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 Uo(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=Ft((await Oo({cwd:t?.cwd??process.cwd()})).entries);return r.length===0?(console.log(j("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):t?await Uo(t,r.map(s=>s.path)):{kind:"forward-to-agent",prompt:Rn(r.map(s=>s.path)),display:"/publish --all"}}catch(r){return console.log(x(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let r;try{r=Ft((await Oo({cwd:t?.cwd??process.cwd()})).entries)}catch(s){return console.log(x(`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(()=>xc({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 Uo(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Lo(o),display:`/publish ${o}`}}async function jn(){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 | adopt) | 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(`
202
+ `),display:"/audit"}}M();import{checkbox as Sc}from"@inquirer/prompts";import{inventoryRepo as Rc,readProjectConfig as ri,writeProjectConfig as Dc}from"document360-engine";function Wo(e,t){let n=ri(e);n&&(n.authoritativeSourceFiles=t,Dc(n,e))}function An(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 si(e,t){let n=t?.cwd??process.cwd();if(!ri(n))return console.log(x("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=Rc(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(E("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(An(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Sc({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${An(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"};Wo(n,r),console.log(j(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}M();import{confirm as Nc}from"@inquirer/prompts";import{applyPull as ui,computeSyncStatus as di,planPull as _c,D360AuthError as Uc}from"document360-engine";M();var ii=[{status:"conflict",header:"Conflicts \u2014 both sides changed; pick a direction (/sync pull <path> or /publish <path>):",paint:x,mark:"!"},{status:"local-ahead",header:"Local ahead \u2014 push with /publish <path>:",paint:L,mark:"M"},{status:"remote-ahead",header:"Remote ahead \u2014 pull with /sync pull <path>:",paint:E,mark:"M"},{status:"deleted-local",header:"Deleted locally \u2014 still on Document360 (pull to restore, or remove from the map):",paint:x,mark:"D"},{status:"deleted-remote",header:"Deleted on Document360 \u2014 still local (publish to recreate, or delete the file):",paint:x,mark:"D"},{status:"orphaned",header:"Orphaned map entries \u2014 gone on both sides (remove from d360-category-map.json):",paint:te,mark:"X"},{status:"untracked-local",header:"Untracked local articles \u2014 publish to start tracking:",paint:f,mark:"?"},{status:"untracked-remote",header:"Untracked Document360 articles \u2014 no local file maps to them:",paint:f,mark:"?"},{status:"unknown-base",header:"No sync base recorded yet \u2014 the next /publish or /sync pull of each records one:",paint:te,mark:"\xB7"}];function jc(e){return e.path?e.path:`${e.title??"(untitled)"} ${te(`[${e.articleId}]`)}`}function En(e){let t=[];for(let c of ii){let p=e.entries.filter(h=>h.status===c.status);if(p.length!==0){t.push(""),t.push(Te(c.header));for(let h of p)t.push(` ${c.paint(c.mark)} ${c.paint(jc(h))}${h.detail?te(` (${h.detail})`):""}`)}}let n=e.counts["in-sync"]??0,o=e.entries.length;t.push("");let r={"in-sync":"in sync","local-ahead":"local ahead","remote-ahead":"remote ahead",conflict:"conflicts","untracked-local":"untracked local","untracked-remote":"untracked remote","deleted-local":"deleted locally","deleted-remote":"deleted on D360",orphaned:"orphaned","unknown-base":"no base yet"},s=o===n?j("\u2713 everything in sync"):[n>0?j(`\u2713 ${n} in sync`):null,...ii.map(c=>{let p=e.counts[c.status]??0;return p>0?`${p} ${r[c.status]}`:null})].filter(Boolean).join(te(" \xB7 "));return t.push(s+te(` \xB7 ${o} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/`)),t}import{structuredPatch as Ac}from"diff";import ai from"picocolors";var li=80,Ec="\x1B[48;2;74;28;28m",Ic="\x1B[48;2;24;66;24m",ci="\x1B[49m",Fo=e=>String(e).padStart(5);function Xe(e,t,n){let o=w=>{let v=w.replace(/\r\n/g,`
203
203
  `);return v.endsWith(`
204
204
  `)||v===""?v:v+`
205
- `},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=jc("a","b",r,s,"","",{context:3}),h=0,b=0,k=[];p.hunks.forEach((w,v)=>{v>0&&k.push(ii.gray(" \u2026"));let C=w.oldStart,I=w.newStart;for(let U of w.lines){let H=U[0],ee=U.slice(1).slice(0,c);H==="-"?(b++,k.push(`${Ac}${Wo(C++)} - ${ee}${li}`)):H==="+"?(h++,k.push(`${Ec}${Wo(I++)} + ${ee}${li}`)):(k.push(ii.gray(Wo(I))+" "+ee),C++,I++)}});let D=k.slice(0,ai);return{added:h,removed:b,lines:D,hidden:Math.max(0,k.length-ai)}}async function di(e,t){let n=Ue(t.cwd,t.profileName);if(!n.ok)return console.log(x(n.reason)),{kind:"continue"};let o=(e[0]??"status").toLowerCase();try{if(o==="status")return await Uc(t.cwd),{kind:"continue"};if(o==="pull")return await Oc(t,e.slice(1)),{kind:"continue"};console.log(x(`Unknown subcommand: /sync ${o}`)),console.log(f("Usage: /sync drift report (local vs Document360)")),console.log(f(" /sync pull <path> pull portal edits into the local file")),console.log(f(" /sync pull --all pull every remote-ahead article"))}catch(r){r instanceof _c?console.log(x(r.message)):console.log(x(`Sync failed: ${r.message}`))}return{kind:"continue"}}async function Uc(e){console.log(f("Checking Document360 for drift\u2026"));let t=await ui({cwd:e});for(let n of An(t))console.log(n);console.log("")}async function Oc(e,t){let n=t[0];if(!n){console.log(x("Usage: /sync pull <article-path> | --all"));return}let o;if(n==="--all"){if(console.log(f("Checking Document360 for drift\u2026")),o=(await ui({cwd:e.cwd})).entries.filter(s=>s.status==="remote-ahead"&&s.path).map(s=>s.path),o.length===0){console.log(j("\u2713 Nothing is remote-ahead \u2014 no pulls needed.")),console.log(f(" (conflicts are never bulk-pulled; pull them one by one: /sync pull <path>)"));return}console.log(`${Te(String(o.length))} article(s) are remote-ahead.`)}else o=[n.replace(/\\/g,"/")];for(let r of o){let s=await Nc({cwd:e.cwd,relPath:r});console.log(""),console.log(`${A("\u25CF")} ${Te(s.title)} ${te(`(${s.path})`)}`);for(let b of s.notes)console.log(L(` \u26A0 ${b}`));s.overwritesLocalChanges&&console.log(L(" \u26A0 This OVERWRITES local edits made since the last sync."));let c=Xe(s.oldContent,s.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!c){console.log(f(" Local file already matches the remote content \u2014 advancing the sync base only.")),ci({cwd:e.cwd},s);continue}let p=b=>b===1?"":"s";console.log(te(` \u23BF Added ${c.added} line${p(c.added)}, removed ${c.removed} line${p(c.removed)}`));for(let b of c.lines)console.log(b);if(c.hidden>0&&console.log(f(` \u2026 +${c.hidden} more diff lines`)),!await e.withPausedInput(()=>Ic({message:`Write ${s.path}?`,default:!s.overwritesLocalChanges}))){console.log(f(" Skipped."));continue}ci({cwd:e.cwd},s),console.log(j(` \u2713 Pulled ${s.path} (sync base advanced).`))}console.log("")}M();import{statSync as Lc}from"node:fs";import{resolve as Mc}from"node:path";import{estimateBulkCost as Wc,planPartitions as Fc,readProjectConfig as Hc,resolveModelForOperation as qc,runPartitioned as Bc,trackedArticlePaths as Gc}from"document360-engine";var Fo=3;function Ho(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 qo(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Bo(e,t){return t.map(n=>{let o=0;try{o=Lc(Mc(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Go(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:
205
+ `},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=Ac("a","b",r,s,"","",{context:3}),h=0,b=0,k=[];p.hunks.forEach((w,v)=>{v>0&&k.push(ai.gray(" \u2026"));let C=w.oldStart,N=w.newStart;for(let U of w.lines){let H=U[0],ee=U.slice(1).slice(0,c);H==="-"?(b++,k.push(`${Ec}${Fo(C++)} - ${ee}${ci}`)):H==="+"?(h++,k.push(`${Ic}${Fo(N++)} + ${ee}${ci}`)):(k.push(ai.gray(Fo(N))+" "+ee),C++,N++)}});let D=k.slice(0,li);return{added:h,removed:b,lines:D,hidden:Math.max(0,k.length-li)}}async function pi(e,t){let n=Se(t.cwd,t.profileName);if(!n.ok)return console.log(x(n.reason)),{kind:"continue"};let o=(e[0]??"status").toLowerCase();try{if(o==="status")return await Oc(t.cwd),{kind:"continue"};if(o==="pull")return await Lc(t,e.slice(1)),{kind:"continue"};console.log(x(`Unknown subcommand: /sync ${o}`)),console.log(f("Usage: /sync drift report (local vs Document360)")),console.log(f(" /sync pull <path> pull portal edits into the local file")),console.log(f(" /sync pull --all pull every remote-ahead article"))}catch(r){r instanceof Uc?console.log(x(r.message)):console.log(x(`Sync failed: ${r.message}`))}return{kind:"continue"}}async function Oc(e){console.log(f("Checking Document360 for drift\u2026"));let t=await di({cwd:e});for(let n of En(t))console.log(n);console.log("")}async function Lc(e,t){let n=t[0];if(!n){console.log(x("Usage: /sync pull <article-path> | --all"));return}let o;if(n==="--all"){if(console.log(f("Checking Document360 for drift\u2026")),o=(await di({cwd:e.cwd})).entries.filter(s=>s.status==="remote-ahead"&&s.path).map(s=>s.path),o.length===0){console.log(j("\u2713 Nothing is remote-ahead \u2014 no pulls needed.")),console.log(f(" (conflicts are never bulk-pulled; pull them one by one: /sync pull <path>)"));return}console.log(`${Te(String(o.length))} article(s) are remote-ahead.`)}else o=[n.replace(/\\/g,"/")];for(let r of o){let s=await _c({cwd:e.cwd,relPath:r});console.log(""),console.log(`${E("\u25CF")} ${Te(s.title)} ${te(`(${s.path})`)}`);for(let b of s.notes)console.log(L(` \u26A0 ${b}`));s.overwritesLocalChanges&&console.log(L(" \u26A0 This OVERWRITES local edits made since the last sync."));let c=Xe(s.oldContent,s.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!c){console.log(f(" Local file already matches the remote content \u2014 advancing the sync base only.")),ui({cwd:e.cwd},s);continue}let p=b=>b===1?"":"s";console.log(te(` \u23BF Added ${c.added} line${p(c.added)}, removed ${c.removed} line${p(c.removed)}`));for(let b of c.lines)console.log(b);if(c.hidden>0&&console.log(f(` \u2026 +${c.hidden} more diff lines`)),!await e.withPausedInput(()=>Nc({message:`Write ${s.path}?`,default:!s.overwritesLocalChanges}))){console.log(f(" Skipped."));continue}ui({cwd:e.cwd},s),console.log(j(` \u2713 Pulled ${s.path} (sync base advanced).`))}console.log("")}M();import{statSync as Mc}from"node:fs";import{resolve as Wc}from"node:path";import{estimateBulkCost as Fc,planPartitions as Hc,readProjectConfig as qc,resolveModelForOperation as Bc,runPartitioned as Gc,trackedArticlePaths as Vc}from"document360-engine";var Ho=3;function qo(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 Bo(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Go(e,t){return t.map(n=>{let o=0;try{o=Mc(Wc(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Vo(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:
206
206
  - 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.
207
207
  - 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.
208
208
  - 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.
209
209
  - Work only on these files:
210
210
  `+e.paths.map(t=>`- ${t}`).join(`
211
- `)}function Vo(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: ${le(r)}\u2013${le(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Yo(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,I)=>C+o(I),0),p=r.reduce((C,I)=>C+o(I),0),h=e.reduce((C,I)=>C+I.costUsd,0),b=e.reduce((C,I)=>C+I.outputTokens,0),k=n==="api"?`${le(h)} total`:_e(b),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,w=C=>`${C} article${C===1?"":"s"}`,v=[];if(s.length===0)v.push(`Converted ${w(c)} (${D}) successfully \xB7 ${k}.`);else{v.push(`Converted ${p}/${w(c)} (${D}) \xB7 ${k}.`),v.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)v.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return v}async function pi(e,t){if(!Hc(t.cwd))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Ho(e),r=Gc(t.cwd,t.profileName);if(r.length===0)return console.log(x("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=qo(r,n);if(s.length===0)return console.log(x(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=Fc(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:h,forced:b}=qc(t.cwd,"light");if(!o){let k=Wc({files:Bo(t.cwd,s),op:"convert",model:h});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let D of Vo(c,k,Fo))console.log(D);return console.log(f(`Model: ${h}${b?" (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${Fo} 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 k of Bc({cwd:t.cwd,partitions:c,promptFor:Go,concurrency:Fo,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:h}))if(k.type==="partition_status")k.status==="running"?console.log(f(` \u25B8 ${k.label} \u2014 converting\u2026`)):k.status==="done"?console.log(j(` \u2713 ${k.label}`)):console.log(x(` \u2717 ${k.label}`));else if(k.type==="run_done"){console.log("");let D=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let w of Yo(k.results,c,D))console.log(k.ok?j(w):L(w))}}catch(k){console.log(x(`Convert run failed: ${k.message}`))}return console.log(""),{kind:"continue"}}M();import{statSync as fi}from"node:fs";import{resolve as mi}from"node:path";import{estimateBulkCost as Vc,planPartitions as Yc,readDocsPlan as zc,readProjectConfig as hi,DEFAULT_DOCS_DIR as Xc,resolveModelForOperation as Kc,runPartitioned as Jc}from"document360-engine";var zo=5;function Xo(e){let t,n,o=!1;for(let s=0;s<e.length;s++){let c=e[s];if(c==="--run"||c==="--yes")o=!0;else{if(c==="--all")continue;c==="--scope"?t=e[++s]:c?.startsWith("--scope=")?t=c.slice(8):c&&!c.startsWith("--")&&(n=c)}}let r=s=>s?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:r(t),path:r(n),run:o}}function Qc(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Zc(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function eu(e,t,n){return n.filter(o=>{try{return fi(mi(e,t,o)).size===0}catch{return!0}})}function Ko(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+=fi(mi(e,c)).size}catch{}return{path:r,bytes:s}})}function Jo(e,t){return`Run the write-article skill to author EACH documentation article listed below. For each path:
211
+ `)}function Yo(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: ${le(r)}\u2013${le(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function zo(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),h=e.reduce((C,N)=>C+N.costUsd,0),b=e.reduce((C,N)=>C+N.outputTokens,0),k=n==="api"?`${le(h)} total`:Ue(b),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,w=C=>`${C} article${C===1?"":"s"}`,v=[];if(s.length===0)v.push(`Converted ${w(c)} (${D}) successfully \xB7 ${k}.`);else{v.push(`Converted ${p}/${w(c)} (${D}) \xB7 ${k}.`),v.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)v.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return v}async function fi(e,t){if(!qc(t.cwd))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=qo(e),r=Vc(t.cwd,t.profileName);if(r.length===0)return console.log(x("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Bo(r,n);if(s.length===0)return console.log(x(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=Hc(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:h,forced:b}=Bc(t.cwd,"light");if(!o){let k=Fc({files:Go(t.cwd,s),op:"convert",model:h});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let D of Yo(c,k,Ho))console.log(D);return console.log(f(`Model: ${h}${b?" (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${Ho} 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 k of Gc({cwd:t.cwd,partitions:c,promptFor:Vo,concurrency:Ho,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:h}))if(k.type==="partition_status")k.status==="running"?console.log(f(` \u25B8 ${k.label} \u2014 converting\u2026`)):k.status==="done"?console.log(j(` \u2713 ${k.label}`)):console.log(x(` \u2717 ${k.label}`));else if(k.type==="run_done"){console.log("");let D=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let w of zo(k.results,c,D))console.log(k.ok?j(w):L(w))}}catch(k){console.log(x(`Convert run failed: ${k.message}`))}return console.log(""),{kind:"continue"}}M();import{statSync as mi}from"node:fs";import{resolve as hi}from"node:path";import{estimateBulkCost as Yc,planPartitions as zc,readDocsPlan as Xc,readProjectConfig as gi,DEFAULT_DOCS_DIR as Kc,resolveModelForOperation as Jc,runPartitioned as Qc}from"document360-engine";var Xo=5;function Ko(e){let t,n,o=!1;for(let s=0;s<e.length;s++){let c=e[s];if(c==="--run"||c==="--yes")o=!0;else{if(c==="--all")continue;c==="--scope"?t=e[++s]:c?.startsWith("--scope=")?t=c.slice(8):c&&!c.startsWith("--")&&(n=c)}}let r=s=>s?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:r(t),path:r(n),run:o}}function Zc(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function eu(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function tu(e,t,n){return n.filter(o=>{try{return mi(hi(e,t,o)).size===0}catch{return!0}})}function Jo(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+=mi(hi(e,c)).size}catch{}return{path:r,bytes:s}})}function Qo(e,t){return`Run the write-article skill to author EACH documentation article listed below. For each path:
212
212
  - 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).
213
213
  - 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.
214
214
  - Write the finished article to ${t}/<path>, following the write-article structure and the project terminologyGlossary. Add the \`sources:\` frontmatter listing the files you actually read.
@@ -216,55 +216,55 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
216
216
  - 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.
217
217
  Articles:
218
218
  `+e.paths.map(n=>`- ${n}`).join(`
219
- `)}function Qo(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: ${le(r)}\u2013${le(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write --run to start."]}function Zo(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,I)=>C+o(I),0),p=r.reduce((C,I)=>C+o(I),0),h=e.reduce((C,I)=>C+I.costUsd,0),b=e.reduce((C,I)=>C+I.outputTokens,0),k=n==="api"?`${le(h)} total`:_e(b),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,w=C=>`${C} article${C===1?"":"s"}`,v=[];if(s.length===0)v.push(`Wrote ${w(c)} (${D}) successfully \xB7 ${k}.`),v.push("Next \u2014 push them to Document360:"),v.push("/publish --all"),v.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{v.push(`Wrote ${p}/${w(c)} (${D}) \xB7 ${k}.`),v.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)v.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return v}function er(e,t,n){let o=(hi(e)?.docsDir??Xc).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Qc(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=Zc(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};let c=eu(e,o,s);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one.`}}return{docsDir:o,targets:c,planCount:r.length}}async function gi(e,t){if(!hi(t.cwd))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=zc(t.cwd);if(n.length===0)return console.log(x("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,run:s}=Xo(e),{docsDir:c,targets:p,reason:h}=er(t.cwd,n,{scope:o,path:r});if(p.length===0)return console.log(h?L(h):L("Nothing to write.")),{kind:"continue"};let b=Yc(p),{model:k,forced:D}=Kc(t.cwd,"standard");if(!s&&!!!r){let v=Vc({files:Ko(t.cwd,n,p),op:"write",model:k});o&&console.log(f(`Scope: ${o} (${p.length} pending).`));for(let C of Qo(b,v,zo))console.log(C);return console.log(f(`Model: ${k}${D?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:" --all"} --run to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${p.length} article${p.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${zo} agents at once) on ${k}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let v of Jc({cwd:t.cwd,partitions:b,promptFor:C=>Jo(C,c),concurrency:zo,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:k}))if(v.type==="partition_status")v.status==="running"?console.log(f(` \u25B8 ${v.label} \u2014 writing\u2026`)):v.status==="done"?console.log(j(` \u2713 ${v.label}`)):console.log(x(` \u2717 ${v.label}`));else if(v.type==="run_done"){console.log("");let C=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let I of Zo(v.results,b,C))console.log(v.ok?j(I):L(I))}}catch(v){console.log(x(`Write run failed: ${v.message}`))}return console.log(""),{kind:"continue"}}M();import{existsSync as tu,readdirSync as wi,statSync as yi}from"node:fs";import{join as ki}from"node:path";import{inputDir as nu,readProjectConfig as ou}from"document360-engine";var bi=/\.(md|markdown|pdf|txt)$/i;function tr(e){let t=nu(e);if(!tu(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of wi(t)){let s=ki(t,r),c=!1;try{c=yi(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=ru(s);p>0&&n.push({name:r,docCount:p})}else bi.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function ru(e){let t=0;for(let n of wi(e))try{yi(ki(e,n)).isFile()&&bi.test(n)&&t++}catch{}return t}function nr(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 En(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 --all. Do NOT write the articles in this turn."].filter(Boolean).join(`
220
- `)}var or="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function xi(e,t){let n=t?.cwd??process.cwd();if(!ou(n))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=tr(n);if(o.length===0&&r===0)return console.log(f(or)),{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:En(p),display:p?`/draft ${p}`:"/draft"}}let c=nr(o,s);return{kind:"forward-to-agent",prompt:En(c??"",c?void 0:s),display:`/draft ${s}`}}M();import{listOpenForDocs as su,readProjectConfig as iu}from"document360-engine";function rr(e){try{return su(e).filter(t=>t.kind==="request").length}catch{return 0}}function sr(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function ir(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(`
221
- `)}var ar="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 $i(e,t){let n=t?.cwd??process.cwd();if(!iu(n))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=sr(e);if(!r&&rr(n)===0)return console.log(f(ar)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:ir(r,o),display:s}}M();import{search as au}from"@inquirer/prompts";import{findByName as lu,getSession as cu,listSessions as uu,relativeTime as Ci}from"document360-engine";async function Pi(e,t){let n=uu(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=lu(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(x(`No session matches "${o}".`)),vi(n),{kind:"continue"})}if(!process.stdin.isTTY)return vi(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>au({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} ${Ci(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=cu(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function vi(e){console.log("");for(let t of e.slice(0,15))console.log(` ${A(t.name)} ${f(Ci(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}M();import{renameSession as du}from"document360-engine";function lr(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 Ti(e,t){let n=lr(e.join(" "));if(!n)return console.log(x("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(du(o,n)?console.log(j(`\u2713 Session renamed to "${n}"`)):console.log(x("Could not find the current session record.")),{kind:"continue"}):(console.log(x("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as Si,readProjectConfig as pu,writeProjectConfig as fu}from"document360-engine";M();function cr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=pu(e);if(!o)return"No .d360-writer.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return Si().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},fu(o,e),null):`Unknown environment "${r}". Known: ${Si().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function Ri(e,t){let n=e[0];if(!n)return hn(t.cwd),{kind:"continue"};if(n==="add"){let o=cr(t.cwd,e[1],e[2]);return o?(console.log(x(o)),{kind:"continue"}):(console.log(j(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${A(`/profile ${e[1]}`)} then ${A("/login")}`),{kind:"continue"})}return gn(t.cwd,n),wn(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}M();import{select as mu}from"@inquirer/prompts";import{readProjectConfig as hu,readUserConfig as Di,resolveModelSetting as ur,writeUserConfig as ji}from"document360-engine";var xe=[{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 In(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=xe.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function gu(e){switch(e.source){case"project":return".d360-writer.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"claude-settings":return"Claude Code's own settings (~/.claude/settings.json)";case"claude-default":return"Claude Code default (no override configured)"}}function Ft(e,t){let n=()=>{let s=ur(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Di();return s.defaultModel?(delete s.defaultModel,ji(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${ur(e).model??"Claude Code default"} (applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}ji({...Di(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=hu(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function Ai(e,t){let n=e[0]?.trim();if(!n){let c=ur(t.cwd);if(!process.stdin.isTTY)return console.log(`${Te("Model:")} ${A(c.model??"Claude Code default")}`),console.log(f(` source: ${gu(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=In(c),h;try{h=await t.withPausedInput(()=>mu({message:`Select model (current: ${c.model??"Claude Code default"})`,default:xe[p].value,choices:xe.map((w,v)=>({name:`${w.label}${v===p?" \u2714":""}`,value:w.value,description:w.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:b,changed:k,effective:D}=Ft(t.cwd,h??"default");for(let w of b)console.log(w.startsWith("\u26A0")?L(w):w.startsWith("\u2713")?j(w):f(w));return k&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Ft(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?L(c):c.startsWith("\u2713")?j(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}Nn();async function Li(e,t){return await t.withPausedInput(()=>ht(t.cwd)),{kind:"clear"}}async function Mi(e,t){return await t.withPausedInput(()=>ps(t.cwd,t.profileName)),{kind:"clear"}}M();import{resolveActiveProfile as Ru}from"document360-engine";async function Wi(e,t){let n=!1;try{n=Ru(t.cwd).production}catch{}return n?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}M();var Fi=async(e,t)=>{try{await t.withPausedInput(()=>mn({}))}catch(n){console.log(x(`Login failed: ${n.message}`))}return{kind:"continue"}};M();import{resolveActiveProfile as Du,clearTokens as ju,clearProfileProject as Au}from"document360-engine";async function Hi(e,t){let n;try{n=Du(t.cwd,t.profileName).name}catch(r){return console.log(x(r.message)),{kind:"continue"}}let o=ju(n);return Au(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 qi}from"node:fs";import{isAbsolute as Eu,join as Iu,resolve as Nu}from"node:path";import{readProjectConfig as _u,screenshotPlaceholderIds as Uu,DEFAULT_CAPTURE_DIR as Ou,DEFAULT_OUTPUT_DIR as Lu}from"document360-engine";var Bi=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function pr(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Bi(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Bi(o),setup:t}:{mode:"single",id:o}}function fr(e,t){let n=_u(e),o=n?.captureDir??Ou,r=n?.outputDir??Lu,s=(c,p)=>Eu(c)?Iu(c,p):Nu(e,c,p);return Uu(e,{scope:t}).map(({id:c,file:p})=>{let h=qi(s(r,`${c}.png`))?"captured":qi(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:h}})}var Mu={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Wu={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function mr(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(` ${Mu[c.state]} ${c.id.padEnd(34)} ${Wu[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Gi(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(`
219
+ `)}function Zo(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: ${le(r)}\u2013${le(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write --run to start."]}function er(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),h=e.reduce((C,N)=>C+N.costUsd,0),b=e.reduce((C,N)=>C+N.outputTokens,0),k=n==="api"?`${le(h)} total`:Ue(b),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,w=C=>`${C} article${C===1?"":"s"}`,v=[];if(s.length===0)v.push(`Wrote ${w(c)} (${D}) successfully \xB7 ${k}.`),v.push("Next \u2014 push them to Document360:"),v.push("/publish --all"),v.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{v.push(`Wrote ${p}/${w(c)} (${D}) \xB7 ${k}.`),v.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)v.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return v}function tr(e,t,n){let o=(gi(e)?.docsDir??Kc).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Zc(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=eu(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};let c=tu(e,o,s);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one.`}}return{docsDir:o,targets:c,planCount:r.length}}async function wi(e,t){if(!gi(t.cwd))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=Xc(t.cwd);if(n.length===0)return console.log(x("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,run:s}=Ko(e),{docsDir:c,targets:p,reason:h}=tr(t.cwd,n,{scope:o,path:r});if(p.length===0)return console.log(h?L(h):L("Nothing to write.")),{kind:"continue"};let b=zc(p),{model:k,forced:D}=Jc(t.cwd,"standard");if(!s&&!!!r){let v=Yc({files:Jo(t.cwd,n,p),op:"write",model:k});o&&console.log(f(`Scope: ${o} (${p.length} pending).`));for(let C of Zo(b,v,Xo))console.log(C);return console.log(f(`Model: ${k}${D?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:" --all"} --run to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${p.length} article${p.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${Xo} agents at once) on ${k}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let v of Qc({cwd:t.cwd,partitions:b,promptFor:C=>Qo(C,c),concurrency:Xo,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:k}))if(v.type==="partition_status")v.status==="running"?console.log(f(` \u25B8 ${v.label} \u2014 writing\u2026`)):v.status==="done"?console.log(j(` \u2713 ${v.label}`)):console.log(x(` \u2717 ${v.label}`));else if(v.type==="run_done"){console.log("");let C=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let N of er(v.results,b,C))console.log(v.ok?j(N):L(N))}}catch(v){console.log(x(`Write run failed: ${v.message}`))}return console.log(""),{kind:"continue"}}M();import{existsSync as nu,readdirSync as yi,statSync as ki}from"node:fs";import{join as bi}from"node:path";import{inputDir as ou,readProjectConfig as ru}from"document360-engine";var xi=/\.(md|markdown|pdf|txt)$/i;function nr(e){let t=ou(e);if(!nu(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of yi(t)){let s=bi(t,r),c=!1;try{c=ki(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=su(s);p>0&&n.push({name:r,docCount:p})}else xi.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function su(e){let t=0;for(let n of yi(e))try{ki(bi(e,n)).isFile()&&xi.test(n)&&t++}catch{}return t}function or(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 In(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 --all. Do NOT write the articles in this turn."].filter(Boolean).join(`
220
+ `)}var rr="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function $i(e,t){let n=t?.cwd??process.cwd();if(!ru(n))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=nr(n);if(o.length===0&&r===0)return console.log(f(rr)),{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:In(p),display:p?`/draft ${p}`:"/draft"}}let c=or(o,s);return{kind:"forward-to-agent",prompt:In(c??"",c?void 0:s),display:`/draft ${s}`}}M();import{listOpenForDocs as iu,readProjectConfig as au}from"document360-engine";function sr(e){try{return iu(e).filter(t=>t.kind==="request").length}catch{return 0}}function ir(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function ar(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(`
221
+ `)}var lr="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 vi(e,t){let n=t?.cwd??process.cwd();if(!au(n))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=ir(e);if(!r&&sr(n)===0)return console.log(f(lr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:ar(r,o),display:s}}M();import{search as lu}from"@inquirer/prompts";import{findByName as cu,getSession as uu,listSessions as du,relativeTime as Pi}from"document360-engine";async function Ti(e,t){let n=du(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=cu(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(x(`No session matches "${o}".`)),Ci(n),{kind:"continue"})}if(!process.stdin.isTTY)return Ci(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>lu({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} ${Pi(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=uu(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Ci(e){console.log("");for(let t of e.slice(0,15))console.log(` ${E(t.name)} ${f(Pi(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}M();import{renameSession as pu}from"document360-engine";function cr(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 Si(e,t){let n=cr(e.join(" "));if(!n)return console.log(x("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(pu(o,n)?console.log(j(`\u2713 Session renamed to "${n}"`)):console.log(x("Could not find the current session record.")),{kind:"continue"}):(console.log(x("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as Ri,readProjectConfig as fu,writeProjectConfig as mu}from"document360-engine";M();function ur(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=fu(e);if(!o)return"No .d360-writer.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return Ri().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},mu(o,e),null):`Unknown environment "${r}". Known: ${Ri().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function Di(e,t){let n=e[0];if(!n)return gn(t.cwd),{kind:"continue"};if(n==="add"){let o=ur(t.cwd,e[1],e[2]);return o?(console.log(x(o)),{kind:"continue"}):(console.log(j(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${E(`/profile ${e[1]}`)} then ${E("/login")}`),{kind:"continue"})}return wn(t.cwd,n),yn(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}M();import{select as hu}from"@inquirer/prompts";import{readProjectConfig as gu,readUserConfig as ji,resolveModelSetting as dr,writeUserConfig as Ai}from"document360-engine";var xe=[{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 Nn(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=xe.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function wu(e){switch(e.source){case"project":return".d360-writer.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"claude-settings":return"Claude Code's own settings (~/.claude/settings.json)";case"claude-default":return"Claude Code default (no override configured)"}}function Ht(e,t){let n=()=>{let s=dr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=ji();return s.defaultModel?(delete s.defaultModel,Ai(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${dr(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}}Ai({...ji(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=gu(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function Ei(e,t){let n=e[0]?.trim();if(!n){let c=dr(t.cwd);if(!process.stdin.isTTY)return console.log(`${Te("Model:")} ${E(c.model??"Claude Code default")}`),console.log(f(` source: ${wu(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Nn(c),h;try{h=await t.withPausedInput(()=>hu({message:`Select model (current: ${c.model??"Claude Code default"})`,default:xe[p].value,choices:xe.map((w,v)=>({name:`${w.label}${v===p?" \u2714":""}`,value:w.value,description:w.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:b,changed:k,effective:D}=Ht(t.cwd,h??"default");for(let w of b)console.log(w.startsWith("\u26A0")?L(w):w.startsWith("\u2713")?j(w):f(w));return k&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Ht(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?L(c):c.startsWith("\u2713")?j(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}_n();async function Mi(e,t){return await t.withPausedInput(()=>ht(t.cwd)),{kind:"clear"}}async function Wi(e,t){return await t.withPausedInput(()=>fs(t.cwd,t.profileName)),{kind:"clear"}}M();import{resolveActiveProfile as Du}from"document360-engine";async function Fi(e,t){let n=!1;try{n=Du(t.cwd).production}catch{}return n?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}M();var Hi=async(e,t)=>{try{await t.withPausedInput(()=>hn({}))}catch(n){console.log(x(`Login failed: ${n.message}`))}return{kind:"continue"}};M();import{resolveActiveProfile as ju,clearTokens as Au,clearProfileProject as Eu}from"document360-engine";async function qi(e,t){let n;try{n=ju(t.cwd,t.profileName).name}catch(r){return console.log(x(r.message)),{kind:"continue"}}let o=Au(n);return Eu(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 Bi}from"node:fs";import{isAbsolute as Iu,join as Nu,resolve as _u}from"node:path";import{readProjectConfig as Uu,screenshotPlaceholderIds as Ou,DEFAULT_CAPTURE_DIR as Lu,DEFAULT_OUTPUT_DIR as Mu}from"document360-engine";var Gi=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function fr(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Gi(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Gi(o),setup:t}:{mode:"single",id:o}}function mr(e,t){let n=Uu(e),o=n?.captureDir??Lu,r=n?.outputDir??Mu,s=(c,p)=>Iu(c)?Nu(c,p):_u(e,c,p);return Ou(e,{scope:t}).map(({id:c,file:p})=>{let h=Bi(s(r,`${c}.png`))?"captured":Bi(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:h}})}var Wu={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Fu={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function hr(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(` ${Wu[c.state]} ${c.id.padEnd(34)} ${Fu[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Vi(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(`
222
222
  `),"","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(`
223
- `)}async function _n(e,t){let n=pr(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of mr(fr(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(`
223
+ `)}async function Un(e,t){let n=fr(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of hr(mr(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(`
224
224
  `),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(`
225
- `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as Fu,readFileSync as Hu}from"node:fs";import{isAbsolute as qu,join as Bu,resolve as Gu}from"node:path";import{readProjectConfig as Vu,DEFAULT_CAPTURE_DIR as Yu}from"document360-engine";async function qt(){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(`
226
- `),display:"/capture-setup"}}var Vi="-".repeat(64);function hr(e){let t=Yu;try{let k=Vu(e);k?.captureDir&&(t=k.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=qu(t)?Bu(t,"CAPTURE-TESTID-REQUESTS.json"):Gu(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Fu(n))return null;let o;try{let k=JSON.parse(Hu(n,"utf8").replace(/^/,""));o=Array.isArray(k?.requests)?k.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(k=>k.file).filter(Boolean)).size,s=o.length,c=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,h=`${t}/CAPTURE-TESTID-REQUESTS.md`,b=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${c} requested across ${p}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",Vi,`Read ${h} and ${b}. They list ${c} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",Vi]}ze();M();import{listOpenForDocs as zu,readProjectConfig as Xu}from"document360-engine";function gr(e){try{return zu(e).length}catch{return 0}}function wr(){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(`
227
- `)}async function Yi(e,t){let n=t?.cwd??process.cwd();return Xu(n)?gr(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:wr(),display:"/inbox"}:(console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"})}M();import{listOpenHints as Ku,listOpenForDocs as Ju,readProjectConfig as Qu}from"document360-engine";function $t(e){let t=0,n=0,o=0;try{t=Ku(e).length}catch{}try{let r=Ju(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 vt(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 yr(e){return{publish:e.includes("--publish")}}function kr({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. Trust the inventory first \u2014 call d360_sync_status. If anything is in conflict or remote-ahead, STOP and tell me what to resolve (never write over a copy you can't trust).","2. Gather the pending work: d360_pending_hints (the builder's per-change hints) AND d360_inbox (open requests + answers).","3. Decide the right doc actions across all of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), and fold any answers into the affected article(s) + the architecture brief.","4. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","5. Write/update the articles as drafts, grounded in the cited sources.","6. Close the loop: stamp consumed hints, and mark handled messages status: done with resulting_articles.","7. Push the drafts to Document360."];return t.push(e?"8. 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(`
228
- `)}async function zi(e,t){let n=t?.cwd??process.cwd();if(!Qu(n))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ue(n,t?.profileName);if(!o.ok)return console.log(x(o.reason)),{kind:"continue"};let{publish:r}=yr(e),s=vt($t(n));return console.log(f(s?`Catching up on ${s} (+ checking Document360 for drift)\u2026`:"No local queue \u2014 checking for code changes and drift\u2026")),{kind:"forward-to-agent",prompt:kr({publish:r}),display:`/catch-up${r?" --publish":""}`}}M();import{spawn as Zu}from"node:child_process";var Ke="document360-writer",Un=`npm i -g ${Ke}@latest`;async function On(){return new Promise(e=>{let t="";try{let n=Zu("npm",["i","-g",`${Ke}@latest`],{stdio:["ignore","pipe","pipe"],shell:process.platform==="win32"});n.stdout?.on("data",o=>t+=String(o)),n.stderr?.on("data",o=>t+=String(o)),n.on("error",o=>e({ok:!1,output:String(o)})),n.on("close",o=>e({ok:o===0,output:t.trim()}))}catch(n){e({ok:!1,output:String(n)})}})}async function Xi(){return console.log(f(`Updating ${Ke}\u2026`)),(await On()).ok?console.log(j("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(x(`Update failed \u2014 run manually: ${Un}`)),{kind:"continue"}}M();ze();import{existsSync as br,rmSync as ed}from"node:fs";import{basename as Ki,resolve as xr}from"node:path";import{execFileSync as td}from"node:child_process";import{input as nd}from"@inquirer/prompts";import{readProjectConfig as od,devHintsGuidePath as rd}from"document360-engine";var sd=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],id=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Ln=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Ji=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Qi(e){let t=Ln(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Ji(t)?!0:id.has(t)}function $r(e){let t=null;try{t=od(e)}catch{t=null}let n=new Set(sd);for(let o of[Ln(t?.docsDir),Ln(t?.captureDir),Ln(t?.outputDir)])o&&Ji(o)&&n.add(o);return[...n].filter(o=>Qi(o)&&br(xr(e,o)))}function vr(e,t){let n=[],o=[];for(let r of t){if(!Qi(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{ed(xr(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Zi(e,t){try{return td("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
229
- `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function ad(e){return Zi(e,".d360-writer/hints")}function ld(e){return Zi(e,".d360-writer/messages")}function Cr(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=ad(e),o=ld(e),r=br(xr(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(s=>` \u2022 ${s}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o>0?[`\u26A0 ${o} message(s) under .d360-writer/messages/ are not committed \u2014 commit them first or they're gone.`]:[],...r?["Protected: root user-docs/ is NOT touched (only .d360-writer/ is removed)."]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${Ki(e)}`]}async function ea(e,t){let n=$r(t.cwd);for(let h of Cr(t.cwd,n))console.log(n.length===0?f(h):h);if(n.length===0)return{kind:"continue"};let o=Ki(t.cwd);if((await t.withPausedInput(()=>nd({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=br(rd(t.cwd)),{removed:c,failed:p}=vr(t.cwd,n);console.log(j(`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`));for(let h of p)console.log(x(` \u2717 ${h.path}: ${h.error}`));if(s){for(let h of Cn())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"}}var ta={help:$o,"?":$o,clear:Cs,exit:vo,quit:vo,init:Hs,mcp:Tn,publish:ni,audit:Dn,scope:ri,sync:di,convert:pi,write:gi,draft:xi,document:$i,resume:Pi,rename:Ti,profile:Ri,model:Ai,doctor:Ht,workspace:Li,project:Mi,"allow-prod":Wi,login:Fi,logout:Hi,screenshot:_n,"capture-setup":qt,devhints:As,inbox:Yi,"catch-up":zi,update:Xi,reset:ea};function na(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}ze();M();var cd={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"},ra=160,Tr=200,sa=40;function pe(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function oa(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}: ${pe(typeof r=="string"?r:JSON.stringify(r),sa)}`);return t.length>4&&n.push("\u2026"),pe(n.join(", "),ra)}var Oe=e=>typeof e=="string"&&e?e:null,Pr=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function ud(e){let t=Oe(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 dd(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Oe(t.title);if(!o)return null;let r=ud(t.local_path);return n("Create article",`"${pe(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Oe(t.title),r=Pr(t.article_id);return n("Update article",o?`"${pe(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Pr(t.article_id)?`id ${Pr(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",Oe(t.name)?`"${pe(Oe(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Oe(t.file_path);return n("Upload image",o?pe(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Mn(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),c=s.join("__");if(r==="document360"){let b=dd(c,t);if(b)return b}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:oa(t)}}let n=cd[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:pe(o,ra)}:{title:e,sep:"",arg:oa(t)}}function pd(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 fd(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(pd).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>pe(r,Tr))]}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}: ${pe(String(r),sa)}`);return n.length>0?[pe(n.join(" \xB7 "),Tr)]:null}return null}function md(e){let t=Oe(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function hd(e,t,n){switch(e){case"d360_create_article":{let o=md(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=Oe(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 ${pe(o[0],120)}`:""}`]}default:return null}}function Wn(e,t=4,n,o){let r=e.replace(/\r\n/g,`
230
- `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=hd(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let s=fd(r)??r.split(`
231
- `);return{lines:s.slice(0,t).map(c=>pe(c,Tr)),hidden:Math.max(0,s.length-t)}}function Fn(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Hn(e,t){if(typeof e.article_id=="string"&&e.article_id)return e.article_id;try{let n=JSON.parse(t),r=(Array.isArray(n)?n[0]:n)?.id;return typeof r=="string"&&r?r:null}catch{return null}}function qn(e){try{let t=JSON.parse(e),o=(Array.isArray(t)?t[0]:t)?.url;return typeof o=="string"&&/^https?:\/\//.test(o)?o:null}catch{return null}}var Sd=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Rd(e,t,n,o){if(Sd.test(e))try{let r=ca(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=Hn(t,n),p=qn(n);e.endsWith("publish_article")&&p&&console.log(A(` \u2B95 Live: ${p}`)),c&&s&&console.log(A(` \u2B95 Preview: ${Fn(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function ua(e=process.cwd(),t="auto",n){let o=wd(t);o.kind==="none"&&(console.error(""),console.error(x("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${A("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${A('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${A("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${A("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Dd(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=Sr({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=gd({input:process.stdin,output:process.stdout}),h=[],b=null,k=!1;p.on("line",v=>{if(b){let C=b;b=null,C(v)}else h.push(v)}),p.on("close",()=>{if(k=!0,b){let v=b;b=null,v(null)}});function D(){return h.length>0?Promise.resolve(h.shift()):k?Promise.resolve(null):(process.stdout.write(A("> ")),new Promise(v=>{b=v}))}let w={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=Sr({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setModel:async v=>s.setModel(v),withPausedInput:async v=>{p.pause();try{return await v()}finally{p.resume()}}};try{for(;;){let v=await D();if(v===null)break;let C=v.trim();if(C){if(C.startsWith("/")){let I=na(C);if(!I)continue;let U=ta[I.name];if(!U){console.log(x(`Unknown command: /${I.name}`)),console.log(f("Type /help for the list."));continue}let H=await U(I.args,w);if(H.kind==="exit")break;if(H.kind==="clear"){w.restartAgent();continue}if(H.kind==="allow-prod"){r=!0,w.restartAgent(),console.log(j("\u2713 Production writes authorized for this session.")),console.log("");continue}if(H.kind==="resume"){s.close(),s=Sr({cwd:e,resume:H.uuid,profileName:n,allowProdWrites:r});let ee=yd(H.uuid);c={uuid:H.uuid,firstPrompt:ee?.firstPrompt??null,titleFired:!0},la(H.uuid),console.log(j(`\u2713 Resumed "${H.name}"`)),console.log("");continue}H.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=H.display??H.prompt),await aa(s,H.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=C),await aa(s,C,o,c,e)}}}finally{s.close(),p.close()}}function Dd(e,t){console.log(""),console.log(At("document360-writer")),console.log(f(` cwd: ${e}`));let n=vd(e);if(console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(jd(e,t)),!Cd(e))console.log(L(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{try{$n(e);for(let o of vn(e))console.log(L(` ${o}`))}catch{}try{let o=vt($t(e));o&&console.log(L(` \u{1F4CB} ${o} from the repo's coding agent \u2014 run /catch-up.`))}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function jd(e,t){try{let n=ca(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=Td(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...ia(r.idToken)??{},...ia(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return Pd(r)&&!r.refreshToken?L(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function Ad(){console.error(""),console.error(`Sign in with your Claude subscription: run ${A("claude")} once, then retry.`),console.error(` (No Claude Code? ${A("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${A("https://console.anthropic.com/settings/keys")}`)}function Ed(e,t,n){e.uuid=t;let o=new Date().toISOString();xd({uuid:t,name:bd(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o})}function Id(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||$d(o,t).then(r=>{r&&kd(n,r)}).catch(()=>{})}async function aa(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))Nd(c,o,r,n,s)}function Nd(e,t,n,o,r){switch(e.type){case"session":t.uuid||Ed(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Mn(e.name,e.input);s&&(process.stdout.write(`
232
-
233
- `),console.log(`${j("\u25CF")} ${Te(s.title)}${s.arg!==null?te(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=Xe(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=p=>p===1?"":"s";console.log(te(` \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=Wn(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?x:te;c.lines.forEach((h,b)=>console.log(p((b===0?" \u23BF ":" ")+h))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||Rd(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
234
- `),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&&(la(t.uuid),t.titleFired||Id(t,n));break;case"error":console.error(""),console.error(x(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Ad();break}}import{render as Mp}from"ink";import{resolveAuth as Wp}from"document360-engine";import{useCallback as B,useEffect as $e,useMemo as Er,useRef as X,useState as W}from"react";import{Box as Q,Text as S,useApp as Yd,useInput as zd,useStdout as Xd}from"ink";import{existsSync as Vt,readFileSync as Ir,readdirSync as La}from"node:fs";import{basename as Yt,isAbsolute as Kd,join as zt}from"node:path";import{createSession as Da,classifyClaudeAuth as Ma,CLAUDE_CODE_SETUP_HINT as Jd,loginPkce as Qd,toStoredTokens as Zd,saveTokens as ep,getAccessToken as tp,resolveActiveProfile as fe,resolveProjectId as np,getArticle as op,decodeJwtClaims as Ct,isExpired as Le,loadTokens as Je,clearTokens as rp,clearProfileProject as sp,setTitle as ip,slugify as ap,touchSession as Nr,upsertSession as lp,generateTitle as ja,findByName as cp,listSessions as up,renameSession as dp,suggestNextAction as pp,readProjectConfig as Z,writeProjectConfig as fp,resolveModelSetting as Lr,loadProfileMap as Aa,applyPull as mp,computeSyncStatus as _r,planPull as hp,inventoryRepo as gp,knownEnvironments as wp,resolveEnvironment as yp,planPartitions as Ur,partitionEvenly as kp,screenshotPlaceholderIds as bp,trackedArticlePaths as xp,runPartitioned as Xn,estimateBulkCost as Ea,resolveModelForOperation as Kn,readDocsPlan as $p,checkForUpdate as vp,detectInstallKind as Cp,isSelfUpdatable as Pp,devHintsGuidePath as Ia,toolFeedbackPath as Tp,DEFAULT_DOCS_DIR as Wa,setProfileProject as Sp}from"document360-engine";ze();import{spawn as _d}from"node:child_process";function Ud(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Od(e,t,n){return new Promise(o=>{try{let r=_d(e,t,{stdio:["pipe","ignore","ignore"],shell:process.platform==="win32"});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 da(e){for(let[t,n]of Ud())if(await Od(t,n,e))return!0;return!1}import{existsSync as Ld,mkdirSync as Md,readFileSync as Wd,writeFileSync as Fd}from"node:fs";import{join as pa}from"node:path";import{writerDir as Hd}from"document360-engine";function fa(e){return pa(Hd(e),".sessions")}function ma(e,t){return pa(fa(e),`${t}.json`)}function ha(e,t,n){try{Md(fa(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Fd(ma(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Rr(e,t){try{let n=ma(e,t);if(!Ld(n))return[];let o=JSON.parse(Wd(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var qd=e=>`\x1B]0;${e}\x07`,Bd=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function ga(e){process.stdout.isTTY&&process.stdout.write(e)}function Bt(e){ga(qd(e))}function Bn(e){ga(Bd(e))}var Gn=["\xB7 "," \xB7"],Dr="\u{1F7E3}";Nn();var Gd=/^(?:\d+[.)]|[-*•])\s+/;function wa(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
235
- `)){let c=s.trim().replace(Gd,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let h=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!h||!o.has(h[1].toLowerCase()))continue;let b=`/${h[1].toLowerCase()}${h[2]?` ${h[2]}`:""}`;if(r.includes(b)||r.push(b),r.length>=n)break}return r}M();function Gt(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Se(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function jr(e){return e.replace(/^[\w.-]+\//,"")}var Vn=16,ya={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Ar(e){return e.trim().split(/\s+/).slice(1).join(" ")}function ka(e,t){let n=Ar(t);return e.some(r=>r.trim()===t.trim()||!!n&&Ar(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&Ar(r)===n)):[]}var Vd=/\[Pasted text #\d+ \+\d+ lines?\]/g;function ba(e){return e.replace(/\r\n?/g,`
236
- `)}function xa(e){return e.includes(`
237
- `)||e.length>200}function $a(e,t){let n=t.split(`
238
- `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function va(e,t){return e.replace(Vd,n=>t.get(n)??n)}function Ca(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Yn(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
239
- `)){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 zn(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Pa(e,t,n){let o=zn(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 Ta(e,t,n){let o=e[zn(e,t)];return n==="start"?o.start:o.end}function Sa(e,t,n){let o=Math.max(1,n),r=e.split(`
225
+ `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as Hu,readFileSync as qu}from"node:fs";import{isAbsolute as Bu,join as Gu,resolve as Vu}from"node:path";import{readProjectConfig as Yu,DEFAULT_CAPTURE_DIR as zu}from"document360-engine";async function Bt(){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(`
226
+ `),display:"/capture-setup"}}var Yi="-".repeat(64);function gr(e){let t=zu;try{let k=Yu(e);k?.captureDir&&(t=k.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Bu(t)?Gu(t,"CAPTURE-TESTID-REQUESTS.json"):Vu(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Hu(n))return null;let o;try{let k=JSON.parse(qu(n,"utf8").replace(/^/,""));o=Array.isArray(k?.requests)?k.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(k=>k.file).filter(Boolean)).size,s=o.length,c=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,h=`${t}/CAPTURE-TESTID-REQUESTS.md`,b=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${c} requested across ${p}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",Yi,`Read ${h} and ${b}. They list ${c} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",Yi]}ze();M();import{listOpenForDocs as Xu,readProjectConfig as Ku}from"document360-engine";function wr(e){try{return Xu(e).length}catch{return 0}}function yr(){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(`
227
+ `)}async function zi(e,t){let n=t?.cwd??process.cwd();return Ku(n)?wr(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:yr(),display:"/inbox"}:(console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"})}M();import{listOpenHints as Ju,listOpenForDocs as Qu,readProjectConfig as Zu}from"document360-engine";function $t(e){let t=0,n=0,o=0;try{t=Ju(e).length}catch{}try{let r=Qu(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 vt(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 kr(e){return{publish:e.includes("--publish")}}function br({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. Trust the inventory first \u2014 call d360_sync_status. If anything is in conflict or remote-ahead, STOP and tell me what to resolve (never write over a copy you can't trust).","2. Gather the pending work: d360_pending_hints (the builder's per-change hints) AND d360_inbox (open requests + answers).","3. Decide the right doc actions across all of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), and fold any answers into the affected article(s) + the architecture brief.","4. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","5. Write/update the articles as drafts, grounded in the cited sources.","6. Close the loop: stamp consumed hints, and mark handled messages status: done with resulting_articles.","7. Push the drafts to Document360."];return t.push(e?"8. 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(`
228
+ `)}async function Xi(e,t){let n=t?.cwd??process.cwd();if(!Zu(n))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Se(n,t?.profileName);if(!o.ok)return console.log(x(o.reason)),{kind:"continue"};let{publish:r}=kr(e),s=vt($t(n));return console.log(f(s?`Catching up on ${s} (+ checking Document360 for drift)\u2026`:"No local queue \u2014 checking for code changes and drift\u2026")),{kind:"forward-to-agent",prompt:br({publish:r}),display:`/catch-up${r?" --publish":""}`}}M();import{spawn as ed}from"node:child_process";var Ke="document360-writer",On=`npm i -g ${Ke}@latest`;async function Ln(){return new Promise(e=>{let t="";try{let n=ed("npm",["i","-g",`${Ke}@latest`],{stdio:["ignore","pipe","pipe"],shell:process.platform==="win32"});n.stdout?.on("data",o=>t+=String(o)),n.stderr?.on("data",o=>t+=String(o)),n.on("error",o=>e({ok:!1,output:String(o)})),n.on("close",o=>e({ok:o===0,output:t.trim()}))}catch(n){e({ok:!1,output:String(n)})}})}async function Ki(){return console.log(f(`Updating ${Ke}\u2026`)),(await Ln()).ok?console.log(j("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(x(`Update failed \u2014 run manually: ${On}`)),{kind:"continue"}}M();ze();import{existsSync as xr,rmSync as td}from"node:fs";import{basename as Ji,resolve as $r}from"node:path";import{execFileSync as nd}from"node:child_process";import{input as od}from"@inquirer/prompts";import{readProjectConfig as rd,devHintsGuidePath as sd}from"document360-engine";var id=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],ad=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Mn=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Qi=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Zi(e){let t=Mn(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Qi(t)?!0:ad.has(t)}function vr(e){let t=null;try{t=rd(e)}catch{t=null}let n=new Set(id);for(let o of[Mn(t?.docsDir),Mn(t?.captureDir),Mn(t?.outputDir)])o&&Qi(o)&&n.add(o);return[...n].filter(o=>Zi(o)&&xr($r(e,o)))}function Cr(e,t){let n=[],o=[];for(let r of t){if(!Zi(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{td($r(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function ea(e,t){try{return nd("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
229
+ `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function ld(e){return ea(e,".d360-writer/hints")}function cd(e){return ea(e,".d360-writer/messages")}function Pr(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=ld(e),o=cd(e),r=xr($r(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(s=>` \u2022 ${s}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o>0?[`\u26A0 ${o} message(s) under .d360-writer/messages/ are not committed \u2014 commit them first or they're gone.`]:[],...r?["Protected: root user-docs/ is NOT touched (only .d360-writer/ is removed)."]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${Ji(e)}`]}async function ta(e,t){let n=vr(t.cwd);for(let h of Pr(t.cwd,n))console.log(n.length===0?f(h):h);if(n.length===0)return{kind:"continue"};let o=Ji(t.cwd);if((await t.withPausedInput(()=>od({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=xr(sd(t.cwd)),{removed:c,failed:p}=Cr(t.cwd,n);console.log(j(`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`));for(let h of p)console.log(x(` \u2717 ${h.path}: ${h.error}`));if(s){for(let h of Pn())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"}}var na={help:vo,"?":vo,clear:Ps,exit:Co,quit:Co,init:qs,mcp:Sn,publish:oi,audit:jn,scope:si,sync:pi,convert:fi,write:wi,draft:$i,document:vi,resume:Ti,rename:Si,profile:Di,model:Ei,doctor:qt,workspace:Mi,project:Wi,"allow-prod":Fi,login:Hi,logout:qi,screenshot:Un,"capture-setup":Bt,devhints:Es,inbox:zi,"catch-up":Xi,update:Ki,reset:ta};function oa(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}ze();M();var ud={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"},sa=160,Sr=200,ia=40;function pe(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function ra(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}: ${pe(typeof r=="string"?r:JSON.stringify(r),ia)}`);return t.length>4&&n.push("\u2026"),pe(n.join(", "),sa)}var Oe=e=>typeof e=="string"&&e?e:null,Tr=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function dd(e){let t=Oe(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 pd(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Oe(t.title);if(!o)return null;let r=dd(t.local_path);return n("Create article",`"${pe(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Oe(t.title),r=Tr(t.article_id);return n("Update article",o?`"${pe(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Tr(t.article_id)?`id ${Tr(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",Oe(t.name)?`"${pe(Oe(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Oe(t.file_path);return n("Upload image",o?pe(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Wn(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),c=s.join("__");if(r==="document360"){let b=pd(c,t);if(b)return b}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:ra(t)}}let n=ud[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:pe(o,sa)}:{title:e,sep:"",arg:ra(t)}}function fd(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 md(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(fd).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>pe(r,Sr))]}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}: ${pe(String(r),ia)}`);return n.length>0?[pe(n.join(" \xB7 "),Sr)]:null}return null}function hd(e){let t=Oe(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function gd(e,t,n){switch(e){case"d360_create_article":{let o=hd(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=Oe(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 ${pe(o[0],120)}`:""}`]}default:return null}}function Fn(e,t=4,n,o){let r=e.replace(/\r\n/g,`
230
+ `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=gd(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let s=md(r)??r.split(`
231
+ `);return{lines:s.slice(0,t).map(c=>pe(c,Sr)),hidden:Math.max(0,s.length-t)}}function Hn(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function qn(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 Bn(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 Rd=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Dd(e,t,n,o){if(Rd.test(e))try{let r=ua(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=qn(t,n),p=Bn(n);e.endsWith("publish_article")&&p&&console.log(E(` \u2B95 Live: ${p}`)),c&&s&&console.log(E(` \u2B95 Preview: ${Hn(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function da(e=process.cwd(),t="auto",n){let o=yd(t);o.kind==="none"&&(console.error(""),console.error(x("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${E("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${E('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${E("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${E("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),jd(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=Rr({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=wd({input:process.stdin,output:process.stdout}),h=[],b=null,k=!1;p.on("line",v=>{if(b){let C=b;b=null,C(v)}else h.push(v)}),p.on("close",()=>{if(k=!0,b){let v=b;b=null,v(null)}});function D(){return h.length>0?Promise.resolve(h.shift()):k?Promise.resolve(null):(process.stdout.write(E("> ")),new Promise(v=>{b=v}))}let w={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=Rr({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setModel:async v=>s.setModel(v),withPausedInput:async v=>{p.pause();try{return await v()}finally{p.resume()}}};try{for(;;){let v=await D();if(v===null)break;let C=v.trim();if(C){if(C.startsWith("/")){let N=oa(C);if(!N)continue;let U=na[N.name];if(!U){console.log(x(`Unknown command: /${N.name}`)),console.log(f("Type /help for the list."));continue}let H=await U(N.args,w);if(H.kind==="exit")break;if(H.kind==="clear"){w.restartAgent();continue}if(H.kind==="allow-prod"){r=!0,w.restartAgent(),console.log(j("\u2713 Production writes authorized for this session.")),console.log("");continue}if(H.kind==="resume"){s.close(),s=Rr({cwd:e,resume:H.uuid,profileName:n,allowProdWrites:r});let ee=kd(H.uuid);c={uuid:H.uuid,firstPrompt:ee?.firstPrompt??null,titleFired:!0},ca(H.uuid),console.log(j(`\u2713 Resumed "${H.name}"`)),console.log("");continue}H.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=H.display??H.prompt),await la(s,H.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=C),await la(s,C,o,c,e)}}}finally{s.close(),p.close()}}function jd(e,t){console.log(""),console.log(Et("document360-writer")),console.log(f(` cwd: ${e}`));let n=Cd(e);if(console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(Ad(e,t)),!Pd(e))console.log(L(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{try{vn(e);for(let o of Cn(e))console.log(L(` ${o}`))}catch{}try{let o=vt($t(e));o&&console.log(L(` \u{1F4CB} ${o} from the repo's coding agent \u2014 run /catch-up.`))}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Ad(e,t){try{let n=ua(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=Sd(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...aa(r.idToken)??{},...aa(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return Td(r)&&!r.refreshToken?L(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function Ed(){console.error(""),console.error(`Sign in with your Claude subscription: run ${E("claude")} once, then retry.`),console.error(` (No Claude Code? ${E("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${E("https://console.anthropic.com/settings/keys")}`)}function Id(e,t,n){e.uuid=t;let o=new Date().toISOString();$d({uuid:t,name:xd(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o})}function Nd(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||vd(o,t).then(r=>{r&&bd(n,r)}).catch(()=>{})}async function la(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))_d(c,o,r,n,s)}function _d(e,t,n,o,r){switch(e.type){case"session":t.uuid||Id(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Wn(e.name,e.input);s&&(process.stdout.write(`
232
+
233
+ `),console.log(`${j("\u25CF")} ${Te(s.title)}${s.arg!==null?te(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=Xe(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=p=>p===1?"":"s";console.log(te(` \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=Fn(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?x:te;c.lines.forEach((h,b)=>console.log(p((b===0?" \u23BF ":" ")+h))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||Dd(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
234
+ `),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&&(ca(t.uuid),t.titleFired||Nd(t,n));break;case"error":console.error(""),console.error(x(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Ed();break}}import{render as Wp}from"ink";import{resolveAuth as Fp}from"document360-engine";import{useCallback as G,useEffect as $e,useMemo as Ir,useRef as X,useState as W}from"react";import{Box as Q,Text as S,useApp as zd,useInput as Xd,useStdout as Kd}from"ink";import{existsSync as Yt,readFileSync as Nr,readdirSync as Ma}from"node:fs";import{basename as zt,isAbsolute as Jd,join as Xt}from"node:path";import{createSession as ja,classifyClaudeAuth as Wa,CLAUDE_CODE_SETUP_HINT as Qd,loginPkce as Zd,toStoredTokens as ep,saveTokens as tp,getAccessToken as np,resolveActiveProfile as fe,resolveProjectId as op,getArticle as rp,decodeJwtClaims as Ct,isExpired as Le,loadTokens as Je,clearTokens as sp,clearProfileProject as ip,setTitle as ap,slugify as lp,touchSession as _r,upsertSession as cp,generateTitle as Aa,findByName as up,listSessions as dp,renameSession as pp,suggestNextAction as fp,readProjectConfig as Z,writeProjectConfig as mp,resolveModelSetting as Mr,loadProfileMap as Ea,applyPull as hp,computeSyncStatus as Ur,planPull as gp,inventoryRepo as wp,knownEnvironments as yp,resolveEnvironment as kp,planPartitions as Or,partitionEvenly as bp,screenshotPlaceholderIds as xp,trackedArticlePaths as $p,runPartitioned as Kn,estimateBulkCost as Ia,resolveModelForOperation as Jn,readDocsPlan as vp,checkForUpdate as Cp,detectInstallKind as Pp,isSelfUpdatable as Tp,devHintsGuidePath as Na,toolFeedbackPath as Sp,DEFAULT_DOCS_DIR as Fa,setProfileProject as Rp}from"document360-engine";ze();import{spawn as Ud}from"node:child_process";function Od(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Ld(e,t,n){return new Promise(o=>{try{let r=Ud(e,t,{stdio:["pipe","ignore","ignore"],shell:process.platform==="win32"});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 pa(e){for(let[t,n]of Od())if(await Ld(t,n,e))return!0;return!1}import{existsSync as Md,mkdirSync as Wd,readFileSync as Fd,writeFileSync as Hd}from"node:fs";import{join as fa}from"node:path";import{writerDir as qd}from"document360-engine";function ma(e){return fa(qd(e),".sessions")}function ha(e,t){return fa(ma(e),`${t}.json`)}function ga(e,t,n){try{Wd(ma(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Hd(ha(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Dr(e,t){try{let n=ha(e,t);if(!Md(n))return[];let o=JSON.parse(Fd(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Bd=e=>`\x1B]0;${e}\x07`,Gd=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function wa(e){process.stdout.isTTY&&process.stdout.write(e)}function Gt(e){wa(Bd(e))}function Gn(e){wa(Gd(e))}var Vn=["\xB7 "," \xB7"],jr="\u{1F7E3}";_n();var Vd=/^(?:\d+[.)]|[-*•])\s+/;function ya(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
235
+ `)){let c=s.trim().replace(Vd,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let h=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!h||!o.has(h[1].toLowerCase()))continue;let b=`/${h[1].toLowerCase()}${h[2]?` ${h[2]}`:""}`;if(r.includes(b)||r.push(b),r.length>=n)break}return r}M();function Vt(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Re(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Ar(e){return e.replace(/^[\w.-]+\//,"")}var Yn=16,ka={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Er(e){return e.trim().split(/\s+/).slice(1).join(" ")}function ba(e,t){let n=Er(t);return e.some(r=>r.trim()===t.trim()||!!n&&Er(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&Er(r)===n)):[]}var Yd=/\[Pasted text #\d+ \+\d+ lines?\]/g;function xa(e){return e.replace(/\r\n?/g,`
236
+ `)}function $a(e){return e.includes(`
237
+ `)||e.length>200}function va(e,t){let n=t.split(`
238
+ `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Ca(e,t){return e.replace(Yd,n=>t.get(n)??n)}function Pa(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function zn(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
239
+ `)){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 Xn(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Ta(e,t,n){let o=Xn(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 Sa(e,t,n){let o=e[Xn(e,t)];return n==="start"?o.start:o.end}function Ra(e,t,n){let o=Math.max(1,n),r=e.split(`
240
240
  `),s=0;for(let c=r.length-1;c>=0;c--){let p=r[c];if(s+=Math.max(1,Math.ceil(p.length/o)),s>=t){let h=s-t;return{text:[h>0?p.slice(h*o):p,...r.slice(c+1)].join(`
241
- `),truncated:c>0||h>0}}}return{text:e,truncated:!1}}function Ra(e){let t=!1,n=0,o=0;for(let r of e.split(`
242
- `)){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 Or,jsx as R,jsxs as F}from"react/jsx-runtime";var Rp={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},Na=` 1. /init \u2014 pick your Document360 environment & scaffold config
241
+ `),truncated:c>0||h>0}}}return{text:e,truncated:!1}}function Da(e){let t=!1,n=0,o=0;for(let r of e.split(`
242
+ `)){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 Lr,jsx as R,jsxs as F}from"react/jsx-runtime";var Dp={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},_a=` 1. /init \u2014 pick your Document360 environment & scaffold config
243
243
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
244
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Dp(e,t,n,o){let r=Ma(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=Lr(e),p=Z(e),h=(p?.docsDir??Wa).replace(/\/+$/,""),b=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${h}/ + config`,k={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:Rp[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:b};if(p===null)return k;try{let D=fe(e,o);k.profile=D.name,k.apiUrl=D.connection.apiUrl,k.prod=D.production,k.project=D.project.projectName??D.project.projectId??"(chosen at login)";let w=Je(D.name);if(w){let v={...Ct(w.idToken)??{},...Ct(w.accessToken)??{}},C=v.email??v.preferred_username??"signed in";Le(w)?w.refreshToken&&(k.who=C,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=C,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(w.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function jp(e,t){try{let n=fe(e,t),o=Je(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Ct(o.idToken)??{},...Ct(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return Le(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 _a=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Qn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ap="Ask me to write or update an article\u2026";function Jn({ch:e,dim:t}){let[n,o]=W(!0);return $e(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),R(S,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Ep=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Ua(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Ip=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Oa(e){try{return La(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Np(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Oa(zt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Oa(zt(e,o)))}function _p({startTime:e,chars:t}){let[n,o]=W(0);$e(()=>{let h=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(h)},[]);let r=Qn[n%Qn.length],s=_a[Math.floor(n/16)%_a.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return F(Q,{children:[R(S,{color:q,children:` ${r} ${s}\u2026 `}),R(S,{color:"gray",children:`(${Lt(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var Up=12e4;function Op({p:e}){let[t,n]=W(0);$e(()=>{let U=setInterval(()=>n(H=>H+1),150);return()=>clearInterval(U)},[]);let o=Qn[t%Qn.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>=Up,h=e.verb??"Converting",b=e.unit??"article",k=e.rows.reduce((U,H)=>U+H.items,0),D=h.toLowerCase(),w=e.rows,v=0;if(w.length>Vn){let U=w.findIndex(ee=>ee.status==="active"||ee.status==="pending"),H=Math.max(0,Math.min(U-2,w.length-Vn));v=w.slice(0,H).filter(ee=>ee.status==="done").length,w=w.slice(H,H+Vn)}let C=Math.min(40,Math.max(...w.map(U=>jr(U.label).length),0)),I=U=>U==="failed"?"red":U==="active"?q:void 0;return F(Q,{flexDirection:"column",children:[F(Q,{children:[R(S,{color:q,children:` ${o} ${h} ${k} ${b}${k===1?"":"s"} `}),R(S,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${Lt(r)} \xB7 esc to stop`})]}),v>0&&R(S,{dimColor:!0,children:` \u2714 +${v} done`}),w.map(U=>F(S,{color:I(U.status),dimColor:U.status==="done"||U.status==="pending",children:[` ${ya[U.status]} ${jr(U.label).padEnd(C)}`,U.status!=="pending"?` (${U.items} ${b}${U.items===1?"":"s"})`:"",U.status==="active"?` \u2190 ${D}\u2026`:""]},U.label)),p&&R(S,{color:"yellow",children:` \u26A0 no activity for ${Lt(s)} \u2014 press esc to stop if it's wedged`})]})}var Lp=10800*1e3;function Fa({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Yd(),[s,c]=W(n),[p,h]=W(null),[b,k]=W({text:"",pos:0}),D=b.text,w=B(l=>{k(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),v=B(l=>{k(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),C=B(()=>{k(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=Ca(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[I,U]=W(!1),[H,ee]=W(!1),[ve,oe]=W(0),[ke,se]=W(null),[Pt,V]=W([]),Qe=X(0),[Ga,Xt]=W(!1),[Va,Ze]=W(0),Me=X(0),[Tt,et]=W(0),[tt,Kt]=W(null),Fr=X(new Map),Ya=X(0),nt=X([]),me=X(null);me.current===null&&(me.current=Da({cwd:e,profileName:s,allowProdWrites:!1}));let Ce=X({uuid:null,firstPrompt:null,titleFired:!1}),Jt=X(new Map),ot=X(!1),Zn=X([]),De=X([]),eo=X(null),[Hr,rt]=W(null),[We,Fe]=W(null),[Pe,st]=W(null),[je,it]=W(null),[ie,at]=W(null),[he,lt]=W(null),[He,ct]=W(null),[qr,Qt]=W(null),[ge,qe]=W(null),[ce,ut]=W(null),[Br,to]=W([]),Be=X([]),St=X(!1),we=X(null),[Gr,K]=W(null),Zt=X(!1),en=X(null),[ye,Ge]=W(null),[Vr,dt]=W(0),[Yr,pt]=W(0),[za,zr]=W(0),no=Er(()=>{try{return Lr(e).model??"auto"}catch{return null}},[e,za]),{stdout:be}=Xd(),[,Xa]=W(0),Xr=X(`${be.columns??80}x${be.rows??24}`),Ae=B(()=>Math.max(20,(be.columns??80)-1),[be]),u=B(l=>{nt.current.push(l),console.log(No(l,Ae()))},[Ae]),[oo,ro]=W(null),ft=B(l=>{ro(l),u({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),so=X(!1),io=B(async()=>{try{if(so.current||!Pp(Cp())||Z(e)?.mode==="engineer")return;let l=await vp({pkg:Ke,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;so.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${Ke} ${l.current} \u2192 ${l.latest}\u2026`}),(await On()).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 /exit and relaunch to apply (press 1).`}),V(a=>a.includes("/exit")?a:[...a,"/exit"])):u({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${Un}`})}catch{}},[e,o,u]),ao=B(()=>{let l=Ue(e,s);return l.ok?!0:(u({kind:"note",tone:"warn",text:l.reason}),V(["/login"]),!1)},[e,s,u]),[lo,co]=W(null),Rt=X(!0),tn=X(0);$e(()=>{let l=setInterval(()=>{if(I||Rt.current){tn.current=0;return}try{if(!Vt(Ia(e)))return;if(Ie(e).status==="current"){Rt.current=!0,tn.current=0,u({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."}),ro(null),se("write the docs for this repo");return}tn.current+=1;let i=tn.current;(i===1||i%7===0)&&u({kind:"note",tone:"info",text:Is(e)?"\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.":"\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."})}catch{}},4e3);return()=>clearInterval(l)},[e,I,u]),$e(()=>{let l=`d360-writer \xB7 ${Hr??Yt(e)}`;if(!I){Bn(0),Bt(`${Dr} ${l}`);return}Bn(3);let i=0;Bt(`${Gn[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%Gn.length,Bt(`${Gn[i]} ${l}`)},400);return()=>clearInterval(a)},[I,e,Hr]),$e(()=>()=>Bn(0),[]),$e(()=>{u({kind:"banner",info:Dp(e,o,t,s)});let l=Ma(t).state==="missing";if(l&&u({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.
245
- ${Jd}
244
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function jp(e,t,n,o){let r=Wa(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=Mr(e),p=Z(e),h=(p?.docsDir??Fa).replace(/\/+$/,""),b=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${h}/ + config`,k={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:Dp[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:b};if(p===null)return k;try{let D=fe(e,o);k.profile=D.name,k.apiUrl=D.connection.apiUrl,k.prod=D.production,k.project=D.project.projectName??D.project.projectId??"(chosen at login)";let w=Je(D.name);if(w){let v={...Ct(w.idToken)??{},...Ct(w.accessToken)??{}},C=v.email??v.preferred_username??"signed in";Le(w)?w.refreshToken&&(k.who=C,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=C,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(w.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function Ap(e,t){try{let n=fe(e,t),o=Je(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Ct(o.idToken)??{},...Ct(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return Le(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 Ua=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Zn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ep="Ask me to write or update an article\u2026";function Qn({ch:e,dim:t}){let[n,o]=W(!0);return $e(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),R(S,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Ip=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Oa(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Np=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function La(e){try{return Ma(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function _p(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>La(Xt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&La(Xt(e,o)))}function Up({startTime:e,chars:t}){let[n,o]=W(0);$e(()=>{let h=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(h)},[]);let r=Zn[n%Zn.length],s=Ua[Math.floor(n/16)%Ua.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return F(Q,{children:[R(S,{color:q,children:` ${r} ${s}\u2026 `}),R(S,{color:"gray",children:`(${Mt(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var Op=12e4;function Lp({p:e}){let[t,n]=W(0);$e(()=>{let U=setInterval(()=>n(H=>H+1),150);return()=>clearInterval(U)},[]);let o=Zn[t%Zn.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>=Op,h=e.verb??"Converting",b=e.unit??"article",k=e.rows.reduce((U,H)=>U+H.items,0),D=h.toLowerCase(),w=e.rows,v=0;if(w.length>Yn){let U=w.findIndex(ee=>ee.status==="active"||ee.status==="pending"),H=Math.max(0,Math.min(U-2,w.length-Yn));v=w.slice(0,H).filter(ee=>ee.status==="done").length,w=w.slice(H,H+Yn)}let C=Math.min(40,Math.max(...w.map(U=>Ar(U.label).length),0)),N=U=>U==="failed"?"red":U==="active"?q:void 0;return F(Q,{flexDirection:"column",children:[F(Q,{children:[R(S,{color:q,children:` ${o} ${h} ${k} ${b}${k===1?"":"s"} `}),R(S,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${Mt(r)} \xB7 esc to stop`})]}),v>0&&R(S,{dimColor:!0,children:` \u2714 +${v} done`}),w.map(U=>F(S,{color:N(U.status),dimColor:U.status==="done"||U.status==="pending",children:[` ${ka[U.status]} ${Ar(U.label).padEnd(C)}`,U.status!=="pending"?` (${U.items} ${b}${U.items===1?"":"s"})`:"",U.status==="active"?` \u2190 ${D}\u2026`:""]},U.label)),p&&R(S,{color:"yellow",children:` \u26A0 no activity for ${Mt(s)} \u2014 press esc to stop if it's wedged`})]})}var Mp=10800*1e3;function Ha({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=zd(),[s,c]=W(n),[p,h]=W(null),[b,k]=W({text:"",pos:0}),D=b.text,w=G(l=>{k(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),v=G(l=>{k(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),C=G(()=>{k(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=Pa(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[N,U]=W(!1),[H,ee]=W(!1),[ve,oe]=W(0),[ke,se]=W(null),[Pt,B]=W([]),Qe=X(0),[Va,Kt]=W(!1),[Ya,Ze]=W(0),Me=X(0),[Tt,et]=W(0),[tt,Jt]=W(null),Hr=X(new Map),za=X(0),nt=X([]),me=X(null);me.current===null&&(me.current=ja({cwd:e,profileName:s,allowProdWrites:!1}));let Ce=X({uuid:null,firstPrompt:null,titleFired:!1}),Qt=X(new Map),ot=X(!1),eo=X([]),je=X([]),to=X(null),[qr,rt]=W(null),[We,Fe]=W(null),[Pe,st]=W(null),[Ae,it]=W(null),[ie,at]=W(null),[he,lt]=W(null),[He,ct]=W(null),[Br,Zt]=W(null),[ge,qe]=W(null),[ce,ut]=W(null),[Gr,no]=W([]),Be=X([]),St=X(!1),we=X(null),[Vr,K]=W(null),en=X(!1),tn=X(null),Rt=X(null),[ye,Ge]=W(null),[Yr,dt]=W(0),[zr,pt]=W(0),[Xa,Xr]=W(0),oo=Ir(()=>{try{return Mr(e).model??"auto"}catch{return null}},[e,Xa]),{stdout:be}=Kd(),[,Ka]=W(0),Kr=X(`${be.columns??80}x${be.rows??24}`),Ee=G(()=>Math.max(20,(be.columns??80)-1),[be]),u=G(l=>{nt.current.push(l),console.log(_o(l,Ee()))},[Ee]),[ro,so]=W(null),ft=G(l=>{so(l),u({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),io=X(!1),ao=G(async()=>{try{if(io.current||!Tp(Pp())||Z(e)?.mode==="engineer")return;let l=await Cp({pkg:Ke,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;io.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${Ke} ${l.current} \u2192 ${l.latest}\u2026`}),(await Ln()).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 /exit and relaunch to apply (press 1).`}),B(a=>a.includes("/exit")?a:[...a,"/exit"])):u({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${On}`})}catch{}},[e,o,u]),lo=G(l=>{let i=Se(e,s);return i.ok?!0:(u({kind:"note",tone:"warn",text:i.reason}),Rt.current=l,B(["/login"]),!1)},[e,s,u]),[co,uo]=W(null),Dt=X(!0),nn=X(0);$e(()=>{let l=setInterval(()=>{if(N||Dt.current){nn.current=0;return}try{if(!Yt(Na(e)))return;if(Ne(e).status==="current"){Dt.current=!0,nn.current=0,u({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."}),so(null),se("write the docs for this repo");return}nn.current+=1;let i=nn.current;(i===1||i%7===0)&&u({kind:"note",tone:"info",text:Ns(e)?"\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.":"\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."})}catch{}},4e3);return()=>clearInterval(l)},[e,N,u]),$e(()=>{let l=`d360-writer \xB7 ${qr??zt(e)}`;if(!N){Gn(0),Gt(`${jr} ${l}`);return}Gn(3);let i=0;Gt(`${Vn[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%Vn.length,Gt(`${Vn[i]} ${l}`)},400);return()=>clearInterval(a)},[N,e,qr]),$e(()=>()=>Gn(0),[]),$e(()=>{u({kind:"banner",info:jp(e,o,t,s)});let l=Wa(t).state==="missing";if(l&&u({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.
245
+ ${Qd}
246
246
  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)){u({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
247
- ${Na}`}),V(l?["/doctor","/init"]:["/init"]);return}l&&V(["/doctor"]);try{let i=fe(e,s),a=Je(i.name);a&&Le(a)&&a.refreshToken?tp({profile:i.name,connection:i.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),oe(g=>g+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),V(["/login"])}):(!a||Le(a))&&(u({kind:"note",tone:"warn",text:`Profile "${i.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),V(["/login"]))}catch{}try{let i=Z(e),a=fe(e,s),g=Je(a.name);i&&g&&!Le(g)&&Np(e,i.authoritativeSourceFiles)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),V(["/scope"]))}catch{}try{$n(e);let i=vn(e);i.length&&(u({kind:"note",tone:"warn",text:i.join(`
248
- `)}),ft(Ye()),Rt.current=!1)}catch{}try{let i=vt($t(e));i&&(u({kind:"note",tone:"info",text:`\u{1F4CB} ${i} from the repo's coding agent \u2014 press 1 to /catch-up.`}),V(a=>a.includes("/catch-up")?a:[...a,"/catch-up"]))}catch{}io()},[]),$e(()=>{let l=setInterval(()=>{io()},Lp);return()=>clearInterval(l)},[io]),$e(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${be.columns??80}x${be.rows??24}`;g!==Xr.current&&(Xr.current=g,Xa(d=>d+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Qs(nt.current,Ae())+"\x1B[?2026l")},80))},400)};return be.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),be.off("resize",a)}},[be,Ae]);let Ve=Math.max(20,(be.columns??80)-1),Kr=Er(()=>jp(e,s),[e,s,ve]),uo=(()=>{let l=Z(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=zt(e,(l.docsDir??Wa).replace(/\/+$/,"")),a=(()=>{try{return Vt(i)&&La(i).length>0}catch{return!1}})();try{let g=fe(e,s),d=Je(g.name);if(!(!!d&&!(Le(d)&&!d.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:Ap,isSetup:!1}:oo?{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}})(),Dt=$s(D),Jr=Dt.length>0&&!I,po=p!==null?Sa(p,8,Ve):null,nn=ge?ge.paths.filter(l=>!ge.query||l.toLowerCase().includes(ge.query.toLowerCase())).slice(0,8):[],on=ye?ye.sessions.filter(l=>{let i=ye.query.toLowerCase();return!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],ue=B((l,i)=>{me.current?.close(),me.current=Da({cwd:e,resume:l,profileName:i??s,allowProdWrites:ot.current}),l||(Ce.current={uuid:null,firstPrompt:null,titleFired:!1},rt(null)),dt(0),pt(0)},[e,s]),Qr=B((l,i,a)=>{if(Ep.test(l))try{let g=fe(e,s),d=typeof i.project_id=="string"&&i.project_id||g.project.projectId,m=Hn(i,a),y=[],T=qn(a);l.endsWith("publish_article")&&T&&y.push(`Live: ${T}`),m&&d&&y.push(`Preview: ${Fn(g.connection.portalUrl,d,m,g.project.languageCode??"en")}`),y.length>0&&u({kind:"link",lines:y})}catch{}},[e,s,u]),de=B(async(l,i)=>{Xt(!0),se(null),V([]),Qt(null),ro(null),co(null);let a=++Qe.current;i?.quietUser||u({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let g=Ce.current;g.firstPrompt||(g.firstPrompt=i?.display??l),Me.current=Date.now(),Ze(0),U(!0),Jt.current.clear();let d="",m=!1,y=!1,T="",N=null,_=()=>{N||(N=setTimeout(()=>{N=null,h(T.length>0?T:null)},60))},re=()=>{N&&clearTimeout(N),N=null,h(null)},Y=()=>{if(T.trim()){let $=T.trimEnd();u({kind:"assistant",text:$})}T="",re()};try{for await(let $ of me.current.send(l))if($.type==="session"){if(!g.uuid){g.uuid=$.sessionId;let P=new Date().toISOString(),E=ap(g.firstPrompt??"session");lp({uuid:$.sessionId,name:E,renamed:!1,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:P,updatedAt:P}),rt(E)}}else if($.type==="text"){T+=$.delta,d+=$.delta;let P=Ra(T);if(P>0){let E=T.slice(0,P).trimEnd();E&&u({kind:"assistant",text:E}),T=T.slice(P)}_(),Ze(E=>E+$.delta.length)}else if($.type==="tool"){m=!0;let P=Mn($.name,$.input);P&&(Y(),u({kind:"tool",title:P.title,sep:P.sep,arg:P.arg}),Jt.current.set($.id,{name:$.name,input:$.input}))}else if($.type==="article_diff"){let P=Xe($.oldContent,$.newContent,Ae());P&&(Y(),u({kind:"diff",added:P.added,removed:P.removed,lines:P.lines,hidden:P.hidden}))}else if($.type==="tool_result"){$.isError&&/run \/login|not logged in|session expired|rejected the token/i.test($.output)&&(Zt.current=!0);let P=Jt.current.get($.id);if(P){Jt.current.delete($.id),Y();let E=Wn($.output,4,$.isError?void 0:P.name,P.input);u({kind:"tool-result",lines:E.lines,hidden:E.hidden,isError:$.isError}),$.isError||Qr(P.name,P.input,$.output)}}else if($.type==="result"){if(Y(),dt(E=>E+$.outputTokens),pt(E=>E+$.costUsd),u({kind:"done",seconds:Math.round((Date.now()-Me.current)/1e3),tokens:$.outputTokens,costUsd:$.costUsd,ok:$.ok}),!y&&!m&&!d.trim()&&!St.current&&u({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)."}),$.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(d))try{let E=Tp(e);if(Vt(E)){let J=Ir(E,"utf8").trim();J&&(co(J),u({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 P=$.ok?wa(d,Nt.map(E=>E.name)):[];if(P.length>0?V(P):$.ok&&d.trim()&&pp(l,d,e).then(E=>{E&&Qe.current===a&&se(E)}).catch(()=>{}),g.uuid&&(Nr(g.uuid),!g.titleFired)){g.titleFired=!0;let E=g.uuid,J=g.firstPrompt;J&&ja(J,e).then(O=>{O&&(ip(E,O),rt(O))}).catch(()=>{})}}else $.type==="error"&&(Y(),y=!0,$.kind==="auth"&&(Zt.current=!0),u({kind:"note",text:`agent error: ${$.message}`,tone:"error"}))}finally{U(!1),re(),oe($=>$+1),Ce.current.uuid&&ha(e,Ce.current.uuid,nt.current),Zt.current&&(Zt.current=!1,en.current=i?.display??l,V(["/login"])),St.current&&(St.current=!1,Be.current.length>0&&(u({kind:"note",tone:"info",text:`(${Be.current.length} queued message(s) discarded)`}),Be.current=[],to([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,Qr,Ae]),rn=B(async l=>{let i=Ur(l),a=Kn(e,"standard");Me.current=Date.now(),Ze(0),U(!0);let g=new AbortController;we.current=g,K({verb:"Publishing",total:i.length,done:0,active:[],rows:Gt(i),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${Mt} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let d of Xn({cwd:e,partitions:i,promptFor:m=>Sn(m.paths),concurrency:Mt,profileName:s,allowProdWrites:ot.current,model:a.model,signal:g.signal}))if(d.type==="partition_status")d.status==="running"?K(m=>m&&{...m,active:[...m.active,d.label],rows:Se(m.rows,d.label,"active"),lastAt:Date.now()}):K(m=>m&&{...m,active:m.active.filter(y=>y!==d.label),done:m.done+1,rows:Se(m.rows,d.label,d.status==="done"?"done":"failed"),lastAt:Date.now()});else if(d.type==="partition_event")K(m=>{if(!m)return m;let y={...m,lastAt:Date.now()};return d.event.type==="tool"?y.tools=m.tools+1:d.event.type==="text"&&(y.chars=m.chars+d.event.delta.length),y});else if(d.type==="run_done"){pt(T=>T+d.totalCostUsd),dt(T=>T+d.results.reduce((N,_)=>N+_.outputTokens,0));let m=d.aborted?"Stopped. ":"",y=t.kind==="api"?"api":"subscription";u({kind:"note",tone:d.aborted?"warn":d.ok?"ok":"warn",text:m+Lo(d.results,i,y).join(`
249
- `)})}}catch(d){u({kind:"note",tone:"error",text:`Publish run failed: ${d.message}`})}finally{we.current=null,K(null),U(!1),oe(d=>d+1)}},[e,s,u,t]),fo=B(async l=>{await de(Oo(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await Rn(e,s,l.replace(/\\/g,"/"));i.length>0&&(Qt(`Related articles not yet published (${i.length}):`),V([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,de]),mo=B(l=>{let i=Je(l);if(!i||Le(i)&&!i.refreshToken)return null;let a={...Ct(i.idToken)??{},...Ct(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),ho=B((l,i)=>{if(i){let a=Z(e);a&&(a.defaultProfile=l,fp(a,e))}c(l),ue(void 0,l),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),mo(l)||(u({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),V(["/login"])),oe(a=>a+1)},[e,u,ue,mo]),sn=B((l,i,a)=>{dn(e,l,i,a.id,a.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),ue(),Aa(e,l)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({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:"}),u({kind:"note",tone:"info",text:kt(yt(e)).join(`
250
- `)}),ft(Ye()),Rt.current=Ie(e).status==="current",u({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,u,ue,ft]),an=B(async l=>{let i;try{i=await Et(e,l)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),V(["/workspace"]);return}if(i.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(d=>(d.workspace_type??"").toLowerCase()!=="apidocumentation"),g=a.length>0?a:i.workspaces;if(g.length===1){let d=g[0],m=i.workspaces.length-g.length;u({kind:"note",tone:"ok",text:`Selected the "${d.name??d.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),sn(i.profile,i.projectId,d);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),V(["/workspace"])},[e,u,sn]),Zr=B((l,i)=>{bo(e,l,i.id,i.name),u({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),ue(),an(l)},[e,u,ue,an]),es=B(async l=>{let i;try{i=fe(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await gt(e,i.name),g=a.find(d=>d.id===i.project.projectId);g?.name&&Sp(e,i.name,{projectName:g.name})}catch{}await an(i.name);return}u({kind:"note",tone:"info",text:"Next: pick the Document360 project."}),V(["/project"])}},[e,u,an]),ln=B(()=>{let l=De.current[0];if(!l)return;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let a of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${a}`});l.overwritesLocalChanges&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let i=Xe(l.oldContent,l.newContent,Ae());u(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."}),u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,Ae]),ts=B(l=>{if(De.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=De.current.shift();try{mp({cwd:e,profileName:s},a),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),De.current.length===0&&V(g=>g.length>0?g:["/sync"])}catch(g){u({kind:"note",tone:"error",text:`Pull failed: ${g.message}`})}}else if(i==="n"||i==="no"){let a=De.current.shift();u({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=De.current.length;return De.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return ln(),!0},[e,s,ln,u]),ns=B(l=>{let i=eo.current;if(!i)return!1;if(eo.current=null,se(null),Qe.current++,l.trim()!==i.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:g}=vr(e,i.targets);u({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 d of g)u({kind:"note",tone:"error",text:` \u2717 ${d.path}: ${d.error}`});return i.hadDevhints&&(u({kind:"note",tone:"warn",text:Cn().join(`
251
- `)}),ft(To())),u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
252
- ${Na}`}),V(["/init"]),Xt(!1),!0},[e,u,ft]),os=B(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),g=i.slice(1);switch(Xt(!0),a){case"help":u({kind:"note",tone:"info",text:yn().join(`
253
- `)});return;case"exit":case"quit":me.current?.close(),r();return;case"clear":ue(),nt.current=[],Xt(!1),se(null),Qe.current++,u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let d;try{d=fe(e,s)}catch(m){u({kind:"note",tone:"error",text:m.message});return}u({kind:"note",tone:"info",text:`Profile "${d.name}" \u2192 ${d.connection.name} (${d.connection.apiUrl})${d.production?" \u26A0 PRODUCTION":""}`}),ee(!0);try{let m=await Qd(d.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},T=>u({kind:"note",tone:"info",text:T})),y=Zd(d.name,m);ep(y),await xo(y,d.name,T=>u({kind:"note",tone:"info",text:T})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${d.name}" as ${fn(y)}`}),await es(s),en.current&&(se(en.current),en.current=null,u({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(m){u({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{ee(!1),oe(m=>m+1)}return}case"allow-prod":{let d=!1;try{d=fe(e,s).production}catch{}if(!d){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}ot.current=!0,ue(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let d=lr(g.join(" ")),m=Ce.current.uuid;if(!m){u({kind:"note",tone:"error",text:"Send a message first \u2014 sessions save once the agent replies."});return}if(!d){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let y=Ce.current.firstPrompt??"";ja(y,e).then(T=>{T?(se(`/rename ${T}`),u({kind:"note",tone:"info",text:`Suggestion: "${T}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}dp(m,d),rt(d),Bt(`${Dr} d360-writer \xB7 ${d}`),u({kind:"note",tone:"ok",text:`Session renamed to "${d}".`});return}case"profile":{let d=g[0],m=Z(e);if(!d){let y=Object.entries(m?.profiles??{});if(y.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let T=y.map(([re,Y])=>({name:re,env:Y.connection?.environment??"custom",prod:Y.production===!0,who:mo(re)})),N=s??m?.defaultProfile,_=Math.max(0,T.findIndex(re=>re.name===N));st({cursor:_,current:_,rows:T});return}if(d==="add"){let y=cr(e,g[1],g[2]);if(y){u({kind:"note",tone:"error",text:y});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),ho(g[1],!1);return}if(!m?.profiles?.[d]){u({kind:"note",tone:"error",text:`Unknown profile "${d}". Create it: /profile add ${d} <environment>`});return}ho(d,!0);return}case"doctor":await Ht(g,{cwd:e});return;case"mcp":await Tn(g);return;case"init":{if(Z(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer.json directly (or d360-writer init for the CLI wizard)."});return}let d=wp().map(m=>({name:m,apiUrl:yp(m).apiUrl}));it({cursor:0,rows:d});return}case"resume":{let d=g.join(" ").trim(),m=up(e).filter(N=>N.uuid!==Ce.current.uuid);if(!d){if(!m.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Ge({query:"",cursor:0,sessions:m});return}let y=cp(e,d);if(!y){u({kind:"note",tone:"error",text:`No session matches "${d}".`});return}ue(y.uuid),Ce.current={uuid:y.uuid,firstPrompt:y.firstPrompt,titleFired:!0},rt(y.name),Nr(y.uuid),nt.current=[];let T=Rr(e,y.uuid);for(let N of T)u(N);u({kind:"note",tone:"ok",text:T.length?`Resumed "${y.name}" \u2014 restored ${T.length} message(s); continue where you left off.`:`Resumed "${y.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let d=g.join(" ").trim(),m;try{m=await Et(e,s)}catch(T){u({kind:"note",tone:"error",text:`Could not list workspaces: ${T.message}`});return}if(!d){let T=m.workspaces.map(_=>({id:_.id,name:_.name??_.id,type:_.workspace_type}));if(T.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let N=Math.max(0,T.findIndex(_=>_.id===m.current));at({cursor:N,current:N,rows:T,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let y=ko(m.workspaces,d);if(!y){u({kind:"note",tone:"error",text:`No workspace matches "${d}".`});return}sn(m.profile,m.projectId,y);return}case"project":{let d=g.join(" ").trim(),m;try{m=await gt(e,s)}catch(T){u({kind:"note",tone:"error",text:`Could not list projects: ${T.message} (signed in? try /login)`});return}if(!d){let T=m.projects.map(_=>({id:_.id,name:_.name??_.id,sub:_.sub_domain}));if(T.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let N=T.findIndex(_=>_.id===m.current);lt({cursor:Math.max(0,N),current:N,rows:T,profile:m.profile,environment:m.environment});return}let y=ds(m.projects,d);if(!y){u({kind:"note",tone:"error",text:`No project matches "${d}". Available: ${m.projects.map(T=>T.name??T.id).join(", ")}`});return}Zr(m.profile,y);return}case"logout":{let d;try{d=fe(e,s).name}catch(y){u({kind:"note",tone:"error",text:y.message});return}let m=rp(d);sp(e,d),ue(),oe(y=>y+1),u({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${d}" and cleared its project/workspace selection.`:`Profile "${d}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),V(["/login"]);return}case"publish":{if(!ao())return;if(g[0]==="--related"&&g[1]){let m=await Rn(e,s,g[1].replace(/\\/g,"/"));if(m.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await rn(m);return}if(g[0]&&g[0]!=="--all"){await fo(g[0]);return}let d=g[0]==="--all";u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await _r({cwd:e,profileName:s}),y=Wt(m.entries);if(y.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let T=m.counts["unknown-base"]??0;T>0&&u({kind:"note",tone:"info",text:`(${T} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(d){await rn(y.map(T=>T.path));return}ct({cursor:0,rows:ti(y)})}catch(m){u({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let d=g.join(" ").trim();if(!d){let y=[];try{y=Object.keys(Aa(e,fe(e,s).name)?.articles??{})}catch{}if(y.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}qe({query:"",cursor:0,paths:y});return}let m=Kd(d)?d:zt(e,d);if(Vt(m)){try{u({kind:"preview",name:Yt(m),text:Ua(Ir(m,"utf8"))})}catch(y){u({kind:"note",tone:"error",text:`Could not read ${m}: ${y.message}`})}return}if(Ip.test(d)){try{let y=fe(e,s),T={profile:y.name,connection:y.connection},N=y.project.projectId??np(T),_=await op(T,N,d);u({kind:"preview",name:_.title??d,text:_.content??"*(article has no content)*"})}catch(y){u({kind:"note",tone:"error",text:`Could not fetch article: ${y.message}`})}return}u({kind:"note",tone:"error",text:`"${d}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let d=g[0]?.trim();if(!d){let N=In(Lr(e));Fe({cursor:N,current:N});return}let{lines:m,changed:y,effective:T}=Ft(e,d);for(let N of m)u({kind:"note",tone:N.startsWith("\u26A0")?"warn":N.startsWith("\u2713")?"ok":"info",text:N});y&&(zr(N=>N+1),me.current?.setModel(T));return}case"convert":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:d,run:m}=Ho(g),y=xp(e,s);if(y.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let T=qo(y,d);if(T.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${d}". (${y.length} are tracked overall.)`});return}let N=Ur(T),_=3,re=`/convert${d?` --scope ${d}`:""} --run`,Y=Kn(e,"light");if(!m){let P=Ea({files:Bo(e,T),op:"convert",model:Y.model}),E=d?`Scope: ${d} (${T.length} of ${y.length} tracked)
247
+ ${_a}`}),B(l?["/doctor","/init"]:["/init"]);return}l&&B(["/doctor"]);try{let i=fe(e,s),a=Je(i.name);a&&Le(a)&&a.refreshToken?np({profile:i.name,connection:i.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),oe(g=>g+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),B(["/login"])}):(!a||Le(a))&&(u({kind:"note",tone:"warn",text:`Profile "${i.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),B(["/login"]))}catch{}try{let i=Z(e),a=fe(e,s),g=Je(a.name);i&&g&&!Le(g)&&_p(e,i.authoritativeSourceFiles)&&(u({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{vn(e);let i=Cn(e);i.length&&(u({kind:"note",tone:"warn",text:i.join(`
248
+ `)}),ft(Ye()),Dt.current=!1)}catch{}try{let i=vt($t(e));i&&(u({kind:"note",tone:"info",text:`\u{1F4CB} ${i} from the repo's coding agent \u2014 press 1 to /catch-up.`}),B(a=>a.includes("/catch-up")?a:[...a,"/catch-up"]))}catch{}ao()},[]),$e(()=>{let l=setInterval(()=>{ao()},Mp);return()=>clearInterval(l)},[ao]),$e(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${be.columns??80}x${be.rows??24}`;g!==Kr.current&&(Kr.current=g,Ka(d=>d+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Zs(nt.current,Ee())+"\x1B[?2026l")},80))},400)};return be.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),be.off("resize",a)}},[be,Ee]);let Ve=Math.max(20,(be.columns??80)-1),Jr=Ir(()=>Ap(e,s),[e,s,ve]),po=(()=>{let l=Z(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=Xt(e,(l.docsDir??Fa).replace(/\/+$/,"")),a=(()=>{try{return Yt(i)&&Ma(i).length>0}catch{return!1}})();try{let g=fe(e,s),d=Je(g.name);if(!(!!d&&!(Le(d)&&!d.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:Ep,isSetup:!1}:ro?{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}})(),jt=vs(D),Qr=jt.length>0&&!N,fo=p!==null?Ra(p,8,Ve):null,on=ge?ge.paths.filter(l=>!ge.query||l.toLowerCase().includes(ge.query.toLowerCase())).slice(0,8):[],rn=ye?ye.sessions.filter(l=>{let i=ye.query.toLowerCase();return!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],ue=G((l,i)=>{me.current?.close(),me.current=ja({cwd:e,resume:l,profileName:i??s,allowProdWrites:ot.current}),l||(Ce.current={uuid:null,firstPrompt:null,titleFired:!1},rt(null)),dt(0),pt(0)},[e,s]),Zr=G((l,i,a)=>{if(Ip.test(l))try{let g=fe(e,s),d=typeof i.project_id=="string"&&i.project_id||g.project.projectId,m=qn(i,a),y=[],P=Bn(a);l.endsWith("publish_article")&&P&&y.push(`Live: ${P}`),m&&d&&y.push(`Preview: ${Hn(g.connection.portalUrl,d,m,g.project.languageCode??"en")}`),y.length>0&&u({kind:"link",lines:y})}catch{}},[e,s,u]),de=G(async(l,i)=>{Kt(!0),se(null),B([]),Zt(null),so(null),uo(null);let a=++Qe.current;i?.quietUser||u({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let g=Ce.current;g.firstPrompt||(g.firstPrompt=i?.display??l),Me.current=Date.now(),Ze(0),U(!0),Qt.current.clear();let d="",m=!1,y=!1,P="",A=null,_=()=>{A||(A=setTimeout(()=>{A=null,h(P.length>0?P:null)},60))},re=()=>{A&&clearTimeout(A),A=null,h(null)},Y=()=>{if(P.trim()){let $=P.trimEnd();u({kind:"assistant",text:$})}P="",re()};try{for await(let $ of me.current.send(l))if($.type==="session"){if(!g.uuid){g.uuid=$.sessionId;let T=new Date().toISOString(),I=lp(g.firstPrompt??"session");cp({uuid:$.sessionId,name:I,renamed:!1,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:T,updatedAt:T}),rt(I)}}else if($.type==="text"){P+=$.delta,d+=$.delta;let T=Da(P);if(T>0){let I=P.slice(0,T).trimEnd();I&&u({kind:"assistant",text:I}),P=P.slice(T)}_(),Ze(I=>I+$.delta.length)}else if($.type==="tool"){m=!0;let T=Wn($.name,$.input);T&&(Y(),u({kind:"tool",title:T.title,sep:T.sep,arg:T.arg}),Qt.current.set($.id,{name:$.name,input:$.input}))}else if($.type==="article_diff"){let T=Xe($.oldContent,$.newContent,Ee());T&&(Y(),u({kind:"diff",added:T.added,removed:T.removed,lines:T.lines,hidden:T.hidden}))}else if($.type==="tool_result"){$.isError&&/run \/login|not logged in|session expired|rejected the token/i.test($.output)&&(en.current=!0);let T=Qt.current.get($.id);if(T){Qt.current.delete($.id),Y();let I=Fn($.output,4,$.isError?void 0:T.name,T.input);u({kind:"tool-result",lines:I.lines,hidden:I.hidden,isError:$.isError}),$.isError||Zr(T.name,T.input,$.output)}}else if($.type==="result"){if(Y(),dt(I=>I+$.outputTokens),pt(I=>I+$.costUsd),u({kind:"done",seconds:Math.round((Date.now()-Me.current)/1e3),tokens:$.outputTokens,costUsd:$.costUsd,ok:$.ok}),!y&&!m&&!d.trim()&&!St.current&&u({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)."}),$.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(d))try{let I=Sp(e);if(Yt(I)){let J=Nr(I,"utf8").trim();J&&(uo(J),u({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 T=$.ok?ya(d,_t.map(I=>I.name)):[];if(T.length>0?B(T):$.ok&&d.trim()&&fp(l,d,e).then(I=>{I&&Qe.current===a&&se(I)}).catch(()=>{}),g.uuid&&(_r(g.uuid),!g.titleFired)){g.titleFired=!0;let I=g.uuid,J=g.firstPrompt;J&&Aa(J,e).then(O=>{O&&(ap(I,O),rt(O))}).catch(()=>{})}}else $.type==="error"&&(Y(),y=!0,$.kind==="auth"&&(en.current=!0),u({kind:"note",text:`agent error: ${$.message}`,tone:"error"}))}finally{U(!1),re(),oe($=>$+1),Ce.current.uuid&&ga(e,Ce.current.uuid,nt.current),en.current&&(en.current=!1,tn.current=i?.display??l,B(["/login"])),St.current&&(St.current=!1,Be.current.length>0&&(u({kind:"note",tone:"info",text:`(${Be.current.length} queued message(s) discarded)`}),Be.current=[],no([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,Zr,Ee]),sn=G(async l=>{let i=Or(l),a=Jn(e,"standard");Me.current=Date.now(),Ze(0),U(!0);let g=new AbortController;we.current=g,K({verb:"Publishing",total:i.length,done:0,active:[],rows:Vt(i),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${Wt} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let d of Kn({cwd:e,partitions:i,promptFor:m=>Rn(m.paths),concurrency:Wt,profileName:s,allowProdWrites:ot.current,model:a.model,signal:g.signal}))if(d.type==="partition_status")d.status==="running"?K(m=>m&&{...m,active:[...m.active,d.label],rows:Re(m.rows,d.label,"active"),lastAt:Date.now()}):K(m=>m&&{...m,active:m.active.filter(y=>y!==d.label),done:m.done+1,rows:Re(m.rows,d.label,d.status==="done"?"done":"failed"),lastAt:Date.now()});else if(d.type==="partition_event")K(m=>{if(!m)return m;let y={...m,lastAt:Date.now()};return d.event.type==="tool"?y.tools=m.tools+1:d.event.type==="text"&&(y.chars=m.chars+d.event.delta.length),y});else if(d.type==="run_done"){pt(P=>P+d.totalCostUsd),dt(P=>P+d.results.reduce((A,_)=>A+_.outputTokens,0));let m=d.aborted?"Stopped. ":"",y=t.kind==="api"?"api":"subscription";u({kind:"note",tone:d.aborted?"warn":d.ok?"ok":"warn",text:m+Mo(d.results,i,y).join(`
249
+ `)})}}catch(d){u({kind:"note",tone:"error",text:`Publish run failed: ${d.message}`})}finally{we.current=null,K(null),U(!1),oe(d=>d+1)}},[e,s,u,t]),mo=G(async l=>{await de(Lo(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await Dn(e,s,l.replace(/\\/g,"/"));i.length>0&&(Zt(`Related articles not yet published (${i.length}):`),B([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,de]),ho=G(l=>{let i=Je(l);if(!i||Le(i)&&!i.refreshToken)return null;let a={...Ct(i.idToken)??{},...Ct(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),go=G((l,i)=>{if(i){let a=Z(e);a&&(a.defaultProfile=l,mp(a,e))}c(l),ue(void 0,l),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),ho(l)||(u({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),B(["/login"])),oe(a=>a+1)},[e,u,ue,ho]),an=G((l,i,a)=>{pn(e,l,i,a.id,a.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),ue(),Ea(e,l)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({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:"}),u({kind:"note",tone:"info",text:kt(yt(e)).join(`
250
+ `)}),ft(Ye()),Dt.current=Ne(e).status==="current",u({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,u,ue,ft]),ln=G(async l=>{let i;try{i=await It(e,l)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),B(["/workspace"]);return}if(i.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(d=>(d.workspace_type??"").toLowerCase()!=="apidocumentation"),g=a.length>0?a:i.workspaces;if(g.length===1){let d=g[0],m=i.workspaces.length-g.length;u({kind:"note",tone:"ok",text:`Selected the "${d.name??d.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),an(i.profile,i.projectId,d);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),B(["/workspace"])},[e,u,an]),es=G((l,i)=>{xo(e,l,i.id,i.name),u({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),ue(),ln(l)},[e,u,ue,ln]),ts=G(async l=>{let i;try{i=fe(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await gt(e,i.name),g=a.find(d=>d.id===i.project.projectId);g?.name&&Rp(e,i.name,{projectName:g.name})}catch{}await ln(i.name);return}u({kind:"note",tone:"info",text:"Next: pick the Document360 project."}),B(["/project"])}},[e,u,ln]),cn=G(()=>{let l=je.current[0];if(!l)return;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let a of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${a}`});l.overwritesLocalChanges&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let i=Xe(l.oldContent,l.newContent,Ee());u(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."}),u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,Ee]),ns=G(l=>{if(je.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=je.current.shift();try{hp({cwd:e,profileName:s},a),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),je.current.length===0&&B(g=>g.length>0?g:["/sync"])}catch(g){u({kind:"note",tone:"error",text:`Pull failed: ${g.message}`})}}else if(i==="n"||i==="no"){let a=je.current.shift();u({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=je.current.length;return je.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return cn(),!0},[e,s,cn,u]),os=G(l=>{let i=to.current;if(!i)return!1;if(to.current=null,se(null),Qe.current++,l.trim()!==i.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:g}=Cr(e,i.targets);u({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 d of g)u({kind:"note",tone:"error",text:` \u2717 ${d.path}: ${d.error}`});return i.hadDevhints&&(u({kind:"note",tone:"warn",text:Pn().join(`
251
+ `)}),ft(So())),u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
252
+ ${_a}`}),B(["/init"]),Kt(!1),!0},[e,u,ft]),rs=G(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),g=i.slice(1);switch(Kt(!0),a){case"help":u({kind:"note",tone:"info",text:kn().join(`
253
+ `)});return;case"exit":case"quit":me.current?.close(),r();return;case"clear":ue(),nt.current=[],Kt(!1),se(null),Qe.current++,u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let d;try{d=fe(e,s)}catch(m){u({kind:"note",tone:"error",text:m.message});return}u({kind:"note",tone:"info",text:`Profile "${d.name}" \u2192 ${d.connection.name} (${d.connection.apiUrl})${d.production?" \u26A0 PRODUCTION":""}`}),ee(!0);try{let m=await Zd(d.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},P=>u({kind:"note",tone:"info",text:P})),y=ep(d.name,m);if(tp(y),await $o(y,d.name,P=>u({kind:"note",tone:"info",text:P})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${d.name}" as ${mn(y)}`}),await ts(s),Rt.current){let P=Rt.current;Rt.current=null;let A=Se(e,s);A.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${P}.`}),B([P])):(u({kind:"note",tone:"warn",text:`${A.reason} (then ${P}.)`}),B(["/login"]),Rt.current=P)}else tn.current&&(se(tn.current),tn.current=null,u({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(m){u({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{ee(!1),oe(m=>m+1)}return}case"allow-prod":{let d=!1;try{d=fe(e,s).production}catch{}if(!d){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}ot.current=!0,ue(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let d=cr(g.join(" ")),m=Ce.current.uuid;if(!m){u({kind:"note",tone:"error",text:"Send a message first \u2014 sessions save once the agent replies."});return}if(!d){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let y=Ce.current.firstPrompt??"";Aa(y,e).then(P=>{P?(se(`/rename ${P}`),u({kind:"note",tone:"info",text:`Suggestion: "${P}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}pp(m,d),rt(d),Gt(`${jr} d360-writer \xB7 ${d}`),u({kind:"note",tone:"ok",text:`Session renamed to "${d}".`});return}case"profile":{let d=g[0],m=Z(e);if(!d){let y=Object.entries(m?.profiles??{});if(y.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let P=y.map(([re,Y])=>({name:re,env:Y.connection?.environment??"custom",prod:Y.production===!0,who:ho(re)})),A=s??m?.defaultProfile,_=Math.max(0,P.findIndex(re=>re.name===A));st({cursor:_,current:_,rows:P});return}if(d==="add"){let y=ur(e,g[1],g[2]);if(y){u({kind:"note",tone:"error",text:y});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),go(g[1],!1);return}if(!m?.profiles?.[d]){u({kind:"note",tone:"error",text:`Unknown profile "${d}". Create it: /profile add ${d} <environment>`});return}go(d,!0);return}case"doctor":await qt(g,{cwd:e});return;case"mcp":await Sn(g);return;case"init":{if(Z(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer.json directly (or d360-writer init for the CLI wizard)."});return}let d=yp().map(m=>({name:m,apiUrl:kp(m).apiUrl}));it({cursor:0,rows:d});return}case"resume":{let d=g.join(" ").trim(),m=dp(e).filter(A=>A.uuid!==Ce.current.uuid);if(!d){if(!m.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Ge({query:"",cursor:0,sessions:m});return}let y=up(e,d);if(!y){u({kind:"note",tone:"error",text:`No session matches "${d}".`});return}ue(y.uuid),Ce.current={uuid:y.uuid,firstPrompt:y.firstPrompt,titleFired:!0},rt(y.name),_r(y.uuid),nt.current=[];let P=Dr(e,y.uuid);for(let A of P)u(A);u({kind:"note",tone:"ok",text:P.length?`Resumed "${y.name}" \u2014 restored ${P.length} message(s); continue where you left off.`:`Resumed "${y.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let d=g.join(" ").trim(),m;try{m=await It(e,s)}catch(P){u({kind:"note",tone:"error",text:`Could not list workspaces: ${P.message}`});return}if(!d){let P=m.workspaces.map(_=>({id:_.id,name:_.name??_.id,type:_.workspace_type}));if(P.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let A=Math.max(0,P.findIndex(_=>_.id===m.current));at({cursor:A,current:A,rows:P,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let y=bo(m.workspaces,d);if(!y){u({kind:"note",tone:"error",text:`No workspace matches "${d}".`});return}an(m.profile,m.projectId,y);return}case"project":{let d=g.join(" ").trim(),m;try{m=await gt(e,s)}catch(P){u({kind:"note",tone:"error",text:`Could not list projects: ${P.message} (signed in? try /login)`});return}if(!d){let P=m.projects.map(_=>({id:_.id,name:_.name??_.id,sub:_.sub_domain}));if(P.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let A=P.findIndex(_=>_.id===m.current);lt({cursor:Math.max(0,A),current:A,rows:P,profile:m.profile,environment:m.environment});return}let y=ps(m.projects,d);if(!y){u({kind:"note",tone:"error",text:`No project matches "${d}". Available: ${m.projects.map(P=>P.name??P.id).join(", ")}`});return}es(m.profile,y);return}case"logout":{let d;try{d=fe(e,s).name}catch(y){u({kind:"note",tone:"error",text:y.message});return}let m=sp(d);ip(e,d),ue(),oe(y=>y+1),u({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${d}" and cleared its project/workspace selection.`:`Profile "${d}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),B(["/login"]);return}case"publish":{if(!lo(l.trim()))return;if(g[0]==="--related"&&g[1]){let m=await Dn(e,s,g[1].replace(/\\/g,"/"));if(m.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await sn(m);return}if(g[0]&&g[0]!=="--all"){await mo(g[0]);return}let d=g[0]==="--all";u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Ur({cwd:e,profileName:s}),y=Ft(m.entries);if(y.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let P=m.counts["unknown-base"]??0;P>0&&u({kind:"note",tone:"info",text:`(${P} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(d){await sn(y.map(P=>P.path));return}ct({cursor:0,rows:ni(y)})}catch(m){u({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let d=g.join(" ").trim();if(!d){let y=[];try{y=Object.keys(Ea(e,fe(e,s).name)?.articles??{})}catch{}if(y.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}qe({query:"",cursor:0,paths:y});return}let m=Jd(d)?d:Xt(e,d);if(Yt(m)){try{u({kind:"preview",name:zt(m),text:Oa(Nr(m,"utf8"))})}catch(y){u({kind:"note",tone:"error",text:`Could not read ${m}: ${y.message}`})}return}if(Np.test(d)){try{let y=fe(e,s),P={profile:y.name,connection:y.connection},A=y.project.projectId??op(P),_=await rp(P,A,d);u({kind:"preview",name:_.title??d,text:_.content??"*(article has no content)*"})}catch(y){u({kind:"note",tone:"error",text:`Could not fetch article: ${y.message}`})}return}u({kind:"note",tone:"error",text:`"${d}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let d=g[0]?.trim();if(!d){let A=Nn(Mr(e));Fe({cursor:A,current:A});return}let{lines:m,changed:y,effective:P}=Ht(e,d);for(let A of m)u({kind:"note",tone:A.startsWith("\u26A0")?"warn":A.startsWith("\u2713")?"ok":"info",text:A});y&&(Xr(A=>A+1),me.current?.setModel(P));return}case"convert":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:d,run:m}=qo(g),y=$p(e,s);if(y.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let P=Bo(y,d);if(P.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${d}". (${y.length} are tracked overall.)`});return}let A=Or(P),_=3,re=`/convert${d?` --scope ${d}`:""} --run`,Y=Jn(e,"light");if(!m){let T=Ia({files:Go(e,P),op:"convert",model:Y.model}),I=d?`Scope: ${d} (${P.length} of ${y.length} tracked)
254
254
  `:"",J=`
255
- Model: ${Y.model}${Y.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:E+Vo(N,P,_).join(`
256
- `)+J}),V([re]);return}Me.current=Date.now(),Ze(0),U(!0);let $=new AbortController;we.current=$,K({verb:"Converting",total:N.length,done:0,active:[],rows:Gt(N),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${T.length} articles across ${N.length} partitions (\u2264${_} agents at once) on ${Y.model}\u2026 (esc to stop)`});try{for await(let P of Xn({cwd:e,partitions:N,promptFor:Go,concurrency:_,profileName:s,allowProdWrites:ot.current,model:Y.model,signal:$.signal}))if(P.type==="partition_status")P.status==="running"?K(E=>E&&{...E,active:[...E.active,P.label],rows:Se(E.rows,P.label,"active"),lastAt:Date.now()}):K(E=>E&&{...E,active:E.active.filter(J=>J!==P.label),done:E.done+1,rows:Se(E.rows,P.label,P.status==="done"?"done":"failed"),lastAt:Date.now()});else if(P.type==="partition_event")K(E=>{if(!E)return E;let J={...E,lastAt:Date.now()};return P.event.type==="tool"?J.tools=E.tools+1:P.event.type==="text"&&(J.chars=E.chars+P.event.delta.length),J});else if(P.type==="run_done"){pt(O=>O+P.totalCostUsd),dt(O=>O+P.results.reduce((z,ae)=>z+ae.outputTokens,0));let E=P.aborted?"Stopped. ":"",J=t.kind==="api"?"api":"subscription";u({kind:"note",tone:P.aborted?"warn":P.ok?"ok":"warn",text:E+Yo(P.results,N,J).join(`
257
- `)})}}catch(P){u({kind:"note",tone:"error",text:`Convert run failed: ${P.message}`})}finally{we.current=null,K(null),U(!1),oe(P=>P+1)}return}case"write":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=$p(e);if(d.length===0){u({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:y,run:T}=Xo(g),{docsDir:N,targets:_,reason:re}=er(e,d,{scope:m,path:y});if(_.length===0){u({kind:"note",tone:"warn",text:re??"Nothing to write."});return}let Y=Ur(_),$=5,P=Kn(e,"standard");if(!T&&!!!y){let O=Ea({files:Ko(e,d,_),op:"write",model:P.model}),z=m?`Scope: ${m} (${_.length} pending)
255
+ Model: ${Y.model}${Y.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:I+Yo(A,T,_).join(`
256
+ `)+J}),B([re]);return}Me.current=Date.now(),Ze(0),U(!0);let $=new AbortController;we.current=$,K({verb:"Converting",total:A.length,done:0,active:[],rows:Vt(A),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${P.length} articles across ${A.length} partitions (\u2264${_} agents at once) on ${Y.model}\u2026 (esc to stop)`});try{for await(let T of Kn({cwd:e,partitions:A,promptFor:Vo,concurrency:_,profileName:s,allowProdWrites:ot.current,model:Y.model,signal:$.signal}))if(T.type==="partition_status")T.status==="running"?K(I=>I&&{...I,active:[...I.active,T.label],rows:Re(I.rows,T.label,"active"),lastAt:Date.now()}):K(I=>I&&{...I,active:I.active.filter(J=>J!==T.label),done:I.done+1,rows:Re(I.rows,T.label,T.status==="done"?"done":"failed"),lastAt:Date.now()});else if(T.type==="partition_event")K(I=>{if(!I)return I;let J={...I,lastAt:Date.now()};return T.event.type==="tool"?J.tools=I.tools+1:T.event.type==="text"&&(J.chars=I.chars+T.event.delta.length),J});else if(T.type==="run_done"){pt(O=>O+T.totalCostUsd),dt(O=>O+T.results.reduce((z,ae)=>z+ae.outputTokens,0));let I=T.aborted?"Stopped. ":"",J=t.kind==="api"?"api":"subscription";u({kind:"note",tone:T.aborted?"warn":T.ok?"ok":"warn",text:I+zo(T.results,A,J).join(`
257
+ `)})}}catch(T){u({kind:"note",tone:"error",text:`Convert run failed: ${T.message}`})}finally{we.current=null,K(null),U(!1),oe(T=>T+1)}return}case"write":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=vp(e);if(d.length===0){u({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:y,run:P}=Ko(g),{docsDir:A,targets:_,reason:re}=tr(e,d,{scope:m,path:y});if(_.length===0){u({kind:"note",tone:"warn",text:re??"Nothing to write."});return}let Y=Or(_),$=5,T=Jn(e,"standard");if(!P&&!!!y){let O=Ia({files:Jo(e,d,_),op:"write",model:T.model}),z=m?`Scope: ${m} (${_.length} pending)
258
258
  `:"",ae=`
259
- Model: ${P.model}${P.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:z+Qo(Y,O,$).join(`
260
- `)+ae}),V([`/write${m?` --scope ${m}`:" --all"} --run`]);return}Me.current=Date.now(),Ze(0),U(!0);let J=new AbortController;we.current=J,K({verb:"Writing",total:Y.length,done:0,active:[],rows:Gt(Y),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${_.length} article${_.length===1?"":"s"} across ${Y.length} partition${Y.length===1?"":"s"} (\u2264${$} agents at once) on ${P.model}${P.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let O of Xn({cwd:e,partitions:Y,promptFor:z=>Jo(z,N),concurrency:$,profileName:s,allowProdWrites:ot.current,model:P.model,signal:J.signal}))if(O.type==="partition_status")O.status==="running"?K(z=>z&&{...z,active:[...z.active,O.label],rows:Se(z.rows,O.label,"active"),lastAt:Date.now()}):K(z=>z&&{...z,active:z.active.filter(ae=>ae!==O.label),done:z.done+1,rows:Se(z.rows,O.label,O.status==="done"?"done":"failed"),lastAt:Date.now()});else if(O.type==="partition_event")K(z=>{if(!z)return z;let ae={...z,lastAt:Date.now()};return O.event.type==="tool"?ae.tools=z.tools+1:O.event.type==="text"&&(ae.chars=z.chars+O.event.delta.length),ae});else if(O.type==="run_done"){pt(wo=>wo+O.totalCostUsd),dt(wo=>wo+O.results.reduce((Qa,Za)=>Qa+Za.outputTokens,0));let z=O.aborted?"Stopped. ":"",ae=t.kind==="api"?"api":"subscription";u({kind:"note",tone:O.aborted?"warn":O.ok?"ok":"warn",text:z+Zo(O.results,Y,ae).join(`
261
- `)}),!O.aborted&&O.ok&&V(["/publish --all","/screenshot --all"])}}catch(O){u({kind:"note",tone:"error",text:`Write run failed: ${O.message}`})}finally{we.current=null,K(null),U(!1),oe(O=>O+1)}return}case"draft":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:d,looseDocs:m}=tr(e);if(d.length===0&&m===0){u({kind:"note",tone:"info",text:or});return}let y=g.join(" ").trim();if(!y&&d.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
259
+ Model: ${T.model}${T.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:z+Zo(Y,O,$).join(`
260
+ `)+ae}),B([`/write${m?` --scope ${m}`:" --all"} --run`]);return}Me.current=Date.now(),Ze(0),U(!0);let J=new AbortController;we.current=J,K({verb:"Writing",total:Y.length,done:0,active:[],rows:Vt(Y),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${_.length} article${_.length===1?"":"s"} across ${Y.length} partition${Y.length===1?"":"s"} (\u2264${$} agents at once) on ${T.model}${T.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let O of Kn({cwd:e,partitions:Y,promptFor:z=>Qo(z,A),concurrency:$,profileName:s,allowProdWrites:ot.current,model:T.model,signal:J.signal}))if(O.type==="partition_status")O.status==="running"?K(z=>z&&{...z,active:[...z.active,O.label],rows:Re(z.rows,O.label,"active"),lastAt:Date.now()}):K(z=>z&&{...z,active:z.active.filter(ae=>ae!==O.label),done:z.done+1,rows:Re(z.rows,O.label,O.status==="done"?"done":"failed"),lastAt:Date.now()});else if(O.type==="partition_event")K(z=>{if(!z)return z;let ae={...z,lastAt:Date.now()};return O.event.type==="tool"?ae.tools=z.tools+1:O.event.type==="text"&&(ae.chars=z.chars+O.event.delta.length),ae});else if(O.type==="run_done"){pt(yo=>yo+O.totalCostUsd),dt(yo=>yo+O.results.reduce((Za,el)=>Za+el.outputTokens,0));let z=O.aborted?"Stopped. ":"",ae=t.kind==="api"?"api":"subscription";u({kind:"note",tone:O.aborted?"warn":O.ok?"ok":"warn",text:z+er(O.results,Y,ae).join(`
261
+ `)}),!O.aborted&&O.ok&&B(["/publish --all","/screenshot --all"])}}catch(O){u({kind:"note",tone:"error",text:`Write run failed: ${O.message}`})}finally{we.current=null,K(null),U(!1),oe(O=>O+1)}return}case"draft":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:d,looseDocs:m}=nr(e);if(d.length===0&&m===0){u({kind:"note",tone:"info",text:rr});return}let y=g.join(" ").trim();if(!y&&d.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
262
262
  ${d.map(_=>` \u2022 ${_.name} (${_.docCount} doc${_.docCount===1?"":"s"})`).join(`
263
- `)}`}),V(d.map(_=>`/draft ${_.name}`));return}let T="",N;if(y){let _=nr(d,y);_?T=_:N=y}else T=d[0]?.name??"";await de(En(T,N),{display:y?`/draft ${y}`:"/draft",quietUser:!0});return}case"sync":{if(!ao())return;let d=(g[0]??"status").toLowerCase();try{if(d==="status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let m=await _r({cwd:e,profileName:s});u({kind:"note",tone:"info",text:An(m).join(`
264
- `)});return}if(d==="pull"){let m=g[1];if(!m){u({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let y;if(m==="--all"){if(u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),y=(await _r({cwd:e,profileName:s})).entries.filter(_=>_.status==="remote-ahead"&&_.path).map(_=>_.path),y.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing is remote-ahead \u2014 no pulls needed. (Conflicts are never bulk-pulled; pull them one by one.)"});return}}else y=[m.replace(/\\/g,"/")];let T=[];for(let N of y)T.push(await hp({cwd:e,profileName:s,relPath:N}));De.current=T,ln();return}u({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${d} \u2014 use /sync or /sync pull <path>|--all.`})}catch(m){u({kind:"note",tone:"error",text:`Sync failed: ${m.message}`})}return}case"scope":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=gp(e);if(d.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}ut({cursor:0,rows:d.map(m=>({...m,checked:m.recommended}))});return}case"audit":case"capture-setup":{let m=await(a==="audit"?Dn:qt)(g,void 0);if(m.kind==="forward-to-agent"&&m.prompt&&await de(m.prompt,{display:m.display,quietUser:!0}),a==="capture-setup"){let y=hr(e);y&&u({kind:"note",tone:"info",text:y.join(`
263
+ `)}`}),B(d.map(_=>`/draft ${_.name}`));return}let P="",A;if(y){let _=or(d,y);_?P=_:A=y}else P=d[0]?.name??"";await de(In(P,A),{display:y?`/draft ${y}`:"/draft",quietUser:!0});return}case"sync":{if(!lo(l.trim()))return;let d=(g[0]??"status").toLowerCase();try{if(d==="status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let m=await Ur({cwd:e,profileName:s});u({kind:"note",tone:"info",text:En(m).join(`
264
+ `)});return}if(d==="pull"){let m=g[1];if(!m){u({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let y;if(m==="--all"){if(u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),y=(await Ur({cwd:e,profileName:s})).entries.filter(_=>_.status==="remote-ahead"&&_.path).map(_=>_.path),y.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing is remote-ahead \u2014 no pulls needed. (Conflicts are never bulk-pulled; pull them one by one.)"});return}}else y=[m.replace(/\\/g,"/")];let P=[];for(let A of y)P.push(await gp({cwd:e,profileName:s,relPath:A}));je.current=P,cn();return}u({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${d} \u2014 use /sync or /sync pull <path>|--all.`})}catch(m){u({kind:"note",tone:"error",text:`Sync failed: ${m.message}`})}return}case"scope":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=wp(e);if(d.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}ut({cursor:0,rows:d.map(m=>({...m,checked:m.recommended}))});return}case"audit":case"capture-setup":{let m=await(a==="audit"?jn:Bt)(g,void 0);if(m.kind==="forward-to-agent"&&m.prompt&&await de(m.prompt,{display:m.display,quietUser:!0}),a==="capture-setup"){let y=gr(e);y&&u({kind:"note",tone:"info",text:y.join(`
265
265
  `)})}return}case"devhints":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:kt(yt(e)).join(`
266
- `)}),ft(Ye()),Rt.current=Ie(e).status==="current";return}case"inbox":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(gr(e)===0){u({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 de(wr(),{display:"/inbox",quietUser:!0});return}case"document":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:d,what:m}=sr(g);if(!m&&rr(e)===0){u({kind:"note",tone:"info",text:ar});return}let y=`/document${m?` ${m}`:""}${d?" --publish":""}`;await de(ir(m,d),{display:y,quietUser:!0});return}case"catch-up":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!ao())return;let{publish:d}=yr(g),m=vt($t(e));u({kind:"note",tone:"info",text:m?`Catching up on ${m} (+ checking Document360 for drift)\u2026`:"No local queue \u2014 checking for code changes and drift\u2026"}),await de(kr({publish:d}),{display:`/catch-up${d?" --publish":""}`,quietUser:!0});return}case"update":{so.current=!0,u({kind:"note",tone:"info",text:`Updating ${Ke}\u2026`}),(await On()).ok?(u({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 /exit and relaunch to apply (press 1)."}),V(m=>m.includes("/exit")?m:[...m,"/exit"])):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Un}`});return}case"screenshot":{let d=pr(g);if(d.mode==="list"){if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:mr(fr(e,d.scope),d.scope).join(`
267
- `)});return}if(d.mode==="single"){let $=await _n(g);$.kind==="forward-to-agent"&&$.prompt&&await de($.prompt,{display:$.display,quietUser:!0});return}if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=d.mode==="scope"?d.scope:void 0,y=bp(e,{scope:m}).map($=>$.id);if(y.length===0){u({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let T=6,N=kp(y,3),_=Kn(e,"standard");Me.current=Date.now(),Ze(0),U(!0);let re=new AbortController;we.current=re,K({verb:"Authoring",unit:"spec",total:N.length,done:0,active:[],rows:Gt(N),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${y.length} screenshot spec${y.length===1?"":"s"} across ${N.length} partition${N.length===1?"":"s"} (\u2264${T} agents at once) on ${_.model}${_.forced?" (forced)":""}\u2026 (esc to stop)`});let Y=!1;try{for await(let $ of Xn({cwd:e,partitions:N,promptFor:Gi,concurrency:T,profileName:s,allowProdWrites:ot.current,model:_.model,signal:re.signal}))if($.type==="partition_status")$.status==="running"?K(P=>P&&{...P,active:[...P.active,$.label],rows:Se(P.rows,$.label,"active"),lastAt:Date.now()}):K(P=>P&&{...P,active:P.active.filter(E=>E!==$.label),done:P.done+1,rows:Se(P.rows,$.label,$.status==="done"?"done":"failed"),lastAt:Date.now()});else if($.type==="partition_event")K(P=>{if(!P)return P;let E={...P,lastAt:Date.now()};return $.event.type==="tool"?E.tools=P.tools+1:$.event.type==="text"&&(E.chars=P.chars+$.event.delta.length),E});else if($.type==="run_done"){pt(O=>O+$.totalCostUsd),dt(O=>O+$.results.reduce((z,ae)=>z+ae.outputTokens,0));let P=$.results.filter(O=>O.ok).length,E=$.aborted?"Stopped. ":"";Y=!$.aborted&&d.setup;let J=$.aborted?"":Y?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";u({kind:"note",tone:$.aborted?"warn":$.ok?"ok":"warn",text:`${E}Authored specs \u2014 ${P}/${$.results.length} batches ok.${J}`})}}catch($){u({kind:"note",tone:"error",text:`Spec authoring failed: ${$.message}`})}finally{we.current=null,K(null),U(!1),oe($=>$+1)}if(Y){let $=await qt();$.kind==="forward-to-agent"&&$.prompt&&await de($.prompt,{display:$.display,quietUser:!0});let P=hr(e);P&&u({kind:"note",tone:"info",text:P.join(`
268
- `)})}return}case"reset":{let d=$r(e);if(d.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}eo.current={repoName:Yt(e),targets:d,hadDevhints:Vt(Ia(e))},u({kind:"note",tone:"warn",text:Cr(e,d).join(`
269
- `)}),se(Yt(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,ln,u,ue,de,rn,fo,es]),cn=B(l=>{let i=(l??D).trim();if(w(""),Kt(null),et(0),i.startsWith("/")&&(se(null),Qe.current++,Qt(null),V(g=>ka(g,i))),!i||ns(i)||ts(i))return;Zn.current.push(i);let a=va(i,Fr.current);i.startsWith("/")?(u({kind:"user",text:i}),os(a)):de(a,{display:i})},[D,ns,ts,os,de]),rs=B(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=ba(l);if(xa(i)){let a=$a(++Ya.current,i);Fr.current.set(a,i),v(a)}else v(i);return}v(l)},[v]),mt=Math.max(10,Ve-6),ss=Er(()=>Yn(b.text,mt),[b.text,mt]),go=B(l=>k(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),un=B(l=>k(i=>({...i,pos:Pa(Yn(i.text,mt),i.pos,l)})),[mt]),jt=B(l=>k(i=>({...i,pos:Ta(Yn(i.text,mt),i.pos,l)})),[mt]),Ka=["\x1B[H","\x1B[1~","\x1BOH"],Ja=["\x1B[F","\x1B[4~","\x1BOF"],is=B((l,i)=>i.leftArrow?(go(-1),!0):i.rightArrow?(go(1),!0):l&&Ka.includes(l)?(jt("start"),!0):l&&Ja.includes(l)?(jt("end"),!0):i.ctrl&&l==="a"?(jt("start"),!0):i.ctrl&&l==="e"?(jt("end"),!0):!1,[go,jt]);return zd((l,i)=>{if(i.ctrl&&l==="c"){me.current?.close(),r();return}if(!H){if(I){if(i.escape){if(we.current){we.current.signal.aborted||(u({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),we.current.abort());return}St.current||(St.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),me.current?.interrupt());return}if(i.return){let a=D.trim();if(!a)return;Be.current.push(a),to([...Be.current]),w("");return}if(is(l,i))return;if(i.upArrow){un(-1);return}if(i.downArrow){un(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&rs(l);return}if(We){if(i.upArrow){Fe(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Fe(a=>a&&{...a,cursor:Math.min(xe.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=xe.length){Fe(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=xe[We.cursor];Fe(null);let{lines:g,changed:d,effective:m}=Ft(e,a.value??"default");for(let y of g)u({kind:"note",tone:y.startsWith("\u26A0")?"warn":y.startsWith("\u2713")?"ok":"info",text:y});d&&(zr(y=>y+1),me.current?.setModel(m));return}if(l==="s"){let a=xe[We.cursor];Fe(null),me.current?.setModel(a.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){Fe(null);return}return}if(Pe){if(i.upArrow){st(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){st(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Pe.rows.length){st(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=Pe.rows[Pe.cursor];st(null),ho(a.name,i.return===!0);return}if(i.escape){st(null);return}return}if(je){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(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=je.rows.length){it(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=je.rows[je.cursor].name;if(it(null),!Ws(e,a).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${a}").`});let d=!1;try{let m=Je(a);d=!!m&&!(Le(m)&&!m.refreshToken)}catch{d=!1}u({kind:"note",tone:"info",text:d?`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)`}),V(["/login"]),oe(m=>m+1);return}if(i.escape){it(null);return}return}if(ie){if(i.upArrow){at(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){at(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ie.rows.length){at(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ie.rows[ie.cursor],{profile:g,projectId:d}=ie;at(null),sn(g,d,a);return}if(i.escape){at(null);return}return}if(he){if(i.upArrow){lt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){lt(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){lt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=he.rows[he.cursor],{profile:g}=he;lt(null),Zr(g,a);return}if(i.escape){lt(null);return}return}if(ce){if(i.upArrow){ut(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){ut(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){ut(a=>a&&{...a,rows:a.rows.map((g,d)=>d===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=ce.rows.filter(g=>g.checked).map(g=>g.path);if(ut(null),a.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Mo(e,a),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer.json`});for(let g of a)u({kind:"note",tone:"info",text:` ${g}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){ut(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&&/^[1-9]$/.test(l)&&Number(l)<=He.rows.length){ct(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=He.rows[He.cursor];ct(null),a.kind==="article"?fo(a.paths[0]):rn(a.paths);return}if(i.escape){ct(null);return}return}if(ge){if(i.escape){qe(null);return}if(i.upArrow){qe(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){qe(a=>a&&{...a,cursor:Math.min(Math.max(0,nn.length-1),a.cursor+1)});return}if(i.return){let a=nn[ge.cursor];if(a){qe(null);try{u({kind:"preview",name:Yt(a),text:Ua(Ir(zt(e,a),"utf8"))})}catch(g){u({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){qe(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){qe(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(ye){if(i.escape){Ge(null);return}if(i.upArrow){Ge(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ge(a=>a&&{...a,cursor:Math.min(Math.max(0,on.length-1),a.cursor+1)});return}if(i.return){let a=on[ye.cursor];if(a){Ge(null),ue(a.uuid),Ce.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},rt(a.name),Nr(a.uuid),nt.current=[];let g=Rr(e,a.uuid);for(let d of g)u(d);u({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){Ge(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){Ge(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!D&&ke){w(ke),se(null),Qe.current++;return}if(!D&&Pt.length>0&&l&&/^[1-9]$/.test(l)){let a=Pt[Number(l)-1];if(a){w(a);return}}if(!D&&(lo||oo)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=lo!=null;da(lo??oo).then(d=>{u({kind:"note",tone:d?"ok":"warn",text:d?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."}),d&&a&&co(null)});return}if(!is(l,i)){if(Jr){if(i.upArrow){et(a=>Math.max(0,a-1));return}if(i.downArrow){et(a=>Math.min(Dt.length-1,a+1));return}if(i.tab){w("/"+(Dt[Tt]?.name??"")+" "),et(0);return}if(i.return){let a=Dt[Tt];if(a){let g=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(vs(a.usage)&&!g){w("/"+a.name+" "),et(0);return}cn("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(D!==""&&tt===null){un(-1);return}let a=Zn.current;if(!a.length)return;let g=tt===null?a.length-1:Math.max(0,tt-1);Kt(g),w(a[g]??"");return}if(i.downArrow){if(D!==""&&tt===null){un(1);return}let a=Zn.current;if(tt===null)return;let g=tt+1;g>=a.length?(Kt(null),w("")):(Kt(g),w(a[g]??""));return}}if(i.return){cn();return}if(i.backspace||i.delete){C();return}if(i.escape){w(""),et(0),se(null),V([]),Qt(null);return}l&&!i.ctrl&&!i.meta&&rs(l)}}}),$e(()=>{if(I||H)return;let l=Be.current.shift();l!==void 0&&(to([...Be.current]),cn(l))},[I,H,cn]),F(Q,{flexDirection:"column",width:Ve,children:[po!==null&&F(Q,{marginTop:1,flexDirection:"column",children:[po.truncated&&R(S,{dimColor:!0,children:"\u2026"}),R(S,{children:po.text})]}),I&&(Gr?R(Op,{p:Gr}):R(_p,{startTime:Me.current,chars:Va})),R(Q,{borderStyle:"round",borderColor:Kr.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?ss.map((l,i)=>{let a=b.text.slice(l.start,l.end),g=i===zn(ss,b.pos),d=Math.min(b.pos,l.end)-l.start;return F(S,{children:[R(S,{color:q,children:i===0?"> ":" "}),g?F(Or,{children:[a.slice(0,d),R(Jn,{ch:a[d]??" "}),a.slice(d+1)]}):a||" "]},`${i}-${l.start}`)}):F(S,{children:[R(S,{color:q,children:"> "}),ke&&!I?F(Or,{children:[R(Jn,{ch:ke[0],dim:!0}),R(S,{color:"gray",children:ke.slice(1)}),R(S,{dimColor:!0,children:" (tab)"})]}):uo.isSetup||!Ga?F(Or,{children:[R(Jn,{ch:uo.text[0],dim:!0}),R(S,{color:"gray",children:uo.text.slice(1)})]}):R(Jn,{ch:" "})]})}),Br.length>0&&R(Q,{flexDirection:"column",paddingX:1,children:Br.map((l,i)=>R(S,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),We?F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:"Select model"}),R(S,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),xe.map((l,i)=>F(S,{color:i===We.cursor?q:void 0,children:[i===We.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===We.current?" \u2714":""}`.padEnd(16),R(S,{color:"gray",children:l.desc})]},l.label)),R(S,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Pe?F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:"Switch connection profile"}),Pe.rows.map((l,i)=>F(S,{color:i===Pe.cursor?q:void 0,children:[i===Pe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===Pe.current?" \u2714":""}`.padEnd(20),R(S,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?R(S,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),R(S,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):je?F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:"Pick your Document360 environment"}),je.rows.map((l,i)=>F(S,{color:i===je.cursor?q:void 0,children:[i===je.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),R(S,{color:"gray",children:l.apiUrl})]},l.name)),R(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ie?F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:"Switch workspace"}),R(S,{dimColor:!0,children:`environment ${ie.environment} \xB7 project ${ie.projectName??`${ie.projectId.slice(0,8)}\u2026`}`}),ie.rows.map((l,i)=>F(S,{color:i===ie.cursor?q:void 0,children:[i===ie.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===ie.current?" \u2714":""}`.padEnd(30),R(S,{color:"gray",children:l.type??""})]},l.id)),R(S,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):he?F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:"Choose project"}),R(S,{dimColor:!0,children:`environment ${he.environment}`}),he.rows.map((l,i)=>F(S,{color:i===he.cursor?q:void 0,children:[i===he.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===he.current?" \u2714":""}`.padEnd(30),R(S,{color:"gray",children:l.sub??""})]},l.id)),R(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ce?(()=>{let i=Math.min(Math.max(0,ce.cursor-Math.floor(7)),Math.max(0,ce.rows.length-14)),a=ce.rows.slice(i,i+14),g=ce.rows.filter(d=>d.checked).length;return F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:`Which folders back the user docs? (${g} selected of ${ce.rows.length})`}),i>0?R(S,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((d,m)=>{let y=i+m;return F(S,{color:y===ce.cursor?q:void 0,children:[y===ce.cursor?"\u276F ":" ",d.checked?"\u25C9 ":"\u25CB ",d.path.padEnd(Math.min(48,Ve-34)),R(S,{color:"gray",children:jn(d)})]},d.path)}),i+14<ce.rows.length?R(S,{dimColor:!0,children:` \u2193 ${ce.rows.length-i-14} more`}):null,R(S,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():He?F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),He.rows.map((l,i)=>{let a=i===He.cursor,g=l.indent?" ":" ",d=`${i+1}.`.padEnd(3);return F(S,{color:a?q:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${d} ${l.label}`.padEnd(Math.min(56,Ve-24)),l.note?R(S,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),R(S,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ge?F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:`Preview article${ge.query?` \u2014 filter: ${ge.query}`:" (type to filter)"}`}),nn.length===0?R(S,{color:"gray",children:"no articles match"}):nn.map((l,i)=>F(S,{color:i===ge.cursor?q:void 0,children:[i===ge.cursor?"\u276F ":" ",l]},l)),R(S,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):ye?F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:`Resume session${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),on.length===0?R(S,{color:"gray",children:"no sessions match"}):on.map((l,i)=>F(S,{color:i===ye.cursor?q:void 0,children:[i===ye.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),R(S,{color:i===ye.cursor?q:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ve-40))})]},l.uuid)),R(S,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Jr?R(Q,{flexDirection:"column",children:Dt.map((l,i)=>F(S,{color:i===Tt?q:void 0,children:[i===Tt?"\u276F ":" ",l.usage.padEnd(22)," ",R(S,{color:i===Tt?q:"gray",children:l.name==="model"&&no?`${l.desc} (currently ${no})`:l.desc})]},l.name))}):!D&&Pt.length>0?F(Q,{flexDirection:"column",paddingX:1,children:[qr?R(S,{color:q,children:qr}):null,Pt.map((l,i)=>F(S,{children:[R(S,{color:q,children:i+1})," ",l.slice(0,Math.max(20,Ve-5))]},l)),R(S,{dimColor:!0,children:`press 1-${Pt.length} to fill the command \xB7 esc dismiss`})]}):R(Q,{paddingX:1,children:F(S,{color:"gray",children:[Kr.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${no??"model n/a"}${t.kind==="api"?Yr>0?` \xB7 ${le(Yr)}`:"":Vr>0?` \xB7 ${_e(Vr)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}M();import{jsx as Fp}from"react/jsx-runtime";async function Ha(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Wp(t);r.kind==="none"&&(console.error(""),console.error(x("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${A("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${A("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Mp(Fp(Fa,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
270
- `),process.exit(0)}var Gp=qp(import.meta.url),qa=Gp("../package.json"),Re=new Hp;function Mr(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Re.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=>{Mr(e),await mn({profile:e.profile,manual:e.manual})});Re.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Mr(e),await ys({profile:e.profile})});Re.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Mr(e),await ws({profile:e.profile})});var Wr=Re.command("profile").description("Manage connection profiles for the current repo");Wr.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>hn(process.cwd()));Wr.command("use <name>").description("Set the default profile for this repo").action(e=>gn(process.cwd(),e));Wr.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>wn(process.cwd(),e));var Ba=Re.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Ba.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>ht(process.cwd(),e.profile));Ba.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await cs(process.cwd(),e,t.profile)});Re.command("logs").description("Show the Document360 API log files (send these to support when reporting a problem)").action(()=>bs());Re.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(()=>(Nn(),Oi)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Re.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(qa.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(Bp.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 xs(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 ua(e.cwd,e.auth,e.profile):await Ha(e.cwd,e.auth,e.profile,qa.version)});Re.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
266
+ `)}),ft(Ye()),Dt.current=Ne(e).status==="current";return}case"inbox":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(wr(e)===0){u({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 de(yr(),{display:"/inbox",quietUser:!0});return}case"document":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:d,what:m}=ir(g);if(!m&&sr(e)===0){u({kind:"note",tone:"info",text:lr});return}let y=`/document${m?` ${m}`:""}${d?" --publish":""}`;await de(ar(m,d),{display:y,quietUser:!0});return}case"catch-up":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!lo(l.trim()))return;let{publish:d}=kr(g),m=vt($t(e));u({kind:"note",tone:"info",text:m?`Catching up on ${m} (+ checking Document360 for drift)\u2026`:"No local queue \u2014 checking for code changes and drift\u2026"}),await de(br({publish:d}),{display:`/catch-up${d?" --publish":""}`,quietUser:!0});return}case"update":{io.current=!0,u({kind:"note",tone:"info",text:`Updating ${Ke}\u2026`}),(await Ln()).ok?(u({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 /exit and relaunch to apply (press 1)."}),B(m=>m.includes("/exit")?m:[...m,"/exit"])):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${On}`});return}case"screenshot":{let d=fr(g);if(d.mode==="list"){if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:hr(mr(e,d.scope),d.scope).join(`
267
+ `)});return}if(d.mode==="single"){let $=await Un(g);$.kind==="forward-to-agent"&&$.prompt&&await de($.prompt,{display:$.display,quietUser:!0});return}if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=d.mode==="scope"?d.scope:void 0,y=xp(e,{scope:m}).map($=>$.id);if(y.length===0){u({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let P=6,A=bp(y,3),_=Jn(e,"standard");Me.current=Date.now(),Ze(0),U(!0);let re=new AbortController;we.current=re,K({verb:"Authoring",unit:"spec",total:A.length,done:0,active:[],rows:Vt(A),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${y.length} screenshot spec${y.length===1?"":"s"} across ${A.length} partition${A.length===1?"":"s"} (\u2264${P} agents at once) on ${_.model}${_.forced?" (forced)":""}\u2026 (esc to stop)`});let Y=!1;try{for await(let $ of Kn({cwd:e,partitions:A,promptFor:Vi,concurrency:P,profileName:s,allowProdWrites:ot.current,model:_.model,signal:re.signal}))if($.type==="partition_status")$.status==="running"?K(T=>T&&{...T,active:[...T.active,$.label],rows:Re(T.rows,$.label,"active"),lastAt:Date.now()}):K(T=>T&&{...T,active:T.active.filter(I=>I!==$.label),done:T.done+1,rows:Re(T.rows,$.label,$.status==="done"?"done":"failed"),lastAt:Date.now()});else if($.type==="partition_event")K(T=>{if(!T)return T;let I={...T,lastAt:Date.now()};return $.event.type==="tool"?I.tools=T.tools+1:$.event.type==="text"&&(I.chars=T.chars+$.event.delta.length),I});else if($.type==="run_done"){pt(O=>O+$.totalCostUsd),dt(O=>O+$.results.reduce((z,ae)=>z+ae.outputTokens,0));let T=$.results.filter(O=>O.ok).length,I=$.aborted?"Stopped. ":"";Y=!$.aborted&&d.setup;let J=$.aborted?"":Y?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";u({kind:"note",tone:$.aborted?"warn":$.ok?"ok":"warn",text:`${I}Authored specs \u2014 ${T}/${$.results.length} batches ok.${J}`})}}catch($){u({kind:"note",tone:"error",text:`Spec authoring failed: ${$.message}`})}finally{we.current=null,K(null),U(!1),oe($=>$+1)}if(Y){let $=await Bt();$.kind==="forward-to-agent"&&$.prompt&&await de($.prompt,{display:$.display,quietUser:!0});let T=gr(e);T&&u({kind:"note",tone:"info",text:T.join(`
268
+ `)})}return}case"reset":{let d=vr(e);if(d.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}to.current={repoName:zt(e),targets:d,hadDevhints:Yt(Na(e))},u({kind:"note",tone:"warn",text:Pr(e,d).join(`
269
+ `)}),se(zt(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,cn,u,ue,de,sn,mo,ts]),un=G(l=>{let i=(l??D).trim();if(w(""),Jt(null),et(0),i.startsWith("/")&&(se(null),Qe.current++,Zt(null),B(g=>ba(g,i))),!i||os(i)||ns(i))return;eo.current.push(i);let a=Ca(i,Hr.current);i.startsWith("/")?(u({kind:"user",text:i}),rs(a)):de(a,{display:i})},[D,os,ns,rs,de]),ss=G(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=xa(l);if($a(i)){let a=va(++za.current,i);Hr.current.set(a,i),v(a)}else v(i);return}v(l)},[v]),mt=Math.max(10,Ve-6),is=Ir(()=>zn(b.text,mt),[b.text,mt]),wo=G(l=>k(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),dn=G(l=>k(i=>({...i,pos:Ta(zn(i.text,mt),i.pos,l)})),[mt]),At=G(l=>k(i=>({...i,pos:Sa(zn(i.text,mt),i.pos,l)})),[mt]),Ja=["\x1B[H","\x1B[1~","\x1BOH"],Qa=["\x1B[F","\x1B[4~","\x1BOF"],as=G((l,i)=>i.leftArrow?(wo(-1),!0):i.rightArrow?(wo(1),!0):l&&Ja.includes(l)?(At("start"),!0):l&&Qa.includes(l)?(At("end"),!0):i.ctrl&&l==="a"?(At("start"),!0):i.ctrl&&l==="e"?(At("end"),!0):!1,[wo,At]);return Xd((l,i)=>{if(i.ctrl&&l==="c"){me.current?.close(),r();return}if(!H){if(N){if(i.escape){if(we.current){we.current.signal.aborted||(u({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),we.current.abort());return}St.current||(St.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),me.current?.interrupt());return}if(i.return){let a=D.trim();if(!a)return;Be.current.push(a),no([...Be.current]),w("");return}if(as(l,i))return;if(i.upArrow){dn(-1);return}if(i.downArrow){dn(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&ss(l);return}if(We){if(i.upArrow){Fe(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Fe(a=>a&&{...a,cursor:Math.min(xe.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=xe.length){Fe(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=xe[We.cursor];Fe(null);let{lines:g,changed:d,effective:m}=Ht(e,a.value??"default");for(let y of g)u({kind:"note",tone:y.startsWith("\u26A0")?"warn":y.startsWith("\u2713")?"ok":"info",text:y});d&&(Xr(y=>y+1),me.current?.setModel(m));return}if(l==="s"){let a=xe[We.cursor];Fe(null),me.current?.setModel(a.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){Fe(null);return}return}if(Pe){if(i.upArrow){st(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){st(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Pe.rows.length){st(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=Pe.rows[Pe.cursor];st(null),go(a.name,i.return===!0);return}if(i.escape){st(null);return}return}if(Ae){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(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ae.rows.length){it(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Ae.rows[Ae.cursor].name;if(it(null),!Fs(e,a).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${a}").`});let d=!1;try{let m=Je(a);d=!!m&&!(Le(m)&&!m.refreshToken)}catch{d=!1}u({kind:"note",tone:"info",text:d?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),B(["/login"]),oe(m=>m+1);return}if(i.escape){it(null);return}return}if(ie){if(i.upArrow){at(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){at(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ie.rows.length){at(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ie.rows[ie.cursor],{profile:g,projectId:d}=ie;at(null),an(g,d,a);return}if(i.escape){at(null);return}return}if(he){if(i.upArrow){lt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){lt(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){lt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=he.rows[he.cursor],{profile:g}=he;lt(null),es(g,a);return}if(i.escape){lt(null);return}return}if(ce){if(i.upArrow){ut(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){ut(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){ut(a=>a&&{...a,rows:a.rows.map((g,d)=>d===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=ce.rows.filter(g=>g.checked).map(g=>g.path);if(ut(null),a.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Wo(e,a),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer.json`});for(let g of a)u({kind:"note",tone:"info",text:` ${g}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){ut(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&&/^[1-9]$/.test(l)&&Number(l)<=He.rows.length){ct(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=He.rows[He.cursor];ct(null),a.kind==="article"?mo(a.paths[0]):sn(a.paths);return}if(i.escape){ct(null);return}return}if(ge){if(i.escape){qe(null);return}if(i.upArrow){qe(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){qe(a=>a&&{...a,cursor:Math.min(Math.max(0,on.length-1),a.cursor+1)});return}if(i.return){let a=on[ge.cursor];if(a){qe(null);try{u({kind:"preview",name:zt(a),text:Oa(Nr(Xt(e,a),"utf8"))})}catch(g){u({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){qe(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){qe(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(ye){if(i.escape){Ge(null);return}if(i.upArrow){Ge(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ge(a=>a&&{...a,cursor:Math.min(Math.max(0,rn.length-1),a.cursor+1)});return}if(i.return){let a=rn[ye.cursor];if(a){Ge(null),ue(a.uuid),Ce.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},rt(a.name),_r(a.uuid),nt.current=[];let g=Dr(e,a.uuid);for(let d of g)u(d);u({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){Ge(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){Ge(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!D&&ke){w(ke),se(null),Qe.current++;return}if(!D&&Pt.length>0&&l&&/^[1-9]$/.test(l)){let a=Pt[Number(l)-1];if(a){w(a);return}}if(!D&&(co||ro)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=co!=null;pa(co??ro).then(d=>{u({kind:"note",tone:d?"ok":"warn",text:d?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."}),d&&a&&uo(null)});return}if(!as(l,i)){if(Qr){if(i.upArrow){et(a=>Math.max(0,a-1));return}if(i.downArrow){et(a=>Math.min(jt.length-1,a+1));return}if(i.tab){w("/"+(jt[Tt]?.name??"")+" "),et(0);return}if(i.return){let a=jt[Tt];if(a){let g=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Cs(a.usage)&&!g){w("/"+a.name+" "),et(0);return}un("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(D!==""&&tt===null){dn(-1);return}let a=eo.current;if(!a.length)return;let g=tt===null?a.length-1:Math.max(0,tt-1);Jt(g),w(a[g]??"");return}if(i.downArrow){if(D!==""&&tt===null){dn(1);return}let a=eo.current;if(tt===null)return;let g=tt+1;g>=a.length?(Jt(null),w("")):(Jt(g),w(a[g]??""));return}}if(i.return){un();return}if(i.backspace||i.delete){C();return}if(i.escape){w(""),et(0),se(null),B([]),Zt(null);return}l&&!i.ctrl&&!i.meta&&ss(l)}}}),$e(()=>{if(N||H)return;let l=Be.current.shift();l!==void 0&&(no([...Be.current]),un(l))},[N,H,un]),F(Q,{flexDirection:"column",width:Ve,children:[fo!==null&&F(Q,{marginTop:1,flexDirection:"column",children:[fo.truncated&&R(S,{dimColor:!0,children:"\u2026"}),R(S,{children:fo.text})]}),N&&(Vr?R(Lp,{p:Vr}):R(Up,{startTime:Me.current,chars:Ya})),R(Q,{borderStyle:"round",borderColor:Jr.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?is.map((l,i)=>{let a=b.text.slice(l.start,l.end),g=i===Xn(is,b.pos),d=Math.min(b.pos,l.end)-l.start;return F(S,{children:[R(S,{color:q,children:i===0?"> ":" "}),g?F(Lr,{children:[a.slice(0,d),R(Qn,{ch:a[d]??" "}),a.slice(d+1)]}):a||" "]},`${i}-${l.start}`)}):F(S,{children:[R(S,{color:q,children:"> "}),ke&&!N?F(Lr,{children:[R(Qn,{ch:ke[0],dim:!0}),R(S,{color:"gray",children:ke.slice(1)}),R(S,{dimColor:!0,children:" (tab)"})]}):po.isSetup||!Va?F(Lr,{children:[R(Qn,{ch:po.text[0],dim:!0}),R(S,{color:"gray",children:po.text.slice(1)})]}):R(Qn,{ch:" "})]})}),Gr.length>0&&R(Q,{flexDirection:"column",paddingX:1,children:Gr.map((l,i)=>R(S,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),We?F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:"Select model"}),R(S,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),xe.map((l,i)=>F(S,{color:i===We.cursor?q:void 0,children:[i===We.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===We.current?" \u2714":""}`.padEnd(16),R(S,{color:"gray",children:l.desc})]},l.label)),R(S,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Pe?F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:"Switch connection profile"}),Pe.rows.map((l,i)=>F(S,{color:i===Pe.cursor?q:void 0,children:[i===Pe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===Pe.current?" \u2714":""}`.padEnd(20),R(S,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?R(S,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),R(S,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ae?F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:"Pick your Document360 environment"}),Ae.rows.map((l,i)=>F(S,{color:i===Ae.cursor?q:void 0,children:[i===Ae.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),R(S,{color:"gray",children:l.apiUrl})]},l.name)),R(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ie?F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:"Switch workspace"}),R(S,{dimColor:!0,children:`environment ${ie.environment} \xB7 project ${ie.projectName??`${ie.projectId.slice(0,8)}\u2026`}`}),ie.rows.map((l,i)=>F(S,{color:i===ie.cursor?q:void 0,children:[i===ie.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===ie.current?" \u2714":""}`.padEnd(30),R(S,{color:"gray",children:l.type??""})]},l.id)),R(S,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):he?F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:"Choose project"}),R(S,{dimColor:!0,children:`environment ${he.environment}`}),he.rows.map((l,i)=>F(S,{color:i===he.cursor?q:void 0,children:[i===he.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===he.current?" \u2714":""}`.padEnd(30),R(S,{color:"gray",children:l.sub??""})]},l.id)),R(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ce?(()=>{let i=Math.min(Math.max(0,ce.cursor-Math.floor(7)),Math.max(0,ce.rows.length-14)),a=ce.rows.slice(i,i+14),g=ce.rows.filter(d=>d.checked).length;return F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:`Which folders back the user docs? (${g} selected of ${ce.rows.length})`}),i>0?R(S,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((d,m)=>{let y=i+m;return F(S,{color:y===ce.cursor?q:void 0,children:[y===ce.cursor?"\u276F ":" ",d.checked?"\u25C9 ":"\u25CB ",d.path.padEnd(Math.min(48,Ve-34)),R(S,{color:"gray",children:An(d)})]},d.path)}),i+14<ce.rows.length?R(S,{dimColor:!0,children:` \u2193 ${ce.rows.length-i-14} more`}):null,R(S,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():He?F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),He.rows.map((l,i)=>{let a=i===He.cursor,g=l.indent?" ":" ",d=`${i+1}.`.padEnd(3);return F(S,{color:a?q:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${d} ${l.label}`.padEnd(Math.min(56,Ve-24)),l.note?R(S,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),R(S,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ge?F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:`Preview article${ge.query?` \u2014 filter: ${ge.query}`:" (type to filter)"}`}),on.length===0?R(S,{color:"gray",children:"no articles match"}):on.map((l,i)=>F(S,{color:i===ge.cursor?q:void 0,children:[i===ge.cursor?"\u276F ":" ",l]},l)),R(S,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):ye?F(Q,{flexDirection:"column",paddingX:1,children:[R(S,{color:q,bold:!0,children:`Resume session${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),rn.length===0?R(S,{color:"gray",children:"no sessions match"}):rn.map((l,i)=>F(S,{color:i===ye.cursor?q:void 0,children:[i===ye.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),R(S,{color:i===ye.cursor?q:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ve-40))})]},l.uuid)),R(S,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Qr?R(Q,{flexDirection:"column",children:jt.map((l,i)=>F(S,{color:i===Tt?q:void 0,children:[i===Tt?"\u276F ":" ",l.usage.padEnd(22)," ",R(S,{color:i===Tt?q:"gray",children:l.name==="model"&&oo?`${l.desc} (currently ${oo})`:l.desc})]},l.name))}):!D&&Pt.length>0?F(Q,{flexDirection:"column",paddingX:1,children:[Br?R(S,{color:q,children:Br}):null,Pt.map((l,i)=>F(S,{children:[R(S,{color:q,children:i+1})," ",l.slice(0,Math.max(20,Ve-5))]},l)),R(S,{dimColor:!0,children:`press 1-${Pt.length} to fill the command \xB7 esc dismiss`})]}):R(Q,{paddingX:1,children:F(S,{color:"gray",children:[Jr.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${oo??"model n/a"}${t.kind==="api"?zr>0?` \xB7 ${le(zr)}`:"":Yr>0?` \xB7 ${Ue(Yr)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}M();import{jsx as Hp}from"react/jsx-runtime";async function qa(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Fp(t);r.kind==="none"&&(console.error(""),console.error(x("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${E("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${E("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Wp(Hp(Ha,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
270
+ `),process.exit(0)}var Vp=Bp(import.meta.url),Ba=Vp("../package.json"),De=new qp;function Wr(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}De.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{Wr(e),await hn({profile:e.profile,manual:e.manual})});De.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Wr(e),await ks({profile:e.profile})});De.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Wr(e),await ys({profile:e.profile})});var Fr=De.command("profile").description("Manage connection profiles for the current repo");Fr.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>gn(process.cwd()));Fr.command("use <name>").description("Set the default profile for this repo").action(e=>wn(process.cwd(),e));Fr.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>yn(process.cwd(),e));var Ga=De.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Ga.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>ht(process.cwd(),e.profile));Ga.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await us(process.cwd(),e,t.profile)});De.command("logs").description("Show the Document360 API log files (send these to support when reporting a problem)").action(()=>xs());De.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(_n(),Li)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});De.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Ba.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(Gp.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 $s(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 da(e.cwd,e.auth,e.profile):await qa(e.cwd,e.auth,e.profile,Ba.version)});De.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});