document360-writer 0.4.64 → 0.4.65

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 +43 -43
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,53 +1,53 @@
1
1
  #!/usr/bin/env node
2
- var ra=Object.defineProperty;var br=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var sa=(e,t)=>{for(var n in t)ra(e,n,{get:t[n],enumerable:!0})};import Ae from"picocolors";var B,ia,aa,la,xr,yt,f,v,L,D,A,ee,Ce,H=br(()=>{"use strict";B="#7f56d9",[ia,aa,la]=[127,86,217],xr=e=>Ae.isColorSupported?`\x1B[38;2;${ia};${aa};${la}m${e}\x1B[39m`:e,yt=e=>Ae.bold(xr(e)),f=e=>Ae.dim(e),v=e=>Ae.red(e),L=e=>Ae.yellow(e),D=e=>Ae.green(e),A=xr,ee=e=>Ae.gray(e),Ce=e=>Ae.bold(e)});var Ls={};sa(Ls,{doctorCommand:()=>Rt,renderDoctorChecks:()=>Ms,runDoctorChecks:()=>Os});import{existsSync as cc}from"node:fs";import{d360GetAll as uc,getAccessToken as dc,isExpired as So,loadProfileMap as pc,loadTokens as fc,packageSkillsDir as _s,projectConfigPath as mc,readProjectConfig as gc,DEFAULT_DOCS_DIR as hc,resolveActiveProfile as wc,resolveAuth as yc,resolveModelSetting as kc}from"document360-engine";async function Os(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=yc("auto");o.kind==="none"?t.push({level:"fail",label:"Claude auth: not configured",fix:"Set ANTHROPIC_API_KEY, or sign in to Claude Code once (subscription reuse)"}):o.kind==="api"?t.push({level:"ok",label:"Claude auth: API key"}):o.stored?t.push({level:"ok",label:"Claude auth: subscription (Claude Code login found)"}):process.platform==="darwin"?t.push({level:"warn",label:"Claude auth: subscription \u2014 no credentials file (may be in the macOS Keychain)",fix:"If a docs turn ends with no output, sign in to Claude Code: run `claude` then /login (or set ANTHROPIC_API_KEY)"}):t.push({level:"fail",label:"Claude auth: subscription \u2014 NOT signed in (no Claude Code login on this machine)",fix:"Sign in to Claude Code on this machine: run `claude` then /login. Or set ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN. (Signing into Document360 or another Claude terminal is separate.)"});let r=kc(e);t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`});let s=gc(e);if(!s)return t.push({level:"fail",label:`No ${mc(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??hc).replace(/\/+$/,"");t.push(s.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let g;try{g=wc(e),t.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(j){return t.push({level:"fail",label:`Profile config: ${j.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let w=fc(g.name);w?So(w)&&!w.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):So(w)?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(w.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${g.name})`}),t.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let b=pc(e,g.name);if(b?b.projectId&&g.project.projectId&&b.projectId!==g.project.projectId?t.push({level:"fail",label:`Category map projectId (${b.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(b.articles).length} articles, ${Object.keys(b.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),t.push(cc(_s())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${_s()}`,fix:"Reinstall document360-writer (broken install)"}),w&&(!So(w)||w.refreshToken)){let j={profile:g.name,connection:g.connection};try{await dc(j);let k=await uc(j,"/v3/projects");t.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${k.length} project(s) visible`})}catch(k){t.push({level:"fail",label:`API call failed: ${k.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}}return t}function Ms(e){let t=[""];for(let r of e){let s=r.level==="ok"?D("\u2713"):r.level==="warn"?L("\u26A0"):v("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${A(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?D(`\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 Rt(e,t){console.log(f("Running checks\u2026"));for(let n of Ms(await Os(t.cwd)))console.log(n);return{kind:"continue"}}var fn=br(()=>{"use strict";H()});import{Command as Td}from"commander";import{createRequire as Sd}from"node:module";import{AUTH_MODES as Rd}from"document360-engine";import{input as $a}from"@inquirer/prompts";import{loginPkce as va,refreshTokens as Ca,toStoredTokens as Rr,clearTokens as Pa,decodeJwtClaims as Sr,isExpired as Ta,loadTokens as Sa,saveTokens as jr,resolveActiveProfile as Xt,setProfileProject as Ra,readProjectConfig as ja}from"document360-engine";H();import{select as ca}from"@inquirer/prompts";import{resolveActiveProfile as ua,setProfileProject as da,resolveProjectId as pa,listWorkspaces as fa}from"document360-engine";async function kt(e,t){let n=ua(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??pa(o);return{workspaces:await fa(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var $r=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Hn(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 Vt(e,t,n,o,r){da(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function vr(e,t,n){let o;try{o=await kt(e,n)}catch(s){return console.log(v(`Could not list workspaces: ${s.message}`)),1}let r=Hn(o.workspaces,t);return r?(Vt(e,o.profile,o.projectId,r.id,r.name),console.log(D(`\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 lt(e,t){let n;try{n=await kt(e,t)}catch(w){console.log(v(`Could not list workspaces: ${w.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 w of o)console.log(` ${w.id===c?A("\u25CF"):" "} ${$r(w)} ${f(w.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await ca({message:"Select the Document360 workspace for this repo:",choices:o.map(w=>({name:`${$r(w)}${w.id===c?" (current)":""}`,value:w.id}))}),g=o.find(w=>w.id===p);Vt(e,s,r,p,g?.name),console.log(D(`\u2713 Workspace set to "${g?.name??p}" for profile "${s}".`))}H();import{select as ma}from"@inquirer/prompts";import{resolveActiveProfile as ga,setProfileProject as ha,listProjects as wa}from"document360-engine";async function ct(e,t){let n=ga(e,t),o={profile:n.name,connection:n.connection};return{projects:await wa(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Cr=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Pr(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 Bn(e,t,n,o){ha(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Tr(e,t){let n;try{n=await ct(e,t)}catch(g){console.log(v(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===s?A("\u25CF"):" "} ${Cr(g)} ${f(g.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await ma({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${Cr(g)}${g.id===s?" (current)":""}`,value:g.id}))}),p=o.find(g=>g.id===c);Bn(e,r,c,p?.name),console.log(D(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}H();import ya from"picocolors";function ka(e=process.env){return e.FORCE_HYPERLINK==="0"||!ya.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 ba(e,t=e,n){return ka(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var xa=/https?:\/\/[^\s\x1b]+/g;function bt(e,t){return e.replace(xa,n=>ba(n,n,t))}function Ar(e){return{...Sr(e.idToken)??{},...Sr(e.accessToken)??{}}}function Kt(e){let t=Ar(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 Jt(e){let t=Xt(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 va(n,{manual:e.manual,promptForRedirect:s=>$a({message:s})},s=>console.log(bt(s))),r=Rr(t.name,o);if(jr(r),await Qt(r,t.name,s=>console.log(f(s))),console.log(""),console.log(D(`\u2713 Logged in to "${t.name}" as ${Kt(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{ja(process.cwd())?.profiles?.[t.name]&&(console.log(""),await lt(process.cwd(),t.name))}catch{}}async function Qt(e,t,n){let r=Ar(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Xt(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await ct(process.cwd(),t);c=p.find(g=>g.id===r)?.name}catch{}Ra(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Dr(e){let t=Xt(process.cwd(),e.profile),n=t.connection,o=Sa(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 ${A(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Kt(o)}`),Ta(o))if(o.refreshToken)try{let r=Rr(t.name,await Ca(n,o.refreshToken));jr(r),console.log(D(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(L("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function Er(e){let t=Xt(process.cwd(),e.profile);Pa(t.name)?console.log(D(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}H();import{readProjectConfig as Ir,writeProjectConfig as Aa,resolveActiveProfile as Da,loadTokens as Ea,isExpired as Ia}from"document360-engine";function Zt(e){let t=Ir(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?A("\u25CF "):" ",s=o.production?L(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Ea(n),g=p?Ia(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${A(n)} \u2192 ${c}${s} [${g}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function en(e,t){let n=Ir(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,Aa(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(D(`\u2713 Default profile is now "${t}"${o}`))}function tn(e,t){try{let n=Da(e,t);console.log(""),console.log(`Profile ${A(n.name)}${n.production?L(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(v(n.message)),process.exitCode=1}}H();import{existsSync as Na,readdirSync as _a,statSync as Oa}from"node:fs";import{join as Ma}from"node:path";import{apiLogDir as La}from"document360-engine";function Nr(){let e=La();if(console.log(""),console.log(`Document360 API logs: ${A(e)}`),!Na(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=_a(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=(Oa(Ma(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("")}H();import{createSession as Ua,resolveAuth as Wa,findByName as Fa,slugify as Ha,touchSession as Ba,upsertSession as qa,resolveActiveProfile as Ga}from"document360-engine";async function _r(e,t,n,o,r,s){let c=Wa(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 ${A("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${A("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Ga(e,r)}catch(k){console.error(v(`Document360 profile error: ${k.message}`)),process.exit(2)}p.production&&(console.error(L(`\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 g;if(o){let k=Fa(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)),g=k.uuid,console.error(f(`Resuming "${k.name}"`))}let w=Ua({cwd:e,resume:g,profileName:r,allowProdWrites:s===!0}),b=g??null,j=1;for await(let k of w.send(t))switch(k.type){case"session":if(!b){b=k.sessionId;let C=new Date().toISOString();qa({uuid:b,name:Ha(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(ee(` \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)}b&&Ba(b),process.stdout.write(`
3
- `),process.exit(j)}import{createInterface as iu}from"node:readline/promises";import{createSession as Fo,resolveAuth as au,getSession as lu,setTitle as cu,slugify as uu,touchSession as di,upsertSession as du,generateTitle as pu,resolveActiveProfile as pi,resolveModelSetting as fu,readProjectConfig as mu,decodeJwtClaims as ci,isExpired as gu,loadTokens as hu}from"document360-engine";var xt=[{name:"init",usage:"/init",desc:"Pick an environment & scaffold .d360-writer.json",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:"Set up the dev\u2192docs hint channel (guide + paste block for your repo agent)",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:"write",usage:"/write [--all|--scope <cat>|<path>] [--run]",desc:"Author the planned articles in parallel (bare = preview + cost; --run starts)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"audit",usage:"/audit",desc:"Gap analysis: code vs docs vs Document360 (what changed)",group:"publish"},{name:"sync",usage:"/sync [pull <path>|--all]",desc:"Drift report local vs Document360; pull portal edits",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"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"}],Ya=[{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 nn(){let e=Math.max(...xt.map(n=>n.usage.length))+2,t=["document360-writer \u2014 commands","",'New here? /init \u2192 "write the docs for this repo" \u2192 /publish',""," Screenshots are optional \u2014 add them anytime:"," /screenshot --all \u2192 d360-capture capture \u2192 re-/publish"];for(let{key:n,label:o}of Ya){t.push("",o);for(let r of xt.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 Or(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return xt.filter(n=>n.name.startsWith(t))}function Mr(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}async function qn(){console.log("");for(let e of nn())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}H();import{getSession as za}from"document360-engine";async function Lr(e,t){let n=t.currentUuid(),o=n?za(n):void 0;return console.log(o?f(`
2
+ var ra=Object.defineProperty;var xr=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var sa=(e,t)=>{for(var n in t)ra(e,n,{get:t[n],enumerable:!0})};import Ae from"picocolors";var B,ia,aa,la,br,yt,f,v,L,D,A,ee,Ce,H=xr(()=>{"use strict";B="#7f56d9",[ia,aa,la]=[127,86,217],br=e=>Ae.isColorSupported?`\x1B[38;2;${ia};${aa};${la}m${e}\x1B[39m`:e,yt=e=>Ae.bold(br(e)),f=e=>Ae.dim(e),v=e=>Ae.red(e),L=e=>Ae.yellow(e),D=e=>Ae.green(e),A=br,ee=e=>Ae.gray(e),Ce=e=>Ae.bold(e)});var Ls={};sa(Ls,{doctorCommand:()=>Rt,renderDoctorChecks:()=>Ms,runDoctorChecks:()=>Os});import{existsSync as cc}from"node:fs";import{d360GetAll as uc,getAccessToken as dc,isExpired as So,loadProfileMap as pc,loadTokens as fc,packageSkillsDir as _s,projectConfigPath as mc,readProjectConfig as gc,DEFAULT_DOCS_DIR as hc,resolveActiveProfile as wc,resolveAuth as yc,resolveModelSetting as kc}from"document360-engine";async function Os(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=yc("auto");o.kind==="none"?t.push({level:"fail",label:"Claude auth: not configured",fix:"Set ANTHROPIC_API_KEY, or sign in to Claude Code once (subscription reuse)"}):o.kind==="api"?t.push({level:"ok",label:"Claude auth: API key"}):o.stored?t.push({level:"ok",label:"Claude auth: subscription (Claude Code login found)"}):process.platform==="darwin"?t.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:"The engine runs on CLAUDE CODE, not Claude Desktop (a different app). If a docs turn ends with no output, sign in to Claude Code (`claude` then /login), or set CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY"}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:"Claude DESKTOP does not count \u2014 the engine needs Claude Code. Do ONE: install + sign in to Claude Code (`npm i -g @anthropic-ai/claude-code`, then `claude` and /login); or set CLAUDE_CODE_OAUTH_TOKEN (from `claude setup-token`); or set ANTHROPIC_API_KEY"});let r=kc(e);t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`});let s=gc(e);if(!s)return t.push({level:"fail",label:`No ${mc(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??hc).replace(/\/+$/,"");t.push(s.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let g;try{g=wc(e),t.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(j){return t.push({level:"fail",label:`Profile config: ${j.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let w=fc(g.name);w?So(w)&&!w.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):So(w)?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(w.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${g.name})`}),t.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let x=pc(e,g.name);if(x?x.projectId&&g.project.projectId&&x.projectId!==g.project.projectId?t.push({level:"fail",label:`Category map projectId (${x.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(x.articles).length} articles, ${Object.keys(x.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),t.push(cc(_s())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${_s()}`,fix:"Reinstall document360-writer (broken install)"}),w&&(!So(w)||w.refreshToken)){let j={profile:g.name,connection:g.connection};try{await dc(j);let k=await uc(j,"/v3/projects");t.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${k.length} project(s) visible`})}catch(k){t.push({level:"fail",label:`API call failed: ${k.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}}return t}function Ms(e){let t=[""];for(let r of e){let s=r.level==="ok"?D("\u2713"):r.level==="warn"?L("\u26A0"):v("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${A(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?D(`\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 Rt(e,t){console.log(f("Running checks\u2026"));for(let n of Ms(await Os(t.cwd)))console.log(n);return{kind:"continue"}}var fn=xr(()=>{"use strict";H()});import{Command as Td}from"commander";import{createRequire as Sd}from"node:module";import{AUTH_MODES as Rd}from"document360-engine";import{input as $a}from"@inquirer/prompts";import{loginPkce as va,refreshTokens as Ca,toStoredTokens as Rr,clearTokens as Pa,decodeJwtClaims as Sr,isExpired as Ta,loadTokens as Sa,saveTokens as jr,resolveActiveProfile as Kt,setProfileProject as Ra,readProjectConfig as ja}from"document360-engine";H();import{select as ca}from"@inquirer/prompts";import{resolveActiveProfile as ua,setProfileProject as da,resolveProjectId as pa,listWorkspaces as fa}from"document360-engine";async function kt(e,t){let n=ua(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??pa(o);return{workspaces:await fa(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var $r=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Hn(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 Vt(e,t,n,o,r){da(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function vr(e,t,n){let o;try{o=await kt(e,n)}catch(s){return console.log(v(`Could not list workspaces: ${s.message}`)),1}let r=Hn(o.workspaces,t);return r?(Vt(e,o.profile,o.projectId,r.id,r.name),console.log(D(`\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 lt(e,t){let n;try{n=await kt(e,t)}catch(w){console.log(v(`Could not list workspaces: ${w.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 w of o)console.log(` ${w.id===c?A("\u25CF"):" "} ${$r(w)} ${f(w.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await ca({message:"Select the Document360 workspace for this repo:",choices:o.map(w=>({name:`${$r(w)}${w.id===c?" (current)":""}`,value:w.id}))}),g=o.find(w=>w.id===p);Vt(e,s,r,p,g?.name),console.log(D(`\u2713 Workspace set to "${g?.name??p}" for profile "${s}".`))}H();import{select as ma}from"@inquirer/prompts";import{resolveActiveProfile as ga,setProfileProject as ha,listProjects as wa}from"document360-engine";async function ct(e,t){let n=ga(e,t),o={profile:n.name,connection:n.connection};return{projects:await wa(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Cr=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Pr(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 Bn(e,t,n,o){ha(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Tr(e,t){let n;try{n=await ct(e,t)}catch(g){console.log(v(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===s?A("\u25CF"):" "} ${Cr(g)} ${f(g.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await ma({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${Cr(g)}${g.id===s?" (current)":""}`,value:g.id}))}),p=o.find(g=>g.id===c);Bn(e,r,c,p?.name),console.log(D(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}H();import ya from"picocolors";function ka(e=process.env){return e.FORCE_HYPERLINK==="0"||!ya.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 xa(e,t=e,n){return ka(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var ba=/https?:\/\/[^\s\x1b]+/g;function xt(e,t){return e.replace(ba,n=>xa(n,n,t))}function Ar(e){return{...Sr(e.idToken)??{},...Sr(e.accessToken)??{}}}function Xt(e){let t=Ar(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 Jt(e){let t=Kt(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 va(n,{manual:e.manual,promptForRedirect:s=>$a({message:s})},s=>console.log(xt(s))),r=Rr(t.name,o);if(jr(r),await Qt(r,t.name,s=>console.log(f(s))),console.log(""),console.log(D(`\u2713 Logged in to "${t.name}" as ${Xt(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{ja(process.cwd())?.profiles?.[t.name]&&(console.log(""),await lt(process.cwd(),t.name))}catch{}}async function Qt(e,t,n){let r=Ar(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Kt(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await ct(process.cwd(),t);c=p.find(g=>g.id===r)?.name}catch{}Ra(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Dr(e){let t=Kt(process.cwd(),e.profile),n=t.connection,o=Sa(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 ${A(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Xt(o)}`),Ta(o))if(o.refreshToken)try{let r=Rr(t.name,await Ca(n,o.refreshToken));jr(r),console.log(D(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(L("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function Er(e){let t=Kt(process.cwd(),e.profile);Pa(t.name)?console.log(D(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}H();import{readProjectConfig as Ir,writeProjectConfig as Aa,resolveActiveProfile as Da,loadTokens as Ea,isExpired as Ia}from"document360-engine";function Zt(e){let t=Ir(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?A("\u25CF "):" ",s=o.production?L(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Ea(n),g=p?Ia(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${A(n)} \u2192 ${c}${s} [${g}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function en(e,t){let n=Ir(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,Aa(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(D(`\u2713 Default profile is now "${t}"${o}`))}function tn(e,t){try{let n=Da(e,t);console.log(""),console.log(`Profile ${A(n.name)}${n.production?L(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(v(n.message)),process.exitCode=1}}H();import{existsSync as Na,readdirSync as _a,statSync as Oa}from"node:fs";import{join as Ma}from"node:path";import{apiLogDir as La}from"document360-engine";function Nr(){let e=La();if(console.log(""),console.log(`Document360 API logs: ${A(e)}`),!Na(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=_a(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=(Oa(Ma(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("")}H();import{createSession as Ua,resolveAuth as Wa,findByName as Fa,slugify as Ha,touchSession as Ba,upsertSession as qa,resolveActiveProfile as Ga}from"document360-engine";async function _r(e,t,n,o,r,s){let c=Wa(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 ${A("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${A("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Ga(e,r)}catch(k){console.error(v(`Document360 profile error: ${k.message}`)),process.exit(2)}p.production&&(console.error(L(`\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 g;if(o){let k=Fa(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)),g=k.uuid,console.error(f(`Resuming "${k.name}"`))}let w=Ua({cwd:e,resume:g,profileName:r,allowProdWrites:s===!0}),x=g??null,j=1;for await(let k of w.send(t))switch(k.type){case"session":if(!x){x=k.sessionId;let C=new Date().toISOString();qa({uuid:x,name:Ha(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(ee(` \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)}x&&Ba(x),process.stdout.write(`
3
+ `),process.exit(j)}import{createInterface as iu}from"node:readline/promises";import{createSession as Fo,resolveAuth as au,getSession as lu,setTitle as cu,slugify as uu,touchSession as di,upsertSession as du,generateTitle as pu,resolveActiveProfile as pi,resolveModelSetting as fu,readProjectConfig as mu,decodeJwtClaims as ci,isExpired as gu,loadTokens as hu}from"document360-engine";var bt=[{name:"init",usage:"/init",desc:"Pick an environment & scaffold .d360-writer.json",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:"Set up the dev\u2192docs hint channel (guide + paste block for your repo agent)",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:"write",usage:"/write [--all|--scope <cat>|<path>] [--run]",desc:"Author the planned articles in parallel (bare = preview + cost; --run starts)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"audit",usage:"/audit",desc:"Gap analysis: code vs docs vs Document360 (what changed)",group:"publish"},{name:"sync",usage:"/sync [pull <path>|--all]",desc:"Drift report local vs Document360; pull portal edits",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"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"}],Ya=[{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 nn(){let e=Math.max(...bt.map(n=>n.usage.length))+2,t=["document360-writer \u2014 commands","",'New here? /init \u2192 "write the docs for this repo" \u2192 /publish',""," Screenshots are optional \u2014 add them anytime:"," /screenshot --all \u2192 d360-capture capture \u2192 re-/publish"];for(let{key:n,label:o}of Ya){t.push("",o);for(let r of bt.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 Or(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return bt.filter(n=>n.name.startsWith(t))}function Mr(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}async function qn(){console.log("");for(let e of nn())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}H();import{getSession as za}from"document360-engine";async function Lr(e,t){let n=t.currentUuid(),o=n?za(n):void 0;return console.log(o?f(`
4
4
  (conversation reset \u2014 "${o.name}" is still available via /resume)
5
5
  `):f(`
6
6
  (conversation reset \u2014 agent will start fresh on the next prompt)
7
- `)),{kind:"clear"}}async function Gn(){return{kind:"exit"}}H();import{input as $t,confirm as Va}from"@inquirer/prompts";import{basename as Ur,join as on}from"node:path";import{existsSync as ut,readFileSync as Xa,readdirSync as Ka,writeFileSync as Ja}from"node:fs";import{writeProjectConfig as Wr,readProjectConfig as Qa,projectConfigPath as Fr,writerDir as Za,DEFAULT_DOCS_DIR as Hr,DEFAULT_CAPTURE_DIR as Br,DEFAULT_OUTPUT_DIR as qr}from"document360-engine";function Gr(e,t="berlin"){let n=Fr(e);if(ut(n))return{created:!1,path:n,profileName:""};let o={projectId:Vr(e)??Ur(e),docsDir:Hr,captureDir:Br,outputDir:qr,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Xr(e)};return Wr(o,e),Yr(e),{created:!0,path:n,profileName:t}}function Yr(e){let t=on(Za(e),".gitignore");ut(t)||Ja(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
8
- `),"utf8")}async function zr(){let e=process.cwd(),t=Fr(e);if(ut(t)&&!await Va({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Vr(e)??Ur(e),o=await $t({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await $t({message:"Capture directory (where document360-capture .spec.ts files live):",default:Br}),s=await $t({message:"Screenshot output directory:",default:qr}),c=await $t({message:"Default connection profile name:",default:"berlin"}),p=await $t({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:Hr,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Xr(e)},w=Qa(e);return w?.terminologyGlossary&&(g.terminologyGlossary=w.terminologyGlossary),Wr(g,e),Yr(e),console.log(""),console.log(D(`\u2713 Wrote ${t}`)),console.log(""),console.log("Next:"),console.log(` ${A(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log(` Then in d360-writer run ${A("/devhints")} ${f("(builder hands over an architecture brief \u2014 best docs)")}, and ask: "write the user docs for this repo"`),console.log(""),{kind:"continue"}}function Vr(e){let t=on(e,"package.json");if(!ut(t))return null;try{return JSON.parse(Xa(t,"utf8")).name??null}catch{return null}}function Xr(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])ut(on(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=on(e,n);ut(o)&&!el(o)&&t.push(n)}return t}function el(e){try{return Ka(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}H();import{readMcpConfig as Yn,writeMcpConfig as Kr}from"document360-engine";async function rn(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(tl(),{kind:"continue"}):t==="add"?(nl(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(ol(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 tl(){let e=Yn(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
7
+ `)),{kind:"clear"}}async function Gn(){return{kind:"exit"}}H();import{input as $t,confirm as Va}from"@inquirer/prompts";import{basename as Ur,join as on}from"node:path";import{existsSync as ut,readFileSync as Ka,readdirSync as Xa,writeFileSync as Ja}from"node:fs";import{writeProjectConfig as Wr,readProjectConfig as Qa,projectConfigPath as Fr,writerDir as Za,DEFAULT_DOCS_DIR as Hr,DEFAULT_CAPTURE_DIR as Br,DEFAULT_OUTPUT_DIR as qr}from"document360-engine";function Gr(e,t="berlin"){let n=Fr(e);if(ut(n))return{created:!1,path:n,profileName:""};let o={projectId:Vr(e)??Ur(e),docsDir:Hr,captureDir:Br,outputDir:qr,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Kr(e)};return Wr(o,e),Yr(e),{created:!0,path:n,profileName:t}}function Yr(e){let t=on(Za(e),".gitignore");ut(t)||Ja(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
8
+ `),"utf8")}async function zr(){let e=process.cwd(),t=Fr(e);if(ut(t)&&!await Va({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Vr(e)??Ur(e),o=await $t({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await $t({message:"Capture directory (where document360-capture .spec.ts files live):",default:Br}),s=await $t({message:"Screenshot output directory:",default:qr}),c=await $t({message:"Default connection profile name:",default:"berlin"}),p=await $t({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:Hr,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Kr(e)},w=Qa(e);return w?.terminologyGlossary&&(g.terminologyGlossary=w.terminologyGlossary),Wr(g,e),Yr(e),console.log(""),console.log(D(`\u2713 Wrote ${t}`)),console.log(""),console.log("Next:"),console.log(` ${A(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log(` Then in d360-writer run ${A("/devhints")} ${f("(builder hands over an architecture brief \u2014 best docs)")}, and ask: "write the user docs for this repo"`),console.log(""),{kind:"continue"}}function Vr(e){let t=on(e,"package.json");if(!ut(t))return null;try{return JSON.parse(Ka(t,"utf8")).name??null}catch{return null}}function Kr(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])ut(on(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=on(e,n);ut(o)&&!el(o)&&t.push(n)}return t}function el(e){try{return Xa(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}H();import{readMcpConfig as Yn,writeMcpConfig as Xr}from"document360-engine";async function rn(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(tl(),{kind:"continue"}):t==="add"?(nl(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(ol(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 tl(){let e=Yn(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
9
9
  No MCP servers registered. Add one with /mcp add <name> <type> <ref>
10
- `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${A(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${A(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function nl(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=Yn(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let g=o[++p],w=g?.match(/^([^:=]+)[:=](.+)$/);if(!w){console.log(v(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}c[w[1].trim()]=w[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,Kr(r),console.log(""),console.log(D(`\u2713 Registered "${t}" (${n})`)),console.log(L(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function ol(e){let t=e[0];if(!t){console.log(v("Usage: /mcp remove <name>"));return}let n=Yn();if(!n.servers[t]){console.log(v(`No server named "${t}".`));return}delete n.servers[t],Kr(n),console.log(D(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}H();import{select as ml}from"@inquirer/prompts";import{computeSyncStatus as to,planPartitions as gl,relatedArticlePaths as hl,resolveModelForOperation as wl,runPartitioned as yl}from"document360-engine";import q from"picocolors";import ns from"wrap-ansi";import Qn from"string-width";H();import De from"picocolors";import zn from"wrap-ansi";import Vn from"string-width";var Jr=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Qr=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Zr=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function rl(e){let t=e.replace(/\r/g,"").split(`
11
- `),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(Jr(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Qr(t[o+1])){let p=Zr(r);o+=2;let g=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)g.push(Zr(t[o++]));n.push({kind:"table",header:p,rows:g});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);)p.push(t[o++].replace(/^\s*([-*]|\d+\.)\s+/,""));n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Jr(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Qr(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function Xn(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?De.bold(t.slice(2,-2)):t.startsWith("`")?A(t.slice(1,-1)):De.italic(t.slice(1,-1)))}var sl=(e,t)=>e+" ".repeat(Math.max(0,t-Vn(e)));function il(e,t,n){let o=e.length,r=e.map((P,N)=>Math.max(Vn(P),...t.map(_=>Vn(_[N]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],g=()=>p.reduce((P,N)=>P+N,0)+c,w=0;for(;g()>s&&w++<1e4;){let P=-1,N=6;for(let _=0;_<o;_++)p[_]>N&&(N=p[_],P=_);if(P===-1)break;p[P]-=1}let b=(P,N,_)=>De.gray(P+p.map(W=>"\u2500".repeat(W+2)).join(N)+_),j=De.gray("\u2502"),k=(P,N)=>{let _=p.map((be,te)=>{let we=P[te]??"",re=N?De.bold(we):Xn(we);return zn(re,be,{hard:!0}).split(`
12
- `)}),W=Math.max(..._.map(be=>be.length)),Z=[];for(let be=0;be<W;be++)Z.push(p.map((te,we)=>`${j} ${sl(_[we][be]??"",te)} `).join("")+j);return Z.join(`
13
- `)},C=[b("\u250C","\u252C","\u2510"),k(e,!0)];return C.push(t.length===0?b("\u2514","\u2534","\u2518"):b("\u251C","\u253C","\u2524")),t.forEach((P,N)=>{C.push(k(P,!1)),C.push(N===t.length-1?b("\u2514","\u2534","\u2518"):b("\u251C","\u253C","\u2524"))}),C.join(`
14
- `)}function al(e,t){switch(e.kind){case"heading":return De.bold(e.text);case"hr":return De.gray("\u2500".repeat(t));case"para":return zn(Xn(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=zn(Xn(n),Math.max(10,t-4)).split(`
10
+ `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${A(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${A(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function nl(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=Yn(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let g=o[++p],w=g?.match(/^([^:=]+)[:=](.+)$/);if(!w){console.log(v(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}c[w[1].trim()]=w[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,Xr(r),console.log(""),console.log(D(`\u2713 Registered "${t}" (${n})`)),console.log(L(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function ol(e){let t=e[0];if(!t){console.log(v("Usage: /mcp remove <name>"));return}let n=Yn();if(!n.servers[t]){console.log(v(`No server named "${t}".`));return}delete n.servers[t],Xr(n),console.log(D(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}H();import{select as ml}from"@inquirer/prompts";import{computeSyncStatus as to,planPartitions as gl,relatedArticlePaths as hl,resolveModelForOperation as wl,runPartitioned as yl}from"document360-engine";import q from"picocolors";import ns from"wrap-ansi";import Qn from"string-width";H();import De from"picocolors";import zn from"wrap-ansi";import Vn from"string-width";var Jr=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Qr=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Zr=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function rl(e){let t=e.replace(/\r/g,"").split(`
11
+ `),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(Jr(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Qr(t[o+1])){let p=Zr(r);o+=2;let g=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)g.push(Zr(t[o++]));n.push({kind:"table",header:p,rows:g});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);)p.push(t[o++].replace(/^\s*([-*]|\d+\.)\s+/,""));n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Jr(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Qr(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function Kn(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?De.bold(t.slice(2,-2)):t.startsWith("`")?A(t.slice(1,-1)):De.italic(t.slice(1,-1)))}var sl=(e,t)=>e+" ".repeat(Math.max(0,t-Vn(e)));function il(e,t,n){let o=e.length,r=e.map((P,N)=>Math.max(Vn(P),...t.map(_=>Vn(_[N]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],g=()=>p.reduce((P,N)=>P+N,0)+c,w=0;for(;g()>s&&w++<1e4;){let P=-1,N=6;for(let _=0;_<o;_++)p[_]>N&&(N=p[_],P=_);if(P===-1)break;p[P]-=1}let x=(P,N,_)=>De.gray(P+p.map(W=>"\u2500".repeat(W+2)).join(N)+_),j=De.gray("\u2502"),k=(P,N)=>{let _=p.map((xe,te)=>{let we=P[te]??"",re=N?De.bold(we):Kn(we);return zn(re,xe,{hard:!0}).split(`
12
+ `)}),W=Math.max(..._.map(xe=>xe.length)),Z=[];for(let xe=0;xe<W;xe++)Z.push(p.map((te,we)=>`${j} ${sl(_[we][xe]??"",te)} `).join("")+j);return Z.join(`
13
+ `)},C=[x("\u250C","\u252C","\u2510"),k(e,!0)];return C.push(t.length===0?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524")),t.forEach((P,N)=>{C.push(k(P,!1)),C.push(N===t.length-1?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524"))}),C.join(`
14
+ `)}function al(e,t){switch(e.kind){case"heading":return De.bold(e.text);case"hr":return De.gray("\u2500".repeat(t));case"para":return zn(Kn(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=zn(Kn(n),Math.max(10,t-4)).split(`
15
15
  `);return" \u2022 "+o+r.map(s=>`
16
16
  `+s).join("")}).join(`
17
17
  `);case"code":return e.lines.map(n=>De.gray(" "+n)).join(`
18
- `);case"table":return il(e.header,e.rows,t)}}function Kn(e,t){let n=Math.max(20,t);return rl(e).map(o=>al(o,n)).join(`
18
+ `);case"table":return il(e.header,e.rows,t)}}function Xn(e,t){let n=Math.max(20,t);return rl(e).map(o=>al(o,n)).join(`
19
19
 
20
20
  `)}H();import ll from"picocolors";var cl=[127,86,217],ul=[22,38,43],es={T:cl,E:ul},vt=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Jn=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,dl=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function ts(){if(!ll.isColorSupported)return[];let e=vt[0].length,t=[];for(let n=0;n<vt.length;n+=2){let o="";for(let r=0;r<e;r++){let s=es[vt[n][r]],c=n+1<vt.length?es[vt[n+1][r]]:void 0;s&&c?o+=`${Jn(s)}${dl(c)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Jn(s)}\u2580\x1B[39m`:c?o+=`${Jn(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Ct(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function ae(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Ee(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var dt=(e,t)=>` ${e.padEnd(13)}${t}`;function pl(e,t){let n=[yt("\u270E document360-writer")+q.gray(` v${e.version}`),q.gray(" Reads your code, writes your docs."),"",dt("Claude:",`${e.claude}${q.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),dt("Document360:",e.configured?e.loggedOut?q.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?q.gray(` (${e.sessionHint})`):""}`:q.yellow("not set up \u2014 run /init")),dt("Profile:",e.configured?`${e.profile}${q.gray(` (${e.apiUrl})`)}${e.prod?q.bold(q.yellow(" \u26A0 PRODUCTION")):""}`:q.gray("\u2014 (run /init)")),dt("Project:",e.project),dt("Mode:",q.gray(e.mode)),dt("cwd:",q.gray(e.cwd))],o=ts();if(o.length===0)return n.join(`
21
- `);let r=2,s=3,c=Qn(o[0]);if(!(t>=r+c+s+Math.max(...n.map(b=>Qn(b)))))return[...o.map(b=>" "+b),...n].join(`
22
- `);let g=Math.max(0,Math.floor((n.length-o.length)/2)),w=[];for(let b=0;b<Math.max(o.length+g,n.length);b++){let j=o[b-g]??" ".repeat(c);w.push((" ".repeat(r)+j+" ".repeat(s)+(n[b]??"")).trimEnd())}return w.join(`
21
+ `);let r=2,s=3,c=Qn(o[0]);if(!(t>=r+c+s+Math.max(...n.map(x=>Qn(x)))))return[...o.map(x=>" "+x),...n].join(`
22
+ `);let g=Math.max(0,Math.floor((n.length-o.length)/2)),w=[];for(let x=0;x<Math.max(o.length+g,n.length);x++){let j=o[x-g]??" ".repeat(c);w.push((" ".repeat(r)+j+" ".repeat(s)+(n[x]??"")).trimEnd())}return w.join(`
23
23
  `)}var fl={error:q.red,warn:q.yellow,ok:q.green,info:q.gray};function Zn(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return pl(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(`
24
24
  `).flatMap(w=>ns(w,s,{hard:!0}).split(`
25
25
  `)),g=Math.max(0,p.length-c);return g>0&&(p=[...p.slice(0,c),q.dim(`\u2026 +${g} more lines`)]),`
26
- `+p.map((w,b)=>o+(b===0?A(" \u276F "):" ")+w+" ".repeat(Math.max(0,s-Qn(w))+1)+r).join(`
26
+ `+p.map((w,x)=>o+(x===0?A(" \u276F "):" ")+w+" ".repeat(Math.max(0,s-Qn(w))+1)+r).join(`
27
27
  `)}case"assistant":return`
28
- `+Kn(e.text,n);case"tool":{let o=e.arg!==null?q.gray(`${e.sep}(${e.arg})`):"";return`
28
+ `+Xn(e.text,n);case"tool":{let o=e.arg!==null?q.gray(`${e.sep}(${e.arg})`):"";return`
29
29
  `+ns(q.green("\u25CF ")+q.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?q.red:q.gray,r=e.lines.map((s,c)=>o((c===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(q.dim(` \u2026 +${e.hidden} lines`)),r.join(`
30
30
  `)}case"diff":{let o=c=>c===1?"":"s",s=[q.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(q.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
31
- `)}case"link":return e.lines.map(o=>A(bt(` \u2B95 ${o}`))).join(`
31
+ `)}case"link":return e.lines.map(o=>A(xt(` \u2B95 ${o}`))).join(`
32
32
  `);case"preview":return`
33
33
  `+yt(`\u25A3 Preview \u2014 ${e.name}`)+`
34
34
 
35
- `+Kn(e.text,n);case"note":return`
36
- `+fl[e.tone](bt(e.text));case"done":return`
35
+ `+Xn(e.text,n);case"note":return`
36
+ `+fl[e.tone](xt(e.text));case"done":return`
37
37
  `+(e.ok?q.magenta("\u2736 "):q.red("\u2736 "))+q.gray(`Cooked for ${Ct(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${ae(e.costUsd)}`:""))}}function os(e,t){return e.map(n=>Zn(n,t)).join(`
38
38
  `)}var Pt=3;function no(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(`
39
39
  `)}var rs={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Tt(e){return e.filter(t=>t.path!==null&&t.status in rs).map(t=>({path:t.path,label:rs[t.status]}))}function kl(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 ss(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:`${kl(o)} (${r.length})`,paths:r.map(s=>s.path),indent:!1});for(let s of r){let c=s.path.replace(/\\/g,"/").split("/").pop()??s.path;t.push({kind:"article",label:c,paths:[s.path],indent:!0,note:s.label})}}return t}function sn(e){return[`Run the publish-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures) and remind me drafts need review in the portal."].join(`
40
- `)}function oo(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),g=n==="api"?`${ae(e.reduce((k,C)=>k+C.costUsd,0))} total`:Ee(e.reduce((k,C)=>k+C.outputTokens,0)),w=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,b=k=>`${k} article${k===1?"":"s"}`,j=[];if(s.length===0)j.push(`Published ${b(c)} (${w}) successfully \xB7 ${g}.`),j.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{j.push(`Published ${p}/${b(c)} (${w}) \xB7 ${g}.`),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 eo(e,t){let n=gl(t),{model:o}=wl(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${Pt} 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 yl({cwd:e.cwd,partitions:n,promptFor:s=>sn(s.paths),concurrency:Pt,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(D(` \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 c of oo(r.results,n,s))console.log(r.ok?D(c):L(c))}}catch(r){console.log(v(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function an(e,t,n){let o=hl(e,n);if(o.length===0)return[];let r=new Set(Tt((await to({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function is(e,t){let n=e[0];if(n==="--related"&&e[1]){if(!t)return{kind:"continue"};let o=await an(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return o.length===0?(console.log(D("\u2713 All related articles are already published.")),{kind:"continue"}):await eo(t,o)}if(n==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let o=Tt((await to({cwd:t?.cwd??process.cwd()})).entries);return o.length===0?(console.log(D("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):t?await eo(t,o.map(r=>r.path)):{kind:"forward-to-agent",prompt:sn(o.map(r=>r.path)),display:"/publish --all"}}catch(o){return console.log(v(`Could not compute sync status: ${o.message}`)),{kind:"continue"}}}if(!n){console.log(f("Checking what needs publishing\u2026"));let o;try{o=Tt((await to({cwd:t?.cwd??process.cwd()})).entries)}catch(r){return console.log(v(`Could not compute sync status: ${r.message}`)),console.log(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(o.length===0)return console.log(D("\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 r of o)console.log(` ${r.path} ${f(`(${r.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{n=await t.withPausedInput(()=>ml({message:"Publish which article?",choices:[...o.length>1?[{name:`All ${o.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...o.map(r=>({name:r.path,value:r.path,description:r.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(n==="--all")return await eo(t,o.map(r=>r.path))}return{kind:"forward-to-agent",prompt:no(n),display:`/publish ${n}`}}async function ln(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | adopt) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
41
- `),display:"/audit"}}H();import{checkbox as bl}from"@inquirer/prompts";import{inventoryRepo as xl,readProjectConfig as as,writeProjectConfig as $l}from"document360-engine";function ro(e,t){let n=as(e);n&&(n.authoritativeSourceFiles=t,$l(n,e))}function cn(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 ls(e,t){let n=t?.cwd??process.cwd();if(!as(n))return console.log(v("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=xl(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(A("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(cn(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>bl({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${cn(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"};ro(n,r),console.log(D(`\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"}}H();import{confirm as Sl}from"@inquirer/prompts";import{applyPull as fs,computeSyncStatus as ms,planPull as Rl,D360AuthError as jl}from"document360-engine";H();var cs=[{status:"conflict",header:"Conflicts \u2014 both sides changed; pick a direction (/sync pull <path> or /publish <path>):",paint:v,mark:"!"},{status:"local-ahead",header:"Local ahead \u2014 push with /publish <path>:",paint:L,mark:"M"},{status:"remote-ahead",header:"Remote ahead \u2014 pull with /sync pull <path>:",paint:A,mark:"M"},{status:"deleted-local",header:"Deleted locally \u2014 still on Document360 (pull to restore, or remove from the map):",paint:v,mark:"D"},{status:"deleted-remote",header:"Deleted on Document360 \u2014 still local (publish to recreate, or delete the file):",paint:v,mark:"D"},{status:"orphaned",header:"Orphaned map entries \u2014 gone on both sides (remove from d360-category-map.json):",paint:ee,mark:"X"},{status:"untracked-local",header:"Untracked local articles \u2014 publish to start tracking:",paint:f,mark:"?"},{status:"untracked-remote",header:"Untracked Document360 articles \u2014 no local file maps to them:",paint:f,mark:"?"},{status:"unknown-base",header:"No sync base recorded yet \u2014 the next /publish or /sync pull of each records one:",paint:ee,mark:"\xB7"}];function vl(e){return e.path?e.path:`${e.title??"(untitled)"} ${ee(`[${e.articleId}]`)}`}function un(e){let t=[];for(let c of cs){let p=e.entries.filter(g=>g.status===c.status);if(p.length!==0){t.push(""),t.push(Ce(c.header));for(let g of p)t.push(` ${c.paint(c.mark)} ${c.paint(vl(g))}${g.detail?ee(` (${g.detail})`):""}`)}}let n=e.counts["in-sync"]??0,o=e.entries.length;t.push("");let r={"in-sync":"in sync","local-ahead":"local ahead","remote-ahead":"remote ahead",conflict:"conflicts","untracked-local":"untracked local","untracked-remote":"untracked remote","deleted-local":"deleted locally","deleted-remote":"deleted on D360",orphaned:"orphaned","unknown-base":"no base yet"},s=o===n?D("\u2713 everything in sync"):[n>0?D(`\u2713 ${n} in sync`):null,...cs.map(c=>{let p=e.counts[c.status]??0;return p>0?`${p} ${r[c.status]}`:null})].filter(Boolean).join(ee(" \xB7 "));return t.push(s+ee(` \xB7 ${o} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/`)),t}import{structuredPatch as Cl}from"diff";import us from"picocolors";var ds=80,Pl="\x1B[48;2;74;28;28m",Tl="\x1B[48;2;24;66;24m",ps="\x1B[49m",so=e=>String(e).padStart(5);function qe(e,t,n){let o=k=>{let C=k.replace(/\r\n/g,`
40
+ `)}function oo(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),g=n==="api"?`${ae(e.reduce((k,C)=>k+C.costUsd,0))} total`:Ee(e.reduce((k,C)=>k+C.outputTokens,0)),w=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,x=k=>`${k} article${k===1?"":"s"}`,j=[];if(s.length===0)j.push(`Published ${x(c)} (${w}) successfully \xB7 ${g}.`),j.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{j.push(`Published ${p}/${x(c)} (${w}) \xB7 ${g}.`),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 eo(e,t){let n=gl(t),{model:o}=wl(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${Pt} 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 yl({cwd:e.cwd,partitions:n,promptFor:s=>sn(s.paths),concurrency:Pt,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(D(` \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 c of oo(r.results,n,s))console.log(r.ok?D(c):L(c))}}catch(r){console.log(v(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function an(e,t,n){let o=hl(e,n);if(o.length===0)return[];let r=new Set(Tt((await to({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function is(e,t){let n=e[0];if(n==="--related"&&e[1]){if(!t)return{kind:"continue"};let o=await an(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return o.length===0?(console.log(D("\u2713 All related articles are already published.")),{kind:"continue"}):await eo(t,o)}if(n==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let o=Tt((await to({cwd:t?.cwd??process.cwd()})).entries);return o.length===0?(console.log(D("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):t?await eo(t,o.map(r=>r.path)):{kind:"forward-to-agent",prompt:sn(o.map(r=>r.path)),display:"/publish --all"}}catch(o){return console.log(v(`Could not compute sync status: ${o.message}`)),{kind:"continue"}}}if(!n){console.log(f("Checking what needs publishing\u2026"));let o;try{o=Tt((await to({cwd:t?.cwd??process.cwd()})).entries)}catch(r){return console.log(v(`Could not compute sync status: ${r.message}`)),console.log(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(o.length===0)return console.log(D("\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 r of o)console.log(` ${r.path} ${f(`(${r.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{n=await t.withPausedInput(()=>ml({message:"Publish which article?",choices:[...o.length>1?[{name:`All ${o.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...o.map(r=>({name:r.path,value:r.path,description:r.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(n==="--all")return await eo(t,o.map(r=>r.path))}return{kind:"forward-to-agent",prompt:no(n),display:`/publish ${n}`}}async function ln(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | adopt) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
41
+ `),display:"/audit"}}H();import{checkbox as xl}from"@inquirer/prompts";import{inventoryRepo as bl,readProjectConfig as as,writeProjectConfig as $l}from"document360-engine";function ro(e,t){let n=as(e);n&&(n.authoritativeSourceFiles=t,$l(n,e))}function cn(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 ls(e,t){let n=t?.cwd??process.cwd();if(!as(n))return console.log(v("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=bl(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(A("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(cn(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>xl({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${cn(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"};ro(n,r),console.log(D(`\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"}}H();import{confirm as Sl}from"@inquirer/prompts";import{applyPull as fs,computeSyncStatus as ms,planPull as Rl,D360AuthError as jl}from"document360-engine";H();var cs=[{status:"conflict",header:"Conflicts \u2014 both sides changed; pick a direction (/sync pull <path> or /publish <path>):",paint:v,mark:"!"},{status:"local-ahead",header:"Local ahead \u2014 push with /publish <path>:",paint:L,mark:"M"},{status:"remote-ahead",header:"Remote ahead \u2014 pull with /sync pull <path>:",paint:A,mark:"M"},{status:"deleted-local",header:"Deleted locally \u2014 still on Document360 (pull to restore, or remove from the map):",paint:v,mark:"D"},{status:"deleted-remote",header:"Deleted on Document360 \u2014 still local (publish to recreate, or delete the file):",paint:v,mark:"D"},{status:"orphaned",header:"Orphaned map entries \u2014 gone on both sides (remove from d360-category-map.json):",paint:ee,mark:"X"},{status:"untracked-local",header:"Untracked local articles \u2014 publish to start tracking:",paint:f,mark:"?"},{status:"untracked-remote",header:"Untracked Document360 articles \u2014 no local file maps to them:",paint:f,mark:"?"},{status:"unknown-base",header:"No sync base recorded yet \u2014 the next /publish or /sync pull of each records one:",paint:ee,mark:"\xB7"}];function vl(e){return e.path?e.path:`${e.title??"(untitled)"} ${ee(`[${e.articleId}]`)}`}function un(e){let t=[];for(let c of cs){let p=e.entries.filter(g=>g.status===c.status);if(p.length!==0){t.push(""),t.push(Ce(c.header));for(let g of p)t.push(` ${c.paint(c.mark)} ${c.paint(vl(g))}${g.detail?ee(` (${g.detail})`):""}`)}}let n=e.counts["in-sync"]??0,o=e.entries.length;t.push("");let r={"in-sync":"in sync","local-ahead":"local ahead","remote-ahead":"remote ahead",conflict:"conflicts","untracked-local":"untracked local","untracked-remote":"untracked remote","deleted-local":"deleted locally","deleted-remote":"deleted on D360",orphaned:"orphaned","unknown-base":"no base yet"},s=o===n?D("\u2713 everything in sync"):[n>0?D(`\u2713 ${n} in sync`):null,...cs.map(c=>{let p=e.counts[c.status]??0;return p>0?`${p} ${r[c.status]}`:null})].filter(Boolean).join(ee(" \xB7 "));return t.push(s+ee(` \xB7 ${o} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/`)),t}import{structuredPatch as Cl}from"diff";import us from"picocolors";var ds=80,Pl="\x1B[48;2;74;28;28m",Tl="\x1B[48;2;24;66;24m",ps="\x1B[49m",so=e=>String(e).padStart(5);function qe(e,t,n){let o=k=>{let C=k.replace(/\r\n/g,`
42
42
  `);return C.endsWith(`
43
43
  `)||C===""?C:C+`
44
- `},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=Cl("a","b",r,s,"","",{context:3}),g=0,w=0,b=[];p.hunks.forEach((k,C)=>{C>0&&b.push(us.gray(" \u2026"));let P=k.oldStart,N=k.newStart;for(let _ of k.lines){let W=_[0],Z=_.slice(1).slice(0,c);W==="-"?(w++,b.push(`${Pl}${so(P++)} - ${Z}${ps}`)):W==="+"?(g++,b.push(`${Tl}${so(N++)} + ${Z}${ps}`)):(b.push(us.gray(so(N))+" "+Z),P++,N++)}});let j=b.slice(0,ds);return{added:g,removed:w,lines:j,hidden:Math.max(0,b.length-ds)}}async function gs(e,t){let n=(e[0]??"status").toLowerCase();try{if(n==="status")return await Al(t.cwd),{kind:"continue"};if(n==="pull")return await Dl(t,e.slice(1)),{kind:"continue"};console.log(v(`Unknown subcommand: /sync ${n}`)),console.log(f("Usage: /sync drift report (local vs Document360)")),console.log(f(" /sync pull <path> pull portal edits into the local file")),console.log(f(" /sync pull --all pull every remote-ahead article"))}catch(o){o instanceof jl?console.log(v(o.message)):console.log(v(`Sync failed: ${o.message}`))}return{kind:"continue"}}async function Al(e){console.log(f("Checking Document360 for drift\u2026"));let t=await ms({cwd:e});for(let n of un(t))console.log(n);console.log("")}async function Dl(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 ms({cwd:e.cwd})).entries.filter(s=>s.status==="remote-ahead"&&s.path).map(s=>s.path),o.length===0){console.log(D("\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(`${Ce(String(o.length))} article(s) are remote-ahead.`)}else o=[n.replace(/\\/g,"/")];for(let r of o){let s=await Rl({cwd:e.cwd,relPath:r});console.log(""),console.log(`${A("\u25CF")} ${Ce(s.title)} ${ee(`(${s.path})`)}`);for(let w of s.notes)console.log(L(` \u26A0 ${w}`));s.overwritesLocalChanges&&console.log(L(" \u26A0 This OVERWRITES local edits made since the last sync."));let c=qe(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.")),fs({cwd:e.cwd},s);continue}let p=w=>w===1?"":"s";console.log(ee(` \u23BF Added ${c.added} line${p(c.added)}, removed ${c.removed} line${p(c.removed)}`));for(let w of c.lines)console.log(w);if(c.hidden>0&&console.log(f(` \u2026 +${c.hidden} more diff lines`)),!await e.withPausedInput(()=>Sl({message:`Write ${s.path}?`,default:!s.overwritesLocalChanges}))){console.log(f(" Skipped."));continue}fs({cwd:e.cwd},s),console.log(D(` \u2713 Pulled ${s.path} (sync base advanced).`))}console.log("")}H();import{statSync as El}from"node:fs";import{resolve as Il}from"node:path";import{estimateBulkCost as Nl,planPartitions as _l,readProjectConfig as Ol,resolveModelForOperation as Ml,runPartitioned as Ll,trackedArticlePaths as Ul}from"document360-engine";var io=3;function ao(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 lo(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function co(e,t){return t.map(n=>{let o=0;try{o=El(Il(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function uo(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:
44
+ `},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=Cl("a","b",r,s,"","",{context:3}),g=0,w=0,x=[];p.hunks.forEach((k,C)=>{C>0&&x.push(us.gray(" \u2026"));let P=k.oldStart,N=k.newStart;for(let _ of k.lines){let W=_[0],Z=_.slice(1).slice(0,c);W==="-"?(w++,x.push(`${Pl}${so(P++)} - ${Z}${ps}`)):W==="+"?(g++,x.push(`${Tl}${so(N++)} + ${Z}${ps}`)):(x.push(us.gray(so(N))+" "+Z),P++,N++)}});let j=x.slice(0,ds);return{added:g,removed:w,lines:j,hidden:Math.max(0,x.length-ds)}}async function gs(e,t){let n=(e[0]??"status").toLowerCase();try{if(n==="status")return await Al(t.cwd),{kind:"continue"};if(n==="pull")return await Dl(t,e.slice(1)),{kind:"continue"};console.log(v(`Unknown subcommand: /sync ${n}`)),console.log(f("Usage: /sync drift report (local vs Document360)")),console.log(f(" /sync pull <path> pull portal edits into the local file")),console.log(f(" /sync pull --all pull every remote-ahead article"))}catch(o){o instanceof jl?console.log(v(o.message)):console.log(v(`Sync failed: ${o.message}`))}return{kind:"continue"}}async function Al(e){console.log(f("Checking Document360 for drift\u2026"));let t=await ms({cwd:e});for(let n of un(t))console.log(n);console.log("")}async function Dl(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 ms({cwd:e.cwd})).entries.filter(s=>s.status==="remote-ahead"&&s.path).map(s=>s.path),o.length===0){console.log(D("\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(`${Ce(String(o.length))} article(s) are remote-ahead.`)}else o=[n.replace(/\\/g,"/")];for(let r of o){let s=await Rl({cwd:e.cwd,relPath:r});console.log(""),console.log(`${A("\u25CF")} ${Ce(s.title)} ${ee(`(${s.path})`)}`);for(let w of s.notes)console.log(L(` \u26A0 ${w}`));s.overwritesLocalChanges&&console.log(L(" \u26A0 This OVERWRITES local edits made since the last sync."));let c=qe(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.")),fs({cwd:e.cwd},s);continue}let p=w=>w===1?"":"s";console.log(ee(` \u23BF Added ${c.added} line${p(c.added)}, removed ${c.removed} line${p(c.removed)}`));for(let w of c.lines)console.log(w);if(c.hidden>0&&console.log(f(` \u2026 +${c.hidden} more diff lines`)),!await e.withPausedInput(()=>Sl({message:`Write ${s.path}?`,default:!s.overwritesLocalChanges}))){console.log(f(" Skipped."));continue}fs({cwd:e.cwd},s),console.log(D(` \u2713 Pulled ${s.path} (sync base advanced).`))}console.log("")}H();import{statSync as El}from"node:fs";import{resolve as Il}from"node:path";import{estimateBulkCost as Nl,planPartitions as _l,readProjectConfig as Ol,resolveModelForOperation as Ml,runPartitioned as Ll,trackedArticlePaths as Ul}from"document360-engine";var io=3;function ao(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 lo(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function co(e,t){return t.map(n=>{let o=0;try{o=El(Il(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function uo(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:
45
45
  - 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.
46
46
  - 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.
47
47
  - 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.
48
48
  - Work only on these files:
49
49
  `+e.paths.map(t=>`- ${t}`).join(`
50
- `)}function po(e,t,n){let o=e.reduce((p,g)=>p+g.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${ae(r)}\u2013${ae(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function fo(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),g=e.reduce((P,N)=>P+N.costUsd,0),w=e.reduce((P,N)=>P+N.outputTokens,0),b=n==="api"?`${ae(g)} total`:Ee(w),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 ${b}.`);else{C.push(`Converted ${p}/${k(c)} (${j}) \xB7 ${b}.`),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 hs(e,t){if(!Ol(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=ao(e),r=Ul(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=lo(r,n);if(s.length===0)return console.log(v(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=_l(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:g,forced:w}=Ml(t.cwd,"light");if(!o){let b=Nl({files:co(t.cwd,s),op:"convert",model:g});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let j of po(c,b,io))console.log(j);return console.log(f(`Model: ${g}${w?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${c.length} partitions (\u2264${io} agents at once) on ${g}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let b of Ll({cwd:t.cwd,partitions:c,promptFor:uo,concurrency:io,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:g}))if(b.type==="partition_status")b.status==="running"?console.log(f(` \u25B8 ${b.label} \u2014 converting\u2026`)):b.status==="done"?console.log(D(` \u2713 ${b.label}`)):console.log(v(` \u2717 ${b.label}`));else if(b.type==="run_done"){console.log("");let j=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let k of fo(b.results,c,j))console.log(b.ok?D(k):L(k))}}catch(b){console.log(v(`Convert run failed: ${b.message}`))}return console.log(""),{kind:"continue"}}H();import{statSync as ws}from"node:fs";import{resolve as ys}from"node:path";import{estimateBulkCost as Wl,planPartitions as Fl,readDocsPlan as Hl,readProjectConfig as ks,DEFAULT_DOCS_DIR as Bl,resolveModelForOperation as ql,runPartitioned as Gl}from"document360-engine";var mo=5;function go(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 Yl(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function zl(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Vl(e,t,n){return n.filter(o=>{try{return ws(ys(e,t,o)).size===0}catch{return!0}})}function ho(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+=ws(ys(e,c)).size}catch{}return{path:r,bytes:s}})}function wo(e,t){return`Run the write-article skill to author EACH documentation article listed below. For each path:
50
+ `)}function po(e,t,n){let o=e.reduce((p,g)=>p+g.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${ae(r)}\u2013${ae(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function fo(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),g=e.reduce((P,N)=>P+N.costUsd,0),w=e.reduce((P,N)=>P+N.outputTokens,0),x=n==="api"?`${ae(g)} total`:Ee(w),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 ${x}.`);else{C.push(`Converted ${p}/${k(c)} (${j}) \xB7 ${x}.`),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 hs(e,t){if(!Ol(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=ao(e),r=Ul(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=lo(r,n);if(s.length===0)return console.log(v(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=_l(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:g,forced:w}=Ml(t.cwd,"light");if(!o){let x=Nl({files:co(t.cwd,s),op:"convert",model:g});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let j of po(c,x,io))console.log(j);return console.log(f(`Model: ${g}${w?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${c.length} partitions (\u2264${io} agents at once) on ${g}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let x of Ll({cwd:t.cwd,partitions:c,promptFor:uo,concurrency:io,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:g}))if(x.type==="partition_status")x.status==="running"?console.log(f(` \u25B8 ${x.label} \u2014 converting\u2026`)):x.status==="done"?console.log(D(` \u2713 ${x.label}`)):console.log(v(` \u2717 ${x.label}`));else if(x.type==="run_done"){console.log("");let j=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let k of fo(x.results,c,j))console.log(x.ok?D(k):L(k))}}catch(x){console.log(v(`Convert run failed: ${x.message}`))}return console.log(""),{kind:"continue"}}H();import{statSync as ws}from"node:fs";import{resolve as ys}from"node:path";import{estimateBulkCost as Wl,planPartitions as Fl,readDocsPlan as Hl,readProjectConfig as ks,DEFAULT_DOCS_DIR as Bl,resolveModelForOperation as ql,runPartitioned as Gl}from"document360-engine";var mo=5;function go(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 Yl(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function zl(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Vl(e,t,n){return n.filter(o=>{try{return ws(ys(e,t,o)).size===0}catch{return!0}})}function ho(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+=ws(ys(e,c)).size}catch{}return{path:r,bytes:s}})}function wo(e,t){return`Run the write-article skill to author EACH documentation article listed below. For each path:
51
51
  - 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).
52
52
  - 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.
53
53
  - 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.
@@ -55,13 +55,13 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
55
55
  - 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.
56
56
  Articles:
57
57
  `+e.paths.map(n=>`- ${n}`).join(`
58
- `)}function yo(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: ${ae(r)}\u2013${ae(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write --run to start."]}function ko(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),g=e.reduce((P,N)=>P+N.costUsd,0),w=e.reduce((P,N)=>P+N.outputTokens,0),b=n==="api"?`${ae(g)} total`:Ee(w),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 ${b}.`),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 ${b}.`),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 bo(e,t,n){let o=(ks(e)?.docsDir??Bl).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Yl(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=zl(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=Vl(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 bs(e,t){if(!ks(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=Hl(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}=go(e),{docsDir:c,targets:p,reason:g}=bo(t.cwd,n,{scope:o,path:r});if(p.length===0)return console.log(g?L(g):L("Nothing to write.")),{kind:"continue"};let w=Fl(p),{model:b,forced:j}=ql(t.cwd,"standard");if(!s&&!!!r){let C=Wl({files:ho(t.cwd,n,p),op:"write",model:b});o&&console.log(f(`Scope: ${o} (${p.length} pending).`));for(let P of yo(w,C,mo))console.log(P);return console.log(f(`Model: ${b}${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 ${w.length} partition${w.length===1?"":"s"} (\u2264${mo} agents at once) on ${b}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let C of Gl({cwd:t.cwd,partitions:w,promptFor:P=>wo(P,c),concurrency:mo,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:b}))if(C.type==="partition_status")C.status==="running"?console.log(f(` \u25B8 ${C.label} \u2014 writing\u2026`)):C.status==="done"?console.log(D(` \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 ko(C.results,w,P))console.log(C.ok?D(N):L(N))}}catch(C){console.log(v(`Write run failed: ${C.message}`))}return console.log(""),{kind:"continue"}}H();import{existsSync as Xl,readdirSync as xs,statSync as $s}from"node:fs";import{join as vs}from"node:path";import{inputDir as Kl,readProjectConfig as Jl}from"document360-engine";var Cs=/\.(md|markdown|pdf|txt)$/i;function xo(e){let t=Kl(e);if(!Xl(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of xs(t)){let s=vs(t,r),c=!1;try{c=$s(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=Ql(s);p>0&&n.push({name:r,docCount:p})}else Cs.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Ql(e){let t=0;for(let n of xs(e))try{$s(vs(e,n)).isFile()&&Cs.test(n)&&t++}catch{}return t}function $o(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 dn(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(`
59
- `)}var vo="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Ps(e,t){let n=t?.cwd??process.cwd();if(!Jl(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=xo(n);if(o.length===0&&r===0)return console.log(f(vo)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let g of o)console.log(` ${g.name} ${f(`(${g.docCount} doc${g.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:dn(p),display:p?`/draft ${p}`:"/draft"}}let c=$o(o,s);return{kind:"forward-to-agent",prompt:dn(c??"",c?void 0:s),display:`/draft ${s}`}}H();import{search as Zl}from"@inquirer/prompts";import{findByName as ec,getSession as tc,listSessions as nc,relativeTime as Ss}from"document360-engine";async function Rs(e,t){let n=nc(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=ec(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(v(`No session matches "${o}".`)),Ts(n),{kind:"continue"})}if(!process.stdin.isTTY)return Ts(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Zl({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} ${Ss(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=tc(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Ts(e){console.log("");for(let t of e.slice(0,15))console.log(` ${A(t.name)} ${f(Ss(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}H();import{renameSession as oc}from"document360-engine";function Co(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 js(e,t){let n=Co(e.join(" "));if(!n)return console.log(v("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(oc(o,n)?console.log(D(`\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 As,readProjectConfig as rc,writeProjectConfig as sc}from"document360-engine";H();function Po(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=rc(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 As().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},sc(o,e),null):`Unknown environment "${r}". Known: ${As().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function Ds(e,t){let n=e[0];if(!n)return Zt(t.cwd),{kind:"continue"};if(n==="add"){let o=Po(t.cwd,e[1],e[2]);return o?(console.log(v(o)),{kind:"continue"}):(console.log(D(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${A(`/profile ${e[1]}`)} then ${A("/login")}`),{kind:"continue"})}return en(t.cwd,n),tn(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}H();import{select as ic}from"@inquirer/prompts";import{readProjectConfig as ac,readUserConfig as Es,resolveModelSetting as To,writeUserConfig as Is}from"document360-engine";var ke=[{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 pn(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=ke.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function lc(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 St(e,t){let n=()=>{let s=To(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Es();return s.defaultModel?(delete s.defaultModel,Is(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${To(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}}Is({...Es(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=ac(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 Ns(e,t){let n=e[0]?.trim();if(!n){let c=To(t.cwd);if(!process.stdin.isTTY)return console.log(`${Ce("Model:")} ${A(c.model??"Claude Code default")}`),console.log(f(` source: ${lc(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=pn(c),g;try{g=await t.withPausedInput(()=>ic({message:`Select model (current: ${c.model??"Claude Code default"})`,default:ke[p].value,choices:ke.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:w,changed:b,effective:j}=St(t.cwd,g??"default");for(let k of w)console.log(k.startsWith("\u26A0")?L(k):k.startsWith("\u2713")?D(k):f(k));return b&&await t.setModel(j),{kind:"continue"}}let{lines:o,changed:r,effective:s}=St(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?L(c):c.startsWith("\u2713")?D(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}fn();async function Us(e,t){return await t.withPausedInput(()=>lt(t.cwd)),{kind:"clear"}}async function Ws(e,t){return await t.withPausedInput(()=>Tr(t.cwd,t.profileName)),{kind:"clear"}}H();import{resolveActiveProfile as bc}from"document360-engine";async function Fs(e,t){let n=!1;try{n=bc(t.cwd).production}catch{}return n?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}H();var Hs=async(e,t)=>{try{await t.withPausedInput(()=>Jt({}))}catch(n){console.log(v(`Login failed: ${n.message}`))}return{kind:"continue"}};H();import{resolveActiveProfile as xc,clearTokens as $c,clearProfileProject as vc}from"document360-engine";async function Bs(e,t){let n;try{n=xc(t.cwd,t.profileName).name}catch(r){return console.log(v(r.message)),{kind:"continue"}}let o=$c(n);return vc(t.cwd,n),console.log(o?D(`\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 qs}from"node:fs";import{isAbsolute as Cc,join as Pc,resolve as Tc}from"node:path";import{readProjectConfig as Sc,screenshotPlaceholderIds as Rc,DEFAULT_CAPTURE_DIR as jc,DEFAULT_OUTPUT_DIR as Ac}from"document360-engine";var Gs=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ro(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Gs(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Gs(o),setup:t}:{mode:"single",id:o}}function jo(e,t){let n=Sc(e),o=n?.captureDir??jc,r=n?.outputDir??Ac,s=(c,p)=>Cc(c)?Pc(c,p):Tc(e,c,p);return Rc(e,{scope:t}).map(({id:c,file:p})=>{let g=qs(s(r,`${c}.png`))?"captured":qs(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:g}})}var Dc={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Ec={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Ao(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(` ${Dc[c.state]} ${c.id.padEnd(34)} ${Ec[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Ys(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(`
58
+ `)}function yo(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: ${ae(r)}\u2013${ae(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write --run to start."]}function ko(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),g=e.reduce((P,N)=>P+N.costUsd,0),w=e.reduce((P,N)=>P+N.outputTokens,0),x=n==="api"?`${ae(g)} total`:Ee(w),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 ${x}.`),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 ${x}.`),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 xo(e,t,n){let o=(ks(e)?.docsDir??Bl).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Yl(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=zl(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=Vl(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 xs(e,t){if(!ks(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=Hl(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}=go(e),{docsDir:c,targets:p,reason:g}=xo(t.cwd,n,{scope:o,path:r});if(p.length===0)return console.log(g?L(g):L("Nothing to write.")),{kind:"continue"};let w=Fl(p),{model:x,forced:j}=ql(t.cwd,"standard");if(!s&&!!!r){let C=Wl({files:ho(t.cwd,n,p),op:"write",model:x});o&&console.log(f(`Scope: ${o} (${p.length} pending).`));for(let P of yo(w,C,mo))console.log(P);return console.log(f(`Model: ${x}${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 ${w.length} partition${w.length===1?"":"s"} (\u2264${mo} agents at once) on ${x}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let C of Gl({cwd:t.cwd,partitions:w,promptFor:P=>wo(P,c),concurrency:mo,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:x}))if(C.type==="partition_status")C.status==="running"?console.log(f(` \u25B8 ${C.label} \u2014 writing\u2026`)):C.status==="done"?console.log(D(` \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 ko(C.results,w,P))console.log(C.ok?D(N):L(N))}}catch(C){console.log(v(`Write run failed: ${C.message}`))}return console.log(""),{kind:"continue"}}H();import{existsSync as Kl,readdirSync as bs,statSync as $s}from"node:fs";import{join as vs}from"node:path";import{inputDir as Xl,readProjectConfig as Jl}from"document360-engine";var Cs=/\.(md|markdown|pdf|txt)$/i;function bo(e){let t=Xl(e);if(!Kl(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of bs(t)){let s=vs(t,r),c=!1;try{c=$s(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=Ql(s);p>0&&n.push({name:r,docCount:p})}else Cs.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Ql(e){let t=0;for(let n of bs(e))try{$s(vs(e,n)).isFile()&&Cs.test(n)&&t++}catch{}return t}function $o(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 dn(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(`
59
+ `)}var vo="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Ps(e,t){let n=t?.cwd??process.cwd();if(!Jl(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=bo(n);if(o.length===0&&r===0)return console.log(f(vo)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let g of o)console.log(` ${g.name} ${f(`(${g.docCount} doc${g.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:dn(p),display:p?`/draft ${p}`:"/draft"}}let c=$o(o,s);return{kind:"forward-to-agent",prompt:dn(c??"",c?void 0:s),display:`/draft ${s}`}}H();import{search as Zl}from"@inquirer/prompts";import{findByName as ec,getSession as tc,listSessions as nc,relativeTime as Ss}from"document360-engine";async function Rs(e,t){let n=nc(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=ec(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(v(`No session matches "${o}".`)),Ts(n),{kind:"continue"})}if(!process.stdin.isTTY)return Ts(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Zl({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} ${Ss(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=tc(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Ts(e){console.log("");for(let t of e.slice(0,15))console.log(` ${A(t.name)} ${f(Ss(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}H();import{renameSession as oc}from"document360-engine";function Co(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 js(e,t){let n=Co(e.join(" "));if(!n)return console.log(v("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(oc(o,n)?console.log(D(`\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 As,readProjectConfig as rc,writeProjectConfig as sc}from"document360-engine";H();function Po(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=rc(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 As().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},sc(o,e),null):`Unknown environment "${r}". Known: ${As().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function Ds(e,t){let n=e[0];if(!n)return Zt(t.cwd),{kind:"continue"};if(n==="add"){let o=Po(t.cwd,e[1],e[2]);return o?(console.log(v(o)),{kind:"continue"}):(console.log(D(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${A(`/profile ${e[1]}`)} then ${A("/login")}`),{kind:"continue"})}return en(t.cwd,n),tn(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}H();import{select as ic}from"@inquirer/prompts";import{readProjectConfig as ac,readUserConfig as Es,resolveModelSetting as To,writeUserConfig as Is}from"document360-engine";var ke=[{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 pn(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=ke.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function lc(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 St(e,t){let n=()=>{let s=To(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Es();return s.defaultModel?(delete s.defaultModel,Is(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${To(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}}Is({...Es(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=ac(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 Ns(e,t){let n=e[0]?.trim();if(!n){let c=To(t.cwd);if(!process.stdin.isTTY)return console.log(`${Ce("Model:")} ${A(c.model??"Claude Code default")}`),console.log(f(` source: ${lc(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=pn(c),g;try{g=await t.withPausedInput(()=>ic({message:`Select model (current: ${c.model??"Claude Code default"})`,default:ke[p].value,choices:ke.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:w,changed:x,effective:j}=St(t.cwd,g??"default");for(let k of w)console.log(k.startsWith("\u26A0")?L(k):k.startsWith("\u2713")?D(k):f(k));return x&&await t.setModel(j),{kind:"continue"}}let{lines:o,changed:r,effective:s}=St(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?L(c):c.startsWith("\u2713")?D(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}fn();async function Us(e,t){return await t.withPausedInput(()=>lt(t.cwd)),{kind:"clear"}}async function Ws(e,t){return await t.withPausedInput(()=>Tr(t.cwd,t.profileName)),{kind:"clear"}}H();import{resolveActiveProfile as xc}from"document360-engine";async function Fs(e,t){let n=!1;try{n=xc(t.cwd).production}catch{}return n?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}H();var Hs=async(e,t)=>{try{await t.withPausedInput(()=>Jt({}))}catch(n){console.log(v(`Login failed: ${n.message}`))}return{kind:"continue"}};H();import{resolveActiveProfile as bc,clearTokens as $c,clearProfileProject as vc}from"document360-engine";async function Bs(e,t){let n;try{n=bc(t.cwd,t.profileName).name}catch(r){return console.log(v(r.message)),{kind:"continue"}}let o=$c(n);return vc(t.cwd,n),console.log(o?D(`\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 qs}from"node:fs";import{isAbsolute as Cc,join as Pc,resolve as Tc}from"node:path";import{readProjectConfig as Sc,screenshotPlaceholderIds as Rc,DEFAULT_CAPTURE_DIR as jc,DEFAULT_OUTPUT_DIR as Ac}from"document360-engine";var Gs=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ro(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Gs(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Gs(o),setup:t}:{mode:"single",id:o}}function jo(e,t){let n=Sc(e),o=n?.captureDir??jc,r=n?.outputDir??Ac,s=(c,p)=>Cc(c)?Pc(c,p):Tc(e,c,p);return Rc(e,{scope:t}).map(({id:c,file:p})=>{let g=qs(s(r,`${c}.png`))?"captured":qs(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:g}})}var Dc={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Ec={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Ao(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(` ${Dc[c.state]} ${c.id.padEnd(34)} ${Ec[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Ys(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(`
60
60
  `),"","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(`
61
61
  `)}async function mn(e,t){let n=Ro(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of Ao(jo(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(`
62
62
  `),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(`
63
63
  `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as Ic,readFileSync as Nc}from"node:fs";import{isAbsolute as _c,join as Oc,resolve as Mc}from"node:path";import{readProjectConfig as Lc,DEFAULT_CAPTURE_DIR as Uc}from"document360-engine";async function jt(){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(`
64
- `),display:"/capture-setup"}}var zs="-".repeat(64);function Do(e){let t=Uc;try{let b=Lc(e);b?.captureDir&&(t=b.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=_c(t)?Oc(t,"CAPTURE-TESTID-REQUESTS.json"):Mc(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Ic(n))return null;let o;try{let b=JSON.parse(Nc(n,"utf8").replace(/^/,""));o=Array.isArray(b?.requests)?b.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(b=>b.file).filter(Boolean)).size,s=o.length,c=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,g=`${t}/CAPTURE-TESTID-REQUESTS.md`,w=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${c} requested across ${p}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",zs,`Read ${g} and ${w}. They list ${c} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",zs]}import{existsSync as Wc,writeFileSync as Vs}from"node:fs";import{devHintsGuidePath as Fc,hintsDir as Hc,architectureDir as Bc,creatorNotesPath as Xs,ensureDir as Ks}from"document360-engine";var Js="-".repeat(64),qc=2;function Eo(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
64
+ `),display:"/capture-setup"}}var zs="-".repeat(64);function Do(e){let t=Uc;try{let x=Lc(e);x?.captureDir&&(t=x.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=_c(t)?Oc(t,"CAPTURE-TESTID-REQUESTS.json"):Mc(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Ic(n))return null;let o;try{let x=JSON.parse(Nc(n,"utf8").replace(/^/,""));o=Array.isArray(x?.requests)?x.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(x=>x.file).filter(Boolean)).size,s=o.length,c=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,g=`${t}/CAPTURE-TESTID-REQUESTS.md`,w=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${c} requested across ${p}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",zs,`Read ${g} and ${w}. They list ${c} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",zs]}import{existsSync as Wc,writeFileSync as Vs}from"node:fs";import{devHintsGuidePath as Fc,hintsDir as Hc,architectureDir as Bc,creatorNotesPath as Ks,ensureDir as Xs}from"document360-engine";var Js="-".repeat(64),qc=2;function Eo(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
65
65
 
66
66
  <!-- Guide version: ${qc} \xB7 maintained by document360-writer (/devhints). -->
67
67
 
@@ -162,15 +162,15 @@ Anything only a human knows that would help document this product. For example:
162
162
  - Gotchas or non-obvious behavior.
163
163
 
164
164
  (Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
165
- `}async function Qs(e,t){Ks(Hc(t.cwd)),Ks(Bc(t.cwd)),Wc(Xs(t.cwd))||Vs(Xs(t.cwd),Io()),Vs(Fc(t.cwd),Eo());for(let n of No())console.log(n);return{kind:"continue"}}function Gc(){return['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. 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, 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. 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).","5. 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(`
166
- `)}function No(){return["\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief) and .d360-writer/hints/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",Js,Gc(),Js,"","That one run writes the architecture brief, adds the ongoing-hints rule to your agent memory (CLAUDE.md /","AGENTS.md) and commits it so teammates inherit it, and asks you for any tribal knowledge \u2014 no manual file","edits. When it finishes, come back here and run: write the docs for this repo"]}H();import{existsSync as Zs,rmSync as Yc}from"node:fs";import{basename as ei,resolve as _o}from"node:path";import{execFileSync as zc}from"node:child_process";import{input as Vc}from"@inquirer/prompts";import{readProjectConfig as Xc}from"document360-engine";var Kc=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Jc=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),gn=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),ti=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function ni(e){let t=gn(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:ti(t)?!0:Jc.has(t)}function Oo(e){let t=null;try{t=Xc(e)}catch{t=null}let n=new Set(Kc);for(let o of[gn(t?.docsDir),gn(t?.captureDir),gn(t?.outputDir)])o&&ti(o)&&n.add(o);return[...n].filter(o=>ni(o)&&Zs(_o(e,o)))}function Mo(e,t){let n=[],o=[];for(let r of t){if(!ni(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Yc(_o(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Qc(e){try{return zc("git",["status","--porcelain","--",".d360-writer/hints"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
167
- `).filter(n=>n.trim()&&/\.md\s*$/.test(n)).length}catch{return 0}}function Lo(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Qc(e),o=Zs(_o(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(r=>` \u2022 ${r}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o?["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: ${ei(e)}`]}async function oi(e,t){let n=Oo(t.cwd);for(let p of Lo(t.cwd,n))console.log(n.length===0?f(p):p);if(n.length===0)return{kind:"continue"};let o=ei(t.cwd);if((await t.withPausedInput(()=>Vc({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let{removed:s,failed:c}=Mo(t.cwd,n);console.log(D(`\u2713 Reset complete \u2014 removed ${s.length} item${s.length===1?"":"s"}. The repo is back to its original state.`));for(let p of c)console.log(v(` \u2717 ${p.path}: ${p.error}`));return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}var ri={help:qn,"?":qn,clear:Lr,exit:Gn,quit:Gn,init:zr,mcp:rn,publish:is,audit:ln,scope:ls,sync:gs,convert:hs,write:bs,draft:Ps,resume:Rs,rename:js,profile:Ds,model:Ns,doctor:Rt,workspace:Us,project:Ws,"allow-prod":Fs,login:Hs,logout:Bs,screenshot:mn,"capture-setup":jt,devhints:Qs,reset:oi};function si(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}H();var Zc={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"},ai=160,Wo=200,li=40;function ue(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function ii(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}: ${ue(typeof r=="string"?r:JSON.stringify(r),li)}`);return t.length>4&&n.push("\u2026"),ue(n.join(", "),ai)}var Ie=e=>typeof e=="string"&&e?e:null,Uo=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function eu(e){let t=Ie(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 tu(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Ie(t.title);if(!o)return null;let r=eu(t.local_path);return n("Create article",`"${ue(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Ie(t.title),r=Uo(t.article_id);return n("Update article",o?`"${ue(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Uo(t.article_id)?`id ${Uo(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",Ie(t.name)?`"${ue(Ie(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Ie(t.file_path);return n("Upload image",o?ue(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 w=tu(c,t);if(w)return w}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:ii(t)}}let n=Zc[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:ue(o,ai)}:{title:e,sep:"",arg:ii(t)}}function nu(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 ou(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(nu).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>ue(r,Wo))]}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}: ${ue(String(r),li)}`);return n.length>0?[ue(n.join(" \xB7 "),Wo)]:null}return null}function ru(e){let t=Ie(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function su(e,t,n){switch(e){case"d360_create_article":{let o=ru(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=Ie(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 ${ue(o[0],120)}`:""}`]}default:return null}}function wn(e,t=4,n,o){let r=e.replace(/\r\n/g,`
165
+ `}async function Qs(e,t){Xs(Hc(t.cwd)),Xs(Bc(t.cwd)),Wc(Ks(t.cwd))||Vs(Ks(t.cwd),Io()),Vs(Fc(t.cwd),Eo());for(let n of No())console.log(n);return{kind:"continue"}}function Gc(){return['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. 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, 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. 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).","5. 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(`
166
+ `)}function No(){return["\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief) and .d360-writer/hints/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",Js,Gc(),Js,"","That one run writes the architecture brief, adds the ongoing-hints rule to your agent memory (CLAUDE.md /","AGENTS.md) and commits it so teammates inherit it, and asks you for any tribal knowledge \u2014 no manual file","edits. When it finishes, come back here and run: write the docs for this repo"]}H();import{existsSync as Zs,rmSync as Yc}from"node:fs";import{basename as ei,resolve as _o}from"node:path";import{execFileSync as zc}from"node:child_process";import{input as Vc}from"@inquirer/prompts";import{readProjectConfig as Kc}from"document360-engine";var Xc=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Jc=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),gn=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),ti=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function ni(e){let t=gn(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:ti(t)?!0:Jc.has(t)}function Oo(e){let t=null;try{t=Kc(e)}catch{t=null}let n=new Set(Xc);for(let o of[gn(t?.docsDir),gn(t?.captureDir),gn(t?.outputDir)])o&&ti(o)&&n.add(o);return[...n].filter(o=>ni(o)&&Zs(_o(e,o)))}function Mo(e,t){let n=[],o=[];for(let r of t){if(!ni(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Yc(_o(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Qc(e){try{return zc("git",["status","--porcelain","--",".d360-writer/hints"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
167
+ `).filter(n=>n.trim()&&/\.md\s*$/.test(n)).length}catch{return 0}}function Lo(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Qc(e),o=Zs(_o(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(r=>` \u2022 ${r}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o?["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: ${ei(e)}`]}async function oi(e,t){let n=Oo(t.cwd);for(let p of Lo(t.cwd,n))console.log(n.length===0?f(p):p);if(n.length===0)return{kind:"continue"};let o=ei(t.cwd);if((await t.withPausedInput(()=>Vc({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let{removed:s,failed:c}=Mo(t.cwd,n);console.log(D(`\u2713 Reset complete \u2014 removed ${s.length} item${s.length===1?"":"s"}. The repo is back to its original state.`));for(let p of c)console.log(v(` \u2717 ${p.path}: ${p.error}`));return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}var ri={help:qn,"?":qn,clear:Lr,exit:Gn,quit:Gn,init:zr,mcp:rn,publish:is,audit:ln,scope:ls,sync:gs,convert:hs,write:xs,draft:Ps,resume:Rs,rename:js,profile:Ds,model:Ns,doctor:Rt,workspace:Us,project:Ws,"allow-prod":Fs,login:Hs,logout:Bs,screenshot:mn,"capture-setup":jt,devhints:Qs,reset:oi};function si(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}H();var Zc={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"},ai=160,Wo=200,li=40;function ue(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function ii(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}: ${ue(typeof r=="string"?r:JSON.stringify(r),li)}`);return t.length>4&&n.push("\u2026"),ue(n.join(", "),ai)}var Ie=e=>typeof e=="string"&&e?e:null,Uo=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function eu(e){let t=Ie(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 tu(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Ie(t.title);if(!o)return null;let r=eu(t.local_path);return n("Create article",`"${ue(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Ie(t.title),r=Uo(t.article_id);return n("Update article",o?`"${ue(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Uo(t.article_id)?`id ${Uo(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",Ie(t.name)?`"${ue(Ie(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Ie(t.file_path);return n("Upload image",o?ue(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 w=tu(c,t);if(w)return w}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:ii(t)}}let n=Zc[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:ue(o,ai)}:{title:e,sep:"",arg:ii(t)}}function nu(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 ou(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(nu).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>ue(r,Wo))]}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}: ${ue(String(r),li)}`);return n.length>0?[ue(n.join(" \xB7 "),Wo)]:null}return null}function ru(e){let t=Ie(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function su(e,t,n){switch(e){case"d360_create_article":{let o=ru(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=Ie(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 ${ue(o[0],120)}`:""}`]}default:return null}}function wn(e,t=4,n,o){let r=e.replace(/\r\n/g,`
168
168
  `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=su(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let s=ou(r)??r.split(`
169
- `);return{lines:s.slice(0,t).map(c=>ue(c,Wo)),hidden:Math.max(0,s.length-t)}}function yn(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function kn(e,t){if(typeof e.article_id=="string"&&e.article_id)return e.article_id;try{let n=JSON.parse(t),r=(Array.isArray(n)?n[0]:n)?.id;return typeof r=="string"&&r?r:null}catch{return null}}function bn(e){try{let t=JSON.parse(e),o=(Array.isArray(t)?t[0]:t)?.url;return typeof o=="string"&&/^https?:\/\//.test(o)?o:null}catch{return null}}var wu=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function yu(e,t,n,o){if(wu.test(e))try{let r=pi(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=kn(t,n),p=bn(n);e.endsWith("publish_article")&&p&&console.log(A(` \u2B95 Live: ${p}`)),c&&s&&console.log(A(` \u2B95 Preview: ${yn(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function fi(e=process.cwd(),t="auto",n){let o=au(t);o.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${A("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${A('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${A("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${A("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),ku(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=Fo({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=iu({input:process.stdin,output:process.stdout}),g=[],w=null,b=!1;p.on("line",C=>{if(w){let P=w;w=null,P(C)}else g.push(C)}),p.on("close",()=>{if(b=!0,w){let C=w;w=null,C(null)}});function j(){return g.length>0?Promise.resolve(g.shift()):b?Promise.resolve(null):(process.stdout.write(A("> ")),new Promise(C=>{w=C}))}let k={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=Fo({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=si(P);if(!N)continue;let _=ri[N.name];if(!_){console.log(v(`Unknown command: /${N.name}`)),console.log(f("Type /help for the list."));continue}let W=await _(N.args,k);if(W.kind==="exit")break;if(W.kind==="clear"){k.restartAgent();continue}if(W.kind==="allow-prod"){r=!0,k.restartAgent(),console.log(D("\u2713 Production writes authorized for this session.")),console.log("");continue}if(W.kind==="resume"){s.close(),s=Fo({cwd:e,resume:W.uuid,profileName:n,allowProdWrites:r});let Z=lu(W.uuid);c={uuid:W.uuid,firstPrompt:Z?.firstPrompt??null,titleFired:!0},di(W.uuid),console.log(D(`\u2713 Resumed "${W.name}"`)),console.log("");continue}W.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=W.display??W.prompt),await ui(s,W.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=P),await ui(s,P,o,c,e)}}}finally{s.close(),p.close()}}function ku(e,t){console.log(""),console.log(yt("document360-writer")),console.log(f(` cwd: ${e}`));let n=fu(e);console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(bu(e,t)),mu(e)||console.log(L(" First run: /init \u2192 /login (project & workspace auto-selected) \u2192 /devhints, then ask me to write the docs.")),console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function bu(e,t){try{let n=pi(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=hu(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...ci(r.idToken)??{},...ci(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return gu(r)&&!r.refreshToken?L(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function xu(){console.error(""),console.error(`Sign in with your Claude subscription: run ${A("claude")} once, then retry.`),console.error(` (No Claude Code? ${A("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${A("https://console.anthropic.com/settings/keys")}`)}function $u(e,t,n){e.uuid=t;let o=new Date().toISOString();du({uuid:t,name:uu(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o})}function vu(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||pu(o,t).then(r=>{r&&cu(n,r)}).catch(()=>{})}async function ui(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))Cu(c,o,r,n,s)}function Cu(e,t,n,o,r){switch(e.type){case"session":t.uuid||$u(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(`
169
+ `);return{lines:s.slice(0,t).map(c=>ue(c,Wo)),hidden:Math.max(0,s.length-t)}}function yn(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function kn(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 xn(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 wu=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function yu(e,t,n,o){if(wu.test(e))try{let r=pi(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=kn(t,n),p=xn(n);e.endsWith("publish_article")&&p&&console.log(A(` \u2B95 Live: ${p}`)),c&&s&&console.log(A(` \u2B95 Preview: ${yn(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function fi(e=process.cwd(),t="auto",n){let o=au(t);o.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${A("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${A('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${A("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${A("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),ku(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=Fo({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=iu({input:process.stdin,output:process.stdout}),g=[],w=null,x=!1;p.on("line",C=>{if(w){let P=w;w=null,P(C)}else g.push(C)}),p.on("close",()=>{if(x=!0,w){let C=w;w=null,C(null)}});function j(){return g.length>0?Promise.resolve(g.shift()):x?Promise.resolve(null):(process.stdout.write(A("> ")),new Promise(C=>{w=C}))}let k={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=Fo({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=si(P);if(!N)continue;let _=ri[N.name];if(!_){console.log(v(`Unknown command: /${N.name}`)),console.log(f("Type /help for the list."));continue}let W=await _(N.args,k);if(W.kind==="exit")break;if(W.kind==="clear"){k.restartAgent();continue}if(W.kind==="allow-prod"){r=!0,k.restartAgent(),console.log(D("\u2713 Production writes authorized for this session.")),console.log("");continue}if(W.kind==="resume"){s.close(),s=Fo({cwd:e,resume:W.uuid,profileName:n,allowProdWrites:r});let Z=lu(W.uuid);c={uuid:W.uuid,firstPrompt:Z?.firstPrompt??null,titleFired:!0},di(W.uuid),console.log(D(`\u2713 Resumed "${W.name}"`)),console.log("");continue}W.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=W.display??W.prompt),await ui(s,W.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=P),await ui(s,P,o,c,e)}}}finally{s.close(),p.close()}}function ku(e,t){console.log(""),console.log(yt("document360-writer")),console.log(f(` cwd: ${e}`));let n=fu(e);console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(xu(e,t)),mu(e)||console.log(L(" First run: /init \u2192 /login (project & workspace auto-selected) \u2192 /devhints, then ask me to write the docs.")),console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function xu(e,t){try{let n=pi(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=hu(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...ci(r.idToken)??{},...ci(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return gu(r)&&!r.refreshToken?L(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function bu(){console.error(""),console.error(`Sign in with your Claude subscription: run ${A("claude")} once, then retry.`),console.error(` (No Claude Code? ${A("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${A("https://console.anthropic.com/settings/keys")}`)}function $u(e,t,n){e.uuid=t;let o=new Date().toISOString();du({uuid:t,name:uu(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o})}function vu(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||pu(o,t).then(r=>{r&&cu(n,r)}).catch(()=>{})}async function ui(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))Cu(c,o,r,n,s)}function Cu(e,t,n,o,r){switch(e.type){case"session":t.uuid||$u(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(`
170
170
 
171
171
  `),console.log(`${D("\u25CF")} ${Ce(s.title)}${s.arg!==null?ee(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=qe(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=p=>p===1?"":"s";console.log(ee(` \u23BF Added ${s.added} line${c(s.added)}, removed ${s.removed} line${c(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(f(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let c=wn(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?v:ee;c.lines.forEach((g,w)=>console.log(p((w===0?" \u23BF ":" ")+g))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||yu(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
172
- `),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&&(di(t.uuid),t.titleFired||vu(t,n));break;case"error":console.error(""),console.error(v(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&xu();break}}import{render as vd}from"ink";import{resolveAuth as Cd}from"document360-engine";import{useCallback as z,useEffect as _e,useMemo as Yo,useRef as J,useState as F}from"react";import{Box as K,Text as S,useApp as Nu,useInput as _u,useStdout as Ou}from"ink";import{existsSync as zo,readFileSync as Di,readdirSync as Bi,writeFileSync as Ei}from"node:fs";import{basename as Et,isAbsolute as Mu,join as It}from"node:path";import{createSession as Ii,loginPkce as Lu,toStoredTokens as Uu,saveTokens as Wu,getAccessToken as Fu,resolveActiveProfile as de,resolveProjectId as Hu,getArticle as Bu,decodeJwtClaims as pt,isExpired as Ne,loadTokens as Ge,clearTokens as qu,clearProfileProject as Gu,setTitle as Yu,slugify as zu,touchSession as Vo,upsertSession as Vu,generateTitle as Ni,findByName as Xu,listSessions as Ku,renameSession as Ju,suggestNextAction as Qu,readProjectConfig as oe,writeProjectConfig as Zu,resolveModelSetting as Qo,loadProfileMap as _i,applyPull as ed,computeSyncStatus as Xo,planPull as td,inventoryRepo as nd,knownEnvironments as od,resolveEnvironment as rd,planPartitions as Ko,partitionEvenly as sd,screenshotPlaceholderIds as id,trackedArticlePaths as ad,runPartitioned as Tn,estimateBulkCost as Oi,resolveModelForOperation as Sn,readDocsPlan as ld,ensureDir as Mi,hintsDir as cd,architectureDir as ud,creatorNotesPath as Li,devHintsGuidePath as dd,DEFAULT_DOCS_DIR as qi,setProfileProject as pd}from"document360-engine";import{existsSync as Pu,mkdirSync as Tu,readFileSync as Su,writeFileSync as Ru}from"node:fs";import{join as mi}from"node:path";import{writerDir as ju}from"document360-engine";function gi(e){return mi(ju(e),".sessions")}function hi(e,t){return mi(gi(e),`${t}.json`)}function wi(e,t,n){try{Tu(gi(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Ru(hi(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Ho(e,t){try{let n=hi(e,t);if(!Pu(n))return[];let o=JSON.parse(Su(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Au=e=>`\x1B]0;${e}\x07`,Du=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function yi(e){process.stdout.isTTY&&process.stdout.write(e)}function At(e){yi(Au(e))}function xn(e){yi(Du(e))}var $n=["\xB7 "," \xB7"],Bo="\u{1F7E3}";fn();var Eu=/^(?:\d+[.)]|[-*•])\s+/;function ki(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
173
- `)){let c=s.trim().replace(Eu,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let g=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!g||!o.has(g[1].toLowerCase()))continue;let w=`/${g[1].toLowerCase()}${g[2]?` ${g[2]}`:""}`;if(r.includes(w)||r.push(w),r.length>=n)break}return r}H();function Dt(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Pe(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function qo(e){return e.replace(/^[\w.-]+\//,"")}var vn=16,bi={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Go(e){return e.trim().split(/\s+/).slice(1).join(" ")}function xi(e,t){let n=Go(t);return e.some(r=>r.trim()===t.trim()||!!n&&Go(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&Go(r)===n)):[]}var Iu=/\[Pasted text #\d+ \+\d+ lines?\]/g;function $i(e){return e.replace(/\r\n?/g,`
172
+ `),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&&(di(t.uuid),t.titleFired||vu(t,n));break;case"error":console.error(""),console.error(v(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&bu();break}}import{render as vd}from"ink";import{resolveAuth as Cd}from"document360-engine";import{useCallback as z,useEffect as _e,useMemo as Yo,useRef as J,useState as F}from"react";import{Box as X,Text as S,useApp as Nu,useInput as _u,useStdout as Ou}from"ink";import{existsSync as zo,readFileSync as Di,readdirSync as Bi,writeFileSync as Ei}from"node:fs";import{basename as Et,isAbsolute as Mu,join as It}from"node:path";import{createSession as Ii,loginPkce as Lu,toStoredTokens as Uu,saveTokens as Wu,getAccessToken as Fu,resolveActiveProfile as de,resolveProjectId as Hu,getArticle as Bu,decodeJwtClaims as pt,isExpired as Ne,loadTokens as Ge,clearTokens as qu,clearProfileProject as Gu,setTitle as Yu,slugify as zu,touchSession as Vo,upsertSession as Vu,generateTitle as Ni,findByName as Ku,listSessions as Xu,renameSession as Ju,suggestNextAction as Qu,readProjectConfig as oe,writeProjectConfig as Zu,resolveModelSetting as Qo,loadProfileMap as _i,applyPull as ed,computeSyncStatus as Ko,planPull as td,inventoryRepo as nd,knownEnvironments as od,resolveEnvironment as rd,planPartitions as Xo,partitionEvenly as sd,screenshotPlaceholderIds as id,trackedArticlePaths as ad,runPartitioned as Tn,estimateBulkCost as Oi,resolveModelForOperation as Sn,readDocsPlan as ld,ensureDir as Mi,hintsDir as cd,architectureDir as ud,creatorNotesPath as Li,devHintsGuidePath as dd,DEFAULT_DOCS_DIR as qi,setProfileProject as pd}from"document360-engine";import{existsSync as Pu,mkdirSync as Tu,readFileSync as Su,writeFileSync as Ru}from"node:fs";import{join as mi}from"node:path";import{writerDir as ju}from"document360-engine";function gi(e){return mi(ju(e),".sessions")}function hi(e,t){return mi(gi(e),`${t}.json`)}function wi(e,t,n){try{Tu(gi(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Ru(hi(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Ho(e,t){try{let n=hi(e,t);if(!Pu(n))return[];let o=JSON.parse(Su(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Au=e=>`\x1B]0;${e}\x07`,Du=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function yi(e){process.stdout.isTTY&&process.stdout.write(e)}function At(e){yi(Au(e))}function bn(e){yi(Du(e))}var $n=["\xB7 "," \xB7"],Bo="\u{1F7E3}";fn();var Eu=/^(?:\d+[.)]|[-*•])\s+/;function ki(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
173
+ `)){let c=s.trim().replace(Eu,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let g=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!g||!o.has(g[1].toLowerCase()))continue;let w=`/${g[1].toLowerCase()}${g[2]?` ${g[2]}`:""}`;if(r.includes(w)||r.push(w),r.length>=n)break}return r}H();function Dt(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Pe(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function qo(e){return e.replace(/^[\w.-]+\//,"")}var vn=16,xi={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Go(e){return e.trim().split(/\s+/).slice(1).join(" ")}function bi(e,t){let n=Go(t);return e.some(r=>r.trim()===t.trim()||!!n&&Go(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&Go(r)===n)):[]}var Iu=/\[Pasted text #\d+ \+\d+ lines?\]/g;function $i(e){return e.replace(/\r\n?/g,`
174
174
  `)}function vi(e){return e.includes(`
175
175
  `)||e.length>200}function Ci(e,t){let n=t.split(`
176
176
  `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Pi(e,t){return e.replace(Iu,n=>t.get(n)??n)}function Ti(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Cn(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
@@ -180,25 +180,25 @@ Anything only a human knows that would help document this product. For example:
180
180
  `)){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 Jo,jsx as R,jsxs as U}from"react/jsx-runtime";var fd={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},Ui=` 1. /init \u2014 pick your Document360 environment & scaffold config
181
181
  2. /login \u2014 sign in; your project & workspace are selected automatically
182
182
  3. /devhints \u2014 have your builder hand over an architecture brief, then ask me to write the docs
183
- Press 1 to start.`;function md(e,t,n,o){let r=n.kind==="api"?"API key":n.kind==="subscription"?n.stored||process.platform==="darwin"?"subscription":"subscription \u2014 not signed in (run /doctor)":"not configured",s=Qo(e),c=oe(e),p=(c?.docsDir??qi).replace(/\/+$/,""),g=c?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${p}/ + config`,w={version:t,claude:r,model:s.model??"Claude Code default model",modelSource:fd[s.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:c!==null,mode:g};if(c===null)return w;try{let b=de(e,o);w.profile=b.name,w.apiUrl=b.connection.apiUrl,w.prod=b.production,w.project=b.project.projectName??b.project.projectId??"(chosen at login)";let j=Ge(b.name);if(j){let k={...pt(j.idToken)??{},...pt(j.accessToken)??{}},C=k.email??k.preferred_username??"signed in";Ne(j)?j.refreshToken&&(w.who=C,w.loggedOut=!1,w.sessionHint="session expired \u2014 refreshing\u2026"):(w.who=C,w.loggedOut=!1,w.sessionHint=`session valid until ${new Date(j.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return w}function gd(e,t){try{let n=de(e,t),o=Ge(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...pt(o.idToken)??{},...pt(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return Ne(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 Wi=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],jn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],hd="Ask me to write or update an article\u2026";function Rn({ch:e,dim:t}){let[n,o]=F(!0);return _e(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),R(S,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var wd=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Fi(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var yd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Hi(e){try{return Bi(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function kd(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Hi(It(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Hi(It(e,o)))}function bd({startTime:e,chars:t}){let[n,o]=F(0);_e(()=>{let g=setInterval(()=>o(w=>w+1),120);return()=>clearInterval(g)},[]);let r=jn[n%jn.length],s=Wi[Math.floor(n/16)%Wi.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return U(K,{children:[R(S,{color:B,children:` ${r} ${s}\u2026 `}),R(S,{color:"gray",children:`(${Ct(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var xd=12e4;function $d({p:e}){let[t,n]=F(0);_e(()=>{let _=setInterval(()=>n(W=>W+1),150);return()=>clearInterval(_)},[]);let o=jn[t%jn.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>=xd,g=e.verb??"Converting",w=e.unit??"article",b=e.rows.reduce((_,W)=>_+W.items,0),j=g.toLowerCase(),k=e.rows,C=0;if(k.length>vn){let _=k.findIndex(Z=>Z.status==="active"||Z.status==="pending"),W=Math.max(0,Math.min(_-2,k.length-vn));C=k.slice(0,W).filter(Z=>Z.status==="done").length,k=k.slice(W,W+vn)}let P=Math.min(40,Math.max(...k.map(_=>qo(_.label).length),0)),N=_=>_==="failed"?"red":_==="active"?B:void 0;return U(K,{flexDirection:"column",children:[U(K,{children:[R(S,{color:B,children:` ${o} ${g} ${b} ${w}${b===1?"":"s"} `}),R(S,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${Ct(r)} \xB7 esc to stop`})]}),C>0&&R(S,{dimColor:!0,children:` \u2714 +${C} done`}),k.map(_=>U(S,{color:N(_.status),dimColor:_.status==="done"||_.status==="pending",children:[` ${bi[_.status]} ${qo(_.label).padEnd(P)}`,_.status!=="pending"?` (${_.items} ${w}${_.items===1?"":"s"})`:"",_.status==="active"?` \u2190 ${j}\u2026`:""]},_.label)),p&&R(S,{color:"yellow",children:` \u26A0 no activity for ${Ct(s)} \u2014 press esc to stop if it's wedged`})]})}function Gi({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Nu(),[s,c]=F(n),[p,g]=F(null),[w,b]=F({text:"",pos:0}),j=w.text,k=z(l=>{b(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),C=z(l=>{b(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),P=z(()=>{b(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=Ti(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[N,_]=F(!1),[W,Z]=F(!1),[be,te]=F(0),[we,re]=F(null),[ft,V]=F([]),Ye=J(0),[Xi,Nt]=F(!1),[Ki,ze]=F(0),Oe=J(0),[mt,Ve]=F(0),[Xe,_t]=F(null),tr=J(new Map),Ji=J(0),Ke=J([]),pe=J(null);pe.current===null&&(pe.current=Ii({cwd:e,profileName:s,allowProdWrites:!1}));let xe=J({uuid:null,firstPrompt:null,titleFired:!1}),Ot=J(new Map),Je=J(!1),An=J([]),Se=J([]),Dn=J(null),[nr,Qe]=F(null),[Me,Le]=F(null),[$e,Ze]=F(null),[Re,et]=F(null),[se,tt]=F(null),[fe,nt]=F(null),[Ue,ot]=F(null),[or,Mt]=F(null),[me,We]=F(null),[le,rt]=F(null),[rr,En]=F([]),Fe=J([]),gt=J(!1),ge=J(null),[sr,X]=F(null),Lt=J(!1),Ut=J(null),[he,He]=F(null),[ir,st]=F(0),[ar,it]=F(0),[Qi,lr]=F(0),In=Yo(()=>{try{return Qo(e).model??"auto"}catch{return null}},[e,Qi]),{stdout:ye}=Ou(),[,Zi]=F(0),cr=J(`${ye.columns??80}x${ye.rows??24}`),je=z(()=>Math.max(20,(ye.columns??80)-1),[ye]),d=z(l=>{Ke.current.push(l),console.log(Zn(l,je()))},[je]);_e(()=>{let l=`d360-writer \xB7 ${nr??Et(e)}`;if(!N){xn(0),At(`${Bo} ${l}`);return}xn(3);let i=0;At(`${$n[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%$n.length,At(`${$n[i]} ${l}`)},400);return()=>clearInterval(a)},[N,e,nr]),_e(()=>()=>xn(0),[]),_e(()=>{if(d({kind:"banner",info:md(e,o,t,s)}),!oe(e)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
184
- ${Ui}`}),V(["/init"]);return}try{let l=de(e,s),i=Ge(l.name);i&&Ne(i)&&i.refreshToken?Fu({profile:l.name,connection:l.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),te(a=>a+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),V(["/login"])}):(!i||Ne(i))&&(d({kind:"note",tone:"warn",text:`Profile "${l.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),V(["/login"]))}catch{}try{let l=oe(e),i=de(e,s),a=Ge(i.name);l&&a&&!Ne(a)&&kd(e,l.authoritativeSourceFiles)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),V(["/scope"]))}catch{}},[]),_e(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let h=`${ye.columns??80}x${ye.rows??24}`;h!==cr.current&&(cr.current=h,Zi(u=>u+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+os(Ke.current,je())+"\x1B[?2026l")},80))},400)};return ye.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),ye.off("resize",a)}},[ye,je]);let Be=Math.max(20,(ye.columns??80)-1),ur=Yo(()=>gd(e,s),[e,s,be]),Nn=(()=>{let l=oe(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=It(e,(l.docsDir??qi).replace(/\/+$/,"")),a=(()=>{try{return zo(i)&&Bi(i).length>0}catch{return!1}})();try{let h=de(e,s),u=Ge(h.name);if(!(!!u&&!(Ne(u)&&!u.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${h.name}")\u2026`,isSetup:!0};if(!h.project.workspaceId&&!a)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return a?{text:hd,isSetup:!1}:{text:"Let's get started \u2014 try /devhints (best docs), or: write the docs for this repo",isSetup:!1}})(),ht=Or(j),dr=ht.length>0&&!N,_n=p!==null?ji(p,8,Be):null,Wt=me?me.paths.filter(l=>!me.query||l.toLowerCase().includes(me.query.toLowerCase())).slice(0,8):[],Ft=he?he.sessions.filter(l=>{let i=he.query.toLowerCase();return!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],ce=z((l,i)=>{pe.current?.close(),pe.current=Ii({cwd:e,resume:l,profileName:i??s,allowProdWrites:Je.current}),l||(xe.current={uuid:null,firstPrompt:null,titleFired:!1},Qe(null)),st(0),it(0)},[e,s]),pr=z((l,i,a)=>{if(wd.test(l))try{let h=de(e,s),u=typeof i.project_id=="string"&&i.project_id||h.project.projectId,m=kn(i,a),y=[],T=bn(a);l.endsWith("publish_article")&&T&&y.push(`Live: ${T}`),m&&u&&y.push(`Preview: ${yn(h.connection.portalUrl,u,m,h.project.languageCode??"en")}`),y.length>0&&d({kind:"link",lines:y})}catch{}},[e,s,d]),ve=z(async(l,i)=>{Nt(!0),re(null),V([]),Mt(null);let a=++Ye.current;i?.quietUser||d({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let h=xe.current;h.firstPrompt||(h.firstPrompt=i?.display??l),Oe.current=Date.now(),ze(0),_(!0),Ot.current.clear();let u="",m=!1,y=!1,T="",E=null,I=()=>{E||(E=setTimeout(()=>{E=null,g(T.length>0?T:null)},60))},ne=()=>{E&&clearTimeout(E),E=null,g(null)},G=()=>{if(T.trim()){let x=T.trimEnd();d({kind:"assistant",text:x})}T="",ne()};try{for await(let x of pe.current.send(l))if(x.type==="session"){if(!h.uuid){h.uuid=x.sessionId;let $=new Date().toISOString(),O=zu(h.firstPrompt??"session");Vu({uuid:x.sessionId,name:O,renamed:!1,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:$,updatedAt:$}),Qe(O)}}else if(x.type==="text"){T+=x.delta,u+=x.delta;let $=Ai(T);if($>0){let O=T.slice(0,$).trimEnd();O&&d({kind:"assistant",text:O}),T=T.slice($)}I(),ze(O=>O+x.delta.length)}else if(x.type==="tool"){m=!0;let $=hn(x.name,x.input);$&&(G(),d({kind:"tool",title:$.title,sep:$.sep,arg:$.arg}),Ot.current.set(x.id,{name:x.name,input:x.input}))}else if(x.type==="article_diff"){let $=qe(x.oldContent,x.newContent,je());$&&(G(),d({kind:"diff",added:$.added,removed:$.removed,lines:$.lines,hidden:$.hidden}))}else if(x.type==="tool_result"){x.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(x.output)&&(Lt.current=!0);let $=Ot.current.get(x.id);if($){Ot.current.delete(x.id),G();let O=wn(x.output,4,x.isError?void 0:$.name,$.input);d({kind:"tool-result",lines:O.lines,hidden:O.hidden,isError:x.isError}),x.isError||pr($.name,$.input,x.output)}}else if(x.type==="result"){G(),st(O=>O+x.outputTokens),it(O=>O+x.costUsd),d({kind:"done",seconds:Math.round((Date.now()-Oe.current)/1e3),tokens:x.outputTokens,costUsd:x.costUsd,ok:x.ok}),!y&&!m&&!u.trim()&&!gt.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."});let $=x.ok?ki(u,xt.map(O=>O.name)):[];if($.length>0?V($):x.ok&&u.trim()&&Qu(l,u,e).then(O=>{O&&Ye.current===a&&re(O)}).catch(()=>{}),h.uuid&&(Vo(h.uuid),!h.titleFired)){h.titleFired=!0;let O=h.uuid,Q=h.firstPrompt;Q&&Ni(Q,e).then(M=>{M&&(Yu(O,M),Qe(M))}).catch(()=>{})}}else x.type==="error"&&(G(),y=!0,x.kind==="auth"&&(Lt.current=!0),d({kind:"note",text:`agent error: ${x.message}`,tone:"error"}))}finally{_(!1),ne(),te(x=>x+1),xe.current.uuid&&wi(e,xe.current.uuid,Ke.current),Lt.current&&(Lt.current=!1,Ut.current=i?.display??l,V(["/login"])),gt.current&&(gt.current=!1,Fe.current.length>0&&(d({kind:"note",tone:"info",text:`(${Fe.current.length} queued message(s) discarded)`}),Fe.current=[],En([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,pr,je]),Ht=z(async l=>{let i=Ko(l),a=Sn(e,"standard");Oe.current=Date.now(),ze(0),_(!0);let h=new AbortController;ge.current=h,X({verb:"Publishing",total:i.length,done:0,active:[],rows:Dt(i),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${Pt} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let u of Tn({cwd:e,partitions:i,promptFor:m=>sn(m.paths),concurrency:Pt,profileName:s,allowProdWrites:Je.current,model:a.model,signal:h.signal}))if(u.type==="partition_status")u.status==="running"?X(m=>m&&{...m,active:[...m.active,u.label],rows:Pe(m.rows,u.label,"active"),lastAt:Date.now()}):X(m=>m&&{...m,active:m.active.filter(y=>y!==u.label),done:m.done+1,rows:Pe(m.rows,u.label,u.status==="done"?"done":"failed"),lastAt:Date.now()});else if(u.type==="partition_event")X(m=>{if(!m)return m;let y={...m,lastAt:Date.now()};return u.event.type==="tool"?y.tools=m.tools+1:u.event.type==="text"&&(y.chars=m.chars+u.event.delta.length),y});else if(u.type==="run_done"){it(T=>T+u.totalCostUsd),st(T=>T+u.results.reduce((E,I)=>E+I.outputTokens,0));let m=u.aborted?"Stopped. ":"",y=t.kind==="api"?"api":"subscription";d({kind:"note",tone:u.aborted?"warn":u.ok?"ok":"warn",text:m+oo(u.results,i,y).join(`
185
- `)})}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{ge.current=null,X(null),_(!1),te(u=>u+1)}},[e,s,d,t]),On=z(async l=>{await ve(no(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await an(e,s,l.replace(/\\/g,"/"));i.length>0&&(Mt(`Related articles not yet published (${i.length}):`),V([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ve]),Mn=z(l=>{let i=Ge(l);if(!i||Ne(i)&&!i.refreshToken)return null;let a={...pt(i.idToken)??{},...pt(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),Ln=z((l,i)=>{if(i){let a=oe(e);a&&(a.defaultProfile=l,Zu(a,e))}c(l),ce(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Mn(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),V(["/login"])),te(a=>a+1)},[e,d,ce,Mn]),Bt=z((l,i,a)=>{Vt(e,l,i,a.id,a.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),ce(),_i(e,l)||(d({kind:"note",tone:"info",text:"Setup complete. For the best docs, press tab to run /devhints \u2014 your builder hands over an architecture brief, then ask me to write the docs. (Or just ask me to analyze this repo.)"}),re("/devhints"))},[e,d,ce]),qt=z(async l=>{let i;try{i=await kt(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),V(["/workspace"]);return}if(i.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),h=a.length>0?a:i.workspaces;if(h.length===1){let u=h[0],m=i.workspaces.length-h.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),Bt(i.profile,i.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),V(["/workspace"])},[e,d,Bt]),fr=z((l,i)=>{Bn(e,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),ce(),qt(l)},[e,d,ce,qt]),Un=z(async l=>{let i;try{i=de(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await ct(e,i.name),h=a.find(u=>u.id===i.project.projectId);h?.name&&pd(e,i.name,{projectName:h.name})}catch{}await qt(i.name);return}d({kind:"note",tone:"info",text:"Next: pick the Document360 project."}),V(["/project"])}},[e,d,qt]),Gt=z(()=>{let l=Se.current[0];if(!l)return;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let a of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${a}`});l.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let i=qe(l.oldContent,l.newContent,je());d(i?{kind:"diff",added:i.added,removed:i.removed,lines:i.lines,hidden:i.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,je]),mr=z(l=>{if(Se.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Se.current.shift();try{ed({cwd:e,profileName:s},a),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Se.current.length===0&&V(h=>h.length>0?h:["/sync"])}catch(h){d({kind:"note",tone:"error",text:`Pull failed: ${h.message}`})}}else if(i==="n"||i==="no"){let a=Se.current.shift();d({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Se.current.length;return Se.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return Gt(),!0},[e,s,Gt,d]),gr=z(l=>{let i=Dn.current;if(!i)return!1;if(Dn.current=null,re(null),Ye.current++,l.trim()!==i.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:h}=Mo(e,i.targets);d({kind:"note",tone:h.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let u of h)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
183
+ Press 1 to start.`;function md(e,t,n,o){let r=n.kind==="api"?"API key":n.kind==="subscription"?n.stored||process.platform==="darwin"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)":"not configured",s=Qo(e),c=oe(e),p=(c?.docsDir??qi).replace(/\/+$/,""),g=c?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${p}/ + config`,w={version:t,claude:r,model:s.model??"Claude Code default model",modelSource:fd[s.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:c!==null,mode:g};if(c===null)return w;try{let x=de(e,o);w.profile=x.name,w.apiUrl=x.connection.apiUrl,w.prod=x.production,w.project=x.project.projectName??x.project.projectId??"(chosen at login)";let j=Ge(x.name);if(j){let k={...pt(j.idToken)??{},...pt(j.accessToken)??{}},C=k.email??k.preferred_username??"signed in";Ne(j)?j.refreshToken&&(w.who=C,w.loggedOut=!1,w.sessionHint="session expired \u2014 refreshing\u2026"):(w.who=C,w.loggedOut=!1,w.sessionHint=`session valid until ${new Date(j.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return w}function gd(e,t){try{let n=de(e,t),o=Ge(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...pt(o.idToken)??{},...pt(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return Ne(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 Wi=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],jn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],hd="Ask me to write or update an article\u2026";function Rn({ch:e,dim:t}){let[n,o]=F(!0);return _e(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),R(S,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var wd=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Fi(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var yd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Hi(e){try{return Bi(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function kd(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Hi(It(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Hi(It(e,o)))}function xd({startTime:e,chars:t}){let[n,o]=F(0);_e(()=>{let g=setInterval(()=>o(w=>w+1),120);return()=>clearInterval(g)},[]);let r=jn[n%jn.length],s=Wi[Math.floor(n/16)%Wi.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return U(X,{children:[R(S,{color:B,children:` ${r} ${s}\u2026 `}),R(S,{color:"gray",children:`(${Ct(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var bd=12e4;function $d({p:e}){let[t,n]=F(0);_e(()=>{let _=setInterval(()=>n(W=>W+1),150);return()=>clearInterval(_)},[]);let o=jn[t%jn.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>=bd,g=e.verb??"Converting",w=e.unit??"article",x=e.rows.reduce((_,W)=>_+W.items,0),j=g.toLowerCase(),k=e.rows,C=0;if(k.length>vn){let _=k.findIndex(Z=>Z.status==="active"||Z.status==="pending"),W=Math.max(0,Math.min(_-2,k.length-vn));C=k.slice(0,W).filter(Z=>Z.status==="done").length,k=k.slice(W,W+vn)}let P=Math.min(40,Math.max(...k.map(_=>qo(_.label).length),0)),N=_=>_==="failed"?"red":_==="active"?B:void 0;return U(X,{flexDirection:"column",children:[U(X,{children:[R(S,{color:B,children:` ${o} ${g} ${x} ${w}${x===1?"":"s"} `}),R(S,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${Ct(r)} \xB7 esc to stop`})]}),C>0&&R(S,{dimColor:!0,children:` \u2714 +${C} done`}),k.map(_=>U(S,{color:N(_.status),dimColor:_.status==="done"||_.status==="pending",children:[` ${xi[_.status]} ${qo(_.label).padEnd(P)}`,_.status!=="pending"?` (${_.items} ${w}${_.items===1?"":"s"})`:"",_.status==="active"?` \u2190 ${j}\u2026`:""]},_.label)),p&&R(S,{color:"yellow",children:` \u26A0 no activity for ${Ct(s)} \u2014 press esc to stop if it's wedged`})]})}function Gi({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Nu(),[s,c]=F(n),[p,g]=F(null),[w,x]=F({text:"",pos:0}),j=w.text,k=z(l=>{x(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),C=z(l=>{x(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),P=z(()=>{x(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=Ti(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[N,_]=F(!1),[W,Z]=F(!1),[xe,te]=F(0),[we,re]=F(null),[ft,V]=F([]),Ye=J(0),[Ki,Nt]=F(!1),[Xi,ze]=F(0),Oe=J(0),[mt,Ve]=F(0),[Ke,_t]=F(null),tr=J(new Map),Ji=J(0),Xe=J([]),pe=J(null);pe.current===null&&(pe.current=Ii({cwd:e,profileName:s,allowProdWrites:!1}));let be=J({uuid:null,firstPrompt:null,titleFired:!1}),Ot=J(new Map),Je=J(!1),An=J([]),Se=J([]),Dn=J(null),[nr,Qe]=F(null),[Me,Le]=F(null),[$e,Ze]=F(null),[Re,et]=F(null),[se,tt]=F(null),[fe,nt]=F(null),[Ue,ot]=F(null),[or,Mt]=F(null),[me,We]=F(null),[le,rt]=F(null),[rr,En]=F([]),Fe=J([]),gt=J(!1),ge=J(null),[sr,K]=F(null),Lt=J(!1),Ut=J(null),[he,He]=F(null),[ir,st]=F(0),[ar,it]=F(0),[Qi,lr]=F(0),In=Yo(()=>{try{return Qo(e).model??"auto"}catch{return null}},[e,Qi]),{stdout:ye}=Ou(),[,Zi]=F(0),cr=J(`${ye.columns??80}x${ye.rows??24}`),je=z(()=>Math.max(20,(ye.columns??80)-1),[ye]),d=z(l=>{Xe.current.push(l),console.log(Zn(l,je()))},[je]);_e(()=>{let l=`d360-writer \xB7 ${nr??Et(e)}`;if(!N){bn(0),At(`${Bo} ${l}`);return}bn(3);let i=0;At(`${$n[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%$n.length,At(`${$n[i]} ${l}`)},400);return()=>clearInterval(a)},[N,e,nr]),_e(()=>()=>bn(0),[]),_e(()=>{if(d({kind:"banner",info:md(e,o,t,s)}),!oe(e)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
184
+ ${Ui}`}),V(["/init"]);return}try{let l=de(e,s),i=Ge(l.name);i&&Ne(i)&&i.refreshToken?Fu({profile:l.name,connection:l.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),te(a=>a+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),V(["/login"])}):(!i||Ne(i))&&(d({kind:"note",tone:"warn",text:`Profile "${l.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),V(["/login"]))}catch{}try{let l=oe(e),i=de(e,s),a=Ge(i.name);l&&a&&!Ne(a)&&kd(e,l.authoritativeSourceFiles)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),V(["/scope"]))}catch{}},[]),_e(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let h=`${ye.columns??80}x${ye.rows??24}`;h!==cr.current&&(cr.current=h,Zi(u=>u+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+os(Xe.current,je())+"\x1B[?2026l")},80))},400)};return ye.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),ye.off("resize",a)}},[ye,je]);let Be=Math.max(20,(ye.columns??80)-1),ur=Yo(()=>gd(e,s),[e,s,xe]),Nn=(()=>{let l=oe(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=It(e,(l.docsDir??qi).replace(/\/+$/,"")),a=(()=>{try{return zo(i)&&Bi(i).length>0}catch{return!1}})();try{let h=de(e,s),u=Ge(h.name);if(!(!!u&&!(Ne(u)&&!u.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${h.name}")\u2026`,isSetup:!0};if(!h.project.workspaceId&&!a)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return a?{text:hd,isSetup:!1}:{text:"Let's get started \u2014 try /devhints (best docs), or: write the docs for this repo",isSetup:!1}})(),ht=Or(j),dr=ht.length>0&&!N,_n=p!==null?ji(p,8,Be):null,Wt=me?me.paths.filter(l=>!me.query||l.toLowerCase().includes(me.query.toLowerCase())).slice(0,8):[],Ft=he?he.sessions.filter(l=>{let i=he.query.toLowerCase();return!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],ce=z((l,i)=>{pe.current?.close(),pe.current=Ii({cwd:e,resume:l,profileName:i??s,allowProdWrites:Je.current}),l||(be.current={uuid:null,firstPrompt:null,titleFired:!1},Qe(null)),st(0),it(0)},[e,s]),pr=z((l,i,a)=>{if(wd.test(l))try{let h=de(e,s),u=typeof i.project_id=="string"&&i.project_id||h.project.projectId,m=kn(i,a),y=[],T=xn(a);l.endsWith("publish_article")&&T&&y.push(`Live: ${T}`),m&&u&&y.push(`Preview: ${yn(h.connection.portalUrl,u,m,h.project.languageCode??"en")}`),y.length>0&&d({kind:"link",lines:y})}catch{}},[e,s,d]),ve=z(async(l,i)=>{Nt(!0),re(null),V([]),Mt(null);let a=++Ye.current;i?.quietUser||d({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let h=be.current;h.firstPrompt||(h.firstPrompt=i?.display??l),Oe.current=Date.now(),ze(0),_(!0),Ot.current.clear();let u="",m=!1,y=!1,T="",E=null,I=()=>{E||(E=setTimeout(()=>{E=null,g(T.length>0?T:null)},60))},ne=()=>{E&&clearTimeout(E),E=null,g(null)},G=()=>{if(T.trim()){let b=T.trimEnd();d({kind:"assistant",text:b})}T="",ne()};try{for await(let b of pe.current.send(l))if(b.type==="session"){if(!h.uuid){h.uuid=b.sessionId;let $=new Date().toISOString(),O=zu(h.firstPrompt??"session");Vu({uuid:b.sessionId,name:O,renamed:!1,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:$,updatedAt:$}),Qe(O)}}else if(b.type==="text"){T+=b.delta,u+=b.delta;let $=Ai(T);if($>0){let O=T.slice(0,$).trimEnd();O&&d({kind:"assistant",text:O}),T=T.slice($)}I(),ze(O=>O+b.delta.length)}else if(b.type==="tool"){m=!0;let $=hn(b.name,b.input);$&&(G(),d({kind:"tool",title:$.title,sep:$.sep,arg:$.arg}),Ot.current.set(b.id,{name:b.name,input:b.input}))}else if(b.type==="article_diff"){let $=qe(b.oldContent,b.newContent,je());$&&(G(),d({kind:"diff",added:$.added,removed:$.removed,lines:$.lines,hidden:$.hidden}))}else if(b.type==="tool_result"){b.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(b.output)&&(Lt.current=!0);let $=Ot.current.get(b.id);if($){Ot.current.delete(b.id),G();let O=wn(b.output,4,b.isError?void 0:$.name,$.input);d({kind:"tool-result",lines:O.lines,hidden:O.hidden,isError:b.isError}),b.isError||pr($.name,$.input,b.output)}}else if(b.type==="result"){G(),st(O=>O+b.outputTokens),it(O=>O+b.costUsd),d({kind:"done",seconds:Math.round((Date.now()-Oe.current)/1e3),tokens:b.outputTokens,costUsd:b.costUsd,ok:b.ok}),!y&&!m&&!u.trim()&&!gt.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."});let $=b.ok?ki(u,bt.map(O=>O.name)):[];if($.length>0?V($):b.ok&&u.trim()&&Qu(l,u,e).then(O=>{O&&Ye.current===a&&re(O)}).catch(()=>{}),h.uuid&&(Vo(h.uuid),!h.titleFired)){h.titleFired=!0;let O=h.uuid,Q=h.firstPrompt;Q&&Ni(Q,e).then(M=>{M&&(Yu(O,M),Qe(M))}).catch(()=>{})}}else b.type==="error"&&(G(),y=!0,b.kind==="auth"&&(Lt.current=!0),d({kind:"note",text:`agent error: ${b.message}`,tone:"error"}))}finally{_(!1),ne(),te(b=>b+1),be.current.uuid&&wi(e,be.current.uuid,Xe.current),Lt.current&&(Lt.current=!1,Ut.current=i?.display??l,V(["/login"])),gt.current&&(gt.current=!1,Fe.current.length>0&&(d({kind:"note",tone:"info",text:`(${Fe.current.length} queued message(s) discarded)`}),Fe.current=[],En([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,pr,je]),Ht=z(async l=>{let i=Xo(l),a=Sn(e,"standard");Oe.current=Date.now(),ze(0),_(!0);let h=new AbortController;ge.current=h,K({verb:"Publishing",total:i.length,done:0,active:[],rows:Dt(i),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${Pt} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let u of Tn({cwd:e,partitions:i,promptFor:m=>sn(m.paths),concurrency:Pt,profileName:s,allowProdWrites:Je.current,model:a.model,signal:h.signal}))if(u.type==="partition_status")u.status==="running"?K(m=>m&&{...m,active:[...m.active,u.label],rows:Pe(m.rows,u.label,"active"),lastAt:Date.now()}):K(m=>m&&{...m,active:m.active.filter(y=>y!==u.label),done:m.done+1,rows:Pe(m.rows,u.label,u.status==="done"?"done":"failed"),lastAt:Date.now()});else if(u.type==="partition_event")K(m=>{if(!m)return m;let y={...m,lastAt:Date.now()};return u.event.type==="tool"?y.tools=m.tools+1:u.event.type==="text"&&(y.chars=m.chars+u.event.delta.length),y});else if(u.type==="run_done"){it(T=>T+u.totalCostUsd),st(T=>T+u.results.reduce((E,I)=>E+I.outputTokens,0));let m=u.aborted?"Stopped. ":"",y=t.kind==="api"?"api":"subscription";d({kind:"note",tone:u.aborted?"warn":u.ok?"ok":"warn",text:m+oo(u.results,i,y).join(`
185
+ `)})}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{ge.current=null,K(null),_(!1),te(u=>u+1)}},[e,s,d,t]),On=z(async l=>{await ve(no(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await an(e,s,l.replace(/\\/g,"/"));i.length>0&&(Mt(`Related articles not yet published (${i.length}):`),V([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ve]),Mn=z(l=>{let i=Ge(l);if(!i||Ne(i)&&!i.refreshToken)return null;let a={...pt(i.idToken)??{},...pt(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),Ln=z((l,i)=>{if(i){let a=oe(e);a&&(a.defaultProfile=l,Zu(a,e))}c(l),ce(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Mn(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),V(["/login"])),te(a=>a+1)},[e,d,ce,Mn]),Bt=z((l,i,a)=>{Vt(e,l,i,a.id,a.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),ce(),_i(e,l)||(d({kind:"note",tone:"info",text:"Setup complete. For the best docs, press tab to run /devhints \u2014 your builder hands over an architecture brief, then ask me to write the docs. (Or just ask me to analyze this repo.)"}),re("/devhints"))},[e,d,ce]),qt=z(async l=>{let i;try{i=await kt(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),V(["/workspace"]);return}if(i.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),h=a.length>0?a:i.workspaces;if(h.length===1){let u=h[0],m=i.workspaces.length-h.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),Bt(i.profile,i.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),V(["/workspace"])},[e,d,Bt]),fr=z((l,i)=>{Bn(e,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),ce(),qt(l)},[e,d,ce,qt]),Un=z(async l=>{let i;try{i=de(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await ct(e,i.name),h=a.find(u=>u.id===i.project.projectId);h?.name&&pd(e,i.name,{projectName:h.name})}catch{}await qt(i.name);return}d({kind:"note",tone:"info",text:"Next: pick the Document360 project."}),V(["/project"])}},[e,d,qt]),Gt=z(()=>{let l=Se.current[0];if(!l)return;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let a of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${a}`});l.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let i=qe(l.oldContent,l.newContent,je());d(i?{kind:"diff",added:i.added,removed:i.removed,lines:i.lines,hidden:i.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,je]),mr=z(l=>{if(Se.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Se.current.shift();try{ed({cwd:e,profileName:s},a),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Se.current.length===0&&V(h=>h.length>0?h:["/sync"])}catch(h){d({kind:"note",tone:"error",text:`Pull failed: ${h.message}`})}}else if(i==="n"||i==="no"){let a=Se.current.shift();d({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Se.current.length;return Se.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return Gt(),!0},[e,s,Gt,d]),gr=z(l=>{let i=Dn.current;if(!i)return!1;if(Dn.current=null,re(null),Ye.current++,l.trim()!==i.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:h}=Mo(e,i.targets);d({kind:"note",tone:h.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let u of h)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
186
186
  ${Ui}`}),V(["/init"]),Nt(!1),!0},[e,d]),hr=z(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),h=i.slice(1);switch(Nt(!0),a){case"help":d({kind:"note",tone:"info",text:nn().join(`
187
- `)});return;case"exit":case"quit":pe.current?.close(),r();return;case"clear":ce(),Ke.current=[],Nt(!1),re(null),Ye.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=de(e,s)}catch(m){d({kind:"note",tone:"error",text:m.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),Z(!0);try{let m=await Lu(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},T=>d({kind:"note",tone:"info",text:T})),y=Uu(u.name,m);Wu(y),await Qt(y,u.name,T=>d({kind:"note",tone:"info",text:T})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${Kt(y)}`}),await Un(s),Ut.current&&(re(Ut.current),Ut.current=null,d({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(m){d({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{Z(!1),te(m=>m+1)}return}case"allow-prod":{let u=!1;try{u=de(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Je.current=!0,ce(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Co(h.join(" ")),m=xe.current.uuid;if(!m){d({kind:"note",tone:"error",text:"Send a message first \u2014 sessions save once the agent replies."});return}if(!u){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let y=xe.current.firstPrompt??"";Ni(y,e).then(T=>{T?(re(`/rename ${T}`),d({kind:"note",tone:"info",text:`Suggestion: "${T}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Ju(m,u),Qe(u),At(`${Bo} d360-writer \xB7 ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=h[0],m=oe(e);if(!u){let y=Object.entries(m?.profiles??{});if(y.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let T=y.map(([ne,G])=>({name:ne,env:G.connection?.environment??"custom",prod:G.production===!0,who:Mn(ne)})),E=s??m?.defaultProfile,I=Math.max(0,T.findIndex(ne=>ne.name===E));Ze({cursor:I,current:I,rows:T});return}if(u==="add"){let y=Po(e,h[1],h[2]);if(y){d({kind:"note",tone:"error",text:y});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),Ln(h[1],!1);return}if(!m?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}Ln(u,!0);return}case"doctor":await Rt(h,{cwd:e});return;case"mcp":await rn(h);return;case"init":{if(oe(e)){d({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 u=od().map(m=>({name:m,apiUrl:rd(m).apiUrl}));et({cursor:0,rows:u});return}case"resume":{let u=h.join(" ").trim(),m=Ku(e).filter(E=>E.uuid!==xe.current.uuid);if(!u){if(!m.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}He({query:"",cursor:0,sessions:m});return}let y=Xu(e,u);if(!y){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}ce(y.uuid),xe.current={uuid:y.uuid,firstPrompt:y.firstPrompt,titleFired:!0},Qe(y.name),Vo(y.uuid),Ke.current=[];let T=Ho(e,y.uuid);for(let E of T)d(E);d({kind:"note",tone:"ok",text:T.length?`Resumed "${y.name}" \u2014 restored ${T.length} message(s); continue where you left off.`:`Resumed "${y.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=h.join(" ").trim(),m;try{m=await kt(e,s)}catch(T){d({kind:"note",tone:"error",text:`Could not list workspaces: ${T.message}`});return}if(!u){let T=m.workspaces.map(I=>({id:I.id,name:I.name??I.id,type:I.workspace_type}));if(T.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let E=Math.max(0,T.findIndex(I=>I.id===m.current));tt({cursor:E,current:E,rows:T,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let y=Hn(m.workspaces,u);if(!y){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}Bt(m.profile,m.projectId,y);return}case"project":{let u=h.join(" ").trim(),m;try{m=await ct(e,s)}catch(T){d({kind:"note",tone:"error",text:`Could not list projects: ${T.message} (signed in? try /login)`});return}if(!u){let T=m.projects.map(I=>({id:I.id,name:I.name??I.id,sub:I.sub_domain}));if(T.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let E=T.findIndex(I=>I.id===m.current);nt({cursor:Math.max(0,E),current:E,rows:T,profile:m.profile,environment:m.environment});return}let y=Pr(m.projects,u);if(!y){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${m.projects.map(T=>T.name??T.id).join(", ")}`});return}fr(m.profile,y);return}case"logout":{let u;try{u=de(e,s).name}catch(y){d({kind:"note",tone:"error",text:y.message});return}let m=qu(u);Gu(e,u),ce(),te(y=>y+1),d({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${u}" and cleared its project/workspace selection.`:`Profile "${u}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),V(["/login"]);return}case"publish":{if(h[0]==="--related"&&h[1]){let m=await an(e,s,h[1].replace(/\\/g,"/"));if(m.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Ht(m);return}if(h[0]&&h[0]!=="--all"){await On(h[0]);return}let u=h[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Xo({cwd:e,profileName:s}),y=Tt(m.entries);if(y.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let T=m.counts["unknown-base"]??0;T>0&&d({kind:"note",tone:"info",text:`(${T} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(u){await Ht(y.map(T=>T.path));return}ot({cursor:0,rows:ss(y)})}catch(m){d({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let u=h.join(" ").trim();if(!u){let y=[];try{y=Object.keys(_i(e,de(e,s).name)?.articles??{})}catch{}if(y.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}We({query:"",cursor:0,paths:y});return}let m=Mu(u)?u:It(e,u);if(zo(m)){try{d({kind:"preview",name:Et(m),text:Fi(Di(m,"utf8"))})}catch(y){d({kind:"note",tone:"error",text:`Could not read ${m}: ${y.message}`})}return}if(yd.test(u)){try{let y=de(e,s),T={profile:y.name,connection:y.connection},E=y.project.projectId??Hu(T),I=await Bu(T,E,u);d({kind:"preview",name:I.title??u,text:I.content??"*(article has no content)*"})}catch(y){d({kind:"note",tone:"error",text:`Could not fetch article: ${y.message}`})}return}d({kind:"note",tone:"error",text:`"${u}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let u=h[0]?.trim();if(!u){let E=pn(Qo(e));Le({cursor:E,current:E});return}let{lines:m,changed:y,effective:T}=St(e,u);for(let E of m)d({kind:"note",tone:E.startsWith("\u26A0")?"warn":E.startsWith("\u2713")?"ok":"info",text:E});y&&(lr(E=>E+1),pe.current?.setModel(T));return}case"convert":{if(!oe(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:m}=ao(h),y=ad(e,s);if(y.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let T=lo(y,u);if(T.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${y.length} are tracked overall.)`});return}let E=Ko(T),I=3,ne=`/convert${u?` --scope ${u}`:""} --run`,G=Sn(e,"light");if(!m){let $=Oi({files:co(e,T),op:"convert",model:G.model}),O=u?`Scope: ${u} (${T.length} of ${y.length} tracked)
187
+ `)});return;case"exit":case"quit":pe.current?.close(),r();return;case"clear":ce(),Xe.current=[],Nt(!1),re(null),Ye.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=de(e,s)}catch(m){d({kind:"note",tone:"error",text:m.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),Z(!0);try{let m=await Lu(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},T=>d({kind:"note",tone:"info",text:T})),y=Uu(u.name,m);Wu(y),await Qt(y,u.name,T=>d({kind:"note",tone:"info",text:T})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${Xt(y)}`}),await Un(s),Ut.current&&(re(Ut.current),Ut.current=null,d({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(m){d({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{Z(!1),te(m=>m+1)}return}case"allow-prod":{let u=!1;try{u=de(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Je.current=!0,ce(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Co(h.join(" ")),m=be.current.uuid;if(!m){d({kind:"note",tone:"error",text:"Send a message first \u2014 sessions save once the agent replies."});return}if(!u){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let y=be.current.firstPrompt??"";Ni(y,e).then(T=>{T?(re(`/rename ${T}`),d({kind:"note",tone:"info",text:`Suggestion: "${T}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Ju(m,u),Qe(u),At(`${Bo} d360-writer \xB7 ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=h[0],m=oe(e);if(!u){let y=Object.entries(m?.profiles??{});if(y.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let T=y.map(([ne,G])=>({name:ne,env:G.connection?.environment??"custom",prod:G.production===!0,who:Mn(ne)})),E=s??m?.defaultProfile,I=Math.max(0,T.findIndex(ne=>ne.name===E));Ze({cursor:I,current:I,rows:T});return}if(u==="add"){let y=Po(e,h[1],h[2]);if(y){d({kind:"note",tone:"error",text:y});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),Ln(h[1],!1);return}if(!m?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}Ln(u,!0);return}case"doctor":await Rt(h,{cwd:e});return;case"mcp":await rn(h);return;case"init":{if(oe(e)){d({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 u=od().map(m=>({name:m,apiUrl:rd(m).apiUrl}));et({cursor:0,rows:u});return}case"resume":{let u=h.join(" ").trim(),m=Xu(e).filter(E=>E.uuid!==be.current.uuid);if(!u){if(!m.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}He({query:"",cursor:0,sessions:m});return}let y=Ku(e,u);if(!y){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}ce(y.uuid),be.current={uuid:y.uuid,firstPrompt:y.firstPrompt,titleFired:!0},Qe(y.name),Vo(y.uuid),Xe.current=[];let T=Ho(e,y.uuid);for(let E of T)d(E);d({kind:"note",tone:"ok",text:T.length?`Resumed "${y.name}" \u2014 restored ${T.length} message(s); continue where you left off.`:`Resumed "${y.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=h.join(" ").trim(),m;try{m=await kt(e,s)}catch(T){d({kind:"note",tone:"error",text:`Could not list workspaces: ${T.message}`});return}if(!u){let T=m.workspaces.map(I=>({id:I.id,name:I.name??I.id,type:I.workspace_type}));if(T.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let E=Math.max(0,T.findIndex(I=>I.id===m.current));tt({cursor:E,current:E,rows:T,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let y=Hn(m.workspaces,u);if(!y){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}Bt(m.profile,m.projectId,y);return}case"project":{let u=h.join(" ").trim(),m;try{m=await ct(e,s)}catch(T){d({kind:"note",tone:"error",text:`Could not list projects: ${T.message} (signed in? try /login)`});return}if(!u){let T=m.projects.map(I=>({id:I.id,name:I.name??I.id,sub:I.sub_domain}));if(T.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let E=T.findIndex(I=>I.id===m.current);nt({cursor:Math.max(0,E),current:E,rows:T,profile:m.profile,environment:m.environment});return}let y=Pr(m.projects,u);if(!y){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${m.projects.map(T=>T.name??T.id).join(", ")}`});return}fr(m.profile,y);return}case"logout":{let u;try{u=de(e,s).name}catch(y){d({kind:"note",tone:"error",text:y.message});return}let m=qu(u);Gu(e,u),ce(),te(y=>y+1),d({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${u}" and cleared its project/workspace selection.`:`Profile "${u}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),V(["/login"]);return}case"publish":{if(h[0]==="--related"&&h[1]){let m=await an(e,s,h[1].replace(/\\/g,"/"));if(m.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Ht(m);return}if(h[0]&&h[0]!=="--all"){await On(h[0]);return}let u=h[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Ko({cwd:e,profileName:s}),y=Tt(m.entries);if(y.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let T=m.counts["unknown-base"]??0;T>0&&d({kind:"note",tone:"info",text:`(${T} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(u){await Ht(y.map(T=>T.path));return}ot({cursor:0,rows:ss(y)})}catch(m){d({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let u=h.join(" ").trim();if(!u){let y=[];try{y=Object.keys(_i(e,de(e,s).name)?.articles??{})}catch{}if(y.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}We({query:"",cursor:0,paths:y});return}let m=Mu(u)?u:It(e,u);if(zo(m)){try{d({kind:"preview",name:Et(m),text:Fi(Di(m,"utf8"))})}catch(y){d({kind:"note",tone:"error",text:`Could not read ${m}: ${y.message}`})}return}if(yd.test(u)){try{let y=de(e,s),T={profile:y.name,connection:y.connection},E=y.project.projectId??Hu(T),I=await Bu(T,E,u);d({kind:"preview",name:I.title??u,text:I.content??"*(article has no content)*"})}catch(y){d({kind:"note",tone:"error",text:`Could not fetch article: ${y.message}`})}return}d({kind:"note",tone:"error",text:`"${u}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let u=h[0]?.trim();if(!u){let E=pn(Qo(e));Le({cursor:E,current:E});return}let{lines:m,changed:y,effective:T}=St(e,u);for(let E of m)d({kind:"note",tone:E.startsWith("\u26A0")?"warn":E.startsWith("\u2713")?"ok":"info",text:E});y&&(lr(E=>E+1),pe.current?.setModel(T));return}case"convert":{if(!oe(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:m}=ao(h),y=ad(e,s);if(y.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let T=lo(y,u);if(T.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${y.length} are tracked overall.)`});return}let E=Xo(T),I=3,ne=`/convert${u?` --scope ${u}`:""} --run`,G=Sn(e,"light");if(!m){let $=Oi({files:co(e,T),op:"convert",model:G.model}),O=u?`Scope: ${u} (${T.length} of ${y.length} tracked)
188
188
  `:"",Q=`
189
189
  Model: ${G.model}${G.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:O+po(E,$,I).join(`
190
- `)+Q}),V([ne]);return}Oe.current=Date.now(),ze(0),_(!0);let x=new AbortController;ge.current=x,X({verb:"Converting",total:E.length,done:0,active:[],rows:Dt(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${T.length} articles across ${E.length} partitions (\u2264${I} agents at once) on ${G.model}\u2026 (esc to stop)`});try{for await(let $ of Tn({cwd:e,partitions:E,promptFor:uo,concurrency:I,profileName:s,allowProdWrites:Je.current,model:G.model,signal:x.signal}))if($.type==="partition_status")$.status==="running"?X(O=>O&&{...O,active:[...O.active,$.label],rows:Pe(O.rows,$.label,"active"),lastAt:Date.now()}):X(O=>O&&{...O,active:O.active.filter(Q=>Q!==$.label),done:O.done+1,rows:Pe(O.rows,$.label,$.status==="done"?"done":"failed"),lastAt:Date.now()});else if($.type==="partition_event")X(O=>{if(!O)return O;let Q={...O,lastAt:Date.now()};return $.event.type==="tool"?Q.tools=O.tools+1:$.event.type==="text"&&(Q.chars=O.chars+$.event.delta.length),Q});else if($.type==="run_done"){it(M=>M+$.totalCostUsd),st(M=>M+$.results.reduce((Y,ie)=>Y+ie.outputTokens,0));let O=$.aborted?"Stopped. ":"",Q=t.kind==="api"?"api":"subscription";d({kind:"note",tone:$.aborted?"warn":$.ok?"ok":"warn",text:O+fo($.results,E,Q).join(`
191
- `)})}}catch($){d({kind:"note",tone:"error",text:`Convert run failed: ${$.message}`})}finally{ge.current=null,X(null),_(!1),te($=>$+1)}return}case"write":{if(!oe(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=ld(e);if(u.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:y,run:T}=go(h),{docsDir:E,targets:I,reason:ne}=bo(e,u,{scope:m,path:y});if(I.length===0){d({kind:"note",tone:"warn",text:ne??"Nothing to write."});return}let G=Ko(I),x=5,$=Sn(e,"standard");if(!T&&!!!y){let M=Oi({files:ho(e,u,I),op:"write",model:$.model}),Y=m?`Scope: ${m} (${I.length} pending)
190
+ `)+Q}),V([ne]);return}Oe.current=Date.now(),ze(0),_(!0);let b=new AbortController;ge.current=b,K({verb:"Converting",total:E.length,done:0,active:[],rows:Dt(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${T.length} articles across ${E.length} partitions (\u2264${I} agents at once) on ${G.model}\u2026 (esc to stop)`});try{for await(let $ of Tn({cwd:e,partitions:E,promptFor:uo,concurrency:I,profileName:s,allowProdWrites:Je.current,model:G.model,signal:b.signal}))if($.type==="partition_status")$.status==="running"?K(O=>O&&{...O,active:[...O.active,$.label],rows:Pe(O.rows,$.label,"active"),lastAt:Date.now()}):K(O=>O&&{...O,active:O.active.filter(Q=>Q!==$.label),done:O.done+1,rows:Pe(O.rows,$.label,$.status==="done"?"done":"failed"),lastAt:Date.now()});else if($.type==="partition_event")K(O=>{if(!O)return O;let Q={...O,lastAt:Date.now()};return $.event.type==="tool"?Q.tools=O.tools+1:$.event.type==="text"&&(Q.chars=O.chars+$.event.delta.length),Q});else if($.type==="run_done"){it(M=>M+$.totalCostUsd),st(M=>M+$.results.reduce((Y,ie)=>Y+ie.outputTokens,0));let O=$.aborted?"Stopped. ":"",Q=t.kind==="api"?"api":"subscription";d({kind:"note",tone:$.aborted?"warn":$.ok?"ok":"warn",text:O+fo($.results,E,Q).join(`
191
+ `)})}}catch($){d({kind:"note",tone:"error",text:`Convert run failed: ${$.message}`})}finally{ge.current=null,K(null),_(!1),te($=>$+1)}return}case"write":{if(!oe(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=ld(e);if(u.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:y,run:T}=go(h),{docsDir:E,targets:I,reason:ne}=xo(e,u,{scope:m,path:y});if(I.length===0){d({kind:"note",tone:"warn",text:ne??"Nothing to write."});return}let G=Xo(I),b=5,$=Sn(e,"standard");if(!T&&!!!y){let M=Oi({files:ho(e,u,I),op:"write",model:$.model}),Y=m?`Scope: ${m} (${I.length} pending)
192
192
  `:"",ie=`
193
- Model: ${$.model}${$.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:Y+yo(G,M,x).join(`
194
- `)+ie}),V([`/write${m?` --scope ${m}`:" --all"} --run`]);return}Oe.current=Date.now(),ze(0),_(!0);let Q=new AbortController;ge.current=Q,X({verb:"Writing",total:G.length,done:0,active:[],rows:Dt(G),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${I.length} article${I.length===1?"":"s"} across ${G.length} partition${G.length===1?"":"s"} (\u2264${x} agents at once) on ${$.model}${$.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let M of Tn({cwd:e,partitions:G,promptFor:Y=>wo(Y,E),concurrency:x,profileName:s,allowProdWrites:Je.current,model:$.model,signal:Q.signal}))if(M.type==="partition_status")M.status==="running"?X(Y=>Y&&{...Y,active:[...Y.active,M.label],rows:Pe(Y.rows,M.label,"active"),lastAt:Date.now()}):X(Y=>Y&&{...Y,active:Y.active.filter(ie=>ie!==M.label),done:Y.done+1,rows:Pe(Y.rows,M.label,M.status==="done"?"done":"failed"),lastAt:Date.now()});else if(M.type==="partition_event")X(Y=>{if(!Y)return Y;let ie={...Y,lastAt:Date.now()};return M.event.type==="tool"?ie.tools=Y.tools+1:M.event.type==="text"&&(ie.chars=Y.chars+M.event.delta.length),ie});else if(M.type==="run_done"){it(Fn=>Fn+M.totalCostUsd),st(Fn=>Fn+M.results.reduce((na,oa)=>na+oa.outputTokens,0));let Y=M.aborted?"Stopped. ":"",ie=t.kind==="api"?"api":"subscription";d({kind:"note",tone:M.aborted?"warn":M.ok?"ok":"warn",text:Y+ko(M.results,G,ie).join(`
195
- `)}),!M.aborted&&M.ok&&V(["/publish --all","/screenshot --all"])}}catch(M){d({kind:"note",tone:"error",text:`Write run failed: ${M.message}`})}finally{ge.current=null,X(null),_(!1),te(M=>M+1)}return}case"draft":{if(!oe(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:m}=xo(e);if(u.length===0&&m===0){d({kind:"note",tone:"info",text:vo});return}let y=h.join(" ").trim();if(!y&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
193
+ Model: ${$.model}${$.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:Y+yo(G,M,b).join(`
194
+ `)+ie}),V([`/write${m?` --scope ${m}`:" --all"} --run`]);return}Oe.current=Date.now(),ze(0),_(!0);let Q=new AbortController;ge.current=Q,K({verb:"Writing",total:G.length,done:0,active:[],rows:Dt(G),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${I.length} article${I.length===1?"":"s"} across ${G.length} partition${G.length===1?"":"s"} (\u2264${b} agents at once) on ${$.model}${$.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let M of Tn({cwd:e,partitions:G,promptFor:Y=>wo(Y,E),concurrency:b,profileName:s,allowProdWrites:Je.current,model:$.model,signal:Q.signal}))if(M.type==="partition_status")M.status==="running"?K(Y=>Y&&{...Y,active:[...Y.active,M.label],rows:Pe(Y.rows,M.label,"active"),lastAt:Date.now()}):K(Y=>Y&&{...Y,active:Y.active.filter(ie=>ie!==M.label),done:Y.done+1,rows:Pe(Y.rows,M.label,M.status==="done"?"done":"failed"),lastAt:Date.now()});else if(M.type==="partition_event")K(Y=>{if(!Y)return Y;let ie={...Y,lastAt:Date.now()};return M.event.type==="tool"?ie.tools=Y.tools+1:M.event.type==="text"&&(ie.chars=Y.chars+M.event.delta.length),ie});else if(M.type==="run_done"){it(Fn=>Fn+M.totalCostUsd),st(Fn=>Fn+M.results.reduce((na,oa)=>na+oa.outputTokens,0));let Y=M.aborted?"Stopped. ":"",ie=t.kind==="api"?"api":"subscription";d({kind:"note",tone:M.aborted?"warn":M.ok?"ok":"warn",text:Y+ko(M.results,G,ie).join(`
195
+ `)}),!M.aborted&&M.ok&&V(["/publish --all","/screenshot --all"])}}catch(M){d({kind:"note",tone:"error",text:`Write run failed: ${M.message}`})}finally{ge.current=null,K(null),_(!1),te(M=>M+1)}return}case"draft":{if(!oe(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:m}=bo(e);if(u.length===0&&m===0){d({kind:"note",tone:"info",text:vo});return}let y=h.join(" ").trim();if(!y&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
196
196
  ${u.map(I=>` \u2022 ${I.name} (${I.docCount} doc${I.docCount===1?"":"s"})`).join(`
197
- `)}`}),V(u.map(I=>`/draft ${I.name}`));return}let T="",E;if(y){let I=$o(u,y);I?T=I:E=y}else T=u[0]?.name??"";await ve(dn(T,E),{display:y?`/draft ${y}`:"/draft",quietUser:!0});return}case"sync":{let u=(h[0]??"status").toLowerCase();try{if(u==="status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let m=await Xo({cwd:e,profileName:s});d({kind:"note",tone:"info",text:un(m).join(`
198
- `)});return}if(u==="pull"){let m=h[1];if(!m){d({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let y;if(m==="--all"){if(d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),y=(await Xo({cwd:e,profileName:s})).entries.filter(I=>I.status==="remote-ahead"&&I.path).map(I=>I.path),y.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing is remote-ahead \u2014 no pulls needed. (Conflicts are never bulk-pulled; pull them one by one.)"});return}}else y=[m.replace(/\\/g,"/")];let T=[];for(let E of y)T.push(await td({cwd:e,profileName:s,relPath:E}));Se.current=T,Gt();return}d({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${u} \u2014 use /sync or /sync pull <path>|--all.`})}catch(m){d({kind:"note",tone:"error",text:`Sync failed: ${m.message}`})}return}case"scope":{if(!oe(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=nd(e);if(u.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}rt({cursor:0,rows:u.map(m=>({...m,checked:m.recommended}))});return}case"audit":case"capture-setup":{let m=await(a==="audit"?ln:jt)(h,void 0);if(m.kind==="forward-to-agent"&&m.prompt&&await ve(m.prompt,{display:m.display,quietUser:!0}),a==="capture-setup"){let y=Do(e);y&&d({kind:"note",tone:"info",text:y.join(`
197
+ `)}`}),V(u.map(I=>`/draft ${I.name}`));return}let T="",E;if(y){let I=$o(u,y);I?T=I:E=y}else T=u[0]?.name??"";await ve(dn(T,E),{display:y?`/draft ${y}`:"/draft",quietUser:!0});return}case"sync":{let u=(h[0]??"status").toLowerCase();try{if(u==="status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let m=await Ko({cwd:e,profileName:s});d({kind:"note",tone:"info",text:un(m).join(`
198
+ `)});return}if(u==="pull"){let m=h[1];if(!m){d({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let y;if(m==="--all"){if(d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),y=(await Ko({cwd:e,profileName:s})).entries.filter(I=>I.status==="remote-ahead"&&I.path).map(I=>I.path),y.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing is remote-ahead \u2014 no pulls needed. (Conflicts are never bulk-pulled; pull them one by one.)"});return}}else y=[m.replace(/\\/g,"/")];let T=[];for(let E of y)T.push(await td({cwd:e,profileName:s,relPath:E}));Se.current=T,Gt();return}d({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${u} \u2014 use /sync or /sync pull <path>|--all.`})}catch(m){d({kind:"note",tone:"error",text:`Sync failed: ${m.message}`})}return}case"scope":{if(!oe(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=nd(e);if(u.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}rt({cursor:0,rows:u.map(m=>({...m,checked:m.recommended}))});return}case"audit":case"capture-setup":{let m=await(a==="audit"?ln:jt)(h,void 0);if(m.kind==="forward-to-agent"&&m.prompt&&await ve(m.prompt,{display:m.display,quietUser:!0}),a==="capture-setup"){let y=Do(e);y&&d({kind:"note",tone:"info",text:y.join(`
199
199
  `)})}return}case"devhints":{if(!oe(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}Mi(cd(e)),Mi(ud(e)),zo(Li(e))||Ei(Li(e),Io()),Ei(dd(e),Eo()),d({kind:"note",tone:"info",text:No().join(`
200
200
  `)});return}case"screenshot":{let u=Ro(h);if(u.mode==="list"){if(!oe(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Ao(jo(e,u.scope),u.scope).join(`
201
- `)});return}if(u.mode==="single"){let x=await mn(h);x.kind==="forward-to-agent"&&x.prompt&&await ve(x.prompt,{display:x.display,quietUser:!0});return}if(!oe(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=u.mode==="scope"?u.scope:void 0,y=id(e,{scope:m}).map(x=>x.id);if(y.length===0){d({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let T=6,E=sd(y,3),I=Sn(e,"standard");Oe.current=Date.now(),ze(0),_(!0);let ne=new AbortController;ge.current=ne,X({verb:"Authoring",unit:"spec",total:E.length,done:0,active:[],rows:Dt(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${y.length} screenshot spec${y.length===1?"":"s"} across ${E.length} partition${E.length===1?"":"s"} (\u2264${T} agents at once) on ${I.model}${I.forced?" (forced)":""}\u2026 (esc to stop)`});let G=!1;try{for await(let x of Tn({cwd:e,partitions:E,promptFor:Ys,concurrency:T,profileName:s,allowProdWrites:Je.current,model:I.model,signal:ne.signal}))if(x.type==="partition_status")x.status==="running"?X($=>$&&{...$,active:[...$.active,x.label],rows:Pe($.rows,x.label,"active"),lastAt:Date.now()}):X($=>$&&{...$,active:$.active.filter(O=>O!==x.label),done:$.done+1,rows:Pe($.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_event")X($=>{if(!$)return $;let O={...$,lastAt:Date.now()};return x.event.type==="tool"?O.tools=$.tools+1:x.event.type==="text"&&(O.chars=$.chars+x.event.delta.length),O});else if(x.type==="run_done"){it(M=>M+x.totalCostUsd),st(M=>M+x.results.reduce((Y,ie)=>Y+ie.outputTokens,0));let $=x.results.filter(M=>M.ok).length,O=x.aborted?"Stopped. ":"";G=!x.aborted&&u.setup;let Q=x.aborted?"":G?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:x.aborted?"warn":x.ok?"ok":"warn",text:`${O}Authored specs \u2014 ${$}/${x.results.length} batches ok.${Q}`})}}catch(x){d({kind:"note",tone:"error",text:`Spec authoring failed: ${x.message}`})}finally{ge.current=null,X(null),_(!1),te(x=>x+1)}if(G){let x=await jt();x.kind==="forward-to-agent"&&x.prompt&&await ve(x.prompt,{display:x.display,quietUser:!0});let $=Do(e);$&&d({kind:"note",tone:"info",text:$.join(`
201
+ `)});return}if(u.mode==="single"){let b=await mn(h);b.kind==="forward-to-agent"&&b.prompt&&await ve(b.prompt,{display:b.display,quietUser:!0});return}if(!oe(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=u.mode==="scope"?u.scope:void 0,y=id(e,{scope:m}).map(b=>b.id);if(y.length===0){d({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let T=6,E=sd(y,3),I=Sn(e,"standard");Oe.current=Date.now(),ze(0),_(!0);let ne=new AbortController;ge.current=ne,K({verb:"Authoring",unit:"spec",total:E.length,done:0,active:[],rows:Dt(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${y.length} screenshot spec${y.length===1?"":"s"} across ${E.length} partition${E.length===1?"":"s"} (\u2264${T} agents at once) on ${I.model}${I.forced?" (forced)":""}\u2026 (esc to stop)`});let G=!1;try{for await(let b of Tn({cwd:e,partitions:E,promptFor:Ys,concurrency:T,profileName:s,allowProdWrites:Je.current,model:I.model,signal:ne.signal}))if(b.type==="partition_status")b.status==="running"?K($=>$&&{...$,active:[...$.active,b.label],rows:Pe($.rows,b.label,"active"),lastAt:Date.now()}):K($=>$&&{...$,active:$.active.filter(O=>O!==b.label),done:$.done+1,rows:Pe($.rows,b.label,b.status==="done"?"done":"failed"),lastAt:Date.now()});else if(b.type==="partition_event")K($=>{if(!$)return $;let O={...$,lastAt:Date.now()};return b.event.type==="tool"?O.tools=$.tools+1:b.event.type==="text"&&(O.chars=$.chars+b.event.delta.length),O});else if(b.type==="run_done"){it(M=>M+b.totalCostUsd),st(M=>M+b.results.reduce((Y,ie)=>Y+ie.outputTokens,0));let $=b.results.filter(M=>M.ok).length,O=b.aborted?"Stopped. ":"";G=!b.aborted&&u.setup;let Q=b.aborted?"":G?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:b.aborted?"warn":b.ok?"ok":"warn",text:`${O}Authored specs \u2014 ${$}/${b.results.length} batches ok.${Q}`})}}catch(b){d({kind:"note",tone:"error",text:`Spec authoring failed: ${b.message}`})}finally{ge.current=null,K(null),_(!1),te(b=>b+1)}if(G){let b=await jt();b.kind==="forward-to-agent"&&b.prompt&&await ve(b.prompt,{display:b.display,quietUser:!0});let $=Do(e);$&&d({kind:"note",tone:"info",text:$.join(`
202
202
  `)})}return}case"reset":{let u=Oo(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Dn.current={repoName:Et(e),targets:u},d({kind:"note",tone:"warn",text:Lo(e,u).join(`
203
- `)}),re(Et(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,Gt,d,ce,ve,Ht,On,Un]),Yt=z(l=>{let i=(l??j).trim();if(k(""),_t(null),Ve(0),i.startsWith("/")&&(re(null),Ye.current++,Mt(null),V(h=>xi(h,i))),!i||gr(i)||mr(i))return;An.current.push(i);let a=Pi(i,tr.current);i.startsWith("/")?(d({kind:"user",text:i}),hr(a)):ve(a,{display:i})},[j,gr,mr,hr,ve]),wr=z(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=$i(l);if(vi(i)){let a=Ci(++Ji.current,i);tr.current.set(a,i),C(a)}else C(i);return}C(l)},[C]),at=Math.max(10,Be-6),yr=Yo(()=>Cn(w.text,at),[w.text,at]),Wn=z(l=>b(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),zt=z(l=>b(i=>({...i,pos:Si(Cn(i.text,at),i.pos,l)})),[at]),wt=z(l=>b(i=>({...i,pos:Ri(Cn(i.text,at),i.pos,l)})),[at]),ea=["\x1B[H","\x1B[1~","\x1BOH"],ta=["\x1B[F","\x1B[4~","\x1BOF"],kr=z((l,i)=>i.leftArrow?(Wn(-1),!0):i.rightArrow?(Wn(1),!0):l&&ea.includes(l)?(wt("start"),!0):l&&ta.includes(l)?(wt("end"),!0):i.ctrl&&l==="a"?(wt("start"),!0):i.ctrl&&l==="e"?(wt("end"),!0):!1,[Wn,wt]);return _u((l,i)=>{if(i.ctrl&&l==="c"){pe.current?.close(),r();return}if(!W){if(N){if(i.escape){if(ge.current){ge.current.signal.aborted||(d({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),ge.current.abort());return}gt.current||(gt.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),pe.current?.interrupt());return}if(i.return){let a=j.trim();if(!a)return;Fe.current.push(a),En([...Fe.current]),k("");return}if(kr(l,i))return;if(i.upArrow){zt(-1);return}if(i.downArrow){zt(1);return}if(i.backspace||i.delete){P();return}l&&!i.ctrl&&!i.meta&&wr(l);return}if(Me){if(i.upArrow){Le(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Le(a=>a&&{...a,cursor:Math.min(ke.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ke.length){Le(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ke[Me.cursor];Le(null);let{lines:h,changed:u,effective:m}=St(e,a.value??"default");for(let y of h)d({kind:"note",tone:y.startsWith("\u26A0")?"warn":y.startsWith("\u2713")?"ok":"info",text:y});u&&(lr(y=>y+1),pe.current?.setModel(m));return}if(l==="s"){let a=ke[Me.cursor];Le(null),pe.current?.setModel(a.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){Le(null);return}return}if($e){if(i.upArrow){Ze(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ze(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=$e.rows.length){Ze(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=$e.rows[$e.cursor];Ze(null),Ln(a.name,i.return===!0);return}if(i.escape){Ze(null);return}return}if(Re){if(i.upArrow){et(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){et(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.rows.length){et(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Re.rows[Re.cursor].name;if(et(null),!Gr(e,a).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${a}").`});let u=(()=>{try{let m=Ge(a);return m&&!(Ne(m)&&!m.refreshToken)?m:null}catch{return null}})();u?(d({kind:"note",tone:"info",text:`Already signed in to ${a}.`}),(async()=>(await Qt(u,a,m=>d({kind:"note",tone:"info",text:m})),await Un(a)))()):(d({kind:"note",tone:"info",text:`Next: sign in to Document360 (${a}).`}),V(["/login"])),te(m=>m+1);return}if(i.escape){et(null);return}return}if(se){if(i.upArrow){tt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){tt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=se.rows.length){tt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=se.rows[se.cursor],{profile:h,projectId:u}=se;tt(null),Bt(h,u,a);return}if(i.escape){tt(null);return}return}if(fe){if(i.upArrow){nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){nt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=fe.rows.length){nt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=fe.rows[fe.cursor],{profile:h}=fe;nt(null),fr(h,a);return}if(i.escape){nt(null);return}return}if(le){if(i.upArrow){rt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){rt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){rt(a=>a&&{...a,rows:a.rows.map((h,u)=>u===a.cursor?{...h,checked:!h.checked}:h)});return}if(i.return){let a=le.rows.filter(h=>h.checked).map(h=>h.path);if(rt(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}ro(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer.json`});for(let h of a)d({kind:"note",tone:"info",text:` ${h}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){rt(null);return}return}if(Ue){if(i.upArrow){ot(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){ot(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ue.rows.length){ot(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Ue.rows[Ue.cursor];ot(null),a.kind==="article"?On(a.paths[0]):Ht(a.paths);return}if(i.escape){ot(null);return}return}if(me){if(i.escape){We(null);return}if(i.upArrow){We(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){We(a=>a&&{...a,cursor:Math.min(Math.max(0,Wt.length-1),a.cursor+1)});return}if(i.return){let a=Wt[me.cursor];if(a){We(null);try{d({kind:"preview",name:Et(a),text:Fi(Di(It(e,a),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${a}: ${h.message}`})}}return}if(i.backspace||i.delete){We(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){We(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(he){if(i.escape){He(null);return}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(Math.max(0,Ft.length-1),a.cursor+1)});return}if(i.return){let a=Ft[he.cursor];if(a){He(null),ce(a.uuid),xe.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Qe(a.name),Vo(a.uuid),Ke.current=[];let h=Ho(e,a.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${a.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){He(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){He(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!j&&we){k(we),re(null),Ye.current++;return}if(!j&&ft.length>0&&l&&/^[1-9]$/.test(l)){let a=ft[Number(l)-1];if(a){k(a);return}}if(!kr(l,i)){if(dr){if(i.upArrow){Ve(a=>Math.max(0,a-1));return}if(i.downArrow){Ve(a=>Math.min(ht.length-1,a+1));return}if(i.tab){k("/"+(ht[mt]?.name??"")+" "),Ve(0);return}if(i.return){let a=ht[mt];if(a){let h=j.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Mr(a.usage)&&!h){k("/"+a.name+" "),Ve(0);return}Yt("/"+a.name+(h?" "+h:""));return}}}else{if(i.upArrow){if(j!==""&&Xe===null){zt(-1);return}let a=An.current;if(!a.length)return;let h=Xe===null?a.length-1:Math.max(0,Xe-1);_t(h),k(a[h]??"");return}if(i.downArrow){if(j!==""&&Xe===null){zt(1);return}let a=An.current;if(Xe===null)return;let h=Xe+1;h>=a.length?(_t(null),k("")):(_t(h),k(a[h]??""));return}}if(i.return){Yt();return}if(i.backspace||i.delete){P();return}if(i.escape){k(""),Ve(0),re(null),V([]),Mt(null);return}l&&!i.ctrl&&!i.meta&&wr(l)}}}),_e(()=>{if(N||W)return;let l=Fe.current.shift();l!==void 0&&(En([...Fe.current]),Yt(l))},[N,W,Yt]),U(K,{flexDirection:"column",width:Be,children:[_n!==null&&U(K,{marginTop:1,flexDirection:"column",children:[_n.truncated&&R(S,{dimColor:!0,children:"\u2026"}),R(S,{children:_n.text})]}),N&&(sr?R($d,{p:sr}):R(bd,{startTime:Oe.current,chars:Ki})),R(K,{borderStyle:"round",borderColor:ur.prod?"yellow":B,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:j?yr.map((l,i)=>{let a=w.text.slice(l.start,l.end),h=i===Pn(yr,w.pos),u=Math.min(w.pos,l.end)-l.start;return U(S,{children:[R(S,{color:B,children:i===0?"> ":" "}),h?U(Jo,{children:[a.slice(0,u),R(Rn,{ch:a[u]??" "}),a.slice(u+1)]}):a||" "]},`${i}-${l.start}`)}):U(S,{children:[R(S,{color:B,children:"> "}),we&&!N?U(Jo,{children:[R(Rn,{ch:we[0],dim:!0}),R(S,{color:"gray",children:we.slice(1)}),R(S,{dimColor:!0,children:" (tab)"})]}):Nn.isSetup||!Xi?U(Jo,{children:[R(Rn,{ch:Nn.text[0],dim:!0}),R(S,{color:"gray",children:Nn.text.slice(1)})]}):R(Rn,{ch:" "})]})}),rr.length>0&&R(K,{flexDirection:"column",paddingX:1,children:rr.map((l,i)=>R(S,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Me?U(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:"Select model"}),R(S,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),ke.map((l,i)=>U(S,{color:i===Me.cursor?B:void 0,children:[i===Me.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===Me.current?" \u2714":""}`.padEnd(16),R(S,{color:"gray",children:l.desc})]},l.label)),R(S,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):$e?U(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:"Switch connection profile"}),$e.rows.map((l,i)=>U(S,{color:i===$e.cursor?B:void 0,children:[i===$e.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===$e.current?" \u2714":""}`.padEnd(20),R(S,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?R(S,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),R(S,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Re?U(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:"Pick your Document360 environment"}),Re.rows.map((l,i)=>U(S,{color:i===Re.cursor?B:void 0,children:[i===Re.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),R(S,{color:"gray",children:l.apiUrl})]},l.name)),R(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):se?U(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:"Switch workspace"}),R(S,{dimColor:!0,children:`environment ${se.environment} \xB7 project ${se.projectName??`${se.projectId.slice(0,8)}\u2026`}`}),se.rows.map((l,i)=>U(S,{color:i===se.cursor?B:void 0,children:[i===se.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===se.current?" \u2714":""}`.padEnd(30),R(S,{color:"gray",children:l.type??""})]},l.id)),R(S,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):fe?U(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:"Choose project"}),R(S,{dimColor:!0,children:`environment ${fe.environment}`}),fe.rows.map((l,i)=>U(S,{color:i===fe.cursor?B:void 0,children:[i===fe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===fe.current?" \u2714":""}`.padEnd(30),R(S,{color:"gray",children:l.sub??""})]},l.id)),R(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):le?(()=>{let i=Math.min(Math.max(0,le.cursor-Math.floor(7)),Math.max(0,le.rows.length-14)),a=le.rows.slice(i,i+14),h=le.rows.filter(u=>u.checked).length;return U(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:`Which folders back the user docs? (${h} selected of ${le.rows.length})`}),i>0?R(S,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((u,m)=>{let y=i+m;return U(S,{color:y===le.cursor?B:void 0,children:[y===le.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Be-34)),R(S,{color:"gray",children:cn(u)})]},u.path)}),i+14<le.rows.length?R(S,{dimColor:!0,children:` \u2193 ${le.rows.length-i-14} more`}):null,R(S,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Ue?U(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Ue.rows.map((l,i)=>{let a=i===Ue.cursor,h=l.indent?" ":" ",u=`${i+1}.`.padEnd(3);return U(S,{color:a?B:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${h}${u} ${l.label}`.padEnd(Math.min(56,Be-24)),l.note?R(S,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),R(S,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):me?U(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:`Preview article${me.query?` \u2014 filter: ${me.query}`:" (type to filter)"}`}),Wt.length===0?R(S,{color:"gray",children:"no articles match"}):Wt.map((l,i)=>U(S,{color:i===me.cursor?B:void 0,children:[i===me.cursor?"\u276F ":" ",l]},l)),R(S,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):he?U(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:`Resume session${he.query?` \u2014 filter: ${he.query}`:" (type to filter)"}`}),Ft.length===0?R(S,{color:"gray",children:"no sessions match"}):Ft.map((l,i)=>U(S,{color:i===he.cursor?B:void 0,children:[i===he.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),R(S,{color:i===he.cursor?B:"gray",children:l.firstPrompt.slice(0,Math.max(10,Be-40))})]},l.uuid)),R(S,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):dr?R(K,{flexDirection:"column",children:ht.map((l,i)=>U(S,{color:i===mt?B:void 0,children:[i===mt?"\u276F ":" ",l.usage.padEnd(22)," ",R(S,{color:i===mt?B:"gray",children:l.name==="model"&&In?`${l.desc} (currently ${In})`:l.desc})]},l.name))}):!j&&ft.length>0?U(K,{flexDirection:"column",paddingX:1,children:[or?R(S,{color:B,children:or}):null,ft.map((l,i)=>U(S,{children:[R(S,{color:B,children:i+1})," ",l.slice(0,Math.max(20,Be-5))]},l)),R(S,{dimColor:!0,children:`press 1-${ft.length} to fill the command \xB7 esc dismiss`})]}):R(K,{paddingX:1,children:U(S,{color:"gray",children:[ur.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${In??"model n/a"}${t.kind==="api"?ar>0?` \xB7 ${ae(ar)}`:"":ir>0?` \xB7 ${Ee(ir)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}H();import{jsx as Pd}from"react/jsx-runtime";async function Yi(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Cd(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 ${A("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${A("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=vd(Pd(Gi,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
203
+ `)}),re(Et(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,Gt,d,ce,ve,Ht,On,Un]),Yt=z(l=>{let i=(l??j).trim();if(k(""),_t(null),Ve(0),i.startsWith("/")&&(re(null),Ye.current++,Mt(null),V(h=>bi(h,i))),!i||gr(i)||mr(i))return;An.current.push(i);let a=Pi(i,tr.current);i.startsWith("/")?(d({kind:"user",text:i}),hr(a)):ve(a,{display:i})},[j,gr,mr,hr,ve]),wr=z(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=$i(l);if(vi(i)){let a=Ci(++Ji.current,i);tr.current.set(a,i),C(a)}else C(i);return}C(l)},[C]),at=Math.max(10,Be-6),yr=Yo(()=>Cn(w.text,at),[w.text,at]),Wn=z(l=>x(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),zt=z(l=>x(i=>({...i,pos:Si(Cn(i.text,at),i.pos,l)})),[at]),wt=z(l=>x(i=>({...i,pos:Ri(Cn(i.text,at),i.pos,l)})),[at]),ea=["\x1B[H","\x1B[1~","\x1BOH"],ta=["\x1B[F","\x1B[4~","\x1BOF"],kr=z((l,i)=>i.leftArrow?(Wn(-1),!0):i.rightArrow?(Wn(1),!0):l&&ea.includes(l)?(wt("start"),!0):l&&ta.includes(l)?(wt("end"),!0):i.ctrl&&l==="a"?(wt("start"),!0):i.ctrl&&l==="e"?(wt("end"),!0):!1,[Wn,wt]);return _u((l,i)=>{if(i.ctrl&&l==="c"){pe.current?.close(),r();return}if(!W){if(N){if(i.escape){if(ge.current){ge.current.signal.aborted||(d({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),ge.current.abort());return}gt.current||(gt.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),pe.current?.interrupt());return}if(i.return){let a=j.trim();if(!a)return;Fe.current.push(a),En([...Fe.current]),k("");return}if(kr(l,i))return;if(i.upArrow){zt(-1);return}if(i.downArrow){zt(1);return}if(i.backspace||i.delete){P();return}l&&!i.ctrl&&!i.meta&&wr(l);return}if(Me){if(i.upArrow){Le(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Le(a=>a&&{...a,cursor:Math.min(ke.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ke.length){Le(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ke[Me.cursor];Le(null);let{lines:h,changed:u,effective:m}=St(e,a.value??"default");for(let y of h)d({kind:"note",tone:y.startsWith("\u26A0")?"warn":y.startsWith("\u2713")?"ok":"info",text:y});u&&(lr(y=>y+1),pe.current?.setModel(m));return}if(l==="s"){let a=ke[Me.cursor];Le(null),pe.current?.setModel(a.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){Le(null);return}return}if($e){if(i.upArrow){Ze(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ze(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=$e.rows.length){Ze(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=$e.rows[$e.cursor];Ze(null),Ln(a.name,i.return===!0);return}if(i.escape){Ze(null);return}return}if(Re){if(i.upArrow){et(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){et(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.rows.length){et(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Re.rows[Re.cursor].name;if(et(null),!Gr(e,a).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${a}").`});let u=(()=>{try{let m=Ge(a);return m&&!(Ne(m)&&!m.refreshToken)?m:null}catch{return null}})();u?(d({kind:"note",tone:"info",text:`Already signed in to ${a}.`}),(async()=>(await Qt(u,a,m=>d({kind:"note",tone:"info",text:m})),await Un(a)))()):(d({kind:"note",tone:"info",text:`Next: sign in to Document360 (${a}).`}),V(["/login"])),te(m=>m+1);return}if(i.escape){et(null);return}return}if(se){if(i.upArrow){tt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){tt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=se.rows.length){tt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=se.rows[se.cursor],{profile:h,projectId:u}=se;tt(null),Bt(h,u,a);return}if(i.escape){tt(null);return}return}if(fe){if(i.upArrow){nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){nt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=fe.rows.length){nt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=fe.rows[fe.cursor],{profile:h}=fe;nt(null),fr(h,a);return}if(i.escape){nt(null);return}return}if(le){if(i.upArrow){rt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){rt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){rt(a=>a&&{...a,rows:a.rows.map((h,u)=>u===a.cursor?{...h,checked:!h.checked}:h)});return}if(i.return){let a=le.rows.filter(h=>h.checked).map(h=>h.path);if(rt(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}ro(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer.json`});for(let h of a)d({kind:"note",tone:"info",text:` ${h}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){rt(null);return}return}if(Ue){if(i.upArrow){ot(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){ot(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ue.rows.length){ot(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Ue.rows[Ue.cursor];ot(null),a.kind==="article"?On(a.paths[0]):Ht(a.paths);return}if(i.escape){ot(null);return}return}if(me){if(i.escape){We(null);return}if(i.upArrow){We(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){We(a=>a&&{...a,cursor:Math.min(Math.max(0,Wt.length-1),a.cursor+1)});return}if(i.return){let a=Wt[me.cursor];if(a){We(null);try{d({kind:"preview",name:Et(a),text:Fi(Di(It(e,a),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${a}: ${h.message}`})}}return}if(i.backspace||i.delete){We(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){We(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(he){if(i.escape){He(null);return}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(Math.max(0,Ft.length-1),a.cursor+1)});return}if(i.return){let a=Ft[he.cursor];if(a){He(null),ce(a.uuid),be.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Qe(a.name),Vo(a.uuid),Xe.current=[];let h=Ho(e,a.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${a.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){He(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){He(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!j&&we){k(we),re(null),Ye.current++;return}if(!j&&ft.length>0&&l&&/^[1-9]$/.test(l)){let a=ft[Number(l)-1];if(a){k(a);return}}if(!kr(l,i)){if(dr){if(i.upArrow){Ve(a=>Math.max(0,a-1));return}if(i.downArrow){Ve(a=>Math.min(ht.length-1,a+1));return}if(i.tab){k("/"+(ht[mt]?.name??"")+" "),Ve(0);return}if(i.return){let a=ht[mt];if(a){let h=j.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Mr(a.usage)&&!h){k("/"+a.name+" "),Ve(0);return}Yt("/"+a.name+(h?" "+h:""));return}}}else{if(i.upArrow){if(j!==""&&Ke===null){zt(-1);return}let a=An.current;if(!a.length)return;let h=Ke===null?a.length-1:Math.max(0,Ke-1);_t(h),k(a[h]??"");return}if(i.downArrow){if(j!==""&&Ke===null){zt(1);return}let a=An.current;if(Ke===null)return;let h=Ke+1;h>=a.length?(_t(null),k("")):(_t(h),k(a[h]??""));return}}if(i.return){Yt();return}if(i.backspace||i.delete){P();return}if(i.escape){k(""),Ve(0),re(null),V([]),Mt(null);return}l&&!i.ctrl&&!i.meta&&wr(l)}}}),_e(()=>{if(N||W)return;let l=Fe.current.shift();l!==void 0&&(En([...Fe.current]),Yt(l))},[N,W,Yt]),U(X,{flexDirection:"column",width:Be,children:[_n!==null&&U(X,{marginTop:1,flexDirection:"column",children:[_n.truncated&&R(S,{dimColor:!0,children:"\u2026"}),R(S,{children:_n.text})]}),N&&(sr?R($d,{p:sr}):R(xd,{startTime:Oe.current,chars:Xi})),R(X,{borderStyle:"round",borderColor:ur.prod?"yellow":B,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:j?yr.map((l,i)=>{let a=w.text.slice(l.start,l.end),h=i===Pn(yr,w.pos),u=Math.min(w.pos,l.end)-l.start;return U(S,{children:[R(S,{color:B,children:i===0?"> ":" "}),h?U(Jo,{children:[a.slice(0,u),R(Rn,{ch:a[u]??" "}),a.slice(u+1)]}):a||" "]},`${i}-${l.start}`)}):U(S,{children:[R(S,{color:B,children:"> "}),we&&!N?U(Jo,{children:[R(Rn,{ch:we[0],dim:!0}),R(S,{color:"gray",children:we.slice(1)}),R(S,{dimColor:!0,children:" (tab)"})]}):Nn.isSetup||!Ki?U(Jo,{children:[R(Rn,{ch:Nn.text[0],dim:!0}),R(S,{color:"gray",children:Nn.text.slice(1)})]}):R(Rn,{ch:" "})]})}),rr.length>0&&R(X,{flexDirection:"column",paddingX:1,children:rr.map((l,i)=>R(S,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Me?U(X,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:"Select model"}),R(S,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),ke.map((l,i)=>U(S,{color:i===Me.cursor?B:void 0,children:[i===Me.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===Me.current?" \u2714":""}`.padEnd(16),R(S,{color:"gray",children:l.desc})]},l.label)),R(S,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):$e?U(X,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:"Switch connection profile"}),$e.rows.map((l,i)=>U(S,{color:i===$e.cursor?B:void 0,children:[i===$e.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===$e.current?" \u2714":""}`.padEnd(20),R(S,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?R(S,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),R(S,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Re?U(X,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:"Pick your Document360 environment"}),Re.rows.map((l,i)=>U(S,{color:i===Re.cursor?B:void 0,children:[i===Re.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),R(S,{color:"gray",children:l.apiUrl})]},l.name)),R(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):se?U(X,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:"Switch workspace"}),R(S,{dimColor:!0,children:`environment ${se.environment} \xB7 project ${se.projectName??`${se.projectId.slice(0,8)}\u2026`}`}),se.rows.map((l,i)=>U(S,{color:i===se.cursor?B:void 0,children:[i===se.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===se.current?" \u2714":""}`.padEnd(30),R(S,{color:"gray",children:l.type??""})]},l.id)),R(S,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):fe?U(X,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:"Choose project"}),R(S,{dimColor:!0,children:`environment ${fe.environment}`}),fe.rows.map((l,i)=>U(S,{color:i===fe.cursor?B:void 0,children:[i===fe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===fe.current?" \u2714":""}`.padEnd(30),R(S,{color:"gray",children:l.sub??""})]},l.id)),R(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):le?(()=>{let i=Math.min(Math.max(0,le.cursor-Math.floor(7)),Math.max(0,le.rows.length-14)),a=le.rows.slice(i,i+14),h=le.rows.filter(u=>u.checked).length;return U(X,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:`Which folders back the user docs? (${h} selected of ${le.rows.length})`}),i>0?R(S,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((u,m)=>{let y=i+m;return U(S,{color:y===le.cursor?B:void 0,children:[y===le.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Be-34)),R(S,{color:"gray",children:cn(u)})]},u.path)}),i+14<le.rows.length?R(S,{dimColor:!0,children:` \u2193 ${le.rows.length-i-14} more`}):null,R(S,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Ue?U(X,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Ue.rows.map((l,i)=>{let a=i===Ue.cursor,h=l.indent?" ":" ",u=`${i+1}.`.padEnd(3);return U(S,{color:a?B:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${h}${u} ${l.label}`.padEnd(Math.min(56,Be-24)),l.note?R(S,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),R(S,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):me?U(X,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:`Preview article${me.query?` \u2014 filter: ${me.query}`:" (type to filter)"}`}),Wt.length===0?R(S,{color:"gray",children:"no articles match"}):Wt.map((l,i)=>U(S,{color:i===me.cursor?B:void 0,children:[i===me.cursor?"\u276F ":" ",l]},l)),R(S,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):he?U(X,{flexDirection:"column",paddingX:1,children:[R(S,{color:B,bold:!0,children:`Resume session${he.query?` \u2014 filter: ${he.query}`:" (type to filter)"}`}),Ft.length===0?R(S,{color:"gray",children:"no sessions match"}):Ft.map((l,i)=>U(S,{color:i===he.cursor?B:void 0,children:[i===he.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),R(S,{color:i===he.cursor?B:"gray",children:l.firstPrompt.slice(0,Math.max(10,Be-40))})]},l.uuid)),R(S,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):dr?R(X,{flexDirection:"column",children:ht.map((l,i)=>U(S,{color:i===mt?B:void 0,children:[i===mt?"\u276F ":" ",l.usage.padEnd(22)," ",R(S,{color:i===mt?B:"gray",children:l.name==="model"&&In?`${l.desc} (currently ${In})`:l.desc})]},l.name))}):!j&&ft.length>0?U(X,{flexDirection:"column",paddingX:1,children:[or?R(S,{color:B,children:or}):null,ft.map((l,i)=>U(S,{children:[R(S,{color:B,children:i+1})," ",l.slice(0,Math.max(20,Be-5))]},l)),R(S,{dimColor:!0,children:`press 1-${ft.length} to fill the command \xB7 esc dismiss`})]}):R(X,{paddingX:1,children:U(S,{color:"gray",children:[ur.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${In??"model n/a"}${t.kind==="api"?ar>0?` \xB7 ${ae(ar)}`:"":ir>0?` \xB7 ${Ee(ir)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}H();import{jsx as Pd}from"react/jsx-runtime";async function Yi(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Cd(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 ${A("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${A("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=vd(Pd(Gi,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
204
204
  `),process.exit(0)}var jd=Sd(import.meta.url),zi=jd("../package.json"),Te=new Td;function Zo(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Te.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=>{Zo(e),await Jt({profile:e.profile,manual:e.manual})});Te.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Zo(e),await Er({profile:e.profile})});Te.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Zo(e),await Dr({profile:e.profile})});var er=Te.command("profile").description("Manage connection profiles for the current repo");er.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Zt(process.cwd()));er.command("use <name>").description("Set the default profile for this repo").action(e=>en(process.cwd(),e));er.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>tn(process.cwd(),e));var Vi=Te.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Vi.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>lt(process.cwd(),e.profile));Vi.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await vr(process.cwd(),e,t.profile)});Te.command("logs").description("Show the Document360 API log files (send these to support when reporting a problem)").action(()=>Nr());Te.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(()=>(fn(),Ls)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Te.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(zi.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(Rd.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 _r(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 fi(e.cwd,e.auth,e.profile):await Yi(e.cwd,e.auth,e.profile,zi.version)});Te.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "document360-writer",
3
- "version": "0.4.64",
3
+ "version": "0.4.65",
4
4
  "description": "Standalone documentation agent CLI. Reads your code, writes your docs. Specialized for Document360 publishing.",
5
5
  "type": "module",
6
6
  "bin": {