document360-writer 0.5.6 → 0.5.7

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 +85 -85
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- var cl=Object.defineProperty;var xo=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var ul=(e,t)=>{for(var n in t)cl(e,n,{get:t[n],enumerable:!0})};import Ne from"picocolors";var V,dl,pl,fl,fs,Et,f,v,U,E,I,te,xe,W=xo(()=>{"use strict";V="#7f56d9",[dl,pl,fl]=[127,86,217],fs=e=>Ne.isColorSupported?`\x1B[38;2;${dl};${pl};${fl}m${e}\x1B[39m`:e,Et=e=>Ne.bold(fs(e)),f=e=>Ne.dim(e),v=e=>Ne.red(e),U=e=>Ne.yellow(e),E=e=>Ne.green(e),I=fs,te=e=>Ne.gray(e),xe=e=>Ne.bold(e)});import{existsSync as vn,writeFileSync as Ot,readFileSync as Zl,readdirSync as ec}from"node:fs";import{join as tc}from"node:path";import{devHintsGuidePath as Cn,hintsDir as As,architectureDir as Ns,messagesDir as To,creatorNotesPath as Es,devhintsStatePath as _s,ensureDir as $n,writeMessage as nc,listOpenForDev as oc}from"document360-engine";function Os(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var ul=Object.defineProperty;var vo=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var dl=(e,t)=>{for(var n in t)ul(e,n,{get:t[n],enumerable:!0})};import _e from"picocolors";var V,pl,fl,ml,hs,It,f,v,U,E,I,ne,xe,W=vo(()=>{"use strict";V="#7f56d9",[pl,fl,ml]=[127,86,217],hs=e=>_e.isColorSupported?`\x1B[38;2;${pl};${fl};${ml}m${e}\x1B[39m`:e,It=e=>_e.bold(hs(e)),f=e=>_e.dim(e),v=e=>_e.red(e),U=e=>_e.yellow(e),E=e=>_e.green(e),I=hs,ne=e=>_e.gray(e),xe=e=>_e.bold(e)});import{existsSync as Pn,writeFileSync as Ut,readFileSync as ec,readdirSync as tc}from"node:fs";import{join as nc}from"node:path";import{devHintsGuidePath as Sn,hintsDir as Is,architectureDir as Os,messagesDir as Do,creatorNotesPath as Ns,devhintsStatePath as Us,ensureDir as Cn,writeMessage as oc,listOpenForDev as rc}from"document360-engine";function Ls(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
3
3
 
4
- <!-- devhints script v${oe} \xB7 maintained by document360-writer (/devhints). -->
4
+ <!-- devhints script v${te} \xB7 maintained by document360-writer (/devhints). -->
5
5
 
6
6
  This repo's user documentation is written by **document360-writer** ("the docs agent"), a separate agent.
7
7
  It can read your code, but code alone can't tell it the *intent* \u2014 WHY a feature exists, which of a
@@ -159,7 +159,7 @@ whenever \`git status\` shows changes under \`.d360-writer/\`, commit them (e.g.
159
159
  \`git add .d360-writer && git commit -m "docs: sync d360-writer output"\`) before you push. The docs agent
160
160
  will remind you when it leaves changes, but it's your call to commit them. Without this, the team's docs
161
161
  and \u2014 critically \u2014 the sync map are stranded on one machine.
162
- `}function rc(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
162
+ `}function sc(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
163
163
 
164
164
  <!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
165
165
  The builder agent reads this FIRST and treats it as authoritative when writing the architecture
@@ -173,60 +173,60 @@ Anything only a human knows that would help document this product. For example:
173
173
  - Gotchas or non-obvious behavior.
174
174
 
175
175
  (Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
176
- `}function yt(e){$n(As(e)),$n(Ns(e)),$n(To(e));for(let n of[As(e),To(e)]){let o=tc(n,".gitkeep");vn(o)||Ot(o,`# Keeps this document360-writer inbox tracked in git even when empty.
177
- `)}vn(Es(e))||Ot(Es(e),rc()),Ot(Cn(e),Os());let t=_e(e);return Ls(e,new Date().toISOString()),t}async function Us(e,t){for(let n of kt(yt(t.cwd)))console.log(n);return{kind:"continue"}}function ze(){return[`This is document360-writer's dev hand-off setup (v${oe}).`,'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": ${oe},`,' "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(`
178
- `)}function Ro(e){try{let t=Zl(_s(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Ls(e,t){let o={...Ro(e)??{},emittedVersion:oe,emittedAt:t};Ot(_s(e),`${JSON.stringify(o,null,2)}
179
- `)}function Ms(e){try{return ec(Ns(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function _e(e){let n=Ro(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<oe?"stale":"current",completedVersion:n}}function Pn(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:oe};try{if(!vn(Cn(e)))return n;let o=Ro(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;oe>r&&($n(To(e)),Ot(Cn(e),Os()),Ls(e,t),n.guideRefreshed=!0),oe>s&&(oc(e).some(p=>p.kind==="request"&&p.subject.startsWith(Is))||(nc(e,{id:`onb${oe}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Is}${oe})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${oe}${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:","",ze()].join(`
180
- `)}),n.notifiedBuilder=!0))}catch{}return n}function Sn(e){if(!vn(Cn(e)))return[];let t=_e(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${oe}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,wt,ze(),wt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Do(){return['document360-writer (its "docs agent") has been removed from this repository. Please undo its dev\u2192docs',"hand-off setup and restore this repo to how it was before \u2014 in order:","","1. In this repo's agent-memory file (CLAUDE.md, or AGENTS.md \u2014 whichever it edited), REMOVE the",' "Documentation hand-off" section that was added (the rule about dropping hint files in'," `.d360-writer/hints/`, keeping `.d360-writer/architecture/` current, and checking"," `.d360-writer/messages/`). Leave everything else in that file untouched.","2. The `.d360-writer/` folder is already deleted on disk. If it was committed, remove it from version"," control too \u2014 `git rm -r --cached .d360-writer` (if it still resolves) \u2014 and commit the deletions.","3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
181
- `)}function Tn(){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,Do(),wt]}function kt(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${oe}.`," 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,ze(),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,oe,Is,Ke=xo(()=>{"use strict";wt="-".repeat(64),oe=5;Is="Re-run dev\u2194docs onboarding (protocol v"});var qi={};ul(qi,{doctorCommand:()=>Bt,renderDoctorChecks:()=>Hi,runDoctorChecks:()=>Fi});import{existsSync as Li}from"node:fs";import{d360GetAll as Iu,getAccessToken as Nu,isExpired as hr,loadProfileMap as _u,loadTokens as Ou,packageSkillsDir as Mi,projectConfigPath as Uu,readProjectConfig as Lu,DEFAULT_DOCS_DIR as Mu,resolveActiveProfile as Wu,classifyClaudeAuth as Fu,CLAUDE_CODE_SETUP_HINT as Wi,resolveModelSetting as Hu,devHintsGuidePath as qu}from"document360-engine";async function Fi(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=Fu();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. ${Wi}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Wi});let r=Hu(e);t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`});let s=Lu(e);if(!s)return t.push({level:"fail",label:`No ${Uu(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??Mu).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=Wu(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(k){return t.push({level:"fail",label:`Profile config: ${k.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let b=Ou(h.name);b?hr(b)&&!b.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):hr(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 y=_u(e,h.name);y?y.projectId&&h.project.projectId&&y.projectId!==h.project.projectId?t.push({level:"fail",label:`Category map projectId (${y.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(y.articles).length} articles, ${Object.keys(y.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${h.name}" (created on first /publish)`}),t.push(Li(Mi())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Mi()}`,fix:"Reinstall document360-writer (broken install)"});let j=_e(e);if((Li(qu(e))||j.status!=="unset")&&(j.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${oe})`}):j.status==="stale"?t.push({level:"warn",label:`Dev hand-off: builder on devhints v${j.completedVersion}, current is v${oe}`,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&&(!hr(b)||b.refreshToken)){let k={profile:h.name,connection:h.connection};try{await Nu(k);let C=await Iu(k,"/v3/projects");t.push({level:"ok",label:`API reachable (${h.connection.apiUrl}) \u2014 ${C.length} project(s) visible`})}catch(C){t.push({level:"fail",label:`API call failed: ${C.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}}return t}function Hi(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?U("\u26A0"):v("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${I(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?E(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):v(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Bt(e,t){console.log(f("Running checks\u2026"));for(let n of Hi(await Fi(t.cwd)))console.log(n);return{kind:"continue"}}var Un=xo(()=>{"use strict";Ke();W()});import{Command as sf}from"commander";import{createRequire as af}from"node:module";import{AUTH_MODES as lf}from"document360-engine";import{input as Tl}from"@inquirer/prompts";import{loginPkce as Rl,refreshTokens as Dl,toStoredTokens as bs,clearTokens as jl,decodeJwtClaims as ks,isExpired as Al,loadTokens as El,saveTokens as xs,resolveActiveProfile as hn,setProfileProject as Il,readProjectConfig as Nl}from"document360-engine";W();import{select as ml}from"@inquirer/prompts";import{resolveActiveProfile as hl,setProfileProject as gl,resolveProjectId as wl,listWorkspaces as yl}from"document360-engine";async function It(e,t){let n=hl(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??wl(o);return{workspaces:await yl(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var ms=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function $o(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 mn(e,t,n,o,r){gl(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function hs(e,t,n){let o;try{o=await It(e,n)}catch(s){return console.log(v(`Could not list workspaces: ${s.message}`)),1}let r=$o(o.workspaces,t);return r?(mn(e,o.profile,o.projectId,r.id,r.name),console.log(E(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(v(`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(v(`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?I("\u25CF"):" "} ${ms(b)} ${f(b.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await ml({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${ms(b)}${b.id===c?" (current)":""}`,value:b.id}))}),h=o.find(b=>b.id===p);mn(e,s,r,p,h?.name),console.log(E(`\u2713 Workspace set to "${h?.name??p}" for profile "${s}".`))}W();import{select as kl}from"@inquirer/prompts";import{resolveActiveProfile as bl,setProfileProject as xl,listProjects as $l}from"document360-engine";async function gt(e,t){let n=bl(e,t),o={profile:n.name,connection:n.connection};return{projects:await $l(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var gs=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function ws(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 vo(e,t,n,o){xl(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function ys(e,t){let n;try{n=await gt(e,t)}catch(h){console.log(v(`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?I("\u25CF"):" "} ${gs(h)} ${f(h.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await kl({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${gs(h)}${h.id===s?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===c);vo(e,r,c,p?.name),console.log(E(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import vl from"picocolors";function Cl(e=process.env){return e.FORCE_HYPERLINK==="0"||!vl.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 Pl(e,t=e,n){return Cl(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Sl=/https?:\/\/[^\s\x1b]+/g;function Nt(e,t){return e.replace(Sl,n=>Pl(n,n,t))}function $s(e){return{...ks(e.idToken)??{},...ks(e.accessToken)??{}}}function gn(e){let t=$s(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 wn(e){let t=hn(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 Rl(n,{manual:e.manual,promptForRedirect:s=>Tl({message:s})},s=>console.log(Nt(s))),r=bs(t.name,o);if(xs(r),await Co(r,t.name,s=>console.log(f(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${gn(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{Nl(process.cwd())?.profiles?.[t.name]&&(console.log(""),await ht(process.cwd(),t.name))}catch{}}async function Co(e,t,n){let r=$s(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(hn(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{}Il(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function vs(e){let t=hn(process.cwd(),e.profile),n=t.connection,o=El(t.name);if(!o){console.log(v(`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 ${I(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${gn(o)}`),Al(o))if(o.refreshToken)try{let r=bs(t.name,await Dl(n,o.refreshToken));xs(r),console.log(E(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(U(`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(U("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 Cs(e){let t=hn(process.cwd(),e.profile);jl(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as Ps,writeProjectConfig as _l,resolveActiveProfile as Ol,loadTokens as Ul,isExpired as Ll}from"document360-engine";function yn(e){let t=Ps(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(v("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?I("\u25CF "):" ",s=o.production?U(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Ul(n),h=p?Ll(p)&&!p.refreshToken?U("expired"):f("logged in"):f("not logged in");console.log(`${r}${I(n)} \u2192 ${c}${s} [${h}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function kn(e,t){let n=Ps(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(v(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,_l(n,e);let o=n.profiles[t].production?U(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function bn(e,t){try{let n=Ol(e,t);console.log(""),console.log(`Profile ${I(n.name)}${n.production?U(" \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(v(n.message)),process.exitCode=1}}W();import{existsSync as Ml,readdirSync as Wl,statSync as Fl}from"node:fs";import{join as Hl}from"node:path";import{apiLogDir as ql}from"document360-engine";function Ss(){let e=ql();if(console.log(""),console.log(`Document360 API logs: ${I(e)}`),!Ml(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Wl(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=(Fl(Hl(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("")}W();import{createSession as Bl,resolveAuth as Gl,findByName as Vl,slugify as Yl,touchSession as zl,upsertSession as Kl,resolveActiveProfile as Xl}from"document360-engine";async function Ts(e,t,n,o,r,s){let c=Gl(n);c.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${I("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${I("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=Xl(e,r)}catch(k){console.error(v(`Document360 profile error: ${k.message}`)),process.exit(2)}p.production&&(console.error(U(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(v("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 k=Vl(e,o);k||(console.error(v(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),h=k.uuid,console.error(f(`Resuming "${k.name}"`))}let b=Bl({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),y=h??null,j=1;for await(let k of b.send(t))switch(k.type){case"session":if(!y){y=k.sessionId;let C=new Date().toISOString();Kl({uuid:y,name:Yl(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:C,updatedAt:C})}break;case"text":process.stdout.write(k.delta);break;case"tool":console.error(te(` \u2699 ${k.name}`));break;case"result":j=k.ok?0:1,console.error(f(`(${k.inputTokens}\u2192${k.outputTokens} tokens`+(k.costUsd>0?`, $${k.costUsd<.01?k.costUsd.toFixed(4):k.costUsd.toFixed(2)}`:"")+")")),k.ok||console.error(v("agent finished with an error result"));break;case"error":console.error(""),console.error(v(`agent error: ${k.message}`)),process.exit(1)}y&&zl(y),process.stdout.write(`
182
- `),process.exit(j)}import{createInterface as Ed}from"node:readline/promises";import{createSession as Ar,resolveAuth as Id,getSession as Nd,setTitle as _d,slugify as Od,touchSession as ma,upsertSession as Ud,generateTitle as Ld,resolveActiveProfile as ha,resolveModelSetting as Md,readProjectConfig as Wd,decodeJwtClaims as pa,isExpired as Fd,loadTokens as Hd}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 [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"sync",usage:"/sync [pull <path>|--all] [baseline]",desc:"Drift report local vs Document360; pull portal edits; baseline = set a sync base for not-yet-compared articles",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"}],Jl=[{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 xn(){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 Jl){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 Rs(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return _t.filter(n=>n.name.startsWith(t))}function Ds(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}async function Po(){console.log("");for(let e of xn())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}W();import{getSession as Ql}from"document360-engine";async function js(e,t){let n=t.currentUuid(),o=n?Ql(n):void 0;return console.log(o?f(`
176
+ `}function yt(e){Cn(Is(e)),Cn(Os(e)),Cn(Do(e));for(let n of[Is(e),Do(e)]){let o=nc(n,".gitkeep");Pn(o)||Ut(o,`# Keeps this document360-writer inbox tracked in git even when empty.
177
+ `)}Pn(Ns(e))||Ut(Ns(e),sc()),Ut(Sn(e),Ls());let t=Te(e);return Ws(e,new Date().toISOString()),t}async function Ms(e,t){for(let n of kt(yt(t.cwd)))console.log(n);return{kind:"continue"}}function ze(){return[`This is document360-writer's dev hand-off setup (v${te}).`,'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": ${te},`,' "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(`
178
+ `)}function jo(e){try{let t=ec(Us(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Ws(e,t){let o={...jo(e)??{},emittedVersion:te,emittedAt:t};Ut(Us(e),`${JSON.stringify(o,null,2)}
179
+ `)}function Lt(e){try{return tc(Os(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Te(e){let n=jo(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<te?"stale":"current",completedVersion:n}}function Tn(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:te};try{if(!Pn(Sn(e)))return n;let o=jo(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;te>r&&(Cn(Do(e)),Ut(Sn(e),Ls()),Ws(e,t),n.guideRefreshed=!0),te>s&&(rc(e).some(p=>p.kind==="request"&&p.subject.startsWith(_s))||(oc(e,{id:`onb${te}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${_s}${te})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${te}${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:","",ze()].join(`
180
+ `)}),n.notifiedBuilder=!0))}catch{}return n}function Rn(e){if(!Pn(Sn(e)))return[];let t=Te(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${te}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,wt,ze(),wt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Ao(){return['document360-writer (its "docs agent") has been removed from this repository. Please undo its dev\u2192docs',"hand-off setup and restore this repo to how it was before \u2014 in order:","","1. In this repo's agent-memory file (CLAUDE.md, or AGENTS.md \u2014 whichever it edited), REMOVE the",' "Documentation hand-off" section that was added (the rule about dropping hint files in'," `.d360-writer/hints/`, keeping `.d360-writer/architecture/` current, and checking"," `.d360-writer/messages/`). Leave everything else in that file untouched.","2. The `.d360-writer/` folder is already deleted on disk. If it was committed, remove it from version"," control too \u2014 `git rm -r --cached .d360-writer` (if it still resolves) \u2014 and commit the deletions.","3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
181
+ `)}function Dn(){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,Ao(),wt]}function kt(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${te}.`," 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,ze(),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,te,_s,Ke=vo(()=>{"use strict";wt="-".repeat(64),te=5;_s="Re-run dev\u2194docs onboarding (protocol v"});var Bi={};dl(Bi,{doctorCommand:()=>Vt,renderDoctorChecks:()=>qi,runDoctorChecks:()=>Hi});import{existsSync as Mi}from"node:fs";import{d360GetAll as Nu,getAccessToken as _u,isExpired as wr,loadProfileMap as Ou,loadTokens as Uu,packageSkillsDir as Wi,projectConfigPath as Lu,readProjectConfig as Mu,DEFAULT_DOCS_DIR as Wu,resolveActiveProfile as Fu,classifyClaudeAuth as Hu,CLAUDE_CODE_SETUP_HINT as Fi,resolveModelSetting as qu,probeModel as Bu,devHintsGuidePath as Gu}from"document360-engine";async function Hi(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=Hu();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. ${Fi}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Fi});let r=qu(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let y=await Bu(e,r.model??void 0);y.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(y.latencyMs/1e3).toFixed(1)}s`}):y.timedOut?t.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):t.push({level:"fail",label:`Model call failed \u2014 ${y.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let s=Mu(e);if(!s)return t.push({level:"fail",label:`No ${Lu(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??Wu).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=Fu(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(y){return t.push({level:"fail",label:`Profile config: ${y.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let b=Uu(h.name);b?wr(b)&&!b.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):wr(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=Ou(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(Mi(Wi())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Wi()}`,fix:"Reinstall document360-writer (broken install)"});let j=Te(e);if((Mi(Gu(e))||j.status!=="unset")&&(j.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${te})`}):j.status==="stale"?t.push({level:"warn",label:`Dev hand-off: builder on devhints v${j.completedVersion}, current is v${te}`,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&&(!wr(b)||b.refreshToken)){let y={profile:h.name,connection:h.connection};try{await _u(y);let C=await Nu(y,"/v3/projects");t.push({level:"ok",label:`API reachable (${h.connection.apiUrl}) \u2014 ${C.length} project(s) visible`})}catch(C){t.push({level:"fail",label:`API call failed: ${C.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}}return t}function qi(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?U("\u26A0"):v("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${I(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?E(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):v(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Vt(e,t){console.log(f("Running checks\u2026"));for(let n of qi(await Hi(t.cwd)))console.log(n);return{kind:"continue"}}var Mn=vo(()=>{"use strict";Ke();W()});import{Command as lf}from"commander";import{createRequire as cf}from"node:module";import{AUTH_MODES as uf}from"document360-engine";import{input as Rl}from"@inquirer/prompts";import{loginPkce as Dl,refreshTokens as jl,toStoredTokens as $s,clearTokens as Al,decodeJwtClaims as xs,isExpired as El,loadTokens as Il,saveTokens as vs,resolveActiveProfile as wn,setProfileProject as Nl,readProjectConfig as _l}from"document360-engine";W();import{select as hl}from"@inquirer/prompts";import{resolveActiveProfile as gl,setProfileProject as wl,resolveProjectId as yl,listWorkspaces as kl}from"document360-engine";async function Nt(e,t){let n=gl(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??yl(o);return{workspaces:await kl(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var gs=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Co(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 gn(e,t,n,o,r){wl(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ws(e,t,n){let o;try{o=await Nt(e,n)}catch(s){return console.log(v(`Could not list workspaces: ${s.message}`)),1}let r=Co(o.workspaces,t);return r?(gn(e,o.profile,o.projectId,r.id,r.name),console.log(E(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(v(`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 Nt(e,t)}catch(b){console.log(v(`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?I("\u25CF"):" "} ${gs(b)} ${f(b.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await hl({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${gs(b)}${b.id===c?" (current)":""}`,value:b.id}))}),h=o.find(b=>b.id===p);gn(e,s,r,p,h?.name),console.log(E(`\u2713 Workspace set to "${h?.name??p}" for profile "${s}".`))}W();import{select as bl}from"@inquirer/prompts";import{resolveActiveProfile as xl,setProfileProject as $l,listProjects as vl}from"document360-engine";async function gt(e,t){let n=xl(e,t),o={profile:n.name,connection:n.connection};return{projects:await vl(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ys=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function ks(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 Po(e,t,n,o){$l(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function bs(e,t){let n;try{n=await gt(e,t)}catch(h){console.log(v(`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?I("\u25CF"):" "} ${ys(h)} ${f(h.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await bl({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${ys(h)}${h.id===s?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===c);Po(e,r,c,p?.name),console.log(E(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import Cl from"picocolors";function Pl(e=process.env){return e.FORCE_HYPERLINK==="0"||!Cl.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 Sl(e,t=e,n){return Pl(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Tl=/https?:\/\/[^\s\x1b]+/g;function _t(e,t){return e.replace(Tl,n=>Sl(n,n,t))}function Cs(e){return{...xs(e.idToken)??{},...xs(e.accessToken)??{}}}function yn(e){let t=Cs(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 kn(e){let t=wn(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 Dl(n,{manual:e.manual,promptForRedirect:s=>Rl({message:s})},s=>console.log(_t(s))),r=$s(t.name,o);if(vs(r),await So(r,t.name,s=>console.log(f(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${yn(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{_l(process.cwd())?.profiles?.[t.name]&&(console.log(""),await ht(process.cwd(),t.name))}catch{}}async function So(e,t,n){let r=Cs(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(wn(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{}Nl(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Ps(e){let t=wn(process.cwd(),e.profile),n=t.connection,o=Il(t.name);if(!o){console.log(v(`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 ${I(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${yn(o)}`),El(o))if(o.refreshToken)try{let r=$s(t.name,await jl(n,o.refreshToken));vs(r),console.log(E(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(U(`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(U("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 Ss(e){let t=wn(process.cwd(),e.profile);Al(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as Ts,writeProjectConfig as Ol,resolveActiveProfile as Ul,loadTokens as Ll,isExpired as Ml}from"document360-engine";function bn(e){let t=Ts(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(v("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?I("\u25CF "):" ",s=o.production?U(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Ll(n),h=p?Ml(p)&&!p.refreshToken?U("expired"):f("logged in"):f("not logged in");console.log(`${r}${I(n)} \u2192 ${c}${s} [${h}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function xn(e,t){let n=Ts(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(v(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Ol(n,e);let o=n.profiles[t].production?U(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function $n(e,t){try{let n=Ul(e,t);console.log(""),console.log(`Profile ${I(n.name)}${n.production?U(" \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(v(n.message)),process.exitCode=1}}W();import{existsSync as Wl,readdirSync as Fl,statSync as Hl}from"node:fs";import{join as ql}from"node:path";import{apiLogDir as Bl}from"document360-engine";function Rs(){let e=Bl();if(console.log(""),console.log(`Document360 API logs: ${I(e)}`),!Wl(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Fl(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=(Hl(ql(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("")}W();import{createSession as Gl,resolveAuth as Vl,findByName as Yl,slugify as zl,touchSession as Kl,upsertSession as Xl,resolveActiveProfile as Jl}from"document360-engine";async function Ds(e,t,n,o,r,s){let c=Vl(n);c.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${I("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${I("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=Jl(e,r)}catch(y){console.error(v(`Document360 profile error: ${y.message}`)),process.exit(2)}p.production&&(console.error(U(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(v("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 y=Yl(e,o);y||(console.error(v(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),h=y.uuid,console.error(f(`Resuming "${y.name}"`))}let b=Gl({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),k=h??null,j=1;for await(let y of b.send(t))switch(y.type){case"session":if(!k){k=y.sessionId;let C=new Date().toISOString();Xl({uuid:k,name:zl(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:C,updatedAt:C})}break;case"text":process.stdout.write(y.delta);break;case"tool":console.error(ne(` \u2699 ${y.name}`));break;case"result":j=y.ok?0:1,console.error(f(`(${y.inputTokens}\u2192${y.outputTokens} tokens`+(y.costUsd>0?`, $${y.costUsd<.01?y.costUsd.toFixed(4):y.costUsd.toFixed(2)}`:"")+")")),y.ok||console.error(v("agent finished with an error result"));break;case"error":console.error(""),console.error(v(`agent error: ${y.message}`)),process.exit(1)}k&&Kl(k),process.stdout.write(`
182
+ `),process.exit(j)}import{createInterface as Nd}from"node:readline/promises";import{createSession as Ir,resolveAuth as _d,getSession as Od,setTitle as Ud,slugify as Ld,touchSession as ha,upsertSession as Md,generateTitle as Wd,resolveActiveProfile as ga,resolveModelSetting as Fd,readProjectConfig as Hd,decodeJwtClaims as fa,isExpired as qd,loadTokens as Bd}from"document360-engine";var Ot=[{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 [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"sync",usage:"/sync [pull <path>|--all] [baseline]",desc:"Drift report local vs Document360; pull portal edits; baseline = set a sync base for not-yet-compared articles",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 vn(){let e=Math.max(...Ot.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 Ot.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 js(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Ot.filter(n=>n.name.startsWith(t))}function As(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}async function To(){console.log("");for(let e of vn())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}W();import{getSession as Zl}from"document360-engine";async function Es(e,t){let n=t.currentUuid(),o=n?Zl(n):void 0;return console.log(o?f(`
183
183
  (conversation reset \u2014 "${o.name}" is still available via /resume)
184
184
  `):f(`
185
185
  (conversation reset \u2014 agent will start fresh on the next prompt)
186
- `)),{kind:"clear"}}async function So(){return{kind:"exit"}}W();Ke();import{input as Ut,confirm as sc}from"@inquirer/prompts";import{basename as Ws,join as Rn}from"node:path";import{existsSync as bt,readFileSync as ic,readdirSync as ac,writeFileSync as lc}from"node:fs";import{writeProjectConfig as Fs,readProjectConfig as cc,projectConfigPath as Hs,writerDir as uc,DEFAULT_DOCS_DIR as qs,DEFAULT_CAPTURE_DIR as Bs,DEFAULT_OUTPUT_DIR as Gs}from"document360-engine";function Vs(e,t="berlin"){let n=Hs(e);if(bt(n))return{created:!1,path:n,profileName:""};let o={projectId:Ks(e)??Ws(e),docsDir:qs,captureDir:Bs,outputDir:Gs,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Xs(e)};return Fs(o,e),Ys(e),{created:!0,path:n,profileName:t}}function Ys(e){let t=Rn(uc(e),".gitignore");bt(t)||lc(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
187
- `),"utf8")}async function zs(){let e=process.cwd(),t=Hs(e);if(bt(t)&&!await sc({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Ks(e)??Ws(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:Bs}),s=await Ut({message:"Screenshot output directory:",default:Gs}),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:qs,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Xs(e)},b=cc(e);b?.terminologyGlossary&&(h.terminologyGlossary=b.terminologyGlossary),Fs(h,e),Ys(e);let y=yt(e);console.log(""),console.log(E(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${I(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let j of kt(y))console.log(j);return console.log(""),console.log(`${f("Then ask:")} ${I('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Ks(e){let t=Rn(e,"package.json");if(!bt(t))return null;try{return JSON.parse(ic(t,"utf8")).name??null}catch{return null}}function Xs(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])bt(Rn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Rn(e,n);bt(o)&&!dc(o)&&t.push(n)}return t}function dc(e){try{return ac(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}W();import{readMcpConfig as jo,writeMcpConfig as Js}from"document360-engine";async function Dn(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(pc(),{kind:"continue"}):t==="add"?(fc(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(mc(e.slice(1)),{kind:"continue"}):(console.log(v(`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 pc(){let e=jo(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
186
+ `)),{kind:"clear"}}async function Ro(){return{kind:"exit"}}W();Ke();import{input as Mt,confirm as ic}from"@inquirer/prompts";import{basename as Fs,join as jn}from"node:path";import{existsSync as bt,readFileSync as ac,readdirSync as lc,writeFileSync as cc}from"node:fs";import{writeProjectConfig as Hs,readProjectConfig as uc,projectConfigPath as qs,writerDir as dc,DEFAULT_DOCS_DIR as Bs,DEFAULT_CAPTURE_DIR as Gs,DEFAULT_OUTPUT_DIR as Vs}from"document360-engine";function Ys(e,t="berlin"){let n=qs(e);if(bt(n))return{created:!1,path:n,profileName:""};let o={projectId:Xs(e)??Fs(e),docsDir:Bs,captureDir:Gs,outputDir:Vs,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Js(e)};return Hs(o,e),zs(e),{created:!0,path:n,profileName:t}}function zs(e){let t=jn(dc(e),".gitignore");bt(t)||cc(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
187
+ `),"utf8")}async function Ks(){let e=process.cwd(),t=qs(e);if(bt(t)&&!await ic({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Xs(e)??Fs(e),o=await Mt({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Mt({message:"Capture directory (where document360-capture .spec.ts files live):",default:Gs}),s=await Mt({message:"Screenshot output directory:",default:Vs}),c=await Mt({message:"Default connection profile name:",default:"berlin"}),p=await Mt({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),h={projectId:o,docsDir:Bs,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Js(e)},b=uc(e);b?.terminologyGlossary&&(h.terminologyGlossary=b.terminologyGlossary),Hs(h,e),zs(e);let k=yt(e);console.log(""),console.log(E(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${I(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let j of kt(k))console.log(j);return console.log(""),console.log(`${f("Then ask:")} ${I('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Xs(e){let t=jn(e,"package.json");if(!bt(t))return null;try{return JSON.parse(ac(t,"utf8")).name??null}catch{return null}}function Js(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])bt(jn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=jn(e,n);bt(o)&&!pc(o)&&t.push(n)}return t}function pc(e){try{return lc(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}W();import{readMcpConfig as Eo,writeMcpConfig as Qs}from"document360-engine";async function An(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(fc(),{kind:"continue"}):t==="add"?(mc(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(hc(e.slice(1)),{kind:"continue"}):(console.log(v(`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 fc(){let e=Eo(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
188
188
  No MCP servers registered. Add one with /mcp add <name> <type> <ref>
189
- `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${I(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(` ${I(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function fc(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(v("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(v(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=jo(),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(v(`-H expects key:value (no spaces). Got: ${h??"(nothing)"}`));return}c[b[1].trim()]=b[2].trim()}else{console.log(v(`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,Js(r),console.log(""),console.log(E(`\u2713 Registered "${t}" (${n})`)),console.log(U(" 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 mc(e){let t=e[0];if(!t){console.log(v("Usage: /mcp remove <name>"));return}let n=jo();if(!n.servers[t]){console.log(v(`No server named "${t}".`));return}delete n.servers[t],Js(n),console.log(E(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as Dc}from"node:fs";import{join as jc}from"node:path";import{select as Ac}from"@inquirer/prompts";import{computeSyncStatus as Mo,planPartitions as Ec,relatedArticlePaths as Ic,resolveModelForOperation as Nc,runPartitioned as _c,loadProfileMap as Oc,resolveActiveProfile as Uc,resolveCrossLinks as Lc}from"document360-engine";import z from"picocolors";import oi from"wrap-ansi";import Oo from"string-width";W();import Oe from"picocolors";import Ao from"wrap-ansi";import Eo from"string-width";var Qs=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Zs=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),ei=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function hc(e){let t=e.replace(/\r/g,"").split(`
190
- `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(Qs(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Zs(t[o+1])){let p=ei(r);o+=2;let h=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)h.push(ei(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])&&!Qs(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 Io(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Oe.bold(t.slice(2,-2)):t.startsWith("`")?I(t.slice(1,-1)):Oe.italic(t.slice(1,-1)))}var gc=(e,t)=>e+" ".repeat(Math.max(0,t-Eo(e)));function wc(e,t,n){let o=e.length,r=e.map((P,N)=>Math.max(Eo(P),...t.map(O=>Eo(O[N]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],h=()=>p.reduce((P,N)=>P+N,0)+c,b=0;for(;h()>s&&b++<1e4;){let P=-1,N=6;for(let O=0;O<o;O++)p[O]>N&&(N=p[O],P=O);if(P===-1)break;p[P]-=1}let y=(P,N,O)=>Oe.gray(P+p.map(q=>"\u2500".repeat(q+2)).join(N)+O),j=Oe.gray("\u2502"),k=(P,N)=>{let O=p.map((Ce,re)=>{let ke=P[re]??"",se=N?Oe.bold(ke):Io(ke);return Ao(se,Ce,{hard:!0}).split(`
191
- `)}),q=Math.max(...O.map(Ce=>Ce.length)),ne=[];for(let Ce=0;Ce<q;Ce++)ne.push(p.map((re,ke)=>`${j} ${gc(O[ke][Ce]??"",re)} `).join("")+j);return ne.join(`
192
- `)},C=[y("\u250C","\u252C","\u2510"),k(e,!0)];return C.push(t.length===0?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524")),t.forEach((P,N)=>{C.push(k(P,!1)),C.push(N===t.length-1?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524"))}),C.join(`
193
- `)}function yc(e,t){switch(e.kind){case"heading":return Oe.bold(e.text);case"hr":return Oe.gray("\u2500".repeat(t));case"para":return Ao(Io(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=Ao(Io(n),Math.max(10,t-4)).split(`
189
+ `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${I(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(` ${I(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function mc(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(v("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(v(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Eo(),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(v(`-H expects key:value (no spaces). Got: ${h??"(nothing)"}`));return}c[b[1].trim()]=b[2].trim()}else{console.log(v(`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,Qs(r),console.log(""),console.log(E(`\u2713 Registered "${t}" (${n})`)),console.log(U(" 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 hc(e){let t=e[0];if(!t){console.log(v("Usage: /mcp remove <name>"));return}let n=Eo();if(!n.servers[t]){console.log(v(`No server named "${t}".`));return}delete n.servers[t],Qs(n),console.log(E(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as jc}from"node:fs";import{join as Ac}from"node:path";import{select as Ec}from"@inquirer/prompts";import{computeSyncStatus as Fo,planPartitions as Ic,relatedArticlePaths as Nc,resolveModelForOperation as _c,runPartitioned as Oc,loadProfileMap as Uc,resolveActiveProfile as Lc,resolveCrossLinks as Mc}from"document360-engine";import z from"picocolors";import ri from"wrap-ansi";import Lo from"string-width";W();import Oe from"picocolors";import Io from"wrap-ansi";import No from"string-width";var Zs=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),ei=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),ti=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function gc(e){let t=e.replace(/\r/g,"").split(`
190
+ `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(Zs(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&ei(t[o+1])){let p=ti(r);o+=2;let h=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)h.push(ti(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])&&!Zs(t[o])&&!(t[o].includes("|")&&o+1<t.length&&ei(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function _o(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Oe.bold(t.slice(2,-2)):t.startsWith("`")?I(t.slice(1,-1)):Oe.italic(t.slice(1,-1)))}var wc=(e,t)=>e+" ".repeat(Math.max(0,t-No(e)));function yc(e,t,n){let o=e.length,r=e.map((P,N)=>Math.max(No(P),...t.map(O=>No(O[N]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],h=()=>p.reduce((P,N)=>P+N,0)+c,b=0;for(;h()>s&&b++<1e4;){let P=-1,N=6;for(let O=0;O<o;O++)p[O]>N&&(N=p[O],P=O);if(P===-1)break;p[P]-=1}let k=(P,N,O)=>Oe.gray(P+p.map(q=>"\u2500".repeat(q+2)).join(N)+O),j=Oe.gray("\u2502"),y=(P,N)=>{let O=p.map((Ce,re)=>{let ke=P[re]??"",se=N?Oe.bold(ke):_o(ke);return Io(se,Ce,{hard:!0}).split(`
191
+ `)}),q=Math.max(...O.map(Ce=>Ce.length)),oe=[];for(let Ce=0;Ce<q;Ce++)oe.push(p.map((re,ke)=>`${j} ${wc(O[ke][Ce]??"",re)} `).join("")+j);return oe.join(`
192
+ `)},C=[k("\u250C","\u252C","\u2510"),y(e,!0)];return C.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((P,N)=>{C.push(y(P,!1)),C.push(N===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),C.join(`
193
+ `)}function kc(e,t){switch(e.kind){case"heading":return Oe.bold(e.text);case"hr":return Oe.gray("\u2500".repeat(t));case"para":return Io(_o(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=Io(_o(n),Math.max(10,t-4)).split(`
194
194
  `);return" \u2022 "+o+r.map(s=>`
195
195
  `+s).join("")}).join(`
196
196
  `);case"code":return e.lines.map(n=>Oe.gray(" "+n)).join(`
197
- `);case"table":return wc(e.header,e.rows,t)}}function No(e,t){let n=Math.max(20,t);return hc(e).map(o=>yc(o,n)).join(`
197
+ `);case"table":return yc(e.header,e.rows,t)}}function Oo(e,t){let n=Math.max(20,t);return gc(e).map(o=>kc(o,n)).join(`
198
198
 
199
- `)}W();import kc from"picocolors";var bc=[127,86,217],xc=[22,38,43],ti={T:bc,E:xc},Lt=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],_o=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,$c=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function ni(){if(!kc.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=ti[Lt[n][r]],c=n+1<Lt.length?ti[Lt[n+1][r]]:void 0;s&&c?o+=`${_o(s)}${$c(c)}\u2580\x1B[49m\x1B[39m`:s?o+=`${_o(s)}\u2580\x1B[39m`:c?o+=`${_o(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 ce(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 vc(e,t){let n=[Et("\u270E document360-writer")+z.gray(` v${e.version}`),z.gray(" Reads your code, writes your docs."),"",xt("Claude:",`${e.claude}${z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),xt("Document360:",e.configured?e.loggedOut?z.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?z.gray(` (${e.sessionHint})`):""}`:z.yellow("not set up \u2014 run /init")),xt("Profile:",e.configured?`${e.profile}${z.gray(` (${e.apiUrl})`)}${e.prod?z.bold(z.yellow(" \u26A0 PRODUCTION")):""}`:z.gray("\u2014 (run /init)")),xt("Project:",e.project),xt("Mode:",z.gray(e.mode)),xt("cwd:",z.gray(e.cwd))],o=ni();if(o.length===0)return n.join(`
200
- `);let r=2,s=3,c=Oo(o[0]);if(!(t>=r+c+s+Math.max(...n.map(y=>Oo(y)))))return[...o.map(y=>" "+y),...n].join(`
201
- `);let h=Math.max(0,Math.floor((n.length-o.length)/2)),b=[];for(let y=0;y<Math.max(o.length+h,n.length);y++){let j=o[y-h]??" ".repeat(c);b.push((" ".repeat(r)+j+" ".repeat(s)+(n[y]??"")).trimEnd())}return b.join(`
202
- `)}var Cc={error:z.red,warn:z.yellow,ok:z.green,info:z.gray};function Uo(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return vc(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),c=50,p=e.text.split(`
203
- `).flatMap(b=>oi(b,s,{hard:!0}).split(`
199
+ `)}W();import bc from"picocolors";var xc=[127,86,217],$c=[22,38,43],ni={T:xc,E:$c},Wt=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Uo=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,vc=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function oi(){if(!bc.isColorSupported)return[];let e=Wt[0].length,t=[];for(let n=0;n<Wt.length;n+=2){let o="";for(let r=0;r<e;r++){let s=ni[Wt[n][r]],c=n+1<Wt.length?ni[Wt[n+1][r]]:void 0;s&&c?o+=`${Uo(s)}${vc(c)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Uo(s)}\u2580\x1B[39m`:c?o+=`${Uo(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Ft(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function ce(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 Cc(e,t){let n=[It("\u270E document360-writer")+z.gray(` v${e.version}`),z.gray(" Reads your code, writes your docs."),"",xt("Claude:",`${e.claude}${z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),xt("Document360:",e.configured?e.loggedOut?z.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?z.gray(` (${e.sessionHint})`):""}`:z.yellow("not set up \u2014 run /init")),xt("Profile:",e.configured?`${e.profile}${z.gray(` (${e.apiUrl})`)}${e.prod?z.bold(z.yellow(" \u26A0 PRODUCTION")):""}`:z.gray("\u2014 (run /init)")),xt("Project:",e.project),xt("Mode:",z.gray(e.mode)),xt("cwd:",z.gray(e.cwd))],o=oi();if(o.length===0)return n.join(`
200
+ `);let r=2,s=3,c=Lo(o[0]);if(!(t>=r+c+s+Math.max(...n.map(k=>Lo(k)))))return[...o.map(k=>" "+k),...n].join(`
201
+ `);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 j=o[k-h]??" ".repeat(c);b.push((" ".repeat(r)+j+" ".repeat(s)+(n[k]??"")).trimEnd())}return b.join(`
202
+ `)}var Pc={error:z.red,warn:z.yellow,ok:z.green,info:z.gray};function Mo(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Cc(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),c=50,p=e.text.split(`
203
+ `).flatMap(b=>ri(b,s,{hard:!0}).split(`
204
204
  `)),h=Math.max(0,p.length-c);return h>0&&(p=[...p.slice(0,c),z.dim(`\u2026 +${h} more lines`)]),`
205
- `+p.map((b,y)=>o+(y===0?I(" \u276F "):" ")+b+" ".repeat(Math.max(0,s-Oo(b))+1)+r).join(`
205
+ `+p.map((b,k)=>o+(k===0?I(" \u276F "):" ")+b+" ".repeat(Math.max(0,s-Lo(b))+1)+r).join(`
206
206
  `)}case"assistant":return`
207
- `+No(e.text,n);case"tool":{let o=e.arg!==null?z.gray(`${e.sep}(${e.arg})`):"";return`
208
- `+oi(z.green("\u25CF ")+z.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?z.red:z.gray,r=e.lines.map((s,c)=>o((c===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(z.dim(` \u2026 +${e.hidden} lines`)),r.join(`
207
+ `+Oo(e.text,n);case"tool":{let o=e.arg!==null?z.gray(`${e.sep}(${e.arg})`):"";return`
208
+ `+ri(z.green("\u25CF ")+z.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?z.red:z.gray,r=e.lines.map((s,c)=>o((c===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(z.dim(` \u2026 +${e.hidden} lines`)),r.join(`
209
209
  `)}case"diff":{let o=c=>c===1?"":"s",s=[z.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(z.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
210
- `)}case"link":return e.lines.map(o=>I(Nt(` \u2B95 ${o}`))).join(`
210
+ `)}case"link":return e.lines.map(o=>I(_t(` \u2B95 ${o}`))).join(`
211
211
  `);case"preview":return`
212
- `+Et(`\u25A3 Preview \u2014 ${e.name}`)+`
213
-
214
- `+No(e.text,n);case"note":return`
215
- `+Cc[e.tone](Nt(e.text));case"done":return`
216
- `+(e.ok?z.magenta("\u2736 "):z.red("\u2736 "))+z.gray(`Cooked for ${Mt(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${ce(e.costUsd)}`:""))}}function ri(e,t){return e.map(n=>Uo(n,t)).join(`
217
- `)}import{resolveActiveProfile as Pc,loadTokens as Sc,isExpired as Tc,decodeJwtClaims as si}from"document360-engine";function Rc(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Te(e,t){try{let n=Pc(e,t),o=Sc(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Tc(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={...si(o.idToken)??{},...si(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 ${Rc(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var Wt=3;function Wo(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, strip every <!-- SCREENSHOT ... --> block while keeping the visible [Screenshot: ...] line, normalize cross-article links).","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself \u2014 do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
218
- `)}var ii={"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 ii&&!t.link).map(t=>({path:t.path,label:ii[t.status]}))}function jn(e){return e.filter(t=>t.link).length}function Fo(e,t){try{let n=Oc(e,Uc(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Lc(Dc(jc(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages not published yet \u2014 they show as plain text for now and turn into live links once those pages are published.`}catch{return null}}function Mc(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 ai(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:`${Mc(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 An(e){return[`Run the publish-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures) and remind me drafts need review in the portal."].join(`
219
- `)}function Ho(e,t,n){let o=k=>t[k.index]?.paths.length??0,r=e.filter(k=>k.ok),s=e.filter(k=>!k.ok),c=e.reduce((k,C)=>k+o(C),0),p=r.reduce((k,C)=>k+o(C),0),h=n==="api"?`${ce(e.reduce((k,C)=>k+C.costUsd,0))} total`:Ue(e.reduce((k,C)=>k+C.outputTokens,0)),b=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,y=k=>`${k} article${k===1?"":"s"}`,j=[];if(s.length===0)j.push(`Published ${y(c)} (${b}) successfully \xB7 ${h}.`),j.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{j.push(`Published ${p}/${y(c)} (${b}) \xB7 ${h}.`),j.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 k of s)j.push(` \u2717 ${k.label}${k.error?` \u2014 ${k.error}`:""}`)}return j}async function Lo(e,t){let n=Ec(t),{model:o}=Nc(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 _c({cwd:e.cwd,partitions:n,promptFor:s=>An(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(E(` \u2713 ${r.label}`)):console.log(v(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let s=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of Ho(r.results,n,s))console.log(r.ok?E(p):U(p));let c=Fo(e.cwd,e.profileName);c&&console.log(f(c))}}catch(r){console.log(v(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function En(e,t,n){let o=Ic(e,n);if(o.length===0)return[];let r=new Set(Ft((await Mo({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function li(e,t){let n=Te(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await En(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(E("\u2713 All related articles are already published.")),{kind:"continue"}):await Lo(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await Mo({cwd:t?.cwd??process.cwd()}),s=Ft(r.entries),c=jn(r.entries);return c>0&&console.log(U(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),s.length===0?(console.log(E(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):t?await Lo(t,s.map(p=>p.path)):{kind:"forward-to-agent",prompt:An(s.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log(v(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let s=await Mo({cwd:t?.cwd??process.cwd()});r=Ft(s.entries);let c=jn(s.entries);c>0&&console.log(U(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`))}catch(s){return console.log(v(`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(E("\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(()=>Ac({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 Lo(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Wo(o),display:`/publish ${o}`}}async function Ht(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
220
- `),display:"/audit"}}W();import{checkbox as Wc}from"@inquirer/prompts";import{inventoryRepo as Fc,readProjectConfig as ci,writeProjectConfig as Hc}from"document360-engine";function qo(e,t){let n=ci(e);n&&(n.authoritativeSourceFiles=t,Hc(n,e))}function In(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 ui(e,t){let n=t?.cwd??process.cwd();if(!ci(n))return console.log(v("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=Fc(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(I("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(In(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Wc({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${In(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"};qo(n,r),console.log(E(`\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"}}W();import{confirm as Yc}from"@inquirer/prompts";import{applyPull as hi,computeSyncStatus as gi,planPull as zc,establishBaselines as Kc,D360AuthError as Xc}from"document360-engine";W();var di=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/sync pull <path> or /publish <path>):",paint:v,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:U,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /sync pull <path>:",paint:I,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:v,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:v,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:te,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:f,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet:",paint:f,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /sync baseline to set a baseline (or the next publish/pull sets one):",paint:te,mark:"\xB7"}];function qc(e){return e.path?e.path:`${e.title??"(untitled)"} ${te(`[${e.articleId}]`)}`}function Nn(e){let t=[],n=e.entries.filter(h=>h.link);if(n.length>0){t.push(""),t.push(xe("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let h of n)t.push(` ${U("~")} ${U(h.path??"")} ${te(`\u2192 "${h.link.title}"`)}`)}for(let h of di){let b=e.entries.filter(y=>y.status===h.status&&!(h.status==="untracked-local"&&y.link));if(b.length!==0){t.push(""),t.push(xe(h.header));for(let y of b)t.push(` ${h.paint(h.mark)} ${h.paint(qc(y))}${y.detail?te(` (${y.detail})`):""}`)}}let o=e.counts["in-sync"]??0,r=e.entries.length;t.push("");let s={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},c=n.length,p=r===o?E("\u2713 everything up to date"):[o>0?E(`\u2713 ${o} up to date`):null,c>0?`${c} to link`:null,...di.map(h=>{let b=(e.counts[h.status]??0)-(h.status==="untracked-local"?c:0);return b>0?`${b} ${s[h.status]}`:null})].filter(Boolean).join(te(" \xB7 "));return t.push(p+te(` \xB7 ${r} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/`)),t}import{structuredPatch as Bc}from"diff";import pi from"picocolors";var fi=80,Gc="\x1B[48;2;74;28;28m",Vc="\x1B[48;2;24;66;24m",mi="\x1B[49m",Bo=e=>String(e).padStart(5);function Xe(e,t,n){let o=k=>{let C=k.replace(/\r\n/g,`
212
+ `+It(`\u25A3 Preview \u2014 ${e.name}`)+`
213
+
214
+ `+Oo(e.text,n);case"note":return`
215
+ `+Pc[e.tone](_t(e.text));case"done":return`
216
+ `+(e.ok?z.magenta("\u2736 "):z.red("\u2736 "))+z.gray(`Cooked for ${Ft(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${ce(e.costUsd)}`:""))}}function si(e,t){return e.map(n=>Mo(n,t)).join(`
217
+ `)}import{resolveActiveProfile as Sc,loadTokens as Tc,isExpired as Rc,decodeJwtClaims as ii}from"document360-engine";function Dc(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Re(e,t){try{let n=Sc(e,t),o=Tc(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Rc(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={...ii(o.idToken)??{},...ii(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 ${Dc(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var Ht=3;function Ho(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, strip every <!-- SCREENSHOT ... --> block while keeping the visible [Screenshot: ...] line, normalize cross-article links).","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself \u2014 do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
218
+ `)}var ai={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function qt(e){return e.filter(t=>t.path!==null&&t.status in ai&&!t.link).map(t=>({path:t.path,label:ai[t.status]}))}function En(e){return e.filter(t=>t.link).length}function qo(e,t){try{let n=Uc(e,Lc(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Mc(jc(Ac(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages not published yet \u2014 they show as plain text for now and turn into live links once those pages are published.`}catch{return null}}function Wc(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 li(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:`${Wc(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 In(e){return[`Run the publish-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures) and remind me drafts need review in the portal."].join(`
219
+ `)}function Bo(e,t,n){let o=y=>t[y.index]?.paths.length??0,r=e.filter(y=>y.ok),s=e.filter(y=>!y.ok),c=e.reduce((y,C)=>y+o(C),0),p=r.reduce((y,C)=>y+o(C),0),h=n==="api"?`${ce(e.reduce((y,C)=>y+C.costUsd,0))} total`:Ue(e.reduce((y,C)=>y+C.outputTokens,0)),b=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,k=y=>`${y} article${y===1?"":"s"}`,j=[];if(s.length===0)j.push(`Published ${k(c)} (${b}) successfully \xB7 ${h}.`),j.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{j.push(`Published ${p}/${k(c)} (${b}) \xB7 ${h}.`),j.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 y of s)j.push(` \u2717 ${y.label}${y.error?` \u2014 ${y.error}`:""}`)}return j}async function Wo(e,t){let n=Ic(t),{model:o}=_c(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${Ht} 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 Oc({cwd:e.cwd,partitions:n,promptFor:s=>In(s.paths),concurrency:Ht,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(E(` \u2713 ${r.label}`)):console.log(v(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let s=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of Bo(r.results,n,s))console.log(r.ok?E(p):U(p));let c=qo(e.cwd,e.profileName);c&&console.log(f(c))}}catch(r){console.log(v(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Nn(e,t,n){let o=Nc(e,n);if(o.length===0)return[];let r=new Set(qt((await Fo({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function ci(e,t){let n=Re(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Nn(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(E("\u2713 All related articles are already published.")),{kind:"continue"}):await Wo(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await Fo({cwd:t?.cwd??process.cwd()}),s=qt(r.entries),c=En(r.entries);return c>0&&console.log(U(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),s.length===0?(console.log(E(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):t?await Wo(t,s.map(p=>p.path)):{kind:"forward-to-agent",prompt:In(s.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log(v(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let s=await Fo({cwd:t?.cwd??process.cwd()});r=qt(s.entries);let c=En(s.entries);c>0&&console.log(U(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`))}catch(s){return console.log(v(`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(E("\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(()=>Ec({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 Wo(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Ho(o),display:`/publish ${o}`}}async function Bt(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
220
+ `),display:"/audit"}}W();import{checkbox as Fc}from"@inquirer/prompts";import{inventoryRepo as Hc,readProjectConfig as ui,writeProjectConfig as qc}from"document360-engine";function Go(e,t){let n=ui(e);n&&(n.authoritativeSourceFiles=t,qc(n,e))}function _n(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 di(e,t){let n=t?.cwd??process.cwd();if(!ui(n))return console.log(v("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=Hc(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(I("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(_n(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Fc({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${_n(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"};Go(n,r),console.log(E(`\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"}}W();import{confirm as zc}from"@inquirer/prompts";import{applyPull as gi,computeSyncStatus as wi,planPull as Kc,establishBaselines as Xc,D360AuthError as Jc}from"document360-engine";W();var pi=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/sync pull <path> or /publish <path>):",paint:v,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:U,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /sync pull <path>:",paint:I,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:v,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:v,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ne,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:f,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet:",paint:f,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /sync baseline to set a baseline (or the next publish/pull sets one):",paint:ne,mark:"\xB7"}];function Bc(e){return e.path?e.path:`${e.title??"(untitled)"} ${ne(`[${e.articleId}]`)}`}function On(e){let t=[],n=e.entries.filter(h=>h.link);if(n.length>0){t.push(""),t.push(xe("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let h of n)t.push(` ${U("~")} ${U(h.path??"")} ${ne(`\u2192 "${h.link.title}"`)}`)}for(let h of pi){let b=e.entries.filter(k=>k.status===h.status&&!(h.status==="untracked-local"&&k.link));if(b.length!==0){t.push(""),t.push(xe(h.header));for(let k of b)t.push(` ${h.paint(h.mark)} ${h.paint(Bc(k))}${k.detail?ne(` (${k.detail})`):""}`)}}let o=e.counts["in-sync"]??0,r=e.entries.length;t.push("");let s={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},c=n.length,p=r===o?E("\u2713 everything up to date"):[o>0?E(`\u2713 ${o} up to date`):null,c>0?`${c} to link`:null,...pi.map(h=>{let b=(e.counts[h.status]??0)-(h.status==="untracked-local"?c:0);return b>0?`${b} ${s[h.status]}`:null})].filter(Boolean).join(ne(" \xB7 "));return t.push(p+ne(` \xB7 ${r} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/`)),t}import{structuredPatch as Gc}from"diff";import fi from"picocolors";var mi=80,Vc="\x1B[48;2;74;28;28m",Yc="\x1B[48;2;24;66;24m",hi="\x1B[49m",Vo=e=>String(e).padStart(5);function Xe(e,t,n){let o=y=>{let C=y.replace(/\r\n/g,`
221
221
  `);return C.endsWith(`
222
222
  `)||C===""?C:C+`
223
- `},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=Bc("a","b",r,s,"","",{context:3}),h=0,b=0,y=[];p.hunks.forEach((k,C)=>{C>0&&y.push(pi.gray(" \u2026"));let P=k.oldStart,N=k.newStart;for(let O of k.lines){let q=O[0],ne=O.slice(1).slice(0,c);q==="-"?(b++,y.push(`${Gc}${Bo(P++)} - ${ne}${mi}`)):q==="+"?(h++,y.push(`${Vc}${Bo(N++)} + ${ne}${mi}`)):(y.push(pi.gray(Bo(N))+" "+ne),P++,N++)}});let j=y.slice(0,fi);return{added:h,removed:b,lines:j,hidden:Math.max(0,y.length-fi)}}async function wi(e,t){let n=Te(t.cwd,t.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=(e[0]??"status").toLowerCase();try{if(o==="status")return await Jc(t.cwd),{kind:"continue"};if(o==="pull")return await Zc(t,e.slice(1)),{kind:"continue"};if(o==="baseline")return await Qc(t,e.slice(1)),{kind:"continue"};console.log(v(`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")),console.log(f(" /sync baseline set a sync baseline for tracked-but-not-yet-compared articles"))}catch(r){r instanceof Xc?console.log(v(r.message)):console.log(v(`Sync failed: ${r.message}`))}return{kind:"continue"}}async function Jc(e){console.log(f("Checking Document360 for drift\u2026"));let t=await gi({cwd:e});for(let n of Nn(t))console.log(n);console.log("")}async function Qc(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(f(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Kc({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0});if(o.baselined.length===0&&o.skipped.length===0){console.log(E("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(E(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),o.skipped.length>0){console.log(U(`${o.skipped.length} skipped:`));for(let r of o.skipped)console.log(f(` - ${r.path} (${r.reason})`))}}async function Zc(e,t){let n=t[0];if(!n){console.log(v("Usage: /sync pull <article-path> | --all"));return}let o;if(n==="--all"){if(console.log(f("Checking Document360 for drift\u2026")),o=(await gi({cwd:e.cwd})).entries.filter(s=>s.status==="remote-ahead"&&s.path).map(s=>s.path),o.length===0){console.log(E("\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(`${xe(String(o.length))} article(s) are remote-ahead.`)}else o=[n.replace(/\\/g,"/")];for(let r of o){let s=await zc({cwd:e.cwd,relPath:r});console.log(""),console.log(`${I("\u25CF")} ${xe(s.title)} ${te(`(${s.path})`)}`);for(let b of s.notes)console.log(U(` \u26A0 ${b}`));s.overwritesLocalChanges&&console.log(U(" \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.")),hi({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(()=>Yc({message:`Write ${s.path}?`,default:!s.overwritesLocalChanges}))){console.log(f(" Skipped."));continue}hi({cwd:e.cwd},s),console.log(E(` \u2713 Pulled ${s.path} (sync base advanced).`))}console.log("")}W();import{statSync as eu}from"node:fs";import{resolve as tu}from"node:path";import{estimateBulkCost as nu,planPartitions as ou,readProjectConfig as ru,resolveModelForOperation as su,runPartitioned as iu,trackedArticlePaths as au}from"document360-engine";var Go=3;function Vo(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 Yo(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function zo(e,t){return t.map(n=>{let o=0;try{o=eu(tu(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Ko(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite \u2014 be efficient:
223
+ `},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=Gc("a","b",r,s,"","",{context:3}),h=0,b=0,k=[];p.hunks.forEach((y,C)=>{C>0&&k.push(fi.gray(" \u2026"));let P=y.oldStart,N=y.newStart;for(let O of y.lines){let q=O[0],oe=O.slice(1).slice(0,c);q==="-"?(b++,k.push(`${Vc}${Vo(P++)} - ${oe}${hi}`)):q==="+"?(h++,k.push(`${Yc}${Vo(N++)} + ${oe}${hi}`)):(k.push(fi.gray(Vo(N))+" "+oe),P++,N++)}});let j=k.slice(0,mi);return{added:h,removed:b,lines:j,hidden:Math.max(0,k.length-mi)}}async function yi(e,t){let n=Re(t.cwd,t.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=(e[0]??"status").toLowerCase();try{if(o==="status")return await Qc(t.cwd),{kind:"continue"};if(o==="pull")return await eu(t,e.slice(1)),{kind:"continue"};if(o==="baseline")return await Zc(t,e.slice(1)),{kind:"continue"};console.log(v(`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")),console.log(f(" /sync baseline set a sync baseline for tracked-but-not-yet-compared articles"))}catch(r){r instanceof Jc?console.log(v(r.message)):console.log(v(`Sync failed: ${r.message}`))}return{kind:"continue"}}async function Qc(e){console.log(f("Checking Document360 for drift\u2026"));let t=await wi({cwd:e});for(let n of On(t))console.log(n);console.log("")}async function Zc(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(f(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Xc({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0});if(o.baselined.length===0&&o.skipped.length===0){console.log(E("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(E(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),o.skipped.length>0){console.log(U(`${o.skipped.length} skipped:`));for(let r of o.skipped)console.log(f(` - ${r.path} (${r.reason})`))}}async function eu(e,t){let n=t[0];if(!n){console.log(v("Usage: /sync pull <article-path> | --all"));return}let o;if(n==="--all"){if(console.log(f("Checking Document360 for drift\u2026")),o=(await wi({cwd:e.cwd})).entries.filter(s=>s.status==="remote-ahead"&&s.path).map(s=>s.path),o.length===0){console.log(E("\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(`${xe(String(o.length))} article(s) are remote-ahead.`)}else o=[n.replace(/\\/g,"/")];for(let r of o){let s=await Kc({cwd:e.cwd,relPath:r});console.log(""),console.log(`${I("\u25CF")} ${xe(s.title)} ${ne(`(${s.path})`)}`);for(let b of s.notes)console.log(U(` \u26A0 ${b}`));s.overwritesLocalChanges&&console.log(U(" \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.")),gi({cwd:e.cwd},s);continue}let p=b=>b===1?"":"s";console.log(ne(` \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(()=>zc({message:`Write ${s.path}?`,default:!s.overwritesLocalChanges}))){console.log(f(" Skipped."));continue}gi({cwd:e.cwd},s),console.log(E(` \u2713 Pulled ${s.path} (sync base advanced).`))}console.log("")}W();import{statSync as tu}from"node:fs";import{resolve as nu}from"node:path";import{estimateBulkCost as ou,planPartitions as ru,readProjectConfig as su,resolveModelForOperation as iu,runPartitioned as au,trackedArticlePaths as lu}from"document360-engine";var Yo=3;function zo(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 Ko(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Xo(e,t){return t.map(n=>{let o=0;try{o=tu(nu(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Jo(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite \u2014 be efficient:
224
224
  - Read ONLY the article files listed below. Do NOT read source code, other articles, or fetch the live portal \u2014 you already have everything you need.
225
225
  - Convert in place: wrap callouts, FAQs, tabs, accordions, and media embeds per the d360-markdown skill. Preserve all wording, headings, and structure; change only GFM\u2192DFM syntax.
226
226
  - Publish each as a draft with a single update call. Do NOT re-read, re-verify, or polish after converting, and skip articles already in DFM.
227
227
  - Work only on these files:
228
228
  `+e.paths.map(t=>`- ${t}`).join(`
229
- `)}function Xo(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: ${ce(r)}\u2013${ce(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Jo(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),s=e.filter(P=>!P.ok),c=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),h=e.reduce((P,N)=>P+N.costUsd,0),b=e.reduce((P,N)=>P+N.outputTokens,0),y=n==="api"?`${ce(h)} total`:Ue(b),j=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,k=P=>`${P} article${P===1?"":"s"}`,C=[];if(s.length===0)C.push(`Converted ${k(c)} (${j}) successfully \xB7 ${y}.`);else{C.push(`Converted ${p}/${k(c)} (${j}) \xB7 ${y}.`),C.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let P of s)C.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return C}async function yi(e,t){if(!ru(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Vo(e),r=au(t.cwd,t.profileName);if(r.length===0)return console.log(v("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Yo(r,n);if(s.length===0)return console.log(v(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=ou(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:h,forced:b}=su(t.cwd,"light");if(!o){let y=nu({files:zo(t.cwd,s),op:"convert",model:h});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let j of Xo(c,y,Go))console.log(j);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${Go} 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 y of iu({cwd:t.cwd,partitions:c,promptFor:Ko,concurrency:Go,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:h}))if(y.type==="partition_status")y.status==="running"?console.log(f(` \u25B8 ${y.label} \u2014 converting\u2026`)):y.status==="done"?console.log(E(` \u2713 ${y.label}`)):console.log(v(` \u2717 ${y.label}`));else if(y.type==="run_done"){console.log("");let j=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let k of Jo(y.results,c,j))console.log(y.ok?E(k):U(k))}}catch(y){console.log(v(`Convert run failed: ${y.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as ki}from"node:fs";import{resolve as bi}from"node:path";import{estimateBulkCost as lu,planPartitions as cu,readDocsPlan as uu,readProjectConfig as xi,DEFAULT_DOCS_DIR as du,resolveModelForOperation as pu,runPartitioned as fu}from"document360-engine";var Qo=5;function Zo(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 mu(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function hu(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function gu(e,t,n){return n.filter(o=>{try{return ki(bi(e,t,o)).size===0}catch{return!0}})}function er(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+=ki(bi(e,c)).size}catch{}return{path:r,bytes:s}})}function tr(e,t){return`Run the write-article skill to author EACH documentation article listed below. For each path:
229
+ `)}function Qo(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: ${ce(r)}\u2013${ce(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=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),s=e.filter(P=>!P.ok),c=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),h=e.reduce((P,N)=>P+N.costUsd,0),b=e.reduce((P,N)=>P+N.outputTokens,0),k=n==="api"?`${ce(h)} total`:Ue(b),j=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,y=P=>`${P} article${P===1?"":"s"}`,C=[];if(s.length===0)C.push(`Converted ${y(c)} (${j}) successfully \xB7 ${k}.`);else{C.push(`Converted ${p}/${y(c)} (${j}) \xB7 ${k}.`),C.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let P of s)C.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return C}async function ki(e,t){if(!su(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=zo(e),r=lu(t.cwd,t.profileName);if(r.length===0)return console.log(v("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Ko(r,n);if(s.length===0)return console.log(v(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=ru(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:h,forced:b}=iu(t.cwd,"light");if(!o){let k=ou({files:Xo(t.cwd,s),op:"convert",model:h});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let j of Qo(c,k,Yo))console.log(j);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${Yo} 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 au({cwd:t.cwd,partitions:c,promptFor:Jo,concurrency:Yo,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(E(` \u2713 ${k.label}`)):console.log(v(` \u2717 ${k.label}`));else if(k.type==="run_done"){console.log("");let j=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let y of Zo(k.results,c,j))console.log(k.ok?E(y):U(y))}}catch(k){console.log(v(`Convert run failed: ${k.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as bi}from"node:fs";import{resolve as xi}from"node:path";import{estimateBulkCost as cu,planPartitions as uu,readDocsPlan as du,readProjectConfig as $i,DEFAULT_DOCS_DIR as pu,resolveModelForOperation as fu,runPartitioned as mu}from"document360-engine";var er=5;function tr(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 hu(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function gu(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function wu(e,t,n){return n.filter(o=>{try{return bi(xi(e,t,o)).size===0}catch{return!0}})}function nr(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let c of o.get(r)?.sources??[])try{s+=bi(xi(e,c)).size}catch{}return{path:r,bytes:s}})}function or(e,t){return`Run the write-article skill to author EACH documentation article listed below. For each path:
230
230
  - 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).
231
231
  - 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.
232
232
  - 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.
@@ -234,60 +234,60 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
234
234
  - 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.
235
235
  Articles:
236
236
  `+e.paths.map(n=>`- ${n}`).join(`
237
- `)}function nr(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: ${ce(r)}\u2013${ce(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write --run to start."]}function or(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),s=e.filter(P=>!P.ok),c=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),h=e.reduce((P,N)=>P+N.costUsd,0),b=e.reduce((P,N)=>P+N.outputTokens,0),y=n==="api"?`${ce(h)} total`:Ue(b),j=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,k=P=>`${P} article${P===1?"":"s"}`,C=[];if(s.length===0)C.push(`Wrote ${k(c)} (${j}) successfully \xB7 ${y}.`),C.push("Next \u2014 push them to Document360:"),C.push("/publish --all"),C.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{C.push(`Wrote ${p}/${k(c)} (${j}) \xB7 ${y}.`),C.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let P of s)C.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return C}function rr(e,t,n){let o=(xi(e)?.docsDir??du).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=mu(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=hu(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=gu(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 $i(e,t){if(!xi(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=uu(t.cwd);if(n.length===0)return console.log(v("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}=Zo(e),{docsDir:c,targets:p,reason:h}=rr(t.cwd,n,{scope:o,path:r});if(p.length===0)return console.log(h?U(h):U("Nothing to write.")),{kind:"continue"};let b=cu(p),{model:y,forced:j}=pu(t.cwd,"standard");if(!s&&!!!r){let C=lu({files:er(t.cwd,n,p),op:"write",model:y});o&&console.log(f(`Scope: ${o} (${p.length} pending).`));for(let P of nr(b,C,Qo))console.log(P);return console.log(f(`Model: ${y}${j?" (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${Qo} agents at once) on ${y}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let C of fu({cwd:t.cwd,partitions:b,promptFor:P=>tr(P,c),concurrency:Qo,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:y}))if(C.type==="partition_status")C.status==="running"?console.log(f(` \u25B8 ${C.label} \u2014 writing\u2026`)):C.status==="done"?console.log(E(` \u2713 ${C.label}`)):console.log(v(` \u2717 ${C.label}`));else if(C.type==="run_done"){console.log("");let P=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let N of or(C.results,b,P))console.log(C.ok?E(N):U(N))}}catch(C){console.log(v(`Write run failed: ${C.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as wu,readdirSync as vi,statSync as Ci}from"node:fs";import{join as Pi}from"node:path";import{inputDir as yu,readProjectConfig as ku}from"document360-engine";var Si=/\.(md|markdown|pdf|txt)$/i;function sr(e){let t=yu(e);if(!wu(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of vi(t)){let s=Pi(t,r),c=!1;try{c=Ci(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=bu(s);p>0&&n.push({name:r,docCount:p})}else Si.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function bu(e){let t=0;for(let n of vi(e))try{Ci(Pi(e,n)).isFile()&&Si.test(n)&&t++}catch{}return t}function ir(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 _n(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(`
238
- `)}var ar="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Ti(e,t){let n=t?.cwd??process.cwd();if(!ku(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=sr(n);if(o.length===0&&r===0)return console.log(f(ar)),{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:_n(p),display:p?`/draft ${p}`:"/draft"}}let c=ir(o,s);return{kind:"forward-to-agent",prompt:_n(c??"",c?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as xu,readProjectConfig as $u}from"document360-engine";function lr(e){try{return xu(e).filter(t=>t.kind==="request").length}catch{return 0}}function cr(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function ur(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(`
239
- `)}var dr="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 Ri(e,t){let n=t?.cwd??process.cwd();if(!$u(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=cr(e);if(!r&&lr(n)===0)return console.log(f(dr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:ur(r,o),display:s}}W();import{search as vu}from"@inquirer/prompts";import{findByName as Cu,getSession as Pu,listSessions as Su,relativeTime as ji}from"document360-engine";async function Ai(e,t){let n=Su(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(v(`No session matches "${o}".`)),Di(n),{kind:"continue"})}if(!process.stdin.isTTY)return Di(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>vu({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} ${ji(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Pu(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Di(e){console.log("");for(let t of e.slice(0,15))console.log(` ${I(t.name)} ${f(ji(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Tu}from"document360-engine";function pr(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 Ei(e,t){let n=pr(e.join(" "));if(!n)return console.log(v("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Tu(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log(v("Could not find the current session record.")),{kind:"continue"}):(console.log(v("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as Ii,readProjectConfig as Ru,writeProjectConfig as Du}from"document360-engine";W();function fr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Ru(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 Ii().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Du(o,e),null):`Unknown environment "${r}". Known: ${Ii().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function Ni(e,t){let n=e[0];if(!n)return yn(t.cwd),{kind:"continue"};if(n==="add"){let o=fr(t.cwd,e[1],e[2]);return o?(console.log(v(o)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${I(`/profile ${e[1]}`)} then ${I("/login")}`),{kind:"continue"})}return kn(t.cwd,n),bn(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as ju}from"@inquirer/prompts";import{readProjectConfig as Au,readUserConfig as _i,resolveModelSetting as mr,writeUserConfig as Oi}from"document360-engine";var $e=[{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 On(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=$e.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Eu(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 qt(e,t){let n=()=>{let s=mr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=_i();return s.defaultModel?(delete s.defaultModel,Oi(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${mr(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}}Oi({..._i(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Au(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 Ui(e,t){let n=e[0]?.trim();if(!n){let c=mr(t.cwd);if(!process.stdin.isTTY)return console.log(`${xe("Model:")} ${I(c.model??"Claude Code default")}`),console.log(f(` source: ${Eu(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=On(c),h;try{h=await t.withPausedInput(()=>ju({message:`Select model (current: ${c.model??"Claude Code default"})`,default:$e[p].value,choices:$e.map((k,C)=>({name:`${k.label}${C===p?" \u2714":""}`,value:k.value,description:k.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:b,changed:y,effective:j}=qt(t.cwd,h??"default");for(let k of b)console.log(k.startsWith("\u26A0")?U(k):k.startsWith("\u2713")?E(k):f(k));return y&&await t.setModel(j),{kind:"continue"}}let{lines:o,changed:r,effective:s}=qt(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?U(c):c.startsWith("\u2713")?E(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}Un();async function Bi(e,t){return await t.withPausedInput(()=>ht(t.cwd)),{kind:"clear"}}async function Gi(e,t){return await t.withPausedInput(()=>ys(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as Bu}from"document360-engine";async function Vi(e,t){let n=!1;try{n=Bu(t.cwd).production}catch{}return n?(console.log(U("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var Yi=async(e,t)=>{try{await t.withPausedInput(()=>wn({}))}catch(n){console.log(v(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as Gu,clearTokens as Vu,clearProfileProject as Yu}from"document360-engine";async function zi(e,t){let n;try{n=Gu(t.cwd,t.profileName).name}catch(r){return console.log(v(r.message)),{kind:"continue"}}let o=Vu(n);return Yu(t.cwd,n),console.log(o?E(`\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 Ki}from"node:fs";import{isAbsolute as zu,join as Ku,resolve as Xu}from"node:path";import{readProjectConfig as Ju,screenshotPlaceholderIds as Qu,DEFAULT_CAPTURE_DIR as Zu,DEFAULT_OUTPUT_DIR as ed}from"document360-engine";var Xi=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function gr(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Xi(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Xi(o),setup:t}:{mode:"single",id:o}}function wr(e,t){let n=Ju(e),o=n?.captureDir??Zu,r=n?.outputDir??ed,s=(c,p)=>zu(c)?Ku(c,p):Xu(e,c,p);return Qu(e,{scope:t}).map(({id:c,file:p})=>{let h=Ki(s(r,`${c}.png`))?"captured":Ki(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:h}})}var td={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},nd={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function yr(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(` ${td[c.state]} ${c.id.padEnd(34)} ${nd[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Ji(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(`
237
+ `)}function rr(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: ${ce(r)}\u2013${ce(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write --run to start."]}function sr(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),s=e.filter(P=>!P.ok),c=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),h=e.reduce((P,N)=>P+N.costUsd,0),b=e.reduce((P,N)=>P+N.outputTokens,0),k=n==="api"?`${ce(h)} total`:Ue(b),j=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,y=P=>`${P} article${P===1?"":"s"}`,C=[];if(s.length===0)C.push(`Wrote ${y(c)} (${j}) successfully \xB7 ${k}.`),C.push("Next \u2014 push them to Document360:"),C.push("/publish --all"),C.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{C.push(`Wrote ${p}/${y(c)} (${j}) \xB7 ${k}.`),C.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let P of s)C.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return C}function ir(e,t,n){let o=($i(e)?.docsDir??pu).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=hu(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=gu(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=wu(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 vi(e,t){if(!$i(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=du(t.cwd);if(n.length===0)return console.log(v("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}=tr(e),{docsDir:c,targets:p,reason:h}=ir(t.cwd,n,{scope:o,path:r});if(p.length===0)return console.log(h?U(h):U("Nothing to write.")),{kind:"continue"};let b=uu(p),{model:k,forced:j}=fu(t.cwd,"standard");if(!s&&!!!r){let C=cu({files:nr(t.cwd,n,p),op:"write",model:k});o&&console.log(f(`Scope: ${o} (${p.length} pending).`));for(let P of rr(b,C,er))console.log(P);return console.log(f(`Model: ${k}${j?" (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${er} 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 C of mu({cwd:t.cwd,partitions:b,promptFor:P=>or(P,c),concurrency:er,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:k}))if(C.type==="partition_status")C.status==="running"?console.log(f(` \u25B8 ${C.label} \u2014 writing\u2026`)):C.status==="done"?console.log(E(` \u2713 ${C.label}`)):console.log(v(` \u2717 ${C.label}`));else if(C.type==="run_done"){console.log("");let P=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let N of sr(C.results,b,P))console.log(C.ok?E(N):U(N))}}catch(C){console.log(v(`Write run failed: ${C.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as yu,readdirSync as Ci,statSync as Pi}from"node:fs";import{join as Si}from"node:path";import{inputDir as ku,readProjectConfig as bu}from"document360-engine";var Ti=/\.(md|markdown|pdf|txt)$/i;function ar(e){let t=ku(e);if(!yu(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Ci(t)){let s=Si(t,r),c=!1;try{c=Pi(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=xu(s);p>0&&n.push({name:r,docCount:p})}else Ti.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function xu(e){let t=0;for(let n of Ci(e))try{Pi(Si(e,n)).isFile()&&Ti.test(n)&&t++}catch{}return t}function lr(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 Un(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(`
238
+ `)}var cr="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Ri(e,t){let n=t?.cwd??process.cwd();if(!bu(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=ar(n);if(o.length===0&&r===0)return console.log(f(cr)),{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:Un(p),display:p?`/draft ${p}`:"/draft"}}let c=lr(o,s);return{kind:"forward-to-agent",prompt:Un(c??"",c?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as $u,readProjectConfig as vu}from"document360-engine";function ur(e){try{return $u(e).filter(t=>t.kind==="request").length}catch{return 0}}function dr(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function pr(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(`
239
+ `)}var fr="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 Di(e,t){let n=t?.cwd??process.cwd();if(!vu(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=dr(e);if(!r&&ur(n)===0)return console.log(f(fr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:pr(r,o),display:s}}W();import{search as Cu}from"@inquirer/prompts";import{findByName as Pu,getSession as Su,listSessions as Tu,relativeTime as Ai}from"document360-engine";async function Ei(e,t){let n=Tu(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=Pu(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(v(`No session matches "${o}".`)),ji(n),{kind:"continue"})}if(!process.stdin.isTTY)return ji(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Cu({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} ${Ai(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Su(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function ji(e){console.log("");for(let t of e.slice(0,15))console.log(` ${I(t.name)} ${f(Ai(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Ru}from"document360-engine";function mr(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 Ii(e,t){let n=mr(e.join(" "));if(!n)return console.log(v("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Ru(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log(v("Could not find the current session record.")),{kind:"continue"}):(console.log(v("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as Ni,readProjectConfig as Du,writeProjectConfig as ju}from"document360-engine";W();function hr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Du(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 Ni().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},ju(o,e),null):`Unknown environment "${r}". Known: ${Ni().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function _i(e,t){let n=e[0];if(!n)return bn(t.cwd),{kind:"continue"};if(n==="add"){let o=hr(t.cwd,e[1],e[2]);return o?(console.log(v(o)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${I(`/profile ${e[1]}`)} then ${I("/login")}`),{kind:"continue"})}return xn(t.cwd,n),$n(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Au}from"@inquirer/prompts";import{readProjectConfig as Eu,readUserConfig as Oi,resolveModelSetting as gr,writeUserConfig as Ui}from"document360-engine";var $e=[{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 Ln(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=$e.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Iu(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 Gt(e,t){let n=()=>{let s=gr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Oi();return s.defaultModel?(delete s.defaultModel,Ui(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${gr(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}}Ui({...Oi(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Eu(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 Li(e,t){let n=e[0]?.trim();if(!n){let c=gr(t.cwd);if(!process.stdin.isTTY)return console.log(`${xe("Model:")} ${I(c.model??"Claude Code default")}`),console.log(f(` source: ${Iu(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Ln(c),h;try{h=await t.withPausedInput(()=>Au({message:`Select model (current: ${c.model??"Claude Code default"})`,default:$e[p].value,choices:$e.map((y,C)=>({name:`${y.label}${C===p?" \u2714":""}`,value:y.value,description:y.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:b,changed:k,effective:j}=Gt(t.cwd,h??"default");for(let y of b)console.log(y.startsWith("\u26A0")?U(y):y.startsWith("\u2713")?E(y):f(y));return k&&await t.setModel(j),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Gt(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?U(c):c.startsWith("\u2713")?E(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}Mn();async function Gi(e,t){return await t.withPausedInput(()=>ht(t.cwd)),{kind:"clear"}}async function Vi(e,t){return await t.withPausedInput(()=>bs(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as Vu}from"document360-engine";async function Yi(e,t){let n=!1;try{n=Vu(t.cwd).production}catch{}return n?(console.log(U("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var zi=async(e,t)=>{try{await t.withPausedInput(()=>kn({}))}catch(n){console.log(v(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as Yu,clearTokens as zu,clearProfileProject as Ku}from"document360-engine";async function Ki(e,t){let n;try{n=Yu(t.cwd,t.profileName).name}catch(r){return console.log(v(r.message)),{kind:"continue"}}let o=zu(n);return Ku(t.cwd,n),console.log(o?E(`\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 Xi}from"node:fs";import{isAbsolute as Xu,join as Ju,resolve as Qu}from"node:path";import{readProjectConfig as Zu,screenshotPlaceholderIds as ed,DEFAULT_CAPTURE_DIR as td,DEFAULT_OUTPUT_DIR as nd}from"document360-engine";var Ji=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function yr(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Ji(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Ji(o),setup:t}:{mode:"single",id:o}}function kr(e,t){let n=Zu(e),o=n?.captureDir??td,r=n?.outputDir??nd,s=(c,p)=>Xu(c)?Ju(c,p):Qu(e,c,p);return ed(e,{scope:t}).map(({id:c,file:p})=>{let h=Xi(s(r,`${c}.png`))?"captured":Xi(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:h}})}var od={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},rd={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function br(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(` ${od[c.state]} ${c.id.padEnd(34)} ${rd[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Qi(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(`
240
240
  `),"","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(`
241
- `)}async function Ln(e,t){let n=gr(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of yr(wr(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(`
241
+ `)}async function Wn(e,t){let n=yr(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of br(kr(c,n.scope),n.scope))console.log(p);return{kind:"continue"}}if(n.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${n.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${n.id}.spec.ts. Report the spec path and any TODO data-testids or data to stage.`].join(`
242
242
  `),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(`
243
- `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as od,readFileSync as rd}from"node:fs";import{isAbsolute as sd,join as id,resolve as ad}from"node:path";import{readProjectConfig as ld,DEFAULT_CAPTURE_DIR as cd}from"document360-engine";async function Gt(){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(`
244
- `),display:"/capture-setup"}}var Qi="-".repeat(64);function kr(e){let t=cd;try{let y=ld(e);y?.captureDir&&(t=y.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=sd(t)?id(t,"CAPTURE-TESTID-REQUESTS.json"):ad(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!od(n))return null;let o;try{let y=JSON.parse(rd(n,"utf8").replace(/^/,""));o=Array.isArray(y?.requests)?y.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(y=>y.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.","",Qi,`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.",Qi]}Ke();W();import{listOpenForDocs as ud,readProjectConfig as dd}from"document360-engine";function br(e){try{return ud(e).length}catch{return 0}}function xr(){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(`
245
- `)}async function Zi(e,t){let n=t?.cwd??process.cwd();return dd(n)?br(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:xr(),display:"/inbox"}:(console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as pd,listOpenForDocs as fd,readProjectConfig as md}from"document360-engine";function $t(e){let t=0,n=0,o=0;try{t=pd(e).length}catch{}try{let r=fd(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 $r(e){return{publish:e.includes("--publish")}}function vr({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(`
246
- `)}async function ea(e,t){let n=t?.cwd??process.cwd();if(!md(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Te(n,t?.profileName);if(!o.ok)return console.log(v(o.reason)),{kind:"continue"};let{publish:r}=$r(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:vr({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as hd}from"node:child_process";var Je="document360-writer",Mn=`npm i -g ${Je}@latest`;async function Wn(){let e=process.platform==="win32";return new Promise(t=>{try{let n=hd(`npm i -g ${Je}@latest`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});n.on("error",o=>t({ok:!1,output:String(o)})),n.on("close",o=>t({ok:o===0,output:""})),e||n.unref()}catch(n){t({ok:!1,output:String(n)})}})}async function ta(){return console.log(f(`Updating ${Je}\u2026`)),(await Wn()).ok?console.log(E("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(v(`Update failed \u2014 run manually: ${Mn}`)),{kind:"continue"}}W();Ke();import{existsSync as Cr,rmSync as gd}from"node:fs";import{basename as na,resolve as Pr}from"node:path";import{execFileSync as wd}from"node:child_process";import{input as yd}from"@inquirer/prompts";import{readProjectConfig as kd,devHintsGuidePath as bd}from"document360-engine";var xd=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],$d=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Fn=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),oa=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function ra(e){let t=Fn(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:oa(t)?!0:$d.has(t)}function Sr(e){let t=null;try{t=kd(e)}catch{t=null}let n=new Set(xd);for(let o of[Fn(t?.docsDir),Fn(t?.captureDir),Fn(t?.outputDir)])o&&oa(o)&&n.add(o);return[...n].filter(o=>ra(o)&&Cr(Pr(e,o)))}function Tr(e,t){let n=[],o=[];for(let r of t){if(!ra(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{gd(Pr(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function sa(e,t){try{return wd("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
247
- `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function vd(e){return sa(e,".d360-writer/hints")}function Cd(e){return sa(e,".d360-writer/messages")}function Rr(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=vd(e),o=Cd(e),r=Cr(Pr(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: ${na(e)}`]}async function ia(e,t){let n=Sr(t.cwd);for(let h of Rr(t.cwd,n))console.log(n.length===0?f(h):h);if(n.length===0)return{kind:"continue"};let o=na(t.cwd);if((await t.withPausedInput(()=>yd({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(U("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Cr(bd(t.cwd)),{removed:c,failed:p}=Tr(t.cwd,n);console.log(E(`\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(v(` \u2717 ${h.path}: ${h.error}`));if(s){for(let h of Tn())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 aa={help:Po,"?":Po,clear:js,exit:So,quit:So,init:zs,mcp:Dn,publish:li,audit:Ht,scope:ui,sync:wi,convert:yi,write:$i,draft:Ti,document:Ri,resume:Ai,rename:Ei,profile:Ni,model:Ui,doctor:Bt,workspace:Bi,project:Gi,"allow-prod":Vi,login:Yi,logout:zi,screenshot:Ln,"capture-setup":Gt,devhints:Us,inbox:Zi,"catch-up":ea,update:ta,reset:ia};function la(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),o=(n[0]??"").toLowerCase();return o?{name:o,args:n.slice(1)}:null}Ke();W();var Pd={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"},ua=160,jr=200,da=40;function fe(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function ca(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}: ${fe(typeof r=="string"?r:JSON.stringify(r),da)}`);return t.length>4&&n.push("\u2026"),fe(n.join(", "),ua)}var Le=e=>typeof e=="string"&&e?e:null,Dr=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Sd(e){let t=Le(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 Td(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Le(t.title);if(!o)return null;let r=Sd(t.local_path);return n("Create article",`"${fe(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Le(t.title),r=Dr(t.article_id);return n("Update article",o?`"${fe(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Dr(t.article_id)?`id ${Dr(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",Le(t.name)?`"${fe(Le(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Le(t.file_path);return n("Upload image",o?fe(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Hn(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),c=s.join("__");if(r==="document360"){let b=Td(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:ca(t)}}let n=Pd[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:fe(o,ua)}:{title:e,sep:"",arg:ca(t)}}function Rd(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 Dd(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Rd).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>fe(r,jr))]}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}: ${fe(String(r),da)}`);return n.length>0?[fe(n.join(" \xB7 "),jr)]:null}return null}function jd(e){let t=Le(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Ad(e,t,n){switch(e){case"d360_create_article":{let o=jd(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=Le(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 ${fe(o[0],120)}`:""}`]}default:return null}}function qn(e,t=4,n,o){let r=e.replace(/\r\n/g,`
248
- `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=Ad(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let s=Dd(r)??r.split(`
249
- `);return{lines:s.slice(0,t).map(c=>fe(c,jr)),hidden:Math.max(0,s.length-t)}}function Bn(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Gn(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 Vn(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 qd=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Bd(e,t,n,o){if(qd.test(e))try{let r=ha(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=Gn(t,n),p=Vn(n);e.endsWith("publish_article")&&p&&console.log(I(` \u2B95 Live: ${p}`)),c&&s&&console.log(I(` \u2B95 Preview: ${Bn(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function ga(e=process.cwd(),t="auto",n){let o=Id(t);o.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${I("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${I('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${I("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${I("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Gd(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=Ar({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=Ed({input:process.stdin,output:process.stdout}),h=[],b=null,y=!1;p.on("line",C=>{if(b){let P=b;b=null,P(C)}else h.push(C)}),p.on("close",()=>{if(y=!0,b){let C=b;b=null,C(null)}});function j(){return h.length>0?Promise.resolve(h.shift()):y?Promise.resolve(null):(process.stdout.write(I("> ")),new Promise(C=>{b=C}))}let k={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=Ar({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setModel:async C=>s.setModel(C),withPausedInput:async C=>{p.pause();try{return await C()}finally{p.resume()}}};try{for(;;){let C=await j();if(C===null)break;let P=C.trim();if(P){if(P.startsWith("/")){let N=la(P);if(!N)continue;let O=aa[N.name];if(!O){console.log(v(`Unknown command: /${N.name}`)),console.log(f("Type /help for the list."));continue}let q=await O(N.args,k);if(q.kind==="exit")break;if(q.kind==="clear"){k.restartAgent();continue}if(q.kind==="allow-prod"){r=!0,k.restartAgent(),console.log(E("\u2713 Production writes authorized for this session.")),console.log("");continue}if(q.kind==="resume"){s.close(),s=Ar({cwd:e,resume:q.uuid,profileName:n,allowProdWrites:r});let ne=Nd(q.uuid);c={uuid:q.uuid,firstPrompt:ne?.firstPrompt??null,titleFired:!0},ma(q.uuid),console.log(E(`\u2713 Resumed "${q.name}"`)),console.log("");continue}q.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=q.display??q.prompt),await fa(s,q.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=P),await fa(s,P,o,c,e)}}}finally{s.close(),p.close()}}function Gd(e,t){console.log(""),console.log(Et("document360-writer")),console.log(f(` cwd: ${e}`));let n=Md(e);if(console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(Vd(e,t)),!Wd(e))console.log(U(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{try{Pn(e);for(let o of Sn(e))console.log(U(` ${o}`))}catch{}try{let o=vt($t(e));o&&console.log(U(` \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 Vd(e,t){try{let n=ha(e,t),o=n.production?U(" \u26A0 PRODUCTION"):"",r=Hd(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...pa(r.idToken)??{},...pa(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return Fd(r)&&!r.refreshToken?U(` 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 Yd(){console.error(""),console.error(`Sign in with your Claude subscription: run ${I("claude")} once, then retry.`),console.error(` (No Claude Code? ${I("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${I("https://console.anthropic.com/settings/keys")}`)}function zd(e,t,n){e.uuid=t;let o=new Date().toISOString();Ud({uuid:t,name:Od(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o})}function Kd(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Ld(o,t).then(r=>{r&&_d(n,r)}).catch(()=>{})}async function fa(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))Xd(c,o,r,n,s)}function Xd(e,t,n,o,r){switch(e.type){case"session":t.uuid||zd(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Hn(e.name,e.input);s&&(process.stdout.write(`
250
-
251
- `),console.log(`${E("\u25CF")} ${xe(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=qn(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?v: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||Bd(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
252
- `),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&&(ma(t.uuid),t.titleFired||Kd(t,n));break;case"error":console.error(""),console.error(v(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Yd();break}}import{render as nf}from"ink";import{resolveAuth as of}from"document360-engine";import{useCallback as Y,useEffect as ve,useMemo as Ur,useRef as J,useState as F}from"react";import{Box as ee,Text as T,useApp as cp,useInput as up,useStdout as dp}from"ink";import{existsSync as zt,readFileSync as Lr,readdirSync as Va}from"node:fs";import{spawnSync as pp}from"node:child_process";import{basename as Kt,isAbsolute as fp,join as Xt}from"node:path";import{createSession as Oa,classifyClaudeAuth as Ya,CLAUDE_CODE_SETUP_HINT as mp,loginPkce as hp,toStoredTokens as gp,saveTokens as wp,getAccessToken as yp,resolveActiveProfile as ue,resolveProjectId as kp,getArticle as bp,decodeJwtClaims as Ct,isExpired as De,loadTokens as Me,clearTokens as xp,clearProfileProject as $p,setTitle as vp,slugify as Cp,touchSession as Mr,upsertSession as Pp,generateTitle as Ua,findByName as Sp,listSessions as Tp,renameSession as Rp,suggestNextAction as Dp,readProjectConfig as Z,writeProjectConfig as La,resolveModelSetting as Br,loadProfileMap as Wr,applyPull as jp,computeSyncStatus as Fr,planPull as Ap,establishBaselines as Ep,inventoryRepo as Ip,knownEnvironments as Np,resolveEnvironment as _p,planPartitions as Hr,partitionEvenly as Op,screenshotPlaceholderIds as Up,trackedArticlePaths as Lp,runPartitioned as Qn,estimateBulkCost as Ma,resolveModelForOperation as Zn,readDocsPlan as Mp,checkForUpdate as Wp,detectInstallKind as Fp,isSelfUpdatable as Hp,devHintsGuidePath as Wa,toolFeedbackPath as qp,reconcileToolFeedback as Bp,DEFAULT_DOCS_DIR as za,setProfileProject as Gp}from"document360-engine";Ke();import{spawn as wa}from"node:child_process";function Jd(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Qd(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?wa([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):wa(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",c=>o(c===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function ya(e){for(let[t,n]of Jd())if(await Qd(t,n,e))return!0;return!1}var Zd=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Er(e,t){if(t.closed)return e;let n=e.split(`
253
- `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){Zd.test(s)&&(t.cueSeen=!0);continue}let c=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);c?(n[r]=`${c[1]}${++t.num}. ${c[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
254
- `)}import{existsSync as ep,mkdirSync as tp,readFileSync as np,writeFileSync as op}from"node:fs";import{join as ka}from"node:path";import{writerDir as rp}from"document360-engine";function ba(e){return ka(rp(e),".sessions")}function xa(e,t){return ka(ba(e),`${t}.json`)}function $a(e,t,n){try{tp(ba(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");op(xa(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Ir(e,t){try{let n=xa(e,t);if(!ep(n))return[];let o=JSON.parse(np(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var sp=e=>`\x1B]0;${e}\x07`,ip=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function va(e){process.stdout.isTTY&&process.stdout.write(e)}function Vt(e){va(sp(e))}function Yn(e){va(ip(e))}var zn=["\xB7 "," \xB7"],Nr="\u{1F7E3}";Un();var ap=/^(?:\d+[.)]|[-*•])\s+/;function Ca(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
255
- `)){let c=s.trim().replace(ap,""),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}W();function Yt(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 _r(e){return e.replace(/^[\w.-]+\//,"")}var Kn=16,Pa={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Or(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Sa(e,t){let n=Or(t);return e.some(r=>r.trim()===t.trim()||!!n&&Or(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&Or(r)===n)):[]}var lp=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Ta(e){return e.replace(/\r\n?/g,`
256
- `)}function Ra(e){return e.includes(`
257
- `)||e.length>200}function Da(e,t){let n=t.split(`
258
- `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function ja(e,t){return e.replace(lp,n=>t.get(n)??n)}function Aa(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Xn(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
259
- `)){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 Jn(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Ea(e,t,n){let o=Jn(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 Ia(e,t,n){let o=e[Jn(e,t)];return n==="start"?o.start:o.end}function Na(e,t,n){let o=Math.max(1,n),r=e.split(`
243
+ `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as sd,readFileSync as id}from"node:fs";import{isAbsolute as ad,join as ld,resolve as cd}from"node:path";import{readProjectConfig as ud,DEFAULT_CAPTURE_DIR as dd}from"document360-engine";async function Yt(){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(`
244
+ `),display:"/capture-setup"}}var Zi="-".repeat(64);function xr(e){let t=dd;try{let k=ud(e);k?.captureDir&&(t=k.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=ad(t)?ld(t,"CAPTURE-TESTID-REQUESTS.json"):cd(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!sd(n))return null;let o;try{let k=JSON.parse(id(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.","",Zi,`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.",Zi]}Ke();W();import{listOpenForDocs as pd,readProjectConfig as fd}from"document360-engine";function $r(e){try{return pd(e).length}catch{return 0}}function vr(){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(`
245
+ `)}async function ea(e,t){let n=t?.cwd??process.cwd();return fd(n)?$r(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:vr(),display:"/inbox"}:(console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as md,listOpenForDocs as hd,readProjectConfig as gd}from"document360-engine";function $t(e){let t=0,n=0,o=0;try{t=md(e).length}catch{}try{let r=hd(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 Cr(e){return{publish:e.includes("--publish")}}function Pr({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(`
246
+ `)}async function ta(e,t){let n=t?.cwd??process.cwd();if(!gd(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Re(n,t?.profileName);if(!o.ok)return console.log(v(o.reason)),{kind:"continue"};let{publish:r}=Cr(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:Pr({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as wd}from"node:child_process";var Je="document360-writer",Fn=`npm i -g ${Je}@latest`;async function Hn(){let e=process.platform==="win32";return new Promise(t=>{try{let n=wd(`npm i -g ${Je}@latest`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});n.on("error",o=>t({ok:!1,output:String(o)})),n.on("close",o=>t({ok:o===0,output:""})),e||n.unref()}catch(n){t({ok:!1,output:String(n)})}})}async function na(){return console.log(f(`Updating ${Je}\u2026`)),(await Hn()).ok?console.log(E("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(v(`Update failed \u2014 run manually: ${Fn}`)),{kind:"continue"}}W();Ke();import{existsSync as Sr,rmSync as yd}from"node:fs";import{basename as oa,resolve as Tr}from"node:path";import{execFileSync as kd}from"node:child_process";import{input as bd}from"@inquirer/prompts";import{readProjectConfig as xd,devHintsGuidePath as $d}from"document360-engine";var vd=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Cd=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),qn=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),ra=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function sa(e){let t=qn(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:ra(t)?!0:Cd.has(t)}function Rr(e){let t=null;try{t=xd(e)}catch{t=null}let n=new Set(vd);for(let o of[qn(t?.docsDir),qn(t?.captureDir),qn(t?.outputDir)])o&&ra(o)&&n.add(o);return[...n].filter(o=>sa(o)&&Sr(Tr(e,o)))}function Dr(e,t){let n=[],o=[];for(let r of t){if(!sa(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{yd(Tr(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function ia(e,t){try{return kd("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
247
+ `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Pd(e){return ia(e,".d360-writer/hints")}function Sd(e){return ia(e,".d360-writer/messages")}function jr(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Pd(e),o=Sd(e),r=Sr(Tr(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: ${oa(e)}`]}async function aa(e,t){let n=Rr(t.cwd);for(let h of jr(t.cwd,n))console.log(n.length===0?f(h):h);if(n.length===0)return{kind:"continue"};let o=oa(t.cwd);if((await t.withPausedInput(()=>bd({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(U("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Sr($d(t.cwd)),{removed:c,failed:p}=Dr(t.cwd,n);console.log(E(`\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(v(` \u2717 ${h.path}: ${h.error}`));if(s){for(let h of Dn())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 la={help:To,"?":To,clear:Es,exit:Ro,quit:Ro,init:Ks,mcp:An,publish:ci,audit:Bt,scope:di,sync:yi,convert:ki,write:vi,draft:Ri,document:Di,resume:Ei,rename:Ii,profile:_i,model:Li,doctor:Vt,workspace:Gi,project:Vi,"allow-prod":Yi,login:zi,logout:Ki,screenshot:Wn,"capture-setup":Yt,devhints:Ms,inbox:ea,"catch-up":ta,update:na,reset:aa};function ca(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),o=(n[0]??"").toLowerCase();return o?{name:o,args:n.slice(1)}:null}Ke();W();var Td={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"},da=160,Er=200,pa=40;function fe(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function ua(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}: ${fe(typeof r=="string"?r:JSON.stringify(r),pa)}`);return t.length>4&&n.push("\u2026"),fe(n.join(", "),da)}var Le=e=>typeof e=="string"&&e?e:null,Ar=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Rd(e){let t=Le(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=Le(t.title);if(!o)return null;let r=Rd(t.local_path);return n("Create article",`"${fe(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Le(t.title),r=Ar(t.article_id);return n("Update article",o?`"${fe(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Ar(t.article_id)?`id ${Ar(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",Le(t.name)?`"${fe(Le(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Le(t.file_path);return n("Upload image",o?fe(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Bn(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:ua(t)}}let n=Td[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:fe(o,da)}:{title:e,sep:"",arg:ua(t)}}function jd(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 Ad(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(jd).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>fe(r,Er))]}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}: ${fe(String(r),pa)}`);return n.length>0?[fe(n.join(" \xB7 "),Er)]:null}return null}function Ed(e){let t=Le(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Id(e,t,n){switch(e){case"d360_create_article":{let o=Ed(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=Le(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 ${fe(o[0],120)}`:""}`]}default:return null}}function Gn(e,t=4,n,o){let r=e.replace(/\r\n/g,`
248
+ `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=Id(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let s=Ad(r)??r.split(`
249
+ `);return{lines:s.slice(0,t).map(c=>fe(c,Er)),hidden:Math.max(0,s.length-t)}}function Vn(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Yn(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 zn(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 Gd=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Vd(e,t,n,o){if(Gd.test(e))try{let r=ga(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=Yn(t,n),p=zn(n);e.endsWith("publish_article")&&p&&console.log(I(` \u2B95 Live: ${p}`)),c&&s&&console.log(I(` \u2B95 Preview: ${Vn(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function wa(e=process.cwd(),t="auto",n){let o=_d(t);o.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${I("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${I('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${I("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${I("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Yd(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=Ir({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=Nd({input:process.stdin,output:process.stdout}),h=[],b=null,k=!1;p.on("line",C=>{if(b){let P=b;b=null,P(C)}else h.push(C)}),p.on("close",()=>{if(k=!0,b){let C=b;b=null,C(null)}});function j(){return h.length>0?Promise.resolve(h.shift()):k?Promise.resolve(null):(process.stdout.write(I("> ")),new Promise(C=>{b=C}))}let y={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=Ir({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setModel:async C=>s.setModel(C),withPausedInput:async C=>{p.pause();try{return await C()}finally{p.resume()}}};try{for(;;){let C=await j();if(C===null)break;let P=C.trim();if(P){if(P.startsWith("/")){let N=ca(P);if(!N)continue;let O=la[N.name];if(!O){console.log(v(`Unknown command: /${N.name}`)),console.log(f("Type /help for the list."));continue}let q=await O(N.args,y);if(q.kind==="exit")break;if(q.kind==="clear"){y.restartAgent();continue}if(q.kind==="allow-prod"){r=!0,y.restartAgent(),console.log(E("\u2713 Production writes authorized for this session.")),console.log("");continue}if(q.kind==="resume"){s.close(),s=Ir({cwd:e,resume:q.uuid,profileName:n,allowProdWrites:r});let oe=Od(q.uuid);c={uuid:q.uuid,firstPrompt:oe?.firstPrompt??null,titleFired:!0},ha(q.uuid),console.log(E(`\u2713 Resumed "${q.name}"`)),console.log("");continue}q.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=q.display??q.prompt),await ma(s,q.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=P),await ma(s,P,o,c,e)}}}finally{s.close(),p.close()}}function Yd(e,t){console.log(""),console.log(It("document360-writer")),console.log(f(` cwd: ${e}`));let n=Fd(e);if(console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(zd(e,t)),!Hd(e))console.log(U(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{try{Tn(e);for(let o of Rn(e))console.log(U(` ${o}`))}catch{}try{let o=vt($t(e));o&&console.log(U(` \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 zd(e,t){try{let n=ga(e,t),o=n.production?U(" \u26A0 PRODUCTION"):"",r=Bd(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...fa(r.idToken)??{},...fa(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return qd(r)&&!r.refreshToken?U(` 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 Kd(){console.error(""),console.error(`Sign in with your Claude subscription: run ${I("claude")} once, then retry.`),console.error(` (No Claude Code? ${I("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${I("https://console.anthropic.com/settings/keys")}`)}function Xd(e,t,n){e.uuid=t;let o=new Date().toISOString();Md({uuid:t,name:Ld(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o})}function Jd(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Wd(o,t).then(r=>{r&&Ud(n,r)}).catch(()=>{})}async function ma(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))Qd(c,o,r,n,s)}function Qd(e,t,n,o,r){switch(e.type){case"session":t.uuid||Xd(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Bn(e.name,e.input);s&&(process.stdout.write(`
250
+
251
+ `),console.log(`${E("\u25CF")} ${xe(s.title)}${s.arg!==null?ne(`${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(ne(` \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=Gn(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?v:ne;c.lines.forEach((h,b)=>console.log(p((b===0?" \u23BF ":" ")+h))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||Vd(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
252
+ `),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&&(ha(t.uuid),t.titleFired||Jd(t,n));break;case"error":console.error(""),console.error(v(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Kd();break}}import{render as rf}from"ink";import{resolveAuth as sf}from"document360-engine";import{useCallback as Y,useEffect as ve,useMemo as Mr,useRef as J,useState as F}from"react";import{Box as ee,Text as T,useApp as dp,useInput as pp,useStdout as fp}from"ink";import{existsSync as Xt,readFileSync as Wr,readdirSync as Ya}from"node:fs";import{spawnSync as mp}from"node:child_process";import{basename as Jt,isAbsolute as hp,join as Qt}from"node:path";import{createSession as Ua,classifyClaudeAuth as za,CLAUDE_CODE_SETUP_HINT as gp,loginPkce as wp,toStoredTokens as yp,saveTokens as kp,getAccessToken as bp,resolveActiveProfile as ue,resolveProjectId as xp,getArticle as $p,decodeJwtClaims as Ct,isExpired as je,loadTokens as Me,clearTokens as vp,clearProfileProject as Cp,setTitle as Pp,slugify as Sp,touchSession as Fr,upsertSession as Tp,generateTitle as La,findByName as Rp,listSessions as Dp,renameSession as jp,suggestNextAction as Ap,readProjectConfig as Z,writeProjectConfig as Ma,resolveModelSetting as Vr,loadProfileMap as Hr,applyPull as Ep,computeSyncStatus as qr,planPull as Ip,establishBaselines as Np,inventoryRepo as _p,knownEnvironments as Op,resolveEnvironment as Up,planPartitions as Br,partitionEvenly as Lp,screenshotPlaceholderIds as Mp,trackedArticlePaths as Wp,runPartitioned as eo,estimateBulkCost as Wa,resolveModelForOperation as to,readDocsPlan as Fp,checkForUpdate as Hp,detectInstallKind as qp,isSelfUpdatable as Bp,devHintsGuidePath as Fa,toolFeedbackPath as Gp,reconcileToolFeedback as Vp,DEFAULT_DOCS_DIR as Ka,setProfileProject as Yp}from"document360-engine";Ke();import{spawn as ya}from"node:child_process";function Zd(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function ep(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?ya([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):ya(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",c=>o(c===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function ka(e){for(let[t,n]of Zd())if(await ep(t,n,e))return!0;return!1}var tp=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Nr(e,t){if(t.closed)return e;let n=e.split(`
253
+ `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){tp.test(s)&&(t.cueSeen=!0);continue}let c=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);c?(n[r]=`${c[1]}${++t.num}. ${c[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
254
+ `)}import{existsSync as np,mkdirSync as op,readFileSync as rp,writeFileSync as sp}from"node:fs";import{join as ba}from"node:path";import{writerDir as ip}from"document360-engine";function xa(e){return ba(ip(e),".sessions")}function $a(e,t){return ba(xa(e),`${t}.json`)}function va(e,t,n){try{op(xa(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");sp($a(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function _r(e,t){try{let n=$a(e,t);if(!np(n))return[];let o=JSON.parse(rp(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var ap=e=>`\x1B]0;${e}\x07`,lp=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Ca(e){process.stdout.isTTY&&process.stdout.write(e)}function zt(e){Ca(ap(e))}function Kn(e){Ca(lp(e))}var Xn=["\xB7 "," \xB7"],Or="\u{1F7E3}";Mn();var cp=/^(?:\d+[.)]|[-*•])\s+/;function Pa(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
255
+ `)){let c=s.trim().replace(cp,""),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}W();function Kt(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function De(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Ur(e){return e.replace(/^[\w.-]+\//,"")}var Jn=16,Sa={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Lr(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Ta(e,t){let n=Lr(t);return e.some(r=>r.trim()===t.trim()||!!n&&Lr(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&Lr(r)===n)):[]}var up=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Ra(e){return e.replace(/\r\n?/g,`
256
+ `)}function Da(e){return e.includes(`
257
+ `)||e.length>200}function ja(e,t){let n=t.split(`
258
+ `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Aa(e,t){return e.replace(up,n=>t.get(n)??n)}function Ea(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Qn(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
259
+ `)){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 Ia(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 Na(e,t,n){let o=e[Zn(e,t)];return n==="start"?o.start:o.end}function _a(e,t,n){let o=Math.max(1,n),r=e.split(`
260
260
  `),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(`
261
- `),truncated:c>0||h>0}}}return{text:e,truncated:!1}}function _a(e){let t=!1,n=0,o=0;for(let r of e.split(`
262
- `)){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 qr,jsx as D,jsxs as H}from"react/jsx-runtime";var Vp={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},Fa=` 1. /init \u2014 pick your Document360 environment & scaffold config
261
+ `),truncated:c>0||h>0}}}return{text:e,truncated:!1}}function Oa(e){let t=!1,n=0,o=0;for(let r of e.split(`
262
+ `)){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 Gr,jsx as D,jsxs as H}from"react/jsx-runtime";var zp={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},Ha=` 1. /init \u2014 pick your Document360 environment & scaffold config
263
263
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
264
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Yp(e,t,n,o){let r=Ya(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=Br(e),p=Z(e),h=(p?.docsDir??za).replace(/\/+$/,""),b=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${h}/ + config`,y={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:Vp[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 y;try{let j=ue(e,o);y.profile=j.name,y.apiUrl=j.connection.apiUrl,y.prod=j.production,y.project=j.project.projectName??j.project.projectId??"(chosen at login)";let k=Me(j.name);if(k){let C={...Ct(k.idToken)??{},...Ct(k.accessToken)??{}},P=C.email??C.preferred_username??"signed in";De(k)?k.refreshToken&&(y.who=P,y.loggedOut=!1,y.sessionHint="session expired \u2014 refreshing\u2026"):(y.who=P,y.loggedOut=!1,y.sessionHint=`session valid until ${new Date(k.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return y}function zp(e,t){try{let n=ue(e,t),o=Me(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 De(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 Ha=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],to=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Kp="Ask me to write or update an article\u2026";function eo({ch:e,dim:t}){let[n,o]=F(!0);return ve(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),D(T,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Xp=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function qa(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Jp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ba(e){try{return Va(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Ga(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Ba(Xt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Ba(Xt(e,o)))}function Qp({startTime:e,chars:t}){let[n,o]=F(0);ve(()=>{let h=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(h)},[]);let r=to[n%to.length],s=Ha[Math.floor(n/16)%Ha.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return H(ee,{children:[D(T,{color:V,children:` ${r} ${s}\u2026 `}),D(T,{color:"gray",children:`(${Mt(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var Zp=12e4;function ef({p:e}){let[t,n]=F(0);ve(()=>{let O=setInterval(()=>n(q=>q+1),150);return()=>clearInterval(O)},[]);let o=to[t%to.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>=Zp,h=e.verb??"Converting",b=e.unit??"article",y=e.rows.reduce((O,q)=>O+q.items,0),j=h.toLowerCase(),k=e.rows,C=0;if(k.length>Kn){let O=k.findIndex(ne=>ne.status==="active"||ne.status==="pending"),q=Math.max(0,Math.min(O-2,k.length-Kn));C=k.slice(0,q).filter(ne=>ne.status==="done").length,k=k.slice(q,q+Kn)}let P=Math.min(40,Math.max(...k.map(O=>_r(O.label).length),0)),N=O=>O==="failed"?"red":O==="active"?V:void 0;return H(ee,{flexDirection:"column",children:[H(ee,{children:[D(T,{color:V,children:` ${o} ${h} ${y} ${b}${y===1?"":"s"} `}),D(T,{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`})]}),C>0&&D(T,{dimColor:!0,children:` \u2714 +${C} done`}),k.map(O=>H(T,{color:N(O.status),dimColor:O.status==="done"||O.status==="pending",children:[` ${Pa[O.status]} ${_r(O.label).padEnd(P)}`,O.status!=="pending"?` (${O.items} ${b}${O.items===1?"":"s"})`:"",O.status==="active"?` \u2190 ${j}\u2026`:""]},O.label)),p&&D(T,{color:"yellow",children:` \u26A0 no activity for ${Mt(s)} \u2014 press esc to stop if it's wedged`})]})}var tf=10800*1e3;function Ka({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=cp(),[s,c]=F(n),[p,h]=F(null),[b,y]=F({text:"",pos:0}),j=b.text,k=Y(l=>{y(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),C=Y(l=>{y(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),P=Y(()=>{y(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=Aa(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[N,O]=F(!1),[q,ne]=F(!1),[Ce,re]=F(0),[ke,se]=F(null),[Pt,B]=F([]),Qe=J(0),[Za,Jt]=F(!1),[el,Qt]=F(!1),[tl,Ze]=F(0),We=J(0),[St,et]=F(0),[tt,Zt]=F(null),Yr=J(new Map),nl=J(0),nt=J([]),me=J(null);me.current===null&&(me.current=Oa({cwd:e,profileName:s,allowProdWrites:!1}));let Pe=J({uuid:null,firstPrompt:null,titleFired:!1}),en=J(new Map),ot=J(!1),no=J([]),Ae=J([]),oo=J(null),[zr,rt]=F(null),[Fe,He]=F(null),[Se,st]=F(null),[Ee,it]=F(null),[ae,at]=F(null),[he,lt]=F(null),[qe,ct]=F(null),[Kr,tn]=F(null),[ge,Be]=F(null),[de,ut]=F(null),[Xr,ro]=F([]),Ge=J([]),Tt=J(!1),we=J(null),[Jr,Q]=F(null),nn=J(!1),on=J(null),Rt=J(null),[ye,Ve]=F(null),[Qr,dt]=F(0),[Zr,pt]=F(0),[ol,es]=F(0),so=Ur(()=>{try{return Br(e).model??"auto"}catch{return null}},[e,ol]),{stdout:be}=dp(),[,rl]=F(0),ts=J(`${be.columns??80}x${be.rows??24}`),Ie=Y(()=>Math.max(20,(be.columns??80)-1),[be]),u=Y(l=>{nt.current.push(l),console.log(Uo(l,Ie()))},[Ie]),[io,ao]=F(null),ft=Y(l=>{ao(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]),lo=J(!1),co=Y(async()=>{try{if(lo.current||!Hp(Fp())||Z(e)?.mode==="engineer")return;let l=await Wp({pkg:Je,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;lo.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${Je} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),Qt(!0),(await Wn().finally(()=>Qt(!1))).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),B(a=>a.includes("/exit")?a:[...a,"/exit"])):u({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${Mn}`})}catch{}},[e,o,u]),uo=Y(l=>{let i=Te(e,s);return i.ok?!0:(u({kind:"note",tone:"warn",text:i.reason}),Rt.current=l,B(["/login"]),!1)},[e,s,u]),[po,fo]=F(null),Dt=J(!0),rn=J(0);ve(()=>{let l=setInterval(()=>{if(N||Dt.current){rn.current=0;return}try{if(!zt(Wa(e)))return;if(_e(e).status==="current"){Dt.current=!0,rn.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."}),ao(null),se("write the docs for this repo");return}rn.current+=1;let i=rn.current;(i===1||i%7===0)&&u({kind:"note",tone:"info",text:Ms(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]),ve(()=>{let l=`d360-writer \xB7 ${zr??Kt(e)}`;if(!N){Yn(0),Vt(`${Nr} ${l}`);return}Yn(3);let i=0;Vt(`${zn[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%zn.length,Vt(`${zn[i]} ${l}`)},400);return()=>clearInterval(a)},[N,e,zr]),ve(()=>()=>Yn(0),[]),ve(()=>{u({kind:"banner",info:Yp(e,o,t,s)});let l=Ya(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.
265
- ${mp}
264
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Kp(e,t,n,o){let r=za(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=Vr(e),p=Z(e),h=(p?.docsDir??Ka).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:zp[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 j=ue(e,o);k.profile=j.name,k.apiUrl=j.connection.apiUrl,k.prod=j.production,k.project=j.project.projectName??j.project.projectId??"(chosen at login)";let y=Me(j.name);if(y){let C={...Ct(y.idToken)??{},...Ct(y.accessToken)??{}},P=C.email??C.preferred_username??"signed in";je(y)?y.refreshToken&&(k.who=P,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=P,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(y.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function Xp(e,t){try{let n=ue(e,t),o=Me(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 je(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 qa=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],oo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Jp="Ask me to write or update an article\u2026";function no({ch:e,dim:t}){let[n,o]=F(!0);return ve(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),D(T,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Qp=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Ba(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Zp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ga(e){try{return Ya(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Va(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Ga(Qt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Ga(Qt(e,o)))}function ef({startTime:e,chars:t}){let[n,o]=F(0);ve(()=>{let h=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(h)},[]);let r=oo[n%oo.length],s=qa[Math.floor(n/16)%qa.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return H(ee,{children:[D(T,{color:V,children:` ${r} ${s}\u2026 `}),D(T,{color:"gray",children:`(${Ft(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var tf=12e4;function nf({p:e}){let[t,n]=F(0);ve(()=>{let O=setInterval(()=>n(q=>q+1),150);return()=>clearInterval(O)},[]);let o=oo[t%oo.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>=tf,h=e.verb??"Converting",b=e.unit??"article",k=e.rows.reduce((O,q)=>O+q.items,0),j=h.toLowerCase(),y=e.rows,C=0;if(y.length>Jn){let O=y.findIndex(oe=>oe.status==="active"||oe.status==="pending"),q=Math.max(0,Math.min(O-2,y.length-Jn));C=y.slice(0,q).filter(oe=>oe.status==="done").length,y=y.slice(q,q+Jn)}let P=Math.min(40,Math.max(...y.map(O=>Ur(O.label).length),0)),N=O=>O==="failed"?"red":O==="active"?V:void 0;return H(ee,{flexDirection:"column",children:[H(ee,{children:[D(T,{color:V,children:` ${o} ${h} ${k} ${b}${k===1?"":"s"} `}),D(T,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${Ft(r)} \xB7 esc to stop`})]}),C>0&&D(T,{dimColor:!0,children:` \u2714 +${C} done`}),y.map(O=>H(T,{color:N(O.status),dimColor:O.status==="done"||O.status==="pending",children:[` ${Sa[O.status]} ${Ur(O.label).padEnd(P)}`,O.status!=="pending"?` (${O.items} ${b}${O.items===1?"":"s"})`:"",O.status==="active"?` \u2190 ${j}\u2026`:""]},O.label)),p&&D(T,{color:"yellow",children:` \u26A0 no activity for ${Ft(s)} \u2014 press esc to stop if it's wedged`})]})}var of=10800*1e3;function Xa({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=dp(),[s,c]=F(n),[p,h]=F(null),[b,k]=F({text:"",pos:0}),j=b.text,y=Y(l=>{k(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),C=Y(l=>{k(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),P=Y(()=>{k(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=Ea(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[N,O]=F(!1),[q,oe]=F(!1),[Ce,re]=F(0),[ke,se]=F(null),[Pt,B]=F([]),Qe=J(0),[el,Zt]=F(!1),[tl,en]=F(!1),[nl,Ze]=F(0),We=J(0),[St,et]=F(0),[tt,tn]=F(null),Kr=J(new Map),ol=J(0),nt=J([]),me=J(null);me.current===null&&(me.current=Ua({cwd:e,profileName:s,allowProdWrites:!1}));let Pe=J({uuid:null,firstPrompt:null,titleFired:!1}),nn=J(new Map),ot=J(!1),ro=J([]),Ee=J([]),so=J(null),[Xr,rt]=F(null),[Fe,He]=F(null),[Se,st]=F(null),[Ie,it]=F(null),[ae,at]=F(null),[he,lt]=F(null),[qe,ct]=F(null),[Jr,on]=F(null),[ge,Be]=F(null),[de,ut]=F(null),[Qr,io]=F([]),Ge=J([]),Tt=J(!1),we=J(null),[Zr,Q]=F(null),rn=J(!1),sn=J(null),Rt=J(null),[ye,Ve]=F(null),[es,dt]=F(0),[ts,pt]=F(0),[rl,ns]=F(0),ao=Mr(()=>{try{return Vr(e).model??"auto"}catch{return null}},[e,rl]),{stdout:be}=fp(),[,sl]=F(0),os=J(`${be.columns??80}x${be.rows??24}`),Ne=Y(()=>Math.max(20,(be.columns??80)-1),[be]),u=Y(l=>{nt.current.push(l),console.log(Mo(l,Ne()))},[Ne]),[lo,co]=F(null),ft=Y(l=>{co(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]),uo=J(!1),po=Y(async()=>{try{if(uo.current||!Bp(qp())||Z(e)?.mode==="engineer")return;let l=await Hp({pkg:Je,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;uo.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${Je} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),en(!0),(await Hn().finally(()=>en(!1))).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),B(a=>a.includes("/exit")?a:[...a,"/exit"])):u({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${Fn}`})}catch{}},[e,o,u]),fo=Y(l=>{let i=Re(e,s);return i.ok?!0:(u({kind:"note",tone:"warn",text:i.reason}),Rt.current=l,B(["/login"]),!1)},[e,s,u]),[mo,ho]=F(null),Dt=J(!0),an=J(0),jt=J(0);ve(()=>{let l=setInterval(()=>{if(Dt.current){an.current=0,jt.current=0;return}if(!N)try{if(!Xt(Fa(e)))return;if(Te(e).status==="current"){Dt.current=!0,an.current=0,jt.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."}),co(null),se("write the docs for this repo");return}an.current+=1;let i=an.current;if((i===4||i%15===0)&&jt.current<3){jt.current+=1;let a=jt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";u({kind:"note",tone:"info",text:Lt(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${a}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${a}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,N,u]),ve(()=>{let l=`d360-writer \xB7 ${Xr??Jt(e)}`;if(!N){Kn(0),zt(`${Or} ${l}`);return}Kn(3);let i=0;zt(`${Xn[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%Xn.length,zt(`${Xn[i]} ${l}`)},400);return()=>clearInterval(a)},[N,e,Xr]),ve(()=>()=>Kn(0),[]),ve(()=>{u({kind:"banner",info:Kp(e,o,t,s)});let l=za(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.
265
+ ${gp}
266
266
  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:
267
- ${Fa}`}),B(l?["/doctor","/init"]:["/init"]);return}l&&B(["/doctor"]);try{let i=ue(e,s),a=Me(i.name);a&&De(a)&&a.refreshToken?yp({profile:i.name,connection:i.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),re(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||De(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=ue(e,s),g=Me(a.name);i&&g&&!De(g)&&Ga(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{Pn(e);let i=Sn(e);i.length&&(u({kind:"note",tone:"warn",text:i.join(`
268
- `)}),ft(ze()),Dt.current=!1)}catch{}try{let i=Bp(e);i.archived>0&&u({kind:"note",tone:"ok",text:`\u2713 Tidied ${i.archived} resolved item${i.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${i.open>0?`; ${i.open} still open`:""}.`})}catch{}try{let i=Z(e),a=ue(e,s),g=Me(a.name),d=!!g&&(!De(g)||!!g.refreshToken),m=!i||!Ga(e,i.authoritativeSourceFiles);if(i&&d&&m&&!l){let w=Wr(e,a.name),$=w?Object.keys(w.articles).length:0,S=vt($t(e));if($>0){let R=0;if(w?.lastAnalyzedCommit)try{let K=pp("git",["rev-list","--count",`${w.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:3e3});K.status===0&&(R=parseInt((K.stdout||"").trim(),10)||0)}catch{}if(!S&&R>0&&i.autoAudit)u({kind:"note",tone:"info",text:`\u{1F4CB} ${R} code change${R===1?"":"s"} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}),Ht().then(K=>{K.kind==="forward-to-agent"&&K.prompt&&ie(K.prompt,{display:K.display,quietUser:!0})});else{let K=S?["/catch-up","/audit"]:["/audit","/sync"],X={"/catch-up":"write up everything your builder flagged","/audit":S?"also scan the code for other changes":"check the code for anything new or missing in the docs","/sync":"check Document360 for changes made there"},_=S?`\u{1F4CB} Your builder left ${S} for the docs:`:R>0?`\u{1F4CB} ${R} code change${R===1?"":"s"} since your last docs check \u2014 /audit to see what needs updating (or /audit --auto on to run it for you):`:`\u{1F4DA} ${$} article${$===1?"":"s"} tracked for "${a.name}". What next?`;u({kind:"note",tone:"info",text:[_,...K.map((x,A)=>` ${A+1} ${x.padEnd(9)} ${X[x]}`),"Or just tell me what to write or update."].join(`
269
- `)}),B(K)}}else u({kind:"note",tone:"info",text:'\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.'}),se("write the docs for this repo"),B(S?["/catch-up","/audit"]:["/audit"])}}catch{}co()},[]),ve(()=>{let l=setInterval(()=>{co()},tf);return()=>clearInterval(l)},[co]),ve(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${be.columns??80}x${be.rows??24}`;g!==ts.current&&(ts.current=g,rl(d=>d+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+ri(nt.current,Ie())+"\x1B[?2026l")},80))},400)};return be.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),be.off("resize",a)}},[be,Ie]);let Ye=Math.max(20,(be.columns??80)-1),ns=Ur(()=>zp(e,s),[e,s,Ce]),mo=(()=>{if(el)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};let l=Z(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=Xt(e,(l.docsDir??za).replace(/\/+$/,"")),a=(()=>{try{return zt(i)&&Va(i).length>0}catch{return!1}})();try{let g=ue(e,s),d=Me(g.name);if(!(!!d&&!(De(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:Kp,isSetup:!1}:io?{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=Rs(j),os=jt.length>0&&!N,ho=p!==null?Na(p,8,Ye):null,sn=ge?ge.paths.filter(l=>!ge.query||l.toLowerCase().includes(ge.query.toLowerCase())).slice(0,8):[],an=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):[],pe=Y((l,i)=>{me.current?.close(),me.current=Oa({cwd:e,resume:l,profileName:i??s,allowProdWrites:ot.current}),l||(Pe.current={uuid:null,firstPrompt:null,titleFired:!1},rt(null)),dt(0),pt(0)},[e,s]),rs=Y((l,i,a)=>{if(Xp.test(l))try{let g=ue(e,s),d=typeof i.project_id=="string"&&i.project_id||g.project.projectId,m=Gn(i,a),w=[],$=Vn(a);l.endsWith("publish_article")&&$&&w.push(`Live: ${$}`),m&&d&&w.push(`Preview: ${Bn(g.connection.portalUrl,d,m,g.project.languageCode??"en")}`),w.length>0&&u({kind:"link",lines:w})}catch{}},[e,s,u]),ie=Y(async(l,i)=>{Jt(!0),se(null),B([]),tn(null),ao(null),fo(null);let a=++Qe.current;i?.quietUser||u({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let g=Pe.current;g.firstPrompt||(g.firstPrompt=i?.display??l),We.current=Date.now(),Ze(0),O(!0),en.current.clear();let d="",m=!1,w=!1,$="",S={num:0,closed:!1,cueSeen:!1},R=null,K=()=>{R||(R=setTimeout(()=>{R=null,h($.length>0?$:null)},60))},X=()=>{R&&clearTimeout(R),R=null,h(null)},_=()=>{if($.trim()){let x=Er($.trimEnd(),S);u({kind:"assistant",text:x})}$="",X()};try{for await(let x of me.current.send(l))if(x.type==="session"){if(!g.uuid){g.uuid=x.sessionId;let A=new Date().toISOString(),M=Cp(g.firstPrompt??"session");Pp({uuid:x.sessionId,name:M,renamed:!1,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:A,updatedAt:A}),rt(M)}}else if(x.type==="text"){$+=x.delta,d+=x.delta;let A=_a($);if(A>0){let M=$.slice(0,A).trimEnd();M&&u({kind:"assistant",text:Er(M,S)}),$=$.slice(A)}K(),Ze(M=>M+x.delta.length)}else if(x.type==="tool"){m=!0;let A=Hn(x.name,x.input);A&&(_(),u({kind:"tool",title:A.title,sep:A.sep,arg:A.arg}),en.current.set(x.id,{name:x.name,input:x.input}))}else if(x.type==="article_diff"){let A=Xe(x.oldContent,x.newContent,Ie());A&&(_(),u({kind:"diff",added:A.added,removed:A.removed,lines:A.lines,hidden:A.hidden}))}else if(x.type==="tool_result"){x.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(x.output)&&(nn.current=!0);let A=en.current.get(x.id);if(A){en.current.delete(x.id),_();let M=qn(x.output,4,x.isError?void 0:A.name,A.input);u({kind:"tool-result",lines:M.lines,hidden:M.hidden,isError:x.isError}),x.isError||rs(A.name,A.input,x.output)}}else if(x.type==="result"){if(_(),dt(M=>M+x.outputTokens),pt(M=>M+x.costUsd),u({kind:"done",seconds:Math.round((Date.now()-We.current)/1e3),tokens:x.outputTokens,costUsd:x.costUsd,ok:x.ok}),!w&&!m&&!d.trim()&&!Tt.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)."}),x.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(d))try{let M=qp(e);if(zt(M)){let L=Lr(M,"utf8").trim();L&&(fo(L),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 A=x.ok?Ca(d,_t.map(M=>M.name)):[];if(A.length>0?B(A):x.ok&&d.trim()&&Dp(l,d,e).then(M=>{M&&Qe.current===a&&se(M)}).catch(()=>{}),g.uuid&&(Mr(g.uuid),!g.titleFired)){g.titleFired=!0;let M=g.uuid,L=g.firstPrompt;L&&Ua(L,e).then(G=>{G&&(vp(M,G),rt(G))}).catch(()=>{})}}else x.type==="error"&&(_(),w=!0,x.kind==="auth"&&(nn.current=!0),u({kind:"note",text:`agent error: ${x.message}`,tone:"error"}))}finally{O(!1),X(),re(x=>x+1),Pe.current.uuid&&$a(e,Pe.current.uuid,nt.current),nn.current&&(nn.current=!1,on.current=i?.display??l,B(["/login"])),Tt.current&&(Tt.current=!1,Ge.current.length>0&&(u({kind:"note",tone:"info",text:`(${Ge.current.length} queued message(s) discarded)`}),Ge.current=[],ro([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,rs,Ie]),ln=Y(async l=>{let i=Hr(l),a=Zn(e,"standard");We.current=Date.now(),Ze(0),O(!0);let g=new AbortController;we.current=g,Q({verb:"Publishing",total:i.length,done:0,active:[],rows:Yt(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 Qn({cwd:e,partitions:i,promptFor:m=>An(m.paths),concurrency:Wt,profileName:s,allowProdWrites:ot.current,model:a.model,signal:g.signal}))if(d.type==="partition_status")d.status==="running"?Q(m=>m&&{...m,active:[...m.active,d.label],rows:Re(m.rows,d.label,"active"),lastAt:Date.now()}):Q(m=>m&&{...m,active:m.active.filter(w=>w!==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")Q(m=>{if(!m)return m;let w={...m,lastAt:Date.now()};return d.event.type==="tool"?w.tools=m.tools+1:d.event.type==="text"&&(w.chars=m.chars+d.event.delta.length),w});else if(d.type==="run_done"){pt(S=>S+d.totalCostUsd),dt(S=>S+d.results.reduce((R,K)=>R+K.outputTokens,0));let m=d.aborted?"Stopped. ":"",w=t.kind==="api"?"api":"subscription";u({kind:"note",tone:d.aborted?"warn":d.ok?"ok":"warn",text:m+Ho(d.results,i,w).join(`
270
- `)});let $=Fo(e,s);$&&u({kind:"note",tone:"info",text:$})}}catch(d){u({kind:"note",tone:"error",text:`Publish run failed: ${d.message}`})}finally{we.current=null,Q(null),O(!1),re(d=>d+1)}},[e,s,u,t]),go=Y(async l=>{await ie(Wo(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await En(e,s,l.replace(/\\/g,"/"));i.length>0&&(tn(`Related articles not yet published (${i.length}):`),B([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ie]),wo=Y(l=>{let i=Me(l);if(!i||De(i)&&!i.refreshToken)return null;let a={...Ct(i.idToken)??{},...Ct(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),yo=Y((l,i)=>{if(i){let a=Z(e);a&&(a.defaultProfile=l,La(a,e))}c(l),pe(void 0,l),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),wo(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"])),re(a=>a+1)},[e,u,pe,wo]),cn=Y((l,i,a)=>{mn(e,l,i,a.id,a.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),pe(),Wr(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(`
271
- `)}),ft(ze()),Dt.current=_e(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,pe,ft]),un=Y(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)":""}.`}),cn(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,cn]),ss=Y((l,i)=>{vo(e,l,i.id,i.name),u({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),pe(),un(l)},[e,u,pe,un]),is=Y(async l=>{let i;try{i=ue(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&&Gp(e,i.name,{projectName:g.name})}catch{}await un(i.name);return}u({kind:"note",tone:"info",text:"Next: pick the Document360 project."}),B(["/project"])}},[e,u,un]),dn=Y(()=>{let l=Ae.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,Ie());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,Ie]),as=Y(l=>{if(Ae.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Ae.current.shift();try{jp({cwd:e,profileName:s},a),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Ae.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=Ae.current.shift();u({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Ae.current.length;return Ae.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return dn(),!0},[e,s,dn,u]),ls=Y(l=>{let i=oo.current;if(!i)return!1;if(oo.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}=Tr(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:Tn().join(`
272
- `)}),ft(Do())),u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
273
- ${Fa}`}),B(["/init"]),Jt(!1),!0},[e,u,ft]),cs=Y(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),g=i.slice(1);switch(Jt(!0),a){case"help":u({kind:"note",tone:"info",text:xn().join(`
274
- `)});return;case"exit":case"quit":me.current?.close(),r();return;case"clear":pe(),nt.current=[],Jt(!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=ue(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":""}`}),ne(!0);try{let m=await hp(d.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},$=>u({kind:"note",tone:"info",text:$})),w=gp(d.name,m);if(wp(w),await Co(w,d.name,$=>u({kind:"note",tone:"info",text:$})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${d.name}" as ${gn(w)}`}),await is(s),Rt.current){let $=Rt.current;Rt.current=null;let S=Te(e,s);S.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${$}.`}),B([$])):(u({kind:"note",tone:"warn",text:`${S.reason} (then ${$}.)`}),B(["/login"]),Rt.current=$)}else on.current&&(se(on.current),on.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{ne(!1),re(m=>m+1)}return}case"allow-prod":{let d=!1;try{d=ue(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,pe(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let d=pr(g.join(" ")),m=Pe.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 w=Pe.current.firstPrompt??"";Ua(w,e).then($=>{$?(se(`/rename ${$}`),u({kind:"note",tone:"info",text:`Suggestion: "${$}" \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}Rp(m,d),rt(d),Vt(`${Nr} 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 w=Object.entries(m?.profiles??{});if(w.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let $=w.map(([K,X])=>({name:K,env:X.connection?.environment??"custom",prod:X.production===!0,who:wo(K)})),S=s??m?.defaultProfile,R=Math.max(0,$.findIndex(K=>K.name===S));st({cursor:R,current:R,rows:$});return}if(d==="add"){let w=fr(e,g[1],g[2]);if(w){u({kind:"note",tone:"error",text:w});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),yo(g[1],!1);return}if(!m?.profiles?.[d]){u({kind:"note",tone:"error",text:`Unknown profile "${d}". Create it: /profile add ${d} <environment>`});return}yo(d,!0);return}case"doctor":await Bt(g,{cwd:e});return;case"mcp":await Dn(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=Np().map(m=>({name:m,apiUrl:_p(m).apiUrl}));it({cursor:0,rows:d});return}case"resume":{let d=g.join(" ").trim(),m=Tp(e).filter(S=>S.uuid!==Pe.current.uuid);if(!d){if(!m.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Ve({query:"",cursor:0,sessions:m});return}let w=Sp(e,d);if(!w){u({kind:"note",tone:"error",text:`No session matches "${d}".`});return}pe(w.uuid),Pe.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},rt(w.name),Mr(w.uuid),nt.current=[];let $=Ir(e,w.uuid);for(let S of $)u(S);u({kind:"note",tone:"ok",text:$.length?`Resumed "${w.name}" \u2014 restored ${$.length} message(s); continue where you left off.`:`Resumed "${w.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($){u({kind:"note",tone:"error",text:`Could not list workspaces: ${$.message}`});return}if(!d){let $=m.workspaces.map(R=>({id:R.id,name:R.name??R.id,type:R.workspace_type}));if($.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let S=Math.max(0,$.findIndex(R=>R.id===m.current));at({cursor:S,current:S,rows:$,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let w=$o(m.workspaces,d);if(!w){u({kind:"note",tone:"error",text:`No workspace matches "${d}".`});return}cn(m.profile,m.projectId,w);return}case"project":{let d=g.join(" ").trim(),m;try{m=await gt(e,s)}catch($){u({kind:"note",tone:"error",text:`Could not list projects: ${$.message} (signed in? try /login)`});return}if(!d){let $=m.projects.map(R=>({id:R.id,name:R.name??R.id,sub:R.sub_domain}));if($.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let S=$.findIndex(R=>R.id===m.current);lt({cursor:Math.max(0,S),current:S,rows:$,profile:m.profile,environment:m.environment});return}let w=ws(m.projects,d);if(!w){u({kind:"note",tone:"error",text:`No project matches "${d}". Available: ${m.projects.map($=>$.name??$.id).join(", ")}`});return}ss(m.profile,w);return}case"logout":{let d;try{d=ue(e,s).name}catch(w){u({kind:"note",tone:"error",text:w.message});return}let m=xp(d);$p(e,d),pe(),re(w=>w+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(!uo(l.trim()))return;if(g[0]==="--related"&&g[1]){let m=await En(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 ln(m);return}if(g[0]&&g[0]!=="--all"){await go(g[0]);return}let d=g[0]==="--all";u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Fr({cwd:e,profileName:s}),w=Ft(m.entries),$=jn(m.entries);if($>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${$} article${$===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),w.length===0){u({kind:"note",tone:"ok",text:$>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let S=m.counts["unknown-base"]??0;S>0&&u({kind:"note",tone:"info",text:`(${S} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(d){await ln(w.map(S=>S.path));return}ct({cursor:0,rows:ai(w)})}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 w=[];try{w=Object.keys(Wr(e,ue(e,s).name)?.articles??{})}catch{}if(w.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Be({query:"",cursor:0,paths:w});return}let m=fp(d)?d:Xt(e,d);if(zt(m)){try{u({kind:"preview",name:Kt(m),text:qa(Lr(m,"utf8"))})}catch(w){u({kind:"note",tone:"error",text:`Could not read ${m}: ${w.message}`})}return}if(Jp.test(d)){try{let w=ue(e,s),$={profile:w.name,connection:w.connection},S=w.project.projectId??kp($),R=await bp($,S,d);u({kind:"preview",name:R.title??d,text:R.content??"*(article has no content)*"})}catch(w){u({kind:"note",tone:"error",text:`Could not fetch article: ${w.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 S=On(Br(e));He({cursor:S,current:S});return}let{lines:m,changed:w,effective:$}=qt(e,d);for(let S of m)u({kind:"note",tone:S.startsWith("\u26A0")?"warn":S.startsWith("\u2713")?"ok":"info",text:S});w&&(es(S=>S+1),me.current?.setModel($));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}=Vo(g),w=Lp(e,s);if(w.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let $=Yo(w,d);if($.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${d}". (${w.length} are tracked overall.)`});return}let S=Hr($),R=3,K=`/convert${d?` --scope ${d}`:""} --run`,X=Zn(e,"light");if(!m){let x=Ma({files:zo(e,$),op:"convert",model:X.model}),A=d?`Scope: ${d} (${$.length} of ${w.length} tracked)
267
+ ${Ha}`}),B(l?["/doctor","/init"]:["/init"]);return}l&&B(["/doctor"]);try{let i=ue(e,s),a=Me(i.name);a&&je(a)&&a.refreshToken?bp({profile:i.name,connection:i.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),re(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||je(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=ue(e,s),g=Me(a.name);i&&g&&!je(g)&&Va(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{if(Tn(e),Te(e).status!=="current")if(Lt(e))u({kind:"note",tone:"info",text:`\u{1F514} A newer dev\u2194docs protocol (v${te}) is available \u2014 your builder can re-run /devhints when convenient. Your docs aren't blocked.`});else{let i=Rn(e);i.length&&(u({kind:"note",tone:"warn",text:i.join(`
268
+ `)}),ft(ze()),Dt.current=!1)}}catch{}try{let i=Vp(e);i.archived>0&&u({kind:"note",tone:"ok",text:`\u2713 Tidied ${i.archived} resolved item${i.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${i.open>0?`; ${i.open} still open`:""}.`})}catch{}try{let i=Z(e),a=ue(e,s),g=Me(a.name),d=!!g&&(!je(g)||!!g.refreshToken),m=!i||!Va(e,i.authoritativeSourceFiles);if(i&&d&&m&&!l){let w=Hr(e,a.name),$=w?Object.keys(w.articles).length:0,S=vt($t(e));if($>0){let R=0;if(w?.lastAnalyzedCommit)try{let K=mp("git",["rev-list","--count",`${w.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:3e3});K.status===0&&(R=parseInt((K.stdout||"").trim(),10)||0)}catch{}if(!S&&R>0&&i.autoAudit)u({kind:"note",tone:"info",text:`\u{1F4CB} ${R} code change${R===1?"":"s"} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}),Bt().then(K=>{K.kind==="forward-to-agent"&&K.prompt&&ie(K.prompt,{display:K.display,quietUser:!0})});else{let K=S?["/catch-up","/audit"]:["/audit","/sync"],X={"/catch-up":"write up everything your builder flagged","/audit":S?"also scan the code for other changes":"check the code for anything new or missing in the docs","/sync":"check Document360 for changes made there"},_=S?`\u{1F4CB} Your builder left ${S} for the docs:`:R>0?`\u{1F4CB} ${R} code change${R===1?"":"s"} since your last docs check \u2014 /audit to see what needs updating (or /audit --auto on to run it for you):`:`\u{1F4DA} ${$} article${$===1?"":"s"} tracked for "${a.name}". What next?`;u({kind:"note",tone:"info",text:[_,...K.map((x,A)=>` ${A+1} ${x.padEnd(9)} ${X[x]}`),"Or just tell me what to write or update."].join(`
269
+ `)}),B(K)}}else u({kind:"note",tone:"info",text:'\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.'}),se("write the docs for this repo"),B(S?["/catch-up","/audit"]:["/audit"])}}catch{}po()},[]),ve(()=>{let l=setInterval(()=>{po()},of);return()=>clearInterval(l)},[po]),ve(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${be.columns??80}x${be.rows??24}`;g!==os.current&&(os.current=g,sl(d=>d+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+si(nt.current,Ne())+"\x1B[?2026l")},80))},400)};return be.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),be.off("resize",a)}},[be,Ne]);let Ye=Math.max(20,(be.columns??80)-1),rs=Mr(()=>Xp(e,s),[e,s,Ce]),go=(()=>{if(tl)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};let l=Z(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=Qt(e,(l.docsDir??Ka).replace(/\/+$/,"")),a=(()=>{try{return Xt(i)&&Ya(i).length>0}catch{return!1}})();try{let g=ue(e,s),d=Me(g.name);if(!(!!d&&!(je(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:Jp,isSetup:!1}:lo?{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}})(),At=js(j),ss=At.length>0&&!N,wo=p!==null?_a(p,8,Ye):null,ln=ge?ge.paths.filter(l=>!ge.query||l.toLowerCase().includes(ge.query.toLowerCase())).slice(0,8):[],cn=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):[],pe=Y((l,i)=>{me.current?.close(),me.current=Ua({cwd:e,resume:l,profileName:i??s,allowProdWrites:ot.current}),l||(Pe.current={uuid:null,firstPrompt:null,titleFired:!1},rt(null)),dt(0),pt(0)},[e,s]),is=Y((l,i,a)=>{if(Qp.test(l))try{let g=ue(e,s),d=typeof i.project_id=="string"&&i.project_id||g.project.projectId,m=Yn(i,a),w=[],$=zn(a);l.endsWith("publish_article")&&$&&w.push(`Live: ${$}`),m&&d&&w.push(`Preview: ${Vn(g.connection.portalUrl,d,m,g.project.languageCode??"en")}`),w.length>0&&u({kind:"link",lines:w})}catch{}},[e,s,u]),ie=Y(async(l,i)=>{Zt(!0),se(null),B([]),on(null),co(null),ho(null);let a=++Qe.current;i?.quietUser||u({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let g=Pe.current;g.firstPrompt||(g.firstPrompt=i?.display??l),We.current=Date.now(),Ze(0),O(!0),nn.current.clear();let d="",m=!1,w=!1,$="",S={num:0,closed:!1,cueSeen:!1},R=null,K=()=>{R||(R=setTimeout(()=>{R=null,h($.length>0?$:null)},60))},X=()=>{R&&clearTimeout(R),R=null,h(null)},_=()=>{if($.trim()){let x=Nr($.trimEnd(),S);u({kind:"assistant",text:x})}$="",X()};try{for await(let x of me.current.send(l))if(x.type==="session"){if(!g.uuid){g.uuid=x.sessionId;let A=new Date().toISOString(),M=Sp(g.firstPrompt??"session");Tp({uuid:x.sessionId,name:M,renamed:!1,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:A,updatedAt:A}),rt(M)}}else if(x.type==="text"){$+=x.delta,d+=x.delta;let A=Oa($);if(A>0){let M=$.slice(0,A).trimEnd();M&&u({kind:"assistant",text:Nr(M,S)}),$=$.slice(A)}K(),Ze(M=>M+x.delta.length)}else if(x.type==="tool"){m=!0;let A=Bn(x.name,x.input);A&&(_(),u({kind:"tool",title:A.title,sep:A.sep,arg:A.arg}),nn.current.set(x.id,{name:x.name,input:x.input}))}else if(x.type==="article_diff"){let A=Xe(x.oldContent,x.newContent,Ne());A&&(_(),u({kind:"diff",added:A.added,removed:A.removed,lines:A.lines,hidden:A.hidden}))}else if(x.type==="tool_result"){x.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(x.output)&&(rn.current=!0);let A=nn.current.get(x.id);if(A){nn.current.delete(x.id),_();let M=Gn(x.output,4,x.isError?void 0:A.name,A.input);u({kind:"tool-result",lines:M.lines,hidden:M.hidden,isError:x.isError}),x.isError||is(A.name,A.input,x.output)}}else if(x.type==="result"){if(_(),dt(M=>M+x.outputTokens),pt(M=>M+x.costUsd),u({kind:"done",seconds:Math.round((Date.now()-We.current)/1e3),tokens:x.outputTokens,costUsd:x.costUsd,ok:x.ok}),!w&&!m&&!d.trim()&&!Tt.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)."}),x.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(d))try{let M=Gp(e);if(Xt(M)){let L=Wr(M,"utf8").trim();L&&(ho(L),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 A=x.ok?Pa(d,Ot.map(M=>M.name)):[];if(A.length>0?B(A):x.ok&&d.trim()&&Ap(l,d,e).then(M=>{M&&Qe.current===a&&se(M)}).catch(()=>{}),g.uuid&&(Fr(g.uuid),!g.titleFired)){g.titleFired=!0;let M=g.uuid,L=g.firstPrompt;L&&La(L,e).then(G=>{G&&(Pp(M,G),rt(G))}).catch(()=>{})}}else x.type==="error"&&(_(),w=!0,x.kind==="auth"&&(rn.current=!0),u({kind:"note",text:`agent error: ${x.message}`,tone:"error"}))}finally{O(!1),X(),re(x=>x+1),Pe.current.uuid&&va(e,Pe.current.uuid,nt.current),rn.current&&(rn.current=!1,sn.current=i?.display??l,B(["/login"])),Tt.current&&(Tt.current=!1,Ge.current.length>0&&(u({kind:"note",tone:"info",text:`(${Ge.current.length} queued message(s) discarded)`}),Ge.current=[],io([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,is,Ne]),un=Y(async l=>{let i=Br(l),a=to(e,"standard");We.current=Date.now(),Ze(0),O(!0);let g=new AbortController;we.current=g,Q({verb:"Publishing",total:i.length,done:0,active:[],rows:Kt(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${Ht} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let d of eo({cwd:e,partitions:i,promptFor:m=>In(m.paths),concurrency:Ht,profileName:s,allowProdWrites:ot.current,model:a.model,signal:g.signal}))if(d.type==="partition_status")d.status==="running"?Q(m=>m&&{...m,active:[...m.active,d.label],rows:De(m.rows,d.label,"active"),lastAt:Date.now()}):Q(m=>m&&{...m,active:m.active.filter(w=>w!==d.label),done:m.done+1,rows:De(m.rows,d.label,d.status==="done"?"done":"failed"),lastAt:Date.now()});else if(d.type==="partition_event")Q(m=>{if(!m)return m;let w={...m,lastAt:Date.now()};return d.event.type==="tool"?w.tools=m.tools+1:d.event.type==="text"&&(w.chars=m.chars+d.event.delta.length),w});else if(d.type==="run_done"){pt(S=>S+d.totalCostUsd),dt(S=>S+d.results.reduce((R,K)=>R+K.outputTokens,0));let m=d.aborted?"Stopped. ":"",w=t.kind==="api"?"api":"subscription";u({kind:"note",tone:d.aborted?"warn":d.ok?"ok":"warn",text:m+Bo(d.results,i,w).join(`
270
+ `)});let $=qo(e,s);$&&u({kind:"note",tone:"info",text:$})}}catch(d){u({kind:"note",tone:"error",text:`Publish run failed: ${d.message}`})}finally{we.current=null,Q(null),O(!1),re(d=>d+1)}},[e,s,u,t]),yo=Y(async l=>{await ie(Ho(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await Nn(e,s,l.replace(/\\/g,"/"));i.length>0&&(on(`Related articles not yet published (${i.length}):`),B([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ie]),ko=Y(l=>{let i=Me(l);if(!i||je(i)&&!i.refreshToken)return null;let a={...Ct(i.idToken)??{},...Ct(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),bo=Y((l,i)=>{if(i){let a=Z(e);a&&(a.defaultProfile=l,Ma(a,e))}c(l),pe(void 0,l),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),ko(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"])),re(a=>a+1)},[e,u,pe,ko]),dn=Y((l,i,a)=>{gn(e,l,i,a.id,a.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),pe(),Hr(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(`
271
+ `)}),ft(ze()),Dt.current=Te(e).status==="current"||Lt(e),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,pe,ft]),pn=Y(async l=>{let i;try{i=await Nt(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)":""}.`}),dn(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,dn]),as=Y((l,i)=>{Po(e,l,i.id,i.name),u({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),pe(),pn(l)},[e,u,pe,pn]),ls=Y(async l=>{let i;try{i=ue(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&&Yp(e,i.name,{projectName:g.name})}catch{}await pn(i.name);return}u({kind:"note",tone:"info",text:"Next: pick the Document360 project."}),B(["/project"])}},[e,u,pn]),fn=Y(()=>{let l=Ee.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,Ne());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,Ne]),cs=Y(l=>{if(Ee.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Ee.current.shift();try{Ep({cwd:e,profileName:s},a),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Ee.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=Ee.current.shift();u({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Ee.current.length;return Ee.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return fn(),!0},[e,s,fn,u]),us=Y(l=>{let i=so.current;if(!i)return!1;if(so.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}=Dr(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:Dn().join(`
272
+ `)}),ft(Ao())),u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
273
+ ${Ha}`}),B(["/init"]),Zt(!1),!0},[e,u,ft]),ds=Y(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),g=i.slice(1);switch(Zt(!0),a){case"help":u({kind:"note",tone:"info",text:vn().join(`
274
+ `)});return;case"exit":case"quit":me.current?.close(),r();return;case"clear":pe(),nt.current=[],Zt(!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=ue(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":""}`}),oe(!0);try{let m=await wp(d.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},$=>u({kind:"note",tone:"info",text:$})),w=yp(d.name,m);if(kp(w),await So(w,d.name,$=>u({kind:"note",tone:"info",text:$})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${d.name}" as ${yn(w)}`}),await ls(s),Rt.current){let $=Rt.current;Rt.current=null;let S=Re(e,s);S.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${$}.`}),B([$])):(u({kind:"note",tone:"warn",text:`${S.reason} (then ${$}.)`}),B(["/login"]),Rt.current=$)}else sn.current&&(se(sn.current),sn.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{oe(!1),re(m=>m+1)}return}case"allow-prod":{let d=!1;try{d=ue(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,pe(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let d=mr(g.join(" ")),m=Pe.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 w=Pe.current.firstPrompt??"";La(w,e).then($=>{$?(se(`/rename ${$}`),u({kind:"note",tone:"info",text:`Suggestion: "${$}" \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}jp(m,d),rt(d),zt(`${Or} 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 w=Object.entries(m?.profiles??{});if(w.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let $=w.map(([K,X])=>({name:K,env:X.connection?.environment??"custom",prod:X.production===!0,who:ko(K)})),S=s??m?.defaultProfile,R=Math.max(0,$.findIndex(K=>K.name===S));st({cursor:R,current:R,rows:$});return}if(d==="add"){let w=hr(e,g[1],g[2]);if(w){u({kind:"note",tone:"error",text:w});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),bo(g[1],!1);return}if(!m?.profiles?.[d]){u({kind:"note",tone:"error",text:`Unknown profile "${d}". Create it: /profile add ${d} <environment>`});return}bo(d,!0);return}case"doctor":await Vt(g,{cwd:e});return;case"mcp":await An(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=Op().map(m=>({name:m,apiUrl:Up(m).apiUrl}));it({cursor:0,rows:d});return}case"resume":{let d=g.join(" ").trim(),m=Dp(e).filter(S=>S.uuid!==Pe.current.uuid);if(!d){if(!m.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Ve({query:"",cursor:0,sessions:m});return}let w=Rp(e,d);if(!w){u({kind:"note",tone:"error",text:`No session matches "${d}".`});return}pe(w.uuid),Pe.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},rt(w.name),Fr(w.uuid),nt.current=[];let $=_r(e,w.uuid);for(let S of $)u(S);u({kind:"note",tone:"ok",text:$.length?`Resumed "${w.name}" \u2014 restored ${$.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let d=g.join(" ").trim(),m;try{m=await Nt(e,s)}catch($){u({kind:"note",tone:"error",text:`Could not list workspaces: ${$.message}`});return}if(!d){let $=m.workspaces.map(R=>({id:R.id,name:R.name??R.id,type:R.workspace_type}));if($.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let S=Math.max(0,$.findIndex(R=>R.id===m.current));at({cursor:S,current:S,rows:$,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let w=Co(m.workspaces,d);if(!w){u({kind:"note",tone:"error",text:`No workspace matches "${d}".`});return}dn(m.profile,m.projectId,w);return}case"project":{let d=g.join(" ").trim(),m;try{m=await gt(e,s)}catch($){u({kind:"note",tone:"error",text:`Could not list projects: ${$.message} (signed in? try /login)`});return}if(!d){let $=m.projects.map(R=>({id:R.id,name:R.name??R.id,sub:R.sub_domain}));if($.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let S=$.findIndex(R=>R.id===m.current);lt({cursor:Math.max(0,S),current:S,rows:$,profile:m.profile,environment:m.environment});return}let w=ks(m.projects,d);if(!w){u({kind:"note",tone:"error",text:`No project matches "${d}". Available: ${m.projects.map($=>$.name??$.id).join(", ")}`});return}as(m.profile,w);return}case"logout":{let d;try{d=ue(e,s).name}catch(w){u({kind:"note",tone:"error",text:w.message});return}let m=vp(d);Cp(e,d),pe(),re(w=>w+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(!fo(l.trim()))return;if(g[0]==="--related"&&g[1]){let m=await Nn(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 un(m);return}if(g[0]&&g[0]!=="--all"){await yo(g[0]);return}let d=g[0]==="--all";u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await qr({cwd:e,profileName:s}),w=qt(m.entries),$=En(m.entries);if($>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${$} article${$===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),w.length===0){u({kind:"note",tone:"ok",text:$>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let S=m.counts["unknown-base"]??0;S>0&&u({kind:"note",tone:"info",text:`(${S} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(d){await un(w.map(S=>S.path));return}ct({cursor:0,rows:li(w)})}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 w=[];try{w=Object.keys(Hr(e,ue(e,s).name)?.articles??{})}catch{}if(w.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Be({query:"",cursor:0,paths:w});return}let m=hp(d)?d:Qt(e,d);if(Xt(m)){try{u({kind:"preview",name:Jt(m),text:Ba(Wr(m,"utf8"))})}catch(w){u({kind:"note",tone:"error",text:`Could not read ${m}: ${w.message}`})}return}if(Zp.test(d)){try{let w=ue(e,s),$={profile:w.name,connection:w.connection},S=w.project.projectId??xp($),R=await $p($,S,d);u({kind:"preview",name:R.title??d,text:R.content??"*(article has no content)*"})}catch(w){u({kind:"note",tone:"error",text:`Could not fetch article: ${w.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 S=Ln(Vr(e));He({cursor:S,current:S});return}let{lines:m,changed:w,effective:$}=Gt(e,d);for(let S of m)u({kind:"note",tone:S.startsWith("\u26A0")?"warn":S.startsWith("\u2713")?"ok":"info",text:S});w&&(ns(S=>S+1),me.current?.setModel($));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}=zo(g),w=Wp(e,s);if(w.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let $=Ko(w,d);if($.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${d}". (${w.length} are tracked overall.)`});return}let S=Br($),R=3,K=`/convert${d?` --scope ${d}`:""} --run`,X=to(e,"light");if(!m){let x=Wa({files:Xo(e,$),op:"convert",model:X.model}),A=d?`Scope: ${d} (${$.length} of ${w.length} tracked)
275
275
  `:"",M=`
276
- Model: ${X.model}${X.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:A+Xo(S,x,R).join(`
277
- `)+M}),B([K]);return}We.current=Date.now(),Ze(0),O(!0);let _=new AbortController;we.current=_,Q({verb:"Converting",total:S.length,done:0,active:[],rows:Yt(S),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${$.length} articles across ${S.length} partitions (\u2264${R} agents at once) on ${X.model}\u2026 (esc to stop)`});try{for await(let x of Qn({cwd:e,partitions:S,promptFor:Ko,concurrency:R,profileName:s,allowProdWrites:ot.current,model:X.model,signal:_.signal}))if(x.type==="partition_status")x.status==="running"?Q(A=>A&&{...A,active:[...A.active,x.label],rows:Re(A.rows,x.label,"active"),lastAt:Date.now()}):Q(A=>A&&{...A,active:A.active.filter(M=>M!==x.label),done:A.done+1,rows:Re(A.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_event")Q(A=>{if(!A)return A;let M={...A,lastAt:Date.now()};return x.event.type==="tool"?M.tools=A.tools+1:x.event.type==="text"&&(M.chars=A.chars+x.event.delta.length),M});else if(x.type==="run_done"){pt(L=>L+x.totalCostUsd),dt(L=>L+x.results.reduce((G,le)=>G+le.outputTokens,0));let A=x.aborted?"Stopped. ":"",M=t.kind==="api"?"api":"subscription";u({kind:"note",tone:x.aborted?"warn":x.ok?"ok":"warn",text:A+Jo(x.results,S,M).join(`
278
- `)})}}catch(x){u({kind:"note",tone:"error",text:`Convert run failed: ${x.message}`})}finally{we.current=null,Q(null),O(!1),re(x=>x+1)}return}case"write":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=Mp(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:w,run:$}=Zo(g),{docsDir:S,targets:R,reason:K}=rr(e,d,{scope:m,path:w});if(R.length===0){u({kind:"note",tone:"warn",text:K??"Nothing to write."});return}let X=Hr(R),_=5,x=Zn(e,"standard");if(!$&&!!!w){let L=Ma({files:er(e,d,R),op:"write",model:x.model}),G=m?`Scope: ${m} (${R.length} pending)
276
+ Model: ${X.model}${X.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:A+Qo(S,x,R).join(`
277
+ `)+M}),B([K]);return}We.current=Date.now(),Ze(0),O(!0);let _=new AbortController;we.current=_,Q({verb:"Converting",total:S.length,done:0,active:[],rows:Kt(S),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${$.length} articles across ${S.length} partitions (\u2264${R} agents at once) on ${X.model}\u2026 (esc to stop)`});try{for await(let x of eo({cwd:e,partitions:S,promptFor:Jo,concurrency:R,profileName:s,allowProdWrites:ot.current,model:X.model,signal:_.signal}))if(x.type==="partition_status")x.status==="running"?Q(A=>A&&{...A,active:[...A.active,x.label],rows:De(A.rows,x.label,"active"),lastAt:Date.now()}):Q(A=>A&&{...A,active:A.active.filter(M=>M!==x.label),done:A.done+1,rows:De(A.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_event")Q(A=>{if(!A)return A;let M={...A,lastAt:Date.now()};return x.event.type==="tool"?M.tools=A.tools+1:x.event.type==="text"&&(M.chars=A.chars+x.event.delta.length),M});else if(x.type==="run_done"){pt(L=>L+x.totalCostUsd),dt(L=>L+x.results.reduce((G,le)=>G+le.outputTokens,0));let A=x.aborted?"Stopped. ":"",M=t.kind==="api"?"api":"subscription";u({kind:"note",tone:x.aborted?"warn":x.ok?"ok":"warn",text:A+Zo(x.results,S,M).join(`
278
+ `)})}}catch(x){u({kind:"note",tone:"error",text:`Convert run failed: ${x.message}`})}finally{we.current=null,Q(null),O(!1),re(x=>x+1)}return}case"write":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=Fp(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:w,run:$}=tr(g),{docsDir:S,targets:R,reason:K}=ir(e,d,{scope:m,path:w});if(R.length===0){u({kind:"note",tone:"warn",text:K??"Nothing to write."});return}let X=Br(R),_=5,x=to(e,"standard");if(!$&&!!!w){let L=Wa({files:nr(e,d,R),op:"write",model:x.model}),G=m?`Scope: ${m} (${R.length} pending)
279
279
  `:"",le=`
280
- Model: ${x.model}${x.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:G+nr(X,L,_).join(`
281
- `)+le}),B([`/write${m?` --scope ${m}`:" --all"} --run`]);return}We.current=Date.now(),Ze(0),O(!0);let M=new AbortController;we.current=M,Q({verb:"Writing",total:X.length,done:0,active:[],rows:Yt(X),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${R.length} article${R.length===1?"":"s"} across ${X.length} partition${X.length===1?"":"s"} (\u2264${_} agents at once) on ${x.model}${x.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let L of Qn({cwd:e,partitions:X,promptFor:G=>tr(G,S),concurrency:_,profileName:s,allowProdWrites:ot.current,model:x.model,signal:M.signal}))if(L.type==="partition_status")L.status==="running"?Q(G=>G&&{...G,active:[...G.active,L.label],rows:Re(G.rows,L.label,"active"),lastAt:Date.now()}):Q(G=>G&&{...G,active:G.active.filter(le=>le!==L.label),done:G.done+1,rows:Re(G.rows,L.label,L.status==="done"?"done":"failed"),lastAt:Date.now()});else if(L.type==="partition_event")Q(G=>{if(!G)return G;let le={...G,lastAt:Date.now()};return L.event.type==="tool"?le.tools=G.tools+1:L.event.type==="text"&&(le.chars=G.chars+L.event.delta.length),le});else if(L.type==="run_done"){pt(bo=>bo+L.totalCostUsd),dt(bo=>bo+L.results.reduce((al,ll)=>al+ll.outputTokens,0));let G=L.aborted?"Stopped. ":"",le=t.kind==="api"?"api":"subscription";u({kind:"note",tone:L.aborted?"warn":L.ok?"ok":"warn",text:G+or(L.results,X,le).join(`
282
- `)}),!L.aborted&&L.ok&&B(["/publish --all","/screenshot --all"])}}catch(L){u({kind:"note",tone:"error",text:`Write run failed: ${L.message}`})}finally{we.current=null,Q(null),O(!1),re(L=>L+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}=sr(e);if(d.length===0&&m===0){u({kind:"note",tone:"info",text:ar});return}let w=g.join(" ").trim();if(!w&&d.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
280
+ Model: ${x.model}${x.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:G+rr(X,L,_).join(`
281
+ `)+le}),B([`/write${m?` --scope ${m}`:" --all"} --run`]);return}We.current=Date.now(),Ze(0),O(!0);let M=new AbortController;we.current=M,Q({verb:"Writing",total:X.length,done:0,active:[],rows:Kt(X),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${R.length} article${R.length===1?"":"s"} across ${X.length} partition${X.length===1?"":"s"} (\u2264${_} agents at once) on ${x.model}${x.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let L of eo({cwd:e,partitions:X,promptFor:G=>or(G,S),concurrency:_,profileName:s,allowProdWrites:ot.current,model:x.model,signal:M.signal}))if(L.type==="partition_status")L.status==="running"?Q(G=>G&&{...G,active:[...G.active,L.label],rows:De(G.rows,L.label,"active"),lastAt:Date.now()}):Q(G=>G&&{...G,active:G.active.filter(le=>le!==L.label),done:G.done+1,rows:De(G.rows,L.label,L.status==="done"?"done":"failed"),lastAt:Date.now()});else if(L.type==="partition_event")Q(G=>{if(!G)return G;let le={...G,lastAt:Date.now()};return L.event.type==="tool"?le.tools=G.tools+1:L.event.type==="text"&&(le.chars=G.chars+L.event.delta.length),le});else if(L.type==="run_done"){pt($o=>$o+L.totalCostUsd),dt($o=>$o+L.results.reduce((ll,cl)=>ll+cl.outputTokens,0));let G=L.aborted?"Stopped. ":"",le=t.kind==="api"?"api":"subscription";u({kind:"note",tone:L.aborted?"warn":L.ok?"ok":"warn",text:G+sr(L.results,X,le).join(`
282
+ `)}),!L.aborted&&L.ok&&B(["/publish --all","/screenshot --all"])}}catch(L){u({kind:"note",tone:"error",text:`Write run failed: ${L.message}`})}finally{we.current=null,Q(null),O(!1),re(L=>L+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}=ar(e);if(d.length===0&&m===0){u({kind:"note",tone:"info",text:cr});return}let w=g.join(" ").trim();if(!w&&d.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
283
283
  ${d.map(R=>` \u2022 ${R.name} (${R.docCount} doc${R.docCount===1?"":"s"})`).join(`
284
- `)}`}),B(d.map(R=>`/draft ${R.name}`));return}let $="",S;if(w){let R=ir(d,w);R?$=R:S=w}else $=d[0]?.name??"";await ie(_n($,S),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"sync":{if(!uo(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 Fr({cwd:e,profileName:s});u({kind:"note",tone:"info",text:Nn(m).join(`
285
- `)});return}if(d==="pull"){let m=g[1];if(!m){u({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let w;if(m==="--all"){if(u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),w=(await Fr({cwd:e,profileName:s})).entries.filter(R=>R.status==="remote-ahead"&&R.path).map(R=>R.path),w.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 w=[m.replace(/\\/g,"/")];let $=[];for(let S of w)$.push(await Ap({cwd:e,profileName:s,relPath:S}));Ae.current=$,dn();return}if(d==="baseline"){let m=g[1],w=m&&m!=="--all"?m.replace(/\\/g,"/"):void 0;u({kind:"note",tone:"info",text:w?`Setting the sync baseline for ${w}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let $=await Ep({cwd:e,profileName:s,relPaths:w?[w]:void 0});if($.baselined.length===0&&$.skipped.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}$.baselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Baselined ${$.baselined.length} article${$.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),$.skipped.length>0&&u({kind:"note",tone:"warn",text:`${$.skipped.length} skipped:
284
+ `)}`}),B(d.map(R=>`/draft ${R.name}`));return}let $="",S;if(w){let R=lr(d,w);R?$=R:S=w}else $=d[0]?.name??"";await ie(Un($,S),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"sync":{if(!fo(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 qr({cwd:e,profileName:s});u({kind:"note",tone:"info",text:On(m).join(`
285
+ `)});return}if(d==="pull"){let m=g[1];if(!m){u({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let w;if(m==="--all"){if(u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),w=(await qr({cwd:e,profileName:s})).entries.filter(R=>R.status==="remote-ahead"&&R.path).map(R=>R.path),w.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 w=[m.replace(/\\/g,"/")];let $=[];for(let S of w)$.push(await Ip({cwd:e,profileName:s,relPath:S}));Ee.current=$,fn();return}if(d==="baseline"){let m=g[1],w=m&&m!=="--all"?m.replace(/\\/g,"/"):void 0;u({kind:"note",tone:"info",text:w?`Setting the sync baseline for ${w}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let $=await Np({cwd:e,profileName:s,relPaths:w?[w]:void 0});if($.baselined.length===0&&$.skipped.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}$.baselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Baselined ${$.baselined.length} article${$.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),$.skipped.length>0&&u({kind:"note",tone:"warn",text:`${$.skipped.length} skipped:
286
286
  ${$.skipped.map(S=>` - ${S.path} (${S.reason})`).join(`
287
- `)}`}),re(S=>S+1);return}u({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${d} \u2014 use /sync, /sync pull <path>|--all, or /sync baseline.`})}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=Ip(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":{if(g[0]==="--auto"){let m=Z(e);if(!m){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=g[1]!=="off";La({...m,autoAudit:w},e),u({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let d=await Ht();d.kind==="forward-to-agent"&&d.prompt&&await ie(d.prompt,{display:d.display,quietUser:!0});return}case"capture-setup":{let d=await Gt();d.kind==="forward-to-agent"&&d.prompt&&await ie(d.prompt,{display:d.display,quietUser:!0});let m=kr(e);m&&u({kind:"note",tone:"info",text:m.join(`
287
+ `)}`}),re(S=>S+1);return}u({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${d} \u2014 use /sync, /sync pull <path>|--all, or /sync baseline.`})}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=_p(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":{if(g[0]==="--auto"){let m=Z(e);if(!m){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=g[1]!=="off";Ma({...m,autoAudit:w},e),u({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let d=await Bt();d.kind==="forward-to-agent"&&d.prompt&&await ie(d.prompt,{display:d.display,quietUser:!0});return}case"capture-setup":{let d=await Yt();d.kind==="forward-to-agent"&&d.prompt&&await ie(d.prompt,{display:d.display,quietUser:!0});let m=xr(e);m&&u({kind:"note",tone:"info",text:m.join(`
288
288
  `)});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(`
289
- `)}),ft(ze()),Dt.current=_e(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(br(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 ie(xr(),{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}=cr(g);if(!m&&lr(e)===0){u({kind:"note",tone:"info",text:dr});return}let w=`/document${m?` ${m}`:""}${d?" --publish":""}`;await ie(ur(m,d),{display:w,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(!uo(l.trim()))return;let{publish:d}=$r(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 ie(vr({publish:d}),{display:`/catch-up${d?" --publish":""}`,quietUser:!0});return}case"update":{lo.current=!0,u({kind:"note",tone:"info",text:`Updating ${Je}\u2026 (don\u2019t close this window)`}),Qt(!0),(await Wn().finally(()=>Qt(!1))).ok?(u({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),B(m=>m.includes("/exit")?m:[...m,"/exit"])):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Mn}`});return}case"screenshot":{let d=gr(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:yr(wr(e,d.scope),d.scope).join(`
290
- `)});return}if(d.mode==="single"){let _=await Ln(g);_.kind==="forward-to-agent"&&_.prompt&&await ie(_.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,w=Up(e,{scope:m}).map(_=>_.id);if(w.length===0){u({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let $=6,S=Op(w,3),R=Zn(e,"standard");We.current=Date.now(),Ze(0),O(!0);let K=new AbortController;we.current=K,Q({verb:"Authoring",unit:"spec",total:S.length,done:0,active:[],rows:Yt(S),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${w.length} screenshot spec${w.length===1?"":"s"} across ${S.length} partition${S.length===1?"":"s"} (\u2264${$} agents at once) on ${R.model}${R.forced?" (forced)":""}\u2026 (esc to stop)`});let X=!1;try{for await(let _ of Qn({cwd:e,partitions:S,promptFor:Ji,concurrency:$,profileName:s,allowProdWrites:ot.current,model:R.model,signal:K.signal}))if(_.type==="partition_status")_.status==="running"?Q(x=>x&&{...x,active:[...x.active,_.label],rows:Re(x.rows,_.label,"active"),lastAt:Date.now()}):Q(x=>x&&{...x,active:x.active.filter(A=>A!==_.label),done:x.done+1,rows:Re(x.rows,_.label,_.status==="done"?"done":"failed"),lastAt:Date.now()});else if(_.type==="partition_event")Q(x=>{if(!x)return x;let A={...x,lastAt:Date.now()};return _.event.type==="tool"?A.tools=x.tools+1:_.event.type==="text"&&(A.chars=x.chars+_.event.delta.length),A});else if(_.type==="run_done"){pt(L=>L+_.totalCostUsd),dt(L=>L+_.results.reduce((G,le)=>G+le.outputTokens,0));let x=_.results.filter(L=>L.ok).length,A=_.aborted?"Stopped. ":"";X=!_.aborted&&d.setup;let M=_.aborted?"":X?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";u({kind:"note",tone:_.aborted?"warn":_.ok?"ok":"warn",text:`${A}Authored specs \u2014 ${x}/${_.results.length} batches ok.${M}`})}}catch(_){u({kind:"note",tone:"error",text:`Spec authoring failed: ${_.message}`})}finally{we.current=null,Q(null),O(!1),re(_=>_+1)}if(X){let _=await Gt();_.kind==="forward-to-agent"&&_.prompt&&await ie(_.prompt,{display:_.display,quietUser:!0});let x=kr(e);x&&u({kind:"note",tone:"info",text:x.join(`
291
- `)})}return}case"reset":{let d=Sr(e);if(d.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}oo.current={repoName:Kt(e),targets:d,hadDevhints:zt(Wa(e))},u({kind:"note",tone:"warn",text:Rr(e,d).join(`
292
- `)}),se(Kt(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,dn,u,pe,ie,ln,go,is]),pn=Y(l=>{let i=(l??j).trim();if(k(""),Zt(null),et(0),i.startsWith("/")&&(se(null),Qe.current++,tn(null),B(g=>Sa(g,i))),!i||ls(i)||as(i))return;no.current.push(i);let a=ja(i,Yr.current);i.startsWith("/")?(u({kind:"user",text:i}),cs(a)):ie(a,{display:i})},[j,ls,as,cs,ie]),us=Y(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=Ta(l);if(Ra(i)){let a=Da(++nl.current,i);Yr.current.set(a,i),C(a)}else C(i);return}C(l)},[C]),mt=Math.max(10,Ye-6),ds=Ur(()=>Xn(b.text,mt),[b.text,mt]),ko=Y(l=>y(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),fn=Y(l=>y(i=>({...i,pos:Ea(Xn(i.text,mt),i.pos,l)})),[mt]),At=Y(l=>y(i=>({...i,pos:Ia(Xn(i.text,mt),i.pos,l)})),[mt]),sl=["\x1B[H","\x1B[1~","\x1BOH"],il=["\x1B[F","\x1B[4~","\x1BOF"],ps=Y((l,i)=>i.leftArrow?(ko(-1),!0):i.rightArrow?(ko(1),!0):l&&sl.includes(l)?(At("start"),!0):l&&il.includes(l)?(At("end"),!0):i.ctrl&&l==="a"?(At("start"),!0):i.ctrl&&l==="e"?(At("end"),!0):!1,[ko,At]);return up((l,i)=>{if(i.ctrl&&l==="c"){me.current?.close(),r();return}if(!q){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}Tt.current||(Tt.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),me.current?.interrupt());return}if(i.return){let a=j.trim();if(!a)return;Ge.current.push(a),ro([...Ge.current]),k("");return}if(ps(l,i))return;if(i.upArrow){fn(-1);return}if(i.downArrow){fn(1);return}if(i.backspace||i.delete){P();return}l&&!i.ctrl&&!i.meta&&us(l);return}if(Fe){if(i.upArrow){He(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){He(a=>a&&{...a,cursor:Math.min($e.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=$e.length){He(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=$e[Fe.cursor];He(null);let{lines:g,changed:d,effective:m}=qt(e,a.value??"default");for(let w of g)u({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});d&&(es(w=>w+1),me.current?.setModel(m));return}if(l==="s"){let a=$e[Fe.cursor];He(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){He(null);return}return}if(Se){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)<=Se.rows.length){st(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=Se.rows[Se.cursor];st(null),yo(a.name,i.return===!0);return}if(i.escape){st(null);return}return}if(Ee){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)<=Ee.rows.length){it(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Ee.rows[Ee.cursor].name;if(it(null),!Vs(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=Me(a);d=!!m&&!(De(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"]),re(m=>m+1);return}if(i.escape){it(null);return}return}if(ae){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)<=ae.rows.length){at(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ae.rows[ae.cursor],{profile:g,projectId:d}=ae;at(null),cn(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),ss(g,a);return}if(i.escape){lt(null);return}return}if(de){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=de.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}qo(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(qe){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)<=qe.rows.length){ct(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=qe.rows[qe.cursor];ct(null),a.kind==="article"?go(a.paths[0]):ln(a.paths);return}if(i.escape){ct(null);return}return}if(ge){if(i.escape){Be(null);return}if(i.upArrow){Be(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Be(a=>a&&{...a,cursor:Math.min(Math.max(0,sn.length-1),a.cursor+1)});return}if(i.return){let a=sn[ge.cursor];if(a){Be(null);try{u({kind:"preview",name:Kt(a),text:qa(Lr(Xt(e,a),"utf8"))})}catch(g){u({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){Be(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){Be(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(ye){if(i.escape){Ve(null);return}if(i.upArrow){Ve(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ve(a=>a&&{...a,cursor:Math.min(Math.max(0,an.length-1),a.cursor+1)});return}if(i.return){let a=an[ye.cursor];if(a){Ve(null),pe(a.uuid),Pe.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},rt(a.name),Mr(a.uuid),nt.current=[];let g=Ir(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){Ve(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){Ve(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!j&&ke){k(ke),se(null),Qe.current++;return}if(!j&&Pt.length>0&&l&&/^[1-9]$/.test(l)){let a=Pt[Number(l)-1];if(a){k(a);return}}if(!j&&(po||io)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=po!=null;ya(po??io).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&&fo(null)});return}if(!ps(l,i)){if(os){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){k("/"+(jt[St]?.name??"")+" "),et(0);return}if(i.return){let a=jt[St];if(a){let g=j.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Ds(a.usage)&&!g){k("/"+a.name+" "),et(0);return}pn("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(j!==""&&tt===null){fn(-1);return}let a=no.current;if(!a.length)return;let g=tt===null?a.length-1:Math.max(0,tt-1);Zt(g),k(a[g]??"");return}if(i.downArrow){if(j!==""&&tt===null){fn(1);return}let a=no.current;if(tt===null)return;let g=tt+1;g>=a.length?(Zt(null),k("")):(Zt(g),k(a[g]??""));return}}if(i.return){pn();return}if(i.backspace||i.delete){P();return}if(i.escape){k(""),et(0),se(null),B([]),tn(null);return}l&&!i.ctrl&&!i.meta&&us(l)}}}),ve(()=>{if(N||q)return;let l=Ge.current.shift();l!==void 0&&(ro([...Ge.current]),pn(l))},[N,q,pn]),H(ee,{flexDirection:"column",width:Ye,children:[ho!==null&&H(ee,{marginTop:1,flexDirection:"column",children:[ho.truncated&&D(T,{dimColor:!0,children:"\u2026"}),D(T,{children:ho.text})]}),N&&(Jr?D(ef,{p:Jr}):D(Qp,{startTime:We.current,chars:tl})),D(ee,{borderStyle:"round",borderColor:ns.prod?"yellow":V,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:j?ds.map((l,i)=>{let a=b.text.slice(l.start,l.end),g=i===Jn(ds,b.pos),d=Math.min(b.pos,l.end)-l.start;return H(T,{children:[D(T,{color:V,children:i===0?"> ":" "}),g?H(qr,{children:[a.slice(0,d),D(eo,{ch:a[d]??" "}),a.slice(d+1)]}):a||" "]},`${i}-${l.start}`)}):H(T,{children:[D(T,{color:V,children:"> "}),ke&&!N?H(qr,{children:[D(eo,{ch:ke[0],dim:!0}),D(T,{color:"gray",children:ke.slice(1)}),D(T,{dimColor:!0,children:" (tab)"})]}):mo.isSetup||!Za?H(qr,{children:[D(eo,{ch:mo.text[0],dim:!0}),D(T,{color:"gray",children:mo.text.slice(1)})]}):D(eo,{ch:" "})]})}),Xr.length>0&&D(ee,{flexDirection:"column",paddingX:1,children:Xr.map((l,i)=>D(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Fe?H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:"Select model"}),D(T,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),$e.map((l,i)=>H(T,{color:i===Fe.cursor?V:void 0,children:[i===Fe.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===Fe.current?" \u2714":""}`.padEnd(16),D(T,{color:"gray",children:l.desc})]},l.label)),D(T,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Se?H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:"Switch connection profile"}),Se.rows.map((l,i)=>H(T,{color:i===Se.cursor?V:void 0,children:[i===Se.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===Se.current?" \u2714":""}`.padEnd(20),D(T,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?D(T,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),D(T,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ee?H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:"Pick your Document360 environment"}),Ee.rows.map((l,i)=>H(T,{color:i===Ee.cursor?V:void 0,children:[i===Ee.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),D(T,{color:"gray",children:l.apiUrl})]},l.name)),D(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ae?H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:"Switch workspace"}),D(T,{dimColor:!0,children:`environment ${ae.environment} \xB7 project ${ae.projectName??`${ae.projectId.slice(0,8)}\u2026`}`}),ae.rows.map((l,i)=>H(T,{color:i===ae.cursor?V:void 0,children:[i===ae.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===ae.current?" \u2714":""}`.padEnd(30),D(T,{color:"gray",children:l.type??""})]},l.id)),D(T,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):he?H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:"Choose project"}),D(T,{dimColor:!0,children:`environment ${he.environment}`}),he.rows.map((l,i)=>H(T,{color:i===he.cursor?V:void 0,children:[i===he.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===he.current?" \u2714":""}`.padEnd(30),D(T,{color:"gray",children:l.sub??""})]},l.id)),D(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):de?(()=>{let i=Math.min(Math.max(0,de.cursor-Math.floor(7)),Math.max(0,de.rows.length-14)),a=de.rows.slice(i,i+14),g=de.rows.filter(d=>d.checked).length;return H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:`Which folders back the user docs? (${g} selected of ${de.rows.length})`}),i>0?D(T,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((d,m)=>{let w=i+m;return H(T,{color:w===de.cursor?V:void 0,children:[w===de.cursor?"\u276F ":" ",d.checked?"\u25C9 ":"\u25CB ",d.path.padEnd(Math.min(48,Ye-34)),D(T,{color:"gray",children:In(d)})]},d.path)}),i+14<de.rows.length?D(T,{dimColor:!0,children:` \u2193 ${de.rows.length-i-14} more`}):null,D(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():qe?H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),qe.rows.map((l,i)=>{let a=i===qe.cursor,g=l.indent?" ":" ",d=`${i+1}.`.padEnd(3);return H(T,{color:a?V:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${d} ${l.label}`.padEnd(Math.min(56,Ye-24)),l.note?D(T,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),D(T,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ge?H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:`Preview article${ge.query?` \u2014 filter: ${ge.query}`:" (type to filter)"}`}),sn.length===0?D(T,{color:"gray",children:"no articles match"}):sn.map((l,i)=>H(T,{color:i===ge.cursor?V:void 0,children:[i===ge.cursor?"\u276F ":" ",l]},l)),D(T,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):ye?H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:`Resume session${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),an.length===0?D(T,{color:"gray",children:"no sessions match"}):an.map((l,i)=>H(T,{color:i===ye.cursor?V:void 0,children:[i===ye.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),D(T,{color:i===ye.cursor?V:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ye-40))})]},l.uuid)),D(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):os?D(ee,{flexDirection:"column",children:jt.map((l,i)=>H(T,{color:i===St?V:void 0,children:[i===St?"\u276F ":" ",l.usage.padEnd(22)," ",D(T,{color:i===St?V:"gray",children:l.name==="model"&&so?`${l.desc} (currently ${so})`:l.desc})]},l.name))}):!j&&Pt.length>0?H(ee,{flexDirection:"column",paddingX:1,children:[Kr?D(T,{color:V,children:Kr}):null,Pt.map((l,i)=>H(T,{children:[D(T,{color:V,children:i+1})," ",l.slice(0,Math.max(20,Ye-5))]},l)),D(T,{dimColor:!0,children:`press 1-${Pt.length} to fill the command \xB7 esc dismiss`})]}):D(ee,{paddingX:1,children:H(T,{color:"gray",children:[ns.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${so??"model n/a"}${t.kind==="api"?Zr>0?` \xB7 ${ce(Zr)}`:"":Qr>0?` \xB7 ${Ue(Qr)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as rf}from"react/jsx-runtime";async function Xa(e=process.cwd(),t="auto",n,o="0.0.0"){let r=of(t);r.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${I("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${I("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=nf(rf(Ka,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
293
- `),process.exit(0)}var cf=af(import.meta.url),Ja=cf("../package.json"),je=new sf;function Gr(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}je.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=>{Gr(e),await wn({profile:e.profile,manual:e.manual})});je.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Gr(e),await Cs({profile:e.profile})});je.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Gr(e),await vs({profile:e.profile})});var Vr=je.command("profile").description("Manage connection profiles for the current repo");Vr.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>yn(process.cwd()));Vr.command("use <name>").description("Set the default profile for this repo").action(e=>kn(process.cwd(),e));Vr.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>bn(process.cwd(),e));var Qa=je.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Qa.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));Qa.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await hs(process.cwd(),e,t.profile)});je.command("logs").description("Show the Document360 API log files (send these to support when reporting a problem)").action(()=>Ss());je.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(()=>(Un(),qi)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});je.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Ja.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(lf.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 Ts(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 ga(e.cwd,e.auth,e.profile):await Xa(e.cwd,e.auth,e.profile,Ja.version)});je.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
289
+ `)}),ft(ze()),Dt.current=Te(e).status==="current"||Lt(e);return}case"inbox":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if($r(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 ie(vr(),{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}=dr(g);if(!m&&ur(e)===0){u({kind:"note",tone:"info",text:fr});return}let w=`/document${m?` ${m}`:""}${d?" --publish":""}`;await ie(pr(m,d),{display:w,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(!fo(l.trim()))return;let{publish:d}=Cr(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 ie(Pr({publish:d}),{display:`/catch-up${d?" --publish":""}`,quietUser:!0});return}case"update":{uo.current=!0,u({kind:"note",tone:"info",text:`Updating ${Je}\u2026 (don\u2019t close this window)`}),en(!0),(await Hn().finally(()=>en(!1))).ok?(u({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),B(m=>m.includes("/exit")?m:[...m,"/exit"])):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Fn}`});return}case"screenshot":{let d=yr(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:br(kr(e,d.scope),d.scope).join(`
290
+ `)});return}if(d.mode==="single"){let _=await Wn(g);_.kind==="forward-to-agent"&&_.prompt&&await ie(_.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,w=Mp(e,{scope:m}).map(_=>_.id);if(w.length===0){u({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let $=6,S=Lp(w,3),R=to(e,"standard");We.current=Date.now(),Ze(0),O(!0);let K=new AbortController;we.current=K,Q({verb:"Authoring",unit:"spec",total:S.length,done:0,active:[],rows:Kt(S),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${w.length} screenshot spec${w.length===1?"":"s"} across ${S.length} partition${S.length===1?"":"s"} (\u2264${$} agents at once) on ${R.model}${R.forced?" (forced)":""}\u2026 (esc to stop)`});let X=!1;try{for await(let _ of eo({cwd:e,partitions:S,promptFor:Qi,concurrency:$,profileName:s,allowProdWrites:ot.current,model:R.model,signal:K.signal}))if(_.type==="partition_status")_.status==="running"?Q(x=>x&&{...x,active:[...x.active,_.label],rows:De(x.rows,_.label,"active"),lastAt:Date.now()}):Q(x=>x&&{...x,active:x.active.filter(A=>A!==_.label),done:x.done+1,rows:De(x.rows,_.label,_.status==="done"?"done":"failed"),lastAt:Date.now()});else if(_.type==="partition_event")Q(x=>{if(!x)return x;let A={...x,lastAt:Date.now()};return _.event.type==="tool"?A.tools=x.tools+1:_.event.type==="text"&&(A.chars=x.chars+_.event.delta.length),A});else if(_.type==="run_done"){pt(L=>L+_.totalCostUsd),dt(L=>L+_.results.reduce((G,le)=>G+le.outputTokens,0));let x=_.results.filter(L=>L.ok).length,A=_.aborted?"Stopped. ":"";X=!_.aborted&&d.setup;let M=_.aborted?"":X?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";u({kind:"note",tone:_.aborted?"warn":_.ok?"ok":"warn",text:`${A}Authored specs \u2014 ${x}/${_.results.length} batches ok.${M}`})}}catch(_){u({kind:"note",tone:"error",text:`Spec authoring failed: ${_.message}`})}finally{we.current=null,Q(null),O(!1),re(_=>_+1)}if(X){let _=await Yt();_.kind==="forward-to-agent"&&_.prompt&&await ie(_.prompt,{display:_.display,quietUser:!0});let x=xr(e);x&&u({kind:"note",tone:"info",text:x.join(`
291
+ `)})}return}case"reset":{let d=Rr(e);if(d.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}so.current={repoName:Jt(e),targets:d,hadDevhints:Xt(Fa(e))},u({kind:"note",tone:"warn",text:jr(e,d).join(`
292
+ `)}),se(Jt(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,fn,u,pe,ie,un,yo,ls]),mn=Y(l=>{let i=(l??j).trim();if(y(""),tn(null),et(0),i.startsWith("/")&&(se(null),Qe.current++,on(null),B(g=>Ta(g,i))),!i||us(i)||cs(i))return;ro.current.push(i);let a=Aa(i,Kr.current);i.startsWith("/")?(u({kind:"user",text:i}),ds(a)):ie(a,{display:i})},[j,us,cs,ds,ie]),ps=Y(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=Ra(l);if(Da(i)){let a=ja(++ol.current,i);Kr.current.set(a,i),C(a)}else C(i);return}C(l)},[C]),mt=Math.max(10,Ye-6),fs=Mr(()=>Qn(b.text,mt),[b.text,mt]),xo=Y(l=>k(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),hn=Y(l=>k(i=>({...i,pos:Ia(Qn(i.text,mt),i.pos,l)})),[mt]),Et=Y(l=>k(i=>({...i,pos:Na(Qn(i.text,mt),i.pos,l)})),[mt]),il=["\x1B[H","\x1B[1~","\x1BOH"],al=["\x1B[F","\x1B[4~","\x1BOF"],ms=Y((l,i)=>i.leftArrow?(xo(-1),!0):i.rightArrow?(xo(1),!0):l&&il.includes(l)?(Et("start"),!0):l&&al.includes(l)?(Et("end"),!0):i.ctrl&&l==="a"?(Et("start"),!0):i.ctrl&&l==="e"?(Et("end"),!0):!1,[xo,Et]);return pp((l,i)=>{if(i.ctrl&&l==="c"){me.current?.close(),r();return}if(!q){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}Tt.current||(Tt.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),me.current?.interrupt());return}if(i.return){let a=j.trim();if(!a)return;Ge.current.push(a),io([...Ge.current]),y("");return}if(ms(l,i))return;if(i.upArrow){hn(-1);return}if(i.downArrow){hn(1);return}if(i.backspace||i.delete){P();return}l&&!i.ctrl&&!i.meta&&ps(l);return}if(Fe){if(i.upArrow){He(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){He(a=>a&&{...a,cursor:Math.min($e.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=$e.length){He(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=$e[Fe.cursor];He(null);let{lines:g,changed:d,effective:m}=Gt(e,a.value??"default");for(let w of g)u({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});d&&(ns(w=>w+1),me.current?.setModel(m));return}if(l==="s"){let a=$e[Fe.cursor];He(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){He(null);return}return}if(Se){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)<=Se.rows.length){st(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=Se.rows[Se.cursor];st(null),bo(a.name,i.return===!0);return}if(i.escape){st(null);return}return}if(Ie){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)<=Ie.rows.length){it(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Ie.rows[Ie.cursor].name;if(it(null),!Ys(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=Me(a);d=!!m&&!(je(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"]),re(m=>m+1);return}if(i.escape){it(null);return}return}if(ae){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)<=ae.rows.length){at(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ae.rows[ae.cursor],{profile:g,projectId:d}=ae;at(null),dn(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),as(g,a);return}if(i.escape){lt(null);return}return}if(de){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=de.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}Go(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(qe){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)<=qe.rows.length){ct(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=qe.rows[qe.cursor];ct(null),a.kind==="article"?yo(a.paths[0]):un(a.paths);return}if(i.escape){ct(null);return}return}if(ge){if(i.escape){Be(null);return}if(i.upArrow){Be(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Be(a=>a&&{...a,cursor:Math.min(Math.max(0,ln.length-1),a.cursor+1)});return}if(i.return){let a=ln[ge.cursor];if(a){Be(null);try{u({kind:"preview",name:Jt(a),text:Ba(Wr(Qt(e,a),"utf8"))})}catch(g){u({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){Be(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){Be(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(ye){if(i.escape){Ve(null);return}if(i.upArrow){Ve(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ve(a=>a&&{...a,cursor:Math.min(Math.max(0,cn.length-1),a.cursor+1)});return}if(i.return){let a=cn[ye.cursor];if(a){Ve(null),pe(a.uuid),Pe.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},rt(a.name),Fr(a.uuid),nt.current=[];let g=_r(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){Ve(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){Ve(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!j&&ke){y(ke),se(null),Qe.current++;return}if(!j&&Pt.length>0&&l&&/^[1-9]$/.test(l)){let a=Pt[Number(l)-1];if(a){y(a);return}}if(!j&&(mo||lo)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=mo!=null;ka(mo??lo).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&&ho(null)});return}if(!ms(l,i)){if(ss){if(i.upArrow){et(a=>Math.max(0,a-1));return}if(i.downArrow){et(a=>Math.min(At.length-1,a+1));return}if(i.tab){y("/"+(At[St]?.name??"")+" "),et(0);return}if(i.return){let a=At[St];if(a){let g=j.trim().slice(1).split(/\s+/).slice(1).join(" ");if(As(a.usage)&&!g){y("/"+a.name+" "),et(0);return}mn("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(j!==""&&tt===null){hn(-1);return}let a=ro.current;if(!a.length)return;let g=tt===null?a.length-1:Math.max(0,tt-1);tn(g),y(a[g]??"");return}if(i.downArrow){if(j!==""&&tt===null){hn(1);return}let a=ro.current;if(tt===null)return;let g=tt+1;g>=a.length?(tn(null),y("")):(tn(g),y(a[g]??""));return}}if(i.return){mn();return}if(i.backspace||i.delete){P();return}if(i.escape){y(""),et(0),se(null),B([]),on(null);return}l&&!i.ctrl&&!i.meta&&ps(l)}}}),ve(()=>{if(N||q)return;let l=Ge.current.shift();l!==void 0&&(io([...Ge.current]),mn(l))},[N,q,mn]),H(ee,{flexDirection:"column",width:Ye,children:[wo!==null&&H(ee,{marginTop:1,flexDirection:"column",children:[wo.truncated&&D(T,{dimColor:!0,children:"\u2026"}),D(T,{children:wo.text})]}),N&&(Zr?D(nf,{p:Zr}):D(ef,{startTime:We.current,chars:nl})),D(ee,{borderStyle:"round",borderColor:rs.prod?"yellow":V,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:j?fs.map((l,i)=>{let a=b.text.slice(l.start,l.end),g=i===Zn(fs,b.pos),d=Math.min(b.pos,l.end)-l.start;return H(T,{children:[D(T,{color:V,children:i===0?"> ":" "}),g?H(Gr,{children:[a.slice(0,d),D(no,{ch:a[d]??" "}),a.slice(d+1)]}):a||" "]},`${i}-${l.start}`)}):H(T,{children:[D(T,{color:V,children:"> "}),ke&&!N?H(Gr,{children:[D(no,{ch:ke[0],dim:!0}),D(T,{color:"gray",children:ke.slice(1)}),D(T,{dimColor:!0,children:" (tab)"})]}):go.isSetup||!el?H(Gr,{children:[D(no,{ch:go.text[0],dim:!0}),D(T,{color:"gray",children:go.text.slice(1)})]}):D(no,{ch:" "})]})}),Qr.length>0&&D(ee,{flexDirection:"column",paddingX:1,children:Qr.map((l,i)=>D(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Fe?H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:"Select model"}),D(T,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),$e.map((l,i)=>H(T,{color:i===Fe.cursor?V:void 0,children:[i===Fe.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===Fe.current?" \u2714":""}`.padEnd(16),D(T,{color:"gray",children:l.desc})]},l.label)),D(T,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Se?H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:"Switch connection profile"}),Se.rows.map((l,i)=>H(T,{color:i===Se.cursor?V:void 0,children:[i===Se.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===Se.current?" \u2714":""}`.padEnd(20),D(T,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?D(T,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),D(T,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ie?H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:"Pick your Document360 environment"}),Ie.rows.map((l,i)=>H(T,{color:i===Ie.cursor?V:void 0,children:[i===Ie.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),D(T,{color:"gray",children:l.apiUrl})]},l.name)),D(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ae?H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:"Switch workspace"}),D(T,{dimColor:!0,children:`environment ${ae.environment} \xB7 project ${ae.projectName??`${ae.projectId.slice(0,8)}\u2026`}`}),ae.rows.map((l,i)=>H(T,{color:i===ae.cursor?V:void 0,children:[i===ae.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===ae.current?" \u2714":""}`.padEnd(30),D(T,{color:"gray",children:l.type??""})]},l.id)),D(T,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):he?H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:"Choose project"}),D(T,{dimColor:!0,children:`environment ${he.environment}`}),he.rows.map((l,i)=>H(T,{color:i===he.cursor?V:void 0,children:[i===he.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===he.current?" \u2714":""}`.padEnd(30),D(T,{color:"gray",children:l.sub??""})]},l.id)),D(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):de?(()=>{let i=Math.min(Math.max(0,de.cursor-Math.floor(7)),Math.max(0,de.rows.length-14)),a=de.rows.slice(i,i+14),g=de.rows.filter(d=>d.checked).length;return H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:`Which folders back the user docs? (${g} selected of ${de.rows.length})`}),i>0?D(T,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((d,m)=>{let w=i+m;return H(T,{color:w===de.cursor?V:void 0,children:[w===de.cursor?"\u276F ":" ",d.checked?"\u25C9 ":"\u25CB ",d.path.padEnd(Math.min(48,Ye-34)),D(T,{color:"gray",children:_n(d)})]},d.path)}),i+14<de.rows.length?D(T,{dimColor:!0,children:` \u2193 ${de.rows.length-i-14} more`}):null,D(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():qe?H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),qe.rows.map((l,i)=>{let a=i===qe.cursor,g=l.indent?" ":" ",d=`${i+1}.`.padEnd(3);return H(T,{color:a?V:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${d} ${l.label}`.padEnd(Math.min(56,Ye-24)),l.note?D(T,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),D(T,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ge?H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:`Preview article${ge.query?` \u2014 filter: ${ge.query}`:" (type to filter)"}`}),ln.length===0?D(T,{color:"gray",children:"no articles match"}):ln.map((l,i)=>H(T,{color:i===ge.cursor?V:void 0,children:[i===ge.cursor?"\u276F ":" ",l]},l)),D(T,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):ye?H(ee,{flexDirection:"column",paddingX:1,children:[D(T,{color:V,bold:!0,children:`Resume session${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),cn.length===0?D(T,{color:"gray",children:"no sessions match"}):cn.map((l,i)=>H(T,{color:i===ye.cursor?V:void 0,children:[i===ye.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),D(T,{color:i===ye.cursor?V:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ye-40))})]},l.uuid)),D(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):ss?D(ee,{flexDirection:"column",children:At.map((l,i)=>H(T,{color:i===St?V:void 0,children:[i===St?"\u276F ":" ",l.usage.padEnd(22)," ",D(T,{color:i===St?V:"gray",children:l.name==="model"&&ao?`${l.desc} (currently ${ao})`:l.desc})]},l.name))}):!j&&Pt.length>0?H(ee,{flexDirection:"column",paddingX:1,children:[Jr?D(T,{color:V,children:Jr}):null,Pt.map((l,i)=>H(T,{children:[D(T,{color:V,children:i+1})," ",l.slice(0,Math.max(20,Ye-5))]},l)),D(T,{dimColor:!0,children:`press 1-${Pt.length} to fill the command \xB7 esc dismiss`})]}):D(ee,{paddingX:1,children:H(T,{color:"gray",children:[rs.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ao??"model n/a"}${t.kind==="api"?ts>0?` \xB7 ${ce(ts)}`:"":es>0?` \xB7 ${Ue(es)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as af}from"react/jsx-runtime";async function Ja(e=process.cwd(),t="auto",n,o="0.0.0"){let r=sf(t);r.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${I("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${I("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=rf(af(Xa,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
293
+ `),process.exit(0)}var df=cf(import.meta.url),Qa=df("../package.json"),Ae=new lf;function Yr(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Ae.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{Yr(e),await kn({profile:e.profile,manual:e.manual})});Ae.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Yr(e),await Ss({profile:e.profile})});Ae.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Yr(e),await Ps({profile:e.profile})});var zr=Ae.command("profile").description("Manage connection profiles for the current repo");zr.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>bn(process.cwd()));zr.command("use <name>").description("Set the default profile for this repo").action(e=>xn(process.cwd(),e));zr.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>$n(process.cwd(),e));var Za=Ae.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Za.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));Za.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await ws(process.cwd(),e,t.profile)});Ae.command("logs").description("Show the Document360 API log files (send these to support when reporting a problem)").action(()=>Rs());Ae.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(Mn(),Bi)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Ae.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(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(uf.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 Ds(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 wa(e.cwd,e.auth,e.profile):await Ja(e.cwd,e.auth,e.profile,Qa.version)});Ae.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});