document360-writer 0.4.47 → 0.4.48

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 +42 -42
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,53 +1,53 @@
1
1
  #!/usr/bin/env node
2
- var Ci=Object.defineProperty;var tr=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Pi=(e,t)=>{for(var n in t)Ci(e,n,{get:t[n],enumerable:!0})};import Ae from"picocolors";var G,Si,Ti,Ri,nr,ht,f,b,O,_,j,Z,Pe,q=tr(()=>{"use strict";G="#7f56d9",[Si,Ti,Ri]=[127,86,217],nr=e=>Ae.isColorSupported?`\x1B[38;2;${Si};${Ti};${Ri}m${e}\x1B[39m`:e,ht=e=>Ae.bold(nr(e)),f=e=>Ae.dim(e),b=e=>Ae.red(e),O=e=>Ae.yellow(e),_=e=>Ae.green(e),j=nr,Z=e=>Ae.gray(e),Pe=e=>Ae.bold(e)});var ls={};Pi(ls,{doctorCommand:()=>Pt,renderDoctorChecks:()=>as,runDoctorChecks:()=>is});import{existsSync as gl}from"node:fs";import{d360GetAll as hl,getAccessToken as kl,isExpired as co,loadProfileMap as wl,loadTokens as yl,packageSkillsDir as ss,projectConfigPath as xl,readProjectConfig as $l,resolveActiveProfile as bl,resolveAuth as vl,resolveModelSetting as Cl}from"document360-engine";async function is(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=vl("auto");t.push(o.kind==="none"?{level:"fail",label:"Claude auth: not configured",fix:"Set ANTHROPIC_API_KEY, or sign in to Claude Code once (subscription reuse)"}:{level:"ok",label:`Claude auth: ${o.kind==="api"?"API key":"subscription"}`});let r=Cl(e);t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`});let s=$l(e);if(!s)return t.push({level:"fail",label:`No ${xl(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??"user-docs").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 d=s.authoritativeSourceFiles??[];t.push(d.length>0?{level:"ok",label:`Sources: docs grounded in ${d.length} path(s) (${d.slice(0,3).join(", ")}${d.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 m;try{m=bl(e),t.push({level:"ok",label:`Profile: ${m.name} (${m.connection.name})${m.production?" \u26A0 PRODUCTION":""}`})}catch(D){return t.push({level:"fail",label:`Profile config: ${D.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let h=yl(m.name);h?co(h)&&!h.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):co(h)?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(h.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${m.name})`}),t.push(m.project.workspaceId?{level:"ok",label:`Workspace: ${m.project.workspaceName??m.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let y=wl(e,m.name);if(y?y.projectId&&m.project.projectId&&y.projectId!==m.project.projectId?t.push({level:"fail",label:`Category map projectId (${y.projectId}) \u2260 profile projectId (${m.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(y.articles).length} articles, ${Object.keys(y.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${m.name}" (created on first /publish)`}),t.push(gl(ss())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ss()}`,fix:"Reinstall document360-writer (broken install)"}),h&&(!co(h)||h.refreshToken)){let D={profile:m.name,connection:m.connection};try{await kl(D);let x=await hl(D,"/v3/projects");t.push({level:"ok",label:`API reachable (${m.connection.apiUrl}) \u2014 ${x.length} project(s) visible`})}catch(x){t.push({level:"fail",label:`API call failed: ${x.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}}return t}function as(e){let t=[""];for(let r of e){let s=r.level==="ok"?_("\u2713"):r.level==="warn"?O("\u26A0"):b("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${j(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?_(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):b(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Pt(e,t){console.log(f("Running checks\u2026"));for(let n of as(await is(t.cwd)))console.log(n);return{kind:"continue"}}var rn=tr(()=>{"use strict";q()});import{Command as Eu}from"commander";import{createRequire as Du}from"node:module";import{AUTH_MODES as Iu}from"document360-engine";import{input as Oi}from"@inquirer/prompts";import{loginPkce as Ui,refreshTokens as Wi,toStoredTokens as ir,clearTokens as Hi,decodeJwtClaims as sr,isExpired as Fi,loadTokens as Bi,saveTokens as ar,resolveActiveProfile as Bt,setProfileProject as qi,readProjectConfig as Gi}from"document360-engine";q();import{select as ji}from"@inquirer/prompts";import{resolveActiveProfile as Ai,setProfileProject as Ei,resolveProjectId as Di,listWorkspaces as Ii}from"document360-engine";async function kt(e,t){let n=Ai(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Di(o);return{workspaces:await Ii(o,r),projectId:r,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var or=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Dn(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 Ft(e,t,n,o,r){Ei(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function rr(e,t,n){let o;try{o=await kt(e,n)}catch(s){return console.log(b(`Could not list workspaces: ${s.message}`)),1}let r=Dn(o.workspaces,t);return r?(Ft(e,o.profile,o.projectId,r.id,r.name),console.log(_(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(b(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function ot(e,t){let n;try{n=await kt(e,t)}catch(h){console.log(b(`Could not list workspaces: ${h.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 h of o)console.log(` ${h.id===c?j("\u25CF"):" "} ${or(h)} ${f(h.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let d=await ji({message:"Select the Document360 workspace for this repo:",choices:o.map(h=>({name:`${or(h)}${h.id===c?" (current)":""}`,value:h.id}))}),m=o.find(h=>h.id===d);Ft(e,s,r,d,m?.name),console.log(_(`\u2713 Workspace set to "${m?.name??d}" for profile "${s}".`))}q();import _i from"picocolors";function Ni(e=process.env){return e.FORCE_HYPERLINK==="0"||!_i.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 Mi(e,t=e,n){return Ni(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Li=/https?:\/\/[^\s\x1b]+/g;function wt(e,t){return e.replace(Li,n=>Mi(n,n,t))}function lr(e){return{...sr(e.idToken)??{},...sr(e.accessToken)??{}}}function qt(e){let t=lr(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 Gt(e){let t=Bt(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 Ui(n,{manual:e.manual,promptForRedirect:s=>Oi({message:s})},s=>console.log(wt(s))),r=ir(t.name,o);if(ar(r),In(r,t.name,s=>console.log(f(s))),console.log(""),console.log(_(`\u2713 Logged in to "${t.name}" as ${qt(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{Gi(process.cwd())?.profiles?.[t.name]&&(console.log(""),await ot(process.cwd(),t.name))}catch{}}function In(e,t,n){let r=lr(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Bt(process.cwd(),t).project.projectId)return;qi(process.cwd(),t,{projectId:r}),n(` Project ${r} written to profile "${t}".`)}catch{}}async function cr(e){let t=Bt(process.cwd(),e.profile),n=t.connection,o=Bi(t.name);if(!o){console.log(b(`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 ${j(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${qt(o)}`),Fi(o))if(o.refreshToken)try{let r=ir(t.name,await Wi(n,o.refreshToken));ar(r),console.log(_(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(O(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(O("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function ur(e){let t=Bt(process.cwd(),e.profile);Hi(t.name)?console.log(_(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}q();import{readProjectConfig as dr,writeProjectConfig as zi,resolveActiveProfile as Yi,loadTokens as Vi,isExpired as Xi}from"document360-engine";function zt(e){let t=dr(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(b("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?j("\u25CF "):" ",s=o.production?O(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",d=Vi(n),m=d?Xi(d)&&!d.refreshToken?O("expired"):f("logged in"):f("not logged in");console.log(`${r}${j(n)} \u2192 ${c}${s} [${m}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Yt(e,t){let n=dr(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(b(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,zi(n,e);let o=n.profiles[t].production?O(" \u26A0 PRODUCTION"):"";console.log(_(`\u2713 Default profile is now "${t}"${o}`))}function Vt(e,t){try{let n=Yi(e,t);console.log(""),console.log(`Profile ${j(n.name)}${n.production?O(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(b(n.message)),process.exitCode=1}}q();import{existsSync as Ki,readdirSync as Ji,statSync as Qi}from"node:fs";import{join as Zi}from"node:path";import{apiLogDir as ea}from"document360-engine";function pr(){let e=ea();if(console.log(""),console.log(`Document360 API logs: ${j(e)}`),!Ki(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Ji(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=(Qi(Zi(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("")}q();import{createSession as ta,resolveAuth as na,findByName as oa,slugify as ra,touchSession as sa,upsertSession as ia,resolveActiveProfile as aa}from"document360-engine";async function fr(e,t,n,o,r,s){let c=na(n);c.kind==="none"&&(console.error(""),console.error(b("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${j("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${j("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let d=null;try{d=aa(e,r)}catch(x){console.error(b(`Document360 profile error: ${x.message}`)),process.exit(2)}d.production&&(console.error(O(`\u26A0 Profile "${d.name}" is PRODUCTION.`)),s||(console.error(b("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let m;if(o){let x=oa(e,o);x||(console.error(b(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),m=x.uuid,console.error(f(`Resuming "${x.name}"`))}let h=ta({cwd:e,resume:m,profileName:r,allowProdWrites:s===!0}),y=m??null,D=1;for await(let x of h.send(t))switch(x.type){case"session":if(!y){y=x.sessionId;let v=new Date().toISOString();ia({uuid:y,name:ra(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:v,updatedAt:v})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(Z(` \u2699 ${x.name}`));break;case"result":D=x.ok?0:1,console.error(f(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error(b("agent finished with an error result"));break;case"error":console.error(""),console.error(b(`agent error: ${x.message}`)),process.exit(1)}y&&sa(y),process.stdout.write(`
3
- `),process.exit(D)}import{createInterface as dc}from"node:readline/promises";import{createSession as Co,resolveAuth as pc,getSession as fc,setTitle as mc,slugify as gc,touchSession as Is,upsertSession as hc,generateTitle as kc,resolveActiveProfile as _s,resolveModelSetting as wc,readProjectConfig as yc,decodeJwtClaims as Es,isExpired as xc,loadTokens as $c}from"document360-engine";var yt=[{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:"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"}],la=[{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 Xt(){let e=Math.max(...yt.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 la){t.push("",o);for(let r of yt.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 mr(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return yt.filter(n=>n.name.startsWith(t))}function gr(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}async function _n(){console.log("");for(let e of Xt())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}q();import{getSession as ca}from"document360-engine";async function hr(e,t){let n=t.currentUuid(),o=n?ca(n):void 0;return console.log(o?f(`
2
+ var Ci=Object.defineProperty;var tr=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Pi=(e,t)=>{for(var n in t)Ci(e,n,{get:t[n],enumerable:!0})};import Ae from"picocolors";var G,Si,Ti,Ri,nr,ht,f,b,O,_,j,Z,Pe,q=tr(()=>{"use strict";G="#7f56d9",[Si,Ti,Ri]=[127,86,217],nr=e=>Ae.isColorSupported?`\x1B[38;2;${Si};${Ti};${Ri}m${e}\x1B[39m`:e,ht=e=>Ae.bold(nr(e)),f=e=>Ae.dim(e),b=e=>Ae.red(e),O=e=>Ae.yellow(e),_=e=>Ae.green(e),j=nr,Z=e=>Ae.gray(e),Pe=e=>Ae.bold(e)});var ls={};Pi(ls,{doctorCommand:()=>Pt,renderDoctorChecks:()=>as,runDoctorChecks:()=>is});import{existsSync as gl}from"node:fs";import{d360GetAll as hl,getAccessToken as kl,isExpired as lo,loadProfileMap as wl,loadTokens as yl,packageSkillsDir as ss,projectConfigPath as xl,readProjectConfig as $l,resolveActiveProfile as bl,resolveAuth as vl,resolveModelSetting as Cl}from"document360-engine";async function is(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=vl("auto");t.push(o.kind==="none"?{level:"fail",label:"Claude auth: not configured",fix:"Set ANTHROPIC_API_KEY, or sign in to Claude Code once (subscription reuse)"}:{level:"ok",label:`Claude auth: ${o.kind==="api"?"API key":"subscription"}`});let r=Cl(e);t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`});let s=$l(e);if(!s)return t.push({level:"fail",label:`No ${xl(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??"user-docs").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 d=s.authoritativeSourceFiles??[];t.push(d.length>0?{level:"ok",label:`Sources: docs grounded in ${d.length} path(s) (${d.slice(0,3).join(", ")}${d.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 m;try{m=bl(e),t.push({level:"ok",label:`Profile: ${m.name} (${m.connection.name})${m.production?" \u26A0 PRODUCTION":""}`})}catch(D){return t.push({level:"fail",label:`Profile config: ${D.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let h=yl(m.name);h?lo(h)&&!h.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):lo(h)?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(h.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${m.name})`}),t.push(m.project.workspaceId?{level:"ok",label:`Workspace: ${m.project.workspaceName??m.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let y=wl(e,m.name);if(y?y.projectId&&m.project.projectId&&y.projectId!==m.project.projectId?t.push({level:"fail",label:`Category map projectId (${y.projectId}) \u2260 profile projectId (${m.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(y.articles).length} articles, ${Object.keys(y.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${m.name}" (created on first /publish)`}),t.push(gl(ss())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ss()}`,fix:"Reinstall document360-writer (broken install)"}),h&&(!lo(h)||h.refreshToken)){let D={profile:m.name,connection:m.connection};try{await kl(D);let x=await hl(D,"/v3/projects");t.push({level:"ok",label:`API reachable (${m.connection.apiUrl}) \u2014 ${x.length} project(s) visible`})}catch(x){t.push({level:"fail",label:`API call failed: ${x.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}}return t}function as(e){let t=[""];for(let r of e){let s=r.level==="ok"?_("\u2713"):r.level==="warn"?O("\u26A0"):b("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${j(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?_(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):b(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Pt(e,t){console.log(f("Running checks\u2026"));for(let n of as(await is(t.cwd)))console.log(n);return{kind:"continue"}}var rn=tr(()=>{"use strict";q()});import{Command as Eu}from"commander";import{createRequire as Du}from"node:module";import{AUTH_MODES as Iu}from"document360-engine";import{input as Oi}from"@inquirer/prompts";import{loginPkce as Ui,refreshTokens as Wi,toStoredTokens as ir,clearTokens as Hi,decodeJwtClaims as sr,isExpired as Fi,loadTokens as Bi,saveTokens as ar,resolveActiveProfile as Bt,setProfileProject as qi,readProjectConfig as Gi}from"document360-engine";q();import{select as ji}from"@inquirer/prompts";import{resolveActiveProfile as Ai,setProfileProject as Ei,resolveProjectId as Di,listWorkspaces as Ii}from"document360-engine";async function kt(e,t){let n=Ai(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Di(o);return{workspaces:await Ii(o,r),projectId:r,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var or=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function En(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 Ft(e,t,n,o,r){Ei(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function rr(e,t,n){let o;try{o=await kt(e,n)}catch(s){return console.log(b(`Could not list workspaces: ${s.message}`)),1}let r=En(o.workspaces,t);return r?(Ft(e,o.profile,o.projectId,r.id,r.name),console.log(_(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(b(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function ot(e,t){let n;try{n=await kt(e,t)}catch(h){console.log(b(`Could not list workspaces: ${h.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 h of o)console.log(` ${h.id===c?j("\u25CF"):" "} ${or(h)} ${f(h.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let d=await ji({message:"Select the Document360 workspace for this repo:",choices:o.map(h=>({name:`${or(h)}${h.id===c?" (current)":""}`,value:h.id}))}),m=o.find(h=>h.id===d);Ft(e,s,r,d,m?.name),console.log(_(`\u2713 Workspace set to "${m?.name??d}" for profile "${s}".`))}q();import _i from"picocolors";function Ni(e=process.env){return e.FORCE_HYPERLINK==="0"||!_i.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 Mi(e,t=e,n){return Ni(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Li=/https?:\/\/[^\s\x1b]+/g;function wt(e,t){return e.replace(Li,n=>Mi(n,n,t))}function lr(e){return{...sr(e.idToken)??{},...sr(e.accessToken)??{}}}function qt(e){let t=lr(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 Gt(e){let t=Bt(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 Ui(n,{manual:e.manual,promptForRedirect:s=>Oi({message:s})},s=>console.log(wt(s))),r=ir(t.name,o);if(ar(r),Dn(r,t.name,s=>console.log(f(s))),console.log(""),console.log(_(`\u2713 Logged in to "${t.name}" as ${qt(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{Gi(process.cwd())?.profiles?.[t.name]&&(console.log(""),await ot(process.cwd(),t.name))}catch{}}function Dn(e,t,n){let r=lr(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Bt(process.cwd(),t).project.projectId)return;qi(process.cwd(),t,{projectId:r}),n(` Project ${r} written to profile "${t}".`)}catch{}}async function cr(e){let t=Bt(process.cwd(),e.profile),n=t.connection,o=Bi(t.name);if(!o){console.log(b(`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 ${j(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${qt(o)}`),Fi(o))if(o.refreshToken)try{let r=ir(t.name,await Wi(n,o.refreshToken));ar(r),console.log(_(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(O(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(O("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function ur(e){let t=Bt(process.cwd(),e.profile);Hi(t.name)?console.log(_(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}q();import{readProjectConfig as dr,writeProjectConfig as zi,resolveActiveProfile as Yi,loadTokens as Vi,isExpired as Xi}from"document360-engine";function zt(e){let t=dr(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(b("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?j("\u25CF "):" ",s=o.production?O(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",d=Vi(n),m=d?Xi(d)&&!d.refreshToken?O("expired"):f("logged in"):f("not logged in");console.log(`${r}${j(n)} \u2192 ${c}${s} [${m}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Yt(e,t){let n=dr(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(b(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,zi(n,e);let o=n.profiles[t].production?O(" \u26A0 PRODUCTION"):"";console.log(_(`\u2713 Default profile is now "${t}"${o}`))}function Vt(e,t){try{let n=Yi(e,t);console.log(""),console.log(`Profile ${j(n.name)}${n.production?O(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(b(n.message)),process.exitCode=1}}q();import{existsSync as Ki,readdirSync as Ji,statSync as Qi}from"node:fs";import{join as Zi}from"node:path";import{apiLogDir as ea}from"document360-engine";function pr(){let e=ea();if(console.log(""),console.log(`Document360 API logs: ${j(e)}`),!Ki(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Ji(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=(Qi(Zi(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("")}q();import{createSession as ta,resolveAuth as na,findByName as oa,slugify as ra,touchSession as sa,upsertSession as ia,resolveActiveProfile as aa}from"document360-engine";async function fr(e,t,n,o,r,s){let c=na(n);c.kind==="none"&&(console.error(""),console.error(b("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${j("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${j("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let d=null;try{d=aa(e,r)}catch(x){console.error(b(`Document360 profile error: ${x.message}`)),process.exit(2)}d.production&&(console.error(O(`\u26A0 Profile "${d.name}" is PRODUCTION.`)),s||(console.error(b("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let m;if(o){let x=oa(e,o);x||(console.error(b(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),m=x.uuid,console.error(f(`Resuming "${x.name}"`))}let h=ta({cwd:e,resume:m,profileName:r,allowProdWrites:s===!0}),y=m??null,D=1;for await(let x of h.send(t))switch(x.type){case"session":if(!y){y=x.sessionId;let v=new Date().toISOString();ia({uuid:y,name:ra(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:v,updatedAt:v})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(Z(` \u2699 ${x.name}`));break;case"result":D=x.ok?0:1,console.error(f(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error(b("agent finished with an error result"));break;case"error":console.error(""),console.error(b(`agent error: ${x.message}`)),process.exit(1)}y&&sa(y),process.stdout.write(`
3
+ `),process.exit(D)}import{createInterface as dc}from"node:readline/promises";import{createSession as vo,resolveAuth as pc,getSession as fc,setTitle as mc,slugify as gc,touchSession as Is,upsertSession as hc,generateTitle as kc,resolveActiveProfile as _s,resolveModelSetting as wc,readProjectConfig as yc,decodeJwtClaims as Es,isExpired as xc,loadTokens as $c}from"document360-engine";var yt=[{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:"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"}],la=[{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 Xt(){let e=Math.max(...yt.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 la){t.push("",o);for(let r of yt.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 mr(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return yt.filter(n=>n.name.startsWith(t))}function gr(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}async function In(){console.log("");for(let e of Xt())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}q();import{getSession as ca}from"document360-engine";async function hr(e,t){let n=t.currentUuid(),o=n?ca(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 Nn(){return{kind:"exit"}}q();import{input as xt,confirm as ua}from"@inquirer/prompts";import{basename as kr,join as Kt}from"node:path";import{existsSync as rt,readFileSync as da,readdirSync as pa,writeFileSync as fa}from"node:fs";import{writeProjectConfig as wr,readProjectConfig as ma,projectConfigPath as yr,writerDir as ga}from"document360-engine";function xr(e,t="berlin"){let n=yr(e);if(rt(n))return{created:!1,path:n,profileName:""};let o={projectId:vr(e)??kr(e),captureDir:"user-docs/_capture",outputDir:"user-docs/_screenshots",profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Cr(e)};return wr(o,e),$r(e),{created:!0,path:n,profileName:t}}function $r(e){let t=Kt(ga(e),".gitignore");rt(t)||fa(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
8
- `),"utf8")}async function br(){let e=process.cwd(),t=yr(e);if(rt(t)&&!await ua({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=vr(e)??kr(e),o=await xt({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await xt({message:"Capture directory (where document360-capture .spec.ts files live):",default:"user-docs/_capture"}),s=await xt({message:"Screenshot output directory:",default:"user-docs/_screenshots"}),c=await xt({message:"Default connection profile name:",default:"berlin"}),d=await xt({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),m={projectId:o,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:d},production:!1}},defaultProfile:c,authoritativeSourceFiles:Cr(e)},h=ma(e);return h?.terminologyGlossary&&(m.terminologyGlossary=h.terminologyGlossary),wr(m,e),$r(e),console.log(""),console.log(_(`\u2713 Wrote ${t}`)),console.log(""),console.log("Next:"),console.log(` ${j(`d360-writer login --profile ${c}`)} ${f("(sign in; pick the project)")}`),console.log(' Then ask the agent: "analyze this repo and propose a docs structure"'),console.log(""),{kind:"continue"}}function vr(e){let t=Kt(e,"package.json");if(!rt(t))return null;try{return JSON.parse(da(t,"utf8")).name??null}catch{return null}}function Cr(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])rt(Kt(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Kt(e,n);rt(o)&&!ha(o)&&t.push(n)}return t}function ha(e){try{return pa(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}q();import{readMcpConfig as Mn,writeMcpConfig as Pr}from"document360-engine";async function Jt(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(ka(),{kind:"continue"}):t==="add"?(wa(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(ya(e.slice(1)),{kind:"continue"}):(console.log(b(`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 ka(){let e=Mn(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
7
+ `)),{kind:"clear"}}async function _n(){return{kind:"exit"}}q();import{input as xt,confirm as ua}from"@inquirer/prompts";import{basename as kr,join as Kt}from"node:path";import{existsSync as rt,readFileSync as da,readdirSync as pa,writeFileSync as fa}from"node:fs";import{writeProjectConfig as wr,readProjectConfig as ma,projectConfigPath as yr,writerDir as ga}from"document360-engine";function xr(e,t="berlin"){let n=yr(e);if(rt(n))return{created:!1,path:n,profileName:""};let o={projectId:vr(e)??kr(e),captureDir:"user-docs/_capture",outputDir:"user-docs/_screenshots",profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Cr(e)};return wr(o,e),$r(e),{created:!0,path:n,profileName:t}}function $r(e){let t=Kt(ga(e),".gitignore");rt(t)||fa(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
8
+ `),"utf8")}async function br(){let e=process.cwd(),t=yr(e);if(rt(t)&&!await ua({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=vr(e)??kr(e),o=await xt({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await xt({message:"Capture directory (where document360-capture .spec.ts files live):",default:"user-docs/_capture"}),s=await xt({message:"Screenshot output directory:",default:"user-docs/_screenshots"}),c=await xt({message:"Default connection profile name:",default:"berlin"}),d=await xt({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),m={projectId:o,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:d},production:!1}},defaultProfile:c,authoritativeSourceFiles:Cr(e)},h=ma(e);return h?.terminologyGlossary&&(m.terminologyGlossary=h.terminologyGlossary),wr(m,e),$r(e),console.log(""),console.log(_(`\u2713 Wrote ${t}`)),console.log(""),console.log("Next:"),console.log(` ${j(`d360-writer login --profile ${c}`)} ${f("(sign in; pick the project)")}`),console.log(' Then ask the agent: "analyze this repo and propose a docs structure"'),console.log(""),{kind:"continue"}}function vr(e){let t=Kt(e,"package.json");if(!rt(t))return null;try{return JSON.parse(da(t,"utf8")).name??null}catch{return null}}function Cr(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])rt(Kt(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Kt(e,n);rt(o)&&!ha(o)&&t.push(n)}return t}function ha(e){try{return pa(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}q();import{readMcpConfig as Nn,writeMcpConfig as Pr}from"document360-engine";async function Jt(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(ka(),{kind:"continue"}):t==="add"?(wa(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(ya(e.slice(1)),{kind:"continue"}):(console.log(b(`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 ka(){let e=Nn(),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(` ${j(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(` ${j(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function wa(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(b("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(b(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Mn(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let d=1;d<o.length;d++)if(o[d]==="-H"||o[d]==="--header"){let m=o[++d],h=m?.match(/^([^:=]+)[:=](.+)$/);if(!h){console.log(b(`-H expects key:value (no spaces). Got: ${m??"(nothing)"}`));return}c[h[1].trim()]=h[2].trim()}else{console.log(b(`Unexpected argument: ${o[d]}. 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,Pr(r),console.log(""),console.log(_(`\u2713 Registered "${t}" (${n})`)),console.log(O(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function ya(e){let t=e[0];if(!t){console.log(b("Usage: /mcp remove <name>"));return}let n=Mn();if(!n.servers[t]){console.log(b(`No server named "${t}".`));return}delete n.servers[t],Pr(n),console.log(_(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}q();import{select as xa}from"@inquirer/prompts";import{computeSyncStatus as Sr}from"document360-engine";function Zt(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(`
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(` ${j(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(` ${j(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function wa(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(b("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(b(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Nn(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let d=1;d<o.length;d++)if(o[d]==="-H"||o[d]==="--header"){let m=o[++d],h=m?.match(/^([^:=]+)[:=](.+)$/);if(!h){console.log(b(`-H expects key:value (no spaces). Got: ${m??"(nothing)"}`));return}c[h[1].trim()]=h[2].trim()}else{console.log(b(`Unexpected argument: ${o[d]}. 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,Pr(r),console.log(""),console.log(_(`\u2713 Registered "${t}" (${n})`)),console.log(O(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function ya(e){let t=e[0];if(!t){console.log(b("Usage: /mcp remove <name>"));return}let n=Nn();if(!n.servers[t]){console.log(b(`No server named "${t}".`));return}delete n.servers[t],Pr(n),console.log(_(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}q();import{select as xa}from"@inquirer/prompts";import{computeSyncStatus as Sr}from"document360-engine";function Zt(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(`
11
11
  `)}var Tr={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Qt(e){return e.filter(t=>t.path!==null&&t.status in Tr).map(t=>({path:t.path,label:Tr[t.status]}))}function $t(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(`
12
12
  `)}async function Rr(e,t){let n=e[0];if(n==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let o=Qt((await Sr({cwd:t?.cwd??process.cwd()})).entries);return o.length===0?(console.log(_("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):{kind:"forward-to-agent",prompt:$t(o.map(r=>r.path)),display:"/publish --all"}}catch(o){return console.log(b(`Could not compute sync status: ${o.message}`)),{kind:"continue"}}}if(!n){console.log(f("Checking what needs publishing\u2026"));let o;try{o=Qt((await Sr({cwd:t?.cwd??process.cwd()})).entries)}catch(r){return console.log(b(`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(_("\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(()=>xa({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{kind:"forward-to-agent",prompt:$t(o.map(r=>r.path)),display:"/publish --all"}}return{kind:"forward-to-agent",prompt:Zt(n),display:`/publish ${n}`}}async function en(){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(`
13
- `),display:"/audit"}}q();import{checkbox as $a}from"@inquirer/prompts";import{inventoryRepo as ba,readProjectConfig as jr,writeProjectConfig as va}from"document360-engine";function Ln(e,t){let n=jr(e);n&&(n.authoritativeSourceFiles=t,va(n,e))}function tn(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 Ar(e,t){let n=t?.cwd??process.cwd();if(!jr(n))return console.log(b("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=ba(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(j("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(tn(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>$a({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${tn(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"};Ln(n,r),console.log(_(`\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"}}q();import{confirm as Ra}from"@inquirer/prompts";import{applyPull as Nr,computeSyncStatus as Mr,planPull as ja,D360AuthError as Aa}from"document360-engine";q();var Er=[{status:"conflict",header:"Conflicts \u2014 both sides changed; pick a direction (/sync pull <path> or /publish <path>):",paint:b,mark:"!"},{status:"local-ahead",header:"Local ahead \u2014 push with /publish <path>:",paint:O,mark:"M"},{status:"remote-ahead",header:"Remote ahead \u2014 pull with /sync pull <path>:",paint:j,mark:"M"},{status:"deleted-local",header:"Deleted locally \u2014 still on Document360 (pull to restore, or remove from the map):",paint:b,mark:"D"},{status:"deleted-remote",header:"Deleted on Document360 \u2014 still local (publish to recreate, or delete the file):",paint:b,mark:"D"},{status:"orphaned",header:"Orphaned map entries \u2014 gone on both sides (remove from d360-category-map.json):",paint:Z,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:Z,mark:"\xB7"}];function Ca(e){return e.path?e.path:`${e.title??"(untitled)"} ${Z(`[${e.articleId}]`)}`}function nn(e){let t=[];for(let c of Er){let d=e.entries.filter(m=>m.status===c.status);if(d.length!==0){t.push(""),t.push(Pe(c.header));for(let m of d)t.push(` ${c.paint(c.mark)} ${c.paint(Ca(m))}${m.detail?Z(` (${m.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?_("\u2713 everything in sync"):[n>0?_(`\u2713 ${n} in sync`):null,...Er.map(c=>{let d=e.counts[c.status]??0;return d>0?`${d} ${r[c.status]}`:null})].filter(Boolean).join(Z(" \xB7 "));return t.push(s+Z(` \xB7 ${o} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/`)),t}import{structuredPatch as Pa}from"diff";import Dr from"picocolors";var Ir=80,Sa="\x1B[48;2;74;28;28m",Ta="\x1B[48;2;24;66;24m",_r="\x1B[49m",On=e=>String(e).padStart(5);function He(e,t,n){let o=x=>{let v=x.replace(/\r\n/g,`
13
+ `),display:"/audit"}}q();import{checkbox as $a}from"@inquirer/prompts";import{inventoryRepo as ba,readProjectConfig as jr,writeProjectConfig as va}from"document360-engine";function Mn(e,t){let n=jr(e);n&&(n.authoritativeSourceFiles=t,va(n,e))}function tn(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 Ar(e,t){let n=t?.cwd??process.cwd();if(!jr(n))return console.log(b("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=ba(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(j("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(tn(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>$a({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${tn(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"};Mn(n,r),console.log(_(`\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"}}q();import{confirm as Ra}from"@inquirer/prompts";import{applyPull as Nr,computeSyncStatus as Mr,planPull as ja,D360AuthError as Aa}from"document360-engine";q();var Er=[{status:"conflict",header:"Conflicts \u2014 both sides changed; pick a direction (/sync pull <path> or /publish <path>):",paint:b,mark:"!"},{status:"local-ahead",header:"Local ahead \u2014 push with /publish <path>:",paint:O,mark:"M"},{status:"remote-ahead",header:"Remote ahead \u2014 pull with /sync pull <path>:",paint:j,mark:"M"},{status:"deleted-local",header:"Deleted locally \u2014 still on Document360 (pull to restore, or remove from the map):",paint:b,mark:"D"},{status:"deleted-remote",header:"Deleted on Document360 \u2014 still local (publish to recreate, or delete the file):",paint:b,mark:"D"},{status:"orphaned",header:"Orphaned map entries \u2014 gone on both sides (remove from d360-category-map.json):",paint:Z,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:Z,mark:"\xB7"}];function Ca(e){return e.path?e.path:`${e.title??"(untitled)"} ${Z(`[${e.articleId}]`)}`}function nn(e){let t=[];for(let c of Er){let d=e.entries.filter(m=>m.status===c.status);if(d.length!==0){t.push(""),t.push(Pe(c.header));for(let m of d)t.push(` ${c.paint(c.mark)} ${c.paint(Ca(m))}${m.detail?Z(` (${m.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?_("\u2713 everything in sync"):[n>0?_(`\u2713 ${n} in sync`):null,...Er.map(c=>{let d=e.counts[c.status]??0;return d>0?`${d} ${r[c.status]}`:null})].filter(Boolean).join(Z(" \xB7 "));return t.push(s+Z(` \xB7 ${o} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/`)),t}import{structuredPatch as Pa}from"diff";import Dr from"picocolors";var Ir=80,Sa="\x1B[48;2;74;28;28m",Ta="\x1B[48;2;24;66;24m",_r="\x1B[49m",Ln=e=>String(e).padStart(5);function He(e,t,n){let o=x=>{let v=x.replace(/\r\n/g,`
14
14
  `);return v.endsWith(`
15
15
  `)||v===""?v:v+`
16
- `},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),d=Pa("a","b",r,s,"","",{context:3}),m=0,h=0,y=[];d.hunks.forEach((x,v)=>{v>0&&y.push(Dr.gray(" \u2026"));let $=x.oldStart,I=x.newStart;for(let N of x.lines){let F=N[0],Q=N.slice(1).slice(0,c);F==="-"?(h++,y.push(`${Sa}${On($++)} - ${Q}${_r}`)):F==="+"?(m++,y.push(`${Ta}${On(I++)} + ${Q}${_r}`)):(y.push(Dr.gray(On(I))+" "+Q),$++,I++)}});let D=y.slice(0,Ir);return{added:m,removed:h,lines:D,hidden:Math.max(0,y.length-Ir)}}async function Lr(e,t){let n=(e[0]??"status").toLowerCase();try{if(n==="status")return await Ea(t.cwd),{kind:"continue"};if(n==="pull")return await Da(t,e.slice(1)),{kind:"continue"};console.log(b(`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 Aa?console.log(b(o.message)):console.log(b(`Sync failed: ${o.message}`))}return{kind:"continue"}}async function Ea(e){console.log(f("Checking Document360 for drift\u2026"));let t=await Mr({cwd:e});for(let n of nn(t))console.log(n);console.log("")}async function Da(e,t){let n=t[0];if(!n){console.log(b("Usage: /sync pull <article-path> | --all"));return}let o;if(n==="--all"){if(console.log(f("Checking Document360 for drift\u2026")),o=(await Mr({cwd:e.cwd})).entries.filter(s=>s.status==="remote-ahead"&&s.path).map(s=>s.path),o.length===0){console.log(_("\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(`${Pe(String(o.length))} article(s) are remote-ahead.`)}else o=[n.replace(/\\/g,"/")];for(let r of o){let s=await ja({cwd:e.cwd,relPath:r});console.log(""),console.log(`${j("\u25CF")} ${Pe(s.title)} ${Z(`(${s.path})`)}`);for(let h of s.notes)console.log(O(` \u26A0 ${h}`));s.overwritesLocalChanges&&console.log(O(" \u26A0 This OVERWRITES local edits made since the last sync."));let c=He(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.")),Nr({cwd:e.cwd},s);continue}let d=h=>h===1?"":"s";console.log(Z(` \u23BF Added ${c.added} line${d(c.added)}, removed ${c.removed} line${d(c.removed)}`));for(let h of c.lines)console.log(h);if(c.hidden>0&&console.log(f(` \u2026 +${c.hidden} more diff lines`)),!await e.withPausedInput(()=>Ra({message:`Write ${s.path}?`,default:!s.overwritesLocalChanges}))){console.log(f(" Skipped."));continue}Nr({cwd:e.cwd},s),console.log(_(` \u2713 Pulled ${s.path} (sync base advanced).`))}console.log("")}q();import{statSync as Ba}from"node:fs";import{resolve as qa}from"node:path";import{estimateBulkCost as Ga,planPartitions as za,readProjectConfig as Ya,resolveModelForOperation as Va,runPartitioned as Xa,trackedArticlePaths as Ka}from"document360-engine";import z from"picocolors";import Br from"wrap-ansi";import qn from"string-width";q();import Ee from"picocolors";import Un from"wrap-ansi";import Wn from"string-width";var Or=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Ur=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Wr=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Ia(e){let t=e.replace(/\r/g,"").split(`
17
- `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let d=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)d.push(t[o++]);o++,n.push({kind:"code",lines:d});continue}if(Or(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Ur(t[o+1])){let d=Wr(r);o+=2;let m=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)m.push(Wr(t[o++]));n.push({kind:"table",header:d,rows:m});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 d=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);)d.push(t[o++].replace(/^\s*([-*]|\d+\.)\s+/,""));n.push({kind:"list",items:d});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])&&!Or(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Ur(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function Hn(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ee.bold(t.slice(2,-2)):t.startsWith("`")?j(t.slice(1,-1)):Ee.italic(t.slice(1,-1)))}var _a=(e,t)=>e+" ".repeat(Math.max(0,t-Wn(e)));function Na(e,t,n){let o=e.length,r=e.map(($,I)=>Math.max(Wn($),...t.map(N=>Wn(N[I]??"")))),s=Math.max(24,n),c=3*o+1,d=[...r],m=()=>d.reduce(($,I)=>$+I,0)+c,h=0;for(;m()>s&&h++<1e4;){let $=-1,I=6;for(let N=0;N<o;N++)d[N]>I&&(I=d[N],$=N);if($===-1)break;d[$]-=1}let y=($,I,N)=>Ee.gray($+d.map(F=>"\u2500".repeat(F+2)).join(I)+N),D=Ee.gray("\u2502"),x=($,I)=>{let N=d.map((he,ne)=>{let ke=$[ne]??"",oe=I?Ee.bold(ke):Hn(ke);return Un(oe,he,{hard:!0}).split(`
18
- `)}),F=Math.max(...N.map(he=>he.length)),Q=[];for(let he=0;he<F;he++)Q.push(d.map((ne,ke)=>`${D} ${_a(N[ke][he]??"",ne)} `).join("")+D);return Q.join(`
16
+ `},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),d=Pa("a","b",r,s,"","",{context:3}),m=0,h=0,y=[];d.hunks.forEach((x,v)=>{v>0&&y.push(Dr.gray(" \u2026"));let $=x.oldStart,I=x.newStart;for(let N of x.lines){let F=N[0],Q=N.slice(1).slice(0,c);F==="-"?(h++,y.push(`${Sa}${Ln($++)} - ${Q}${_r}`)):F==="+"?(m++,y.push(`${Ta}${Ln(I++)} + ${Q}${_r}`)):(y.push(Dr.gray(Ln(I))+" "+Q),$++,I++)}});let D=y.slice(0,Ir);return{added:m,removed:h,lines:D,hidden:Math.max(0,y.length-Ir)}}async function Lr(e,t){let n=(e[0]??"status").toLowerCase();try{if(n==="status")return await Ea(t.cwd),{kind:"continue"};if(n==="pull")return await Da(t,e.slice(1)),{kind:"continue"};console.log(b(`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 Aa?console.log(b(o.message)):console.log(b(`Sync failed: ${o.message}`))}return{kind:"continue"}}async function Ea(e){console.log(f("Checking Document360 for drift\u2026"));let t=await Mr({cwd:e});for(let n of nn(t))console.log(n);console.log("")}async function Da(e,t){let n=t[0];if(!n){console.log(b("Usage: /sync pull <article-path> | --all"));return}let o;if(n==="--all"){if(console.log(f("Checking Document360 for drift\u2026")),o=(await Mr({cwd:e.cwd})).entries.filter(s=>s.status==="remote-ahead"&&s.path).map(s=>s.path),o.length===0){console.log(_("\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(`${Pe(String(o.length))} article(s) are remote-ahead.`)}else o=[n.replace(/\\/g,"/")];for(let r of o){let s=await ja({cwd:e.cwd,relPath:r});console.log(""),console.log(`${j("\u25CF")} ${Pe(s.title)} ${Z(`(${s.path})`)}`);for(let h of s.notes)console.log(O(` \u26A0 ${h}`));s.overwritesLocalChanges&&console.log(O(" \u26A0 This OVERWRITES local edits made since the last sync."));let c=He(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.")),Nr({cwd:e.cwd},s);continue}let d=h=>h===1?"":"s";console.log(Z(` \u23BF Added ${c.added} line${d(c.added)}, removed ${c.removed} line${d(c.removed)}`));for(let h of c.lines)console.log(h);if(c.hidden>0&&console.log(f(` \u2026 +${c.hidden} more diff lines`)),!await e.withPausedInput(()=>Ra({message:`Write ${s.path}?`,default:!s.overwritesLocalChanges}))){console.log(f(" Skipped."));continue}Nr({cwd:e.cwd},s),console.log(_(` \u2713 Pulled ${s.path} (sync base advanced).`))}console.log("")}q();import{statSync as Ba}from"node:fs";import{resolve as qa}from"node:path";import{estimateBulkCost as Ga,planPartitions as za,readProjectConfig as Ya,resolveModelForOperation as Va,runPartitioned as Xa,trackedArticlePaths as Ka}from"document360-engine";import z from"picocolors";import Br from"wrap-ansi";import Bn from"string-width";q();import Ee from"picocolors";import On from"wrap-ansi";import Un from"string-width";var Or=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Ur=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Wr=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Ia(e){let t=e.replace(/\r/g,"").split(`
17
+ `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let d=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)d.push(t[o++]);o++,n.push({kind:"code",lines:d});continue}if(Or(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Ur(t[o+1])){let d=Wr(r);o+=2;let m=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)m.push(Wr(t[o++]));n.push({kind:"table",header:d,rows:m});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 d=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);)d.push(t[o++].replace(/^\s*([-*]|\d+\.)\s+/,""));n.push({kind:"list",items:d});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])&&!Or(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Ur(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function Wn(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ee.bold(t.slice(2,-2)):t.startsWith("`")?j(t.slice(1,-1)):Ee.italic(t.slice(1,-1)))}var _a=(e,t)=>e+" ".repeat(Math.max(0,t-Un(e)));function Na(e,t,n){let o=e.length,r=e.map(($,I)=>Math.max(Un($),...t.map(N=>Un(N[I]??"")))),s=Math.max(24,n),c=3*o+1,d=[...r],m=()=>d.reduce(($,I)=>$+I,0)+c,h=0;for(;m()>s&&h++<1e4;){let $=-1,I=6;for(let N=0;N<o;N++)d[N]>I&&(I=d[N],$=N);if($===-1)break;d[$]-=1}let y=($,I,N)=>Ee.gray($+d.map(F=>"\u2500".repeat(F+2)).join(I)+N),D=Ee.gray("\u2502"),x=($,I)=>{let N=d.map((ye,ne)=>{let he=$[ne]??"",oe=I?Ee.bold(he):Wn(he);return On(oe,ye,{hard:!0}).split(`
18
+ `)}),F=Math.max(...N.map(ye=>ye.length)),Q=[];for(let ye=0;ye<F;ye++)Q.push(d.map((ne,he)=>`${D} ${_a(N[he][ye]??"",ne)} `).join("")+D);return Q.join(`
19
19
  `)},v=[y("\u250C","\u252C","\u2510"),x(e,!0)];return v.push(t.length===0?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524")),t.forEach(($,I)=>{v.push(x($,!1)),v.push(I===t.length-1?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524"))}),v.join(`
20
- `)}function Ma(e,t){switch(e.kind){case"heading":return Ee.bold(e.text);case"hr":return Ee.gray("\u2500".repeat(t));case"para":return Un(Hn(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=Un(Hn(n),Math.max(10,t-4)).split(`
20
+ `)}function Ma(e,t){switch(e.kind){case"heading":return Ee.bold(e.text);case"hr":return Ee.gray("\u2500".repeat(t));case"para":return On(Wn(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=On(Wn(n),Math.max(10,t-4)).split(`
21
21
  `);return" \u2022 "+o+r.map(s=>`
22
22
  `+s).join("")}).join(`
23
23
  `);case"code":return e.lines.map(n=>Ee.gray(" "+n)).join(`
24
- `);case"table":return Na(e.header,e.rows,t)}}function Fn(e,t){let n=Math.max(20,t);return Ia(e).map(o=>Ma(o,n)).join(`
24
+ `);case"table":return Na(e.header,e.rows,t)}}function Hn(e,t){let n=Math.max(20,t);return Ia(e).map(o=>Ma(o,n)).join(`
25
25
 
26
- `)}q();import La from"picocolors";var Oa=[127,86,217],Ua=[22,38,43],Hr={T:Oa,E:Ua},bt=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Bn=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Wa=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Fr(){if(!La.isColorSupported)return[];let e=bt[0].length,t=[];for(let n=0;n<bt.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Hr[bt[n][r]],c=n+1<bt.length?Hr[bt[n+1][r]]:void 0;s&&c?o+=`${Bn(s)}${Wa(c)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Bn(s)}\u2580\x1B[39m`:c?o+=`${Bn(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function vt(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function ge(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function it(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var st=(e,t)=>` ${e.padEnd(13)}${t}`;function Ha(e,t){let n=[ht("\u270E document360-writer")+z.gray(` v${e.version}`),z.gray(" Reads your code, writes your docs."),"",st("Claude:",`${e.claude}${z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),st("Document360:",e.configured?e.loggedOut?z.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?z.gray(` (${e.sessionHint})`):""}`:z.yellow("not set up \u2014 run /init")),st("Profile:",e.configured?`${e.profile}${z.gray(` (${e.apiUrl})`)}${e.prod?z.bold(z.yellow(" \u26A0 PRODUCTION")):""}`:z.gray("\u2014 (run /init)")),st("Project:",e.project),st("Mode:",z.gray(e.mode)),st("cwd:",z.gray(e.cwd))],o=Fr();if(o.length===0)return n.join(`
27
- `);let r=2,s=3,c=qn(o[0]);if(!(t>=r+c+s+Math.max(...n.map(y=>qn(y)))))return[...o.map(y=>" "+y),...n].join(`
26
+ `)}q();import La from"picocolors";var Oa=[127,86,217],Ua=[22,38,43],Hr={T:Oa,E:Ua},bt=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Fn=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Wa=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Fr(){if(!La.isColorSupported)return[];let e=bt[0].length,t=[];for(let n=0;n<bt.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Hr[bt[n][r]],c=n+1<bt.length?Hr[bt[n+1][r]]:void 0;s&&c?o+=`${Fn(s)}${Wa(c)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Fn(s)}\u2580\x1B[39m`:c?o+=`${Fn(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function vt(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function ge(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function it(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var st=(e,t)=>` ${e.padEnd(13)}${t}`;function Ha(e,t){let n=[ht("\u270E document360-writer")+z.gray(` v${e.version}`),z.gray(" Reads your code, writes your docs."),"",st("Claude:",`${e.claude}${z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),st("Document360:",e.configured?e.loggedOut?z.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?z.gray(` (${e.sessionHint})`):""}`:z.yellow("not set up \u2014 run /init")),st("Profile:",e.configured?`${e.profile}${z.gray(` (${e.apiUrl})`)}${e.prod?z.bold(z.yellow(" \u26A0 PRODUCTION")):""}`:z.gray("\u2014 (run /init)")),st("Project:",e.project),st("Mode:",z.gray(e.mode)),st("cwd:",z.gray(e.cwd))],o=Fr();if(o.length===0)return n.join(`
27
+ `);let r=2,s=3,c=Bn(o[0]);if(!(t>=r+c+s+Math.max(...n.map(y=>Bn(y)))))return[...o.map(y=>" "+y),...n].join(`
28
28
  `);let m=Math.max(0,Math.floor((n.length-o.length)/2)),h=[];for(let y=0;y<Math.max(o.length+m,n.length);y++){let D=o[y-m]??" ".repeat(c);h.push((" ".repeat(r)+D+" ".repeat(s)+(n[y]??"")).trimEnd())}return h.join(`
29
- `)}var Fa={error:z.red,warn:z.yellow,ok:z.green,info:z.gray};function Gn(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Ha(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),c=50,d=e.text.split(`
29
+ `)}var Fa={error:z.red,warn:z.yellow,ok:z.green,info:z.gray};function qn(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Ha(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),c=50,d=e.text.split(`
30
30
  `).flatMap(h=>Br(h,s,{hard:!0}).split(`
31
31
  `)),m=Math.max(0,d.length-c);return m>0&&(d=[...d.slice(0,c),z.dim(`\u2026 +${m} more lines`)]),`
32
- `+d.map((h,y)=>o+(y===0?j(" \u276F "):" ")+h+" ".repeat(Math.max(0,s-qn(h))+1)+r).join(`
32
+ `+d.map((h,y)=>o+(y===0?j(" \u276F "):" ")+h+" ".repeat(Math.max(0,s-Bn(h))+1)+r).join(`
33
33
  `)}case"assistant":return`
34
- `+Fn(e.text,n);case"tool":{let o=e.arg!==null?z.gray(`${e.sep}(${e.arg})`):"";return`
34
+ `+Hn(e.text,n);case"tool":{let o=e.arg!==null?z.gray(`${e.sep}(${e.arg})`):"";return`
35
35
  `+Br(z.green("\u25CF ")+z.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?z.red:z.gray,r=e.lines.map((s,c)=>o((c===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(z.dim(` \u2026 +${e.hidden} lines`)),r.join(`
36
36
  `)}case"diff":{let o=c=>c===1?"":"s",s=[z.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(z.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
37
37
  `)}case"link":return e.lines.map(o=>j(wt(` \u2B95 ${o}`))).join(`
38
38
  `);case"preview":return`
39
39
  `+ht(`\u25A3 Preview \u2014 ${e.name}`)+`
40
40
 
41
- `+Fn(e.text,n);case"note":return`
41
+ `+Hn(e.text,n);case"note":return`
42
42
  `+Fa[e.tone](wt(e.text));case"done":return`
43
- `+(e.ok?z.magenta("\u2736 "):z.red("\u2736 "))+z.gray(`Cooked for ${vt(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${ge(e.costUsd)}`:""))}}function qr(e,t){return e.map(n=>Gn(n,t)).join(`
44
- `)}var zn=3;function Yn(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 Vn(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Xn(e,t){return t.map(n=>{let o=0;try{o=Ba(qa(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Kn(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:
43
+ `+(e.ok?z.magenta("\u2736 "):z.red("\u2736 "))+z.gray(`Cooked for ${vt(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${ge(e.costUsd)}`:""))}}function qr(e,t){return e.map(n=>qn(n,t)).join(`
44
+ `)}var Gn=3;function zn(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 Yn(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Vn(e,t){return t.map(n=>{let o=0;try{o=Ba(qa(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Xn(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 Jn(e,t,n){let o=e.reduce((d,m)=>d+m.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(d=>` \u2022 ${d.label} \u2014 ${d.paths.length} article${d.paths.length===1?"":"s"}`),"",`Estimated cost: ${ge(r)}\u2013${ge(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Qn(e,t,n){let o=$=>t[$.index]?.paths.length??0,r=e.filter($=>$.ok),s=e.filter($=>!$.ok),c=e.reduce(($,I)=>$+o(I),0),d=r.reduce(($,I)=>$+o(I),0),m=e.reduce(($,I)=>$+I.costUsd,0),h=e.reduce(($,I)=>$+I.outputTokens,0),y=n==="api"?`${ge(m)} total`:it(h),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=$=>`${$} article${$===1?"":"s"}`,v=[];if(s.length===0)v.push(`Converted ${x(c)} (${D}) successfully \xB7 ${y}.`);else{v.push(`Converted ${d}/${x(c)} (${D}) \xB7 ${y}.`),v.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let $ of s)v.push(` \u2717 ${$.label}${$.error?` \u2014 ${$.error}`:""}`)}return v}async function Gr(e,t){if(!Ya(t.cwd))return console.log(b("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Yn(e),r=Ka(t.cwd,t.profileName);if(r.length===0)return console.log(b("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Vn(r,n);if(s.length===0)return console.log(b(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=za(s),d=`/convert${n?` --scope ${n}`:""} --run`,{model:m,forced:h}=Va(t.cwd,"light");if(!o){let y=Ga({files:Xn(t.cwd,s),op:"convert",model:m});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let D of Jn(c,y,zn))console.log(D);return console.log(f(`Model: ${m}${h?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${d} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${c.length} partitions (\u2264${zn} agents at once) on ${m}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let y of Xa({cwd:t.cwd,partitions:c,promptFor:Kn,concurrency:zn,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:m}))if(y.type==="partition_status")y.status==="running"?console.log(f(` \u25B8 ${y.label} \u2014 converting\u2026`)):y.status==="done"?console.log(_(` \u2713 ${y.label}`)):console.log(b(` \u2717 ${y.label}`));else if(y.type==="run_done"){console.log("");let D=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let x of Qn(y.results,c,D))console.log(y.ok?_(x):O(x))}}catch(y){console.log(b(`Convert run failed: ${y.message}`))}return console.log(""),{kind:"continue"}}q();import{statSync as zr}from"node:fs";import{resolve as Yr}from"node:path";import{estimateBulkCost as Ja,planPartitions as Qa,readDocsPlan as Za,readProjectConfig as Vr,resolveModelForOperation as el,runPartitioned as tl}from"document360-engine";var Zn=5;function eo(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 nl(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function ol(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function rl(e,t,n){return n.filter(o=>{try{return zr(Yr(e,t,o)).size===0}catch{return!0}})}function to(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+=zr(Yr(e,c)).size}catch{}return{path:r,bytes:s}})}function no(e,t){return`Run the write-article skill to author EACH documentation article listed below. For each path:
50
+ `)}function Kn(e,t,n){let o=e.reduce((d,m)=>d+m.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(d=>` \u2022 ${d.label} \u2014 ${d.paths.length} article${d.paths.length===1?"":"s"}`),"",`Estimated cost: ${ge(r)}\u2013${ge(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Jn(e,t,n){let o=$=>t[$.index]?.paths.length??0,r=e.filter($=>$.ok),s=e.filter($=>!$.ok),c=e.reduce(($,I)=>$+o(I),0),d=r.reduce(($,I)=>$+o(I),0),m=e.reduce(($,I)=>$+I.costUsd,0),h=e.reduce(($,I)=>$+I.outputTokens,0),y=n==="api"?`${ge(m)} total`:it(h),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=$=>`${$} article${$===1?"":"s"}`,v=[];if(s.length===0)v.push(`Converted ${x(c)} (${D}) successfully \xB7 ${y}.`);else{v.push(`Converted ${d}/${x(c)} (${D}) \xB7 ${y}.`),v.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let $ of s)v.push(` \u2717 ${$.label}${$.error?` \u2014 ${$.error}`:""}`)}return v}async function Gr(e,t){if(!Ya(t.cwd))return console.log(b("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=zn(e),r=Ka(t.cwd,t.profileName);if(r.length===0)return console.log(b("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Yn(r,n);if(s.length===0)return console.log(b(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=za(s),d=`/convert${n?` --scope ${n}`:""} --run`,{model:m,forced:h}=Va(t.cwd,"light");if(!o){let y=Ga({files:Vn(t.cwd,s),op:"convert",model:m});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let D of Kn(c,y,Gn))console.log(D);return console.log(f(`Model: ${m}${h?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${d} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${c.length} partitions (\u2264${Gn} agents at once) on ${m}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let y of Xa({cwd:t.cwd,partitions:c,promptFor:Xn,concurrency:Gn,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:m}))if(y.type==="partition_status")y.status==="running"?console.log(f(` \u25B8 ${y.label} \u2014 converting\u2026`)):y.status==="done"?console.log(_(` \u2713 ${y.label}`)):console.log(b(` \u2717 ${y.label}`));else if(y.type==="run_done"){console.log("");let D=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let x of Jn(y.results,c,D))console.log(y.ok?_(x):O(x))}}catch(y){console.log(b(`Convert run failed: ${y.message}`))}return console.log(""),{kind:"continue"}}q();import{statSync as zr}from"node:fs";import{resolve as Yr}from"node:path";import{estimateBulkCost as Ja,planPartitions as Qa,readDocsPlan as Za,readProjectConfig as Vr,resolveModelForOperation as el,runPartitioned as tl}from"document360-engine";var Qn=5;function Zn(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 nl(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function ol(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function rl(e,t,n){return n.filter(o=>{try{return zr(Yr(e,t,o)).size===0}catch{return!0}})}function eo(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+=zr(Yr(e,c)).size}catch{}return{path:r,bytes:s}})}function to(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,12 +55,12 @@ 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 oo(e,t,n){let o=e.reduce((c,d)=>c+d.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: ${ge(r)}\u2013${ge(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write --run to start."]}function ro(e,t,n){let o=$=>t[$.index]?.paths.length??0,r=e.filter($=>$.ok),s=e.filter($=>!$.ok),c=e.reduce(($,I)=>$+o(I),0),d=r.reduce(($,I)=>$+o(I),0),m=e.reduce(($,I)=>$+I.costUsd,0),h=e.reduce(($,I)=>$+I.outputTokens,0),y=n==="api"?`${ge(m)} total`:it(h),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=$=>`${$} article${$===1?"":"s"}`,v=[];if(s.length===0)v.push(`Wrote ${x(c)} (${D}) successfully \xB7 ${y}.`),v.push("Review them in the docs tree, then /publish when ready.");else{v.push(`Wrote ${d}/${x(c)} (${D}) \xB7 ${y}.`),v.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let $ of s)v.push(` \u2717 ${$.label}${$.error?` \u2014 ${$.error}`:""}`)}return v}function so(e,t,n){let o=(Vr(e)?.docsDir??"user-docs").replace(/\/+$/,""),r=t.map(d=>d.path);if(n.path){let d=nl(n.path,o);return r.includes(d)?{docsDir:o,targets:[d],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${d}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=ol(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=rl(e,o,s);if(c.length===0){let d=n.scope?` under "${n.scope}"`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${d} are already written. Use /write <path> to rewrite one.`}}return{docsDir:o,targets:c,planCount:r.length}}async function Xr(e,t){if(!Vr(t.cwd))return console.log(b("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=Za(t.cwd);if(n.length===0)return console.log(b("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}=eo(e),{docsDir:c,targets:d,reason:m}=so(t.cwd,n,{scope:o,path:r});if(d.length===0)return console.log(m?O(m):O("Nothing to write.")),{kind:"continue"};let h=Qa(d),{model:y,forced:D}=el(t.cwd,"standard");if(!s&&!!!r){let v=Ja({files:to(t.cwd,n,d),op:"write",model:y});o&&console.log(f(`Scope: ${o} (${d.length} pending).`));for(let $ of oo(h,v,Zn))console.log($);return console.log(f(`Model: ${y}${D?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:" --all"} --run to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${d.length} article${d.length===1?"":"s"} across ${h.length} partition${h.length===1?"":"s"} (\u2264${Zn} agents at once) on ${y}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let v of tl({cwd:t.cwd,partitions:h,promptFor:$=>no($,c),concurrency:Zn,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:y}))if(v.type==="partition_status")v.status==="running"?console.log(f(` \u25B8 ${v.label} \u2014 writing\u2026`)):v.status==="done"?console.log(_(` \u2713 ${v.label}`)):console.log(b(` \u2717 ${v.label}`));else if(v.type==="run_done"){console.log("");let $=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let I of ro(v.results,h,$))console.log(v.ok?_(I):O(I))}}catch(v){console.log(b(`Write run failed: ${v.message}`))}return console.log(""),{kind:"continue"}}q();import{search as sl}from"@inquirer/prompts";import{findByName as il,getSession as al,listSessions as ll,relativeTime as Jr}from"document360-engine";async function Qr(e,t){let n=ll(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=il(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(b(`No session matches "${o}".`)),Kr(n),{kind:"continue"})}if(!process.stdin.isTTY)return Kr(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>sl({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return n.filter(d=>!c||d.name.toLowerCase().includes(c)||d.firstPrompt.toLowerCase().includes(c)).map(d=>({name:`${d.name} ${Jr(d.updatedAt)}`,value:d.uuid,description:d.firstPrompt.slice(0,100)}))}})),r=al(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Kr(e){console.log("");for(let t of e.slice(0,15))console.log(` ${j(t.name)} ${f(Jr(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}q();import{renameSession as cl}from"document360-engine";function io(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 Zr(e,t){let n=io(e.join(" "));if(!n)return console.log(b("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(cl(o,n)?console.log(_(`\u2713 Session renamed to "${n}"`)):console.log(b("Could not find the current session record.")),{kind:"continue"}):(console.log(b("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as es,readProjectConfig as ul,writeProjectConfig as dl}from"document360-engine";q();function ao(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=ul(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 es().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},dl(o,e),null):`Unknown environment "${r}". Known: ${es().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function ts(e,t){let n=e[0];if(!n)return zt(t.cwd),{kind:"continue"};if(n==="add"){let o=ao(t.cwd,e[1],e[2]);return o?(console.log(b(o)),{kind:"continue"}):(console.log(_(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${j(`/profile ${e[1]}`)} then ${j("/login")}`),{kind:"continue"})}return Yt(t.cwd,n),Vt(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}q();import{select as pl}from"@inquirer/prompts";import{readProjectConfig as fl,readUserConfig as ns,resolveModelSetting as lo,writeUserConfig as os}from"document360-engine";var ye=[{value:null,label:"Auto",desc:"Engine right-sizes per task \u2014 Sonnet for routine work, Opus for analysis (recommended)"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus 4.8 \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet 4.6 \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku 4.5 \xB7 fastest for quick answers"}];function on(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=ye.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function ml(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 Ct(e,t){let n=()=>{let s=lo(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=ns();return s.defaultModel?(delete s.defaultModel,os(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${lo(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}}os({...ns(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=fl(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 rs(e,t){let n=e[0]?.trim();if(!n){let c=lo(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${j(c.model??"Claude Code default")}`),console.log(f(` source: ${ml(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let d=on(c),m;try{m=await t.withPausedInput(()=>pl({message:`Select model (current: ${c.model??"Claude Code default"})`,default:ye[d].value,choices:ye.map((x,v)=>({name:`${x.label}${v===d?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:h,changed:y,effective:D}=Ct(t.cwd,m??"default");for(let x of h)console.log(x.startsWith("\u26A0")?O(x):x.startsWith("\u2713")?_(x):f(x));return y&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Ct(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?O(c):c.startsWith("\u2713")?_(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}rn();async function cs(e,t){return await t.withPausedInput(()=>ot(t.cwd)),{kind:"clear"}}q();import{select as Pl}from"@inquirer/prompts";import{resolveActiveProfile as Sl,setProfileProject as Tl,listProjects as Rl}from"document360-engine";async function uo(e,t){let n=Sl(e,t),o={profile:n.name,connection:n.connection};return{projects:await Rl(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var us=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function ds(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function po(e,t,n){Tl(e,t,{projectId:n,workspaceId:void 0,workspaceName:void 0})}async function ps(e,t){let n;try{n=await uo(e,t)}catch(m){console.log(b(`Could not list projects: ${m.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 m of o)console.log(` ${m.id===s?j("\u25CF"):" "} ${us(m)} ${f(m.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await Pl({message:"Select the Document360 project for this repo:",choices:o.map(m=>({name:`${us(m)}${m.id===s?" (current)":""}`,value:m.id}))});po(e,r,c);let d=o.find(m=>m.id===c);console.log(_(`\u2713 Project set to "${d?.name??c}" for profile "${r}". Next: pick a workspace.`))}async function fs(e,t){return await t.withPausedInput(()=>ps(t.cwd,t.profileName)),{kind:"clear"}}q();import{resolveActiveProfile as jl}from"document360-engine";async function ms(e,t){let n=!1;try{n=jl(t.cwd).production}catch{}return n?(console.log(O("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}q();var gs=async(e,t)=>{try{await t.withPausedInput(()=>Gt({}))}catch(n){console.log(b(`Login failed: ${n.message}`))}return{kind:"continue"}};q();import{resolveActiveProfile as Al,clearTokens as El,clearProfileProject as Dl}from"document360-engine";async function hs(e,t){let n;try{n=Al(t.cwd,t.profileName).name}catch(r){return console.log(b(r.message)),{kind:"continue"}}let o=El(n);return Dl(t.cwd,n),console.log(o?_(`\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 ks}from"node:fs";import{isAbsolute as Il,join as _l,resolve as Nl}from"node:path";import{readProjectConfig as Ml,screenshotPlaceholderIds as Ll}from"document360-engine";var ws=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function fo(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?ws(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:ws(o),setup:t}:{mode:"single",id:o}}function mo(e,t){let n=Ml(e),o=n?.captureDir??"user-docs/_capture",r=n?.outputDir??"user-docs/_screenshots",s=(c,d)=>Il(c)?_l(c,d):Nl(e,c,d);return Ll(e,{scope:t}).map(({id:c,file:d})=>{let m=ks(s(r,`${c}.png`))?"captured":ks(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:d,state:m}})}var Ol={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Ul={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function go(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(d=>d.file===s))r.push(` ${Ol[c.state]} ${c.id.padEnd(34)} ${Ul[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 no(e,t,n){let o=e.reduce((c,d)=>c+d.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: ${ge(r)}\u2013${ge(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write --run to start."]}function oo(e,t,n){let o=$=>t[$.index]?.paths.length??0,r=e.filter($=>$.ok),s=e.filter($=>!$.ok),c=e.reduce(($,I)=>$+o(I),0),d=r.reduce(($,I)=>$+o(I),0),m=e.reduce(($,I)=>$+I.costUsd,0),h=e.reduce(($,I)=>$+I.outputTokens,0),y=n==="api"?`${ge(m)} total`:it(h),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=$=>`${$} article${$===1?"":"s"}`,v=[];if(s.length===0)v.push(`Wrote ${x(c)} (${D}) successfully \xB7 ${y}.`),v.push("Review them in the docs tree, then /publish when ready.");else{v.push(`Wrote ${d}/${x(c)} (${D}) \xB7 ${y}.`),v.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let $ of s)v.push(` \u2717 ${$.label}${$.error?` \u2014 ${$.error}`:""}`)}return v}function ro(e,t,n){let o=(Vr(e)?.docsDir??"user-docs").replace(/\/+$/,""),r=t.map(d=>d.path);if(n.path){let d=nl(n.path,o);return r.includes(d)?{docsDir:o,targets:[d],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${d}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=ol(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=rl(e,o,s);if(c.length===0){let d=n.scope?` under "${n.scope}"`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${d} are already written. Use /write <path> to rewrite one.`}}return{docsDir:o,targets:c,planCount:r.length}}async function Xr(e,t){if(!Vr(t.cwd))return console.log(b("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=Za(t.cwd);if(n.length===0)return console.log(b("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}=Zn(e),{docsDir:c,targets:d,reason:m}=ro(t.cwd,n,{scope:o,path:r});if(d.length===0)return console.log(m?O(m):O("Nothing to write.")),{kind:"continue"};let h=Qa(d),{model:y,forced:D}=el(t.cwd,"standard");if(!s&&!!!r){let v=Ja({files:eo(t.cwd,n,d),op:"write",model:y});o&&console.log(f(`Scope: ${o} (${d.length} pending).`));for(let $ of no(h,v,Qn))console.log($);return console.log(f(`Model: ${y}${D?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:" --all"} --run to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${d.length} article${d.length===1?"":"s"} across ${h.length} partition${h.length===1?"":"s"} (\u2264${Qn} agents at once) on ${y}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let v of tl({cwd:t.cwd,partitions:h,promptFor:$=>to($,c),concurrency:Qn,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:y}))if(v.type==="partition_status")v.status==="running"?console.log(f(` \u25B8 ${v.label} \u2014 writing\u2026`)):v.status==="done"?console.log(_(` \u2713 ${v.label}`)):console.log(b(` \u2717 ${v.label}`));else if(v.type==="run_done"){console.log("");let $=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let I of oo(v.results,h,$))console.log(v.ok?_(I):O(I))}}catch(v){console.log(b(`Write run failed: ${v.message}`))}return console.log(""),{kind:"continue"}}q();import{search as sl}from"@inquirer/prompts";import{findByName as il,getSession as al,listSessions as ll,relativeTime as Jr}from"document360-engine";async function Qr(e,t){let n=ll(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=il(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(b(`No session matches "${o}".`)),Kr(n),{kind:"continue"})}if(!process.stdin.isTTY)return Kr(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>sl({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return n.filter(d=>!c||d.name.toLowerCase().includes(c)||d.firstPrompt.toLowerCase().includes(c)).map(d=>({name:`${d.name} ${Jr(d.updatedAt)}`,value:d.uuid,description:d.firstPrompt.slice(0,100)}))}})),r=al(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Kr(e){console.log("");for(let t of e.slice(0,15))console.log(` ${j(t.name)} ${f(Jr(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}q();import{renameSession as cl}from"document360-engine";function so(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 Zr(e,t){let n=so(e.join(" "));if(!n)return console.log(b("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(cl(o,n)?console.log(_(`\u2713 Session renamed to "${n}"`)):console.log(b("Could not find the current session record.")),{kind:"continue"}):(console.log(b("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as es,readProjectConfig as ul,writeProjectConfig as dl}from"document360-engine";q();function io(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=ul(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 es().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},dl(o,e),null):`Unknown environment "${r}". Known: ${es().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function ts(e,t){let n=e[0];if(!n)return zt(t.cwd),{kind:"continue"};if(n==="add"){let o=io(t.cwd,e[1],e[2]);return o?(console.log(b(o)),{kind:"continue"}):(console.log(_(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${j(`/profile ${e[1]}`)} then ${j("/login")}`),{kind:"continue"})}return Yt(t.cwd,n),Vt(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}q();import{select as pl}from"@inquirer/prompts";import{readProjectConfig as fl,readUserConfig as ns,resolveModelSetting as ao,writeUserConfig as os}from"document360-engine";var we=[{value:null,label:"Auto",desc:"Engine right-sizes per task \u2014 Sonnet for routine work, Opus for analysis (recommended)"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus 4.8 \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet 4.6 \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku 4.5 \xB7 fastest for quick answers"}];function on(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=we.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function ml(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 Ct(e,t){let n=()=>{let s=ao(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=ns();return s.defaultModel?(delete s.defaultModel,os(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${ao(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}}os({...ns(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=fl(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 rs(e,t){let n=e[0]?.trim();if(!n){let c=ao(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${j(c.model??"Claude Code default")}`),console.log(f(` source: ${ml(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let d=on(c),m;try{m=await t.withPausedInput(()=>pl({message:`Select model (current: ${c.model??"Claude Code default"})`,default:we[d].value,choices:we.map((x,v)=>({name:`${x.label}${v===d?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:h,changed:y,effective:D}=Ct(t.cwd,m??"default");for(let x of h)console.log(x.startsWith("\u26A0")?O(x):x.startsWith("\u2713")?_(x):f(x));return y&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Ct(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?O(c):c.startsWith("\u2713")?_(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}rn();async function cs(e,t){return await t.withPausedInput(()=>ot(t.cwd)),{kind:"clear"}}q();import{select as Pl}from"@inquirer/prompts";import{resolveActiveProfile as Sl,setProfileProject as Tl,listProjects as Rl}from"document360-engine";async function co(e,t){let n=Sl(e,t),o={profile:n.name,connection:n.connection};return{projects:await Rl(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var us=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function ds(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function uo(e,t,n){Tl(e,t,{projectId:n,workspaceId:void 0,workspaceName:void 0})}async function ps(e,t){let n;try{n=await co(e,t)}catch(m){console.log(b(`Could not list projects: ${m.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 m of o)console.log(` ${m.id===s?j("\u25CF"):" "} ${us(m)} ${f(m.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await Pl({message:"Select the Document360 project for this repo:",choices:o.map(m=>({name:`${us(m)}${m.id===s?" (current)":""}`,value:m.id}))});uo(e,r,c);let d=o.find(m=>m.id===c);console.log(_(`\u2713 Project set to "${d?.name??c}" for profile "${r}". Next: pick a workspace.`))}async function fs(e,t){return await t.withPausedInput(()=>ps(t.cwd,t.profileName)),{kind:"clear"}}q();import{resolveActiveProfile as jl}from"document360-engine";async function ms(e,t){let n=!1;try{n=jl(t.cwd).production}catch{}return n?(console.log(O("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}q();var gs=async(e,t)=>{try{await t.withPausedInput(()=>Gt({}))}catch(n){console.log(b(`Login failed: ${n.message}`))}return{kind:"continue"}};q();import{resolveActiveProfile as Al,clearTokens as El,clearProfileProject as Dl}from"document360-engine";async function hs(e,t){let n;try{n=Al(t.cwd,t.profileName).name}catch(r){return console.log(b(r.message)),{kind:"continue"}}let o=El(n);return Dl(t.cwd,n),console.log(o?_(`\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 ks}from"node:fs";import{isAbsolute as Il,join as _l,resolve as Nl}from"node:path";import{readProjectConfig as Ml,screenshotPlaceholderIds as Ll}from"document360-engine";var ws=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function po(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?ws(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:ws(o),setup:t}:{mode:"single",id:o}}function fo(e,t){let n=Ml(e),o=n?.captureDir??"user-docs/_capture",r=n?.outputDir??"user-docs/_screenshots",s=(c,d)=>Il(c)?_l(c,d):Nl(e,c,d);return Ll(e,{scope:t}).map(({id:c,file:d})=>{let m=ks(s(r,`${c}.png`))?"captured":ks(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:d,state:m}})}var Ol={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Ul={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function mo(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(d=>d.file===s))r.push(` ${Ol[c.state]} ${c.id.padEnd(34)} ${Ul[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(`
59
59
  `),"","For each: locate its <!-- SCREENSHOT --> block in user-docs/**/*.md; 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(`
60
- `)}async function sn(e,t){let n=fo(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let d of go(mo(c,n.scope),n.scope))console.log(d);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 user-docs/**/*.md, 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(`
60
+ `)}async function sn(e,t){let n=po(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let d of mo(fo(c,n.scope),n.scope))console.log(d);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 user-docs/**/*.md, 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(`
61
61
  `),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 user-docs/**/*.md"}.`,"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(`
62
62
  `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as Wl,readFileSync as Hl}from"node:fs";import{isAbsolute as Fl,join as Bl,resolve as ql}from"node:path";import{readProjectConfig as Gl}from"document360-engine";async function St(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across user-docs/**/*.md, 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(`
63
- `),display:"/capture-setup"}}var xs="-".repeat(64);function ho(e){let t="user-docs/_capture";try{let y=Gl(e);y?.captureDir&&(t=y.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Fl(t)?Bl(t,"CAPTURE-TESTID-REQUESTS.json"):ql(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Wl(n))return null;let o;try{let y=JSON.parse(Hl(n,"utf8").replace(/^/,""));o=Array.isArray(y?.requests)?y.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(y=>y.file).filter(Boolean)).size,s=o.length,c=`${s} data-testid attribute${s===1?"":"s"}`,d=`${r} source file${r===1?"":"s"}`,m=`${t}/CAPTURE-TESTID-REQUESTS.md`,h=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${c} requested across ${d}.`,"\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.","",xs,`Read ${m} and ${h}. They list ${c} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",xs]}import{writeFileSync as zl}from"node:fs";import{devHintsGuidePath as Yl,hintsDir as Vl,ensureDir as Xl}from"document360-engine";var $s="-".repeat(64),Kl=1;function ko(){return`# Dev \u2192 Docs hints \u2014 protocol guide
63
+ `),display:"/capture-setup"}}var xs="-".repeat(64);function go(e){let t="user-docs/_capture";try{let y=Gl(e);y?.captureDir&&(t=y.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Fl(t)?Bl(t,"CAPTURE-TESTID-REQUESTS.json"):ql(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Wl(n))return null;let o;try{let y=JSON.parse(Hl(n,"utf8").replace(/^/,""));o=Array.isArray(y?.requests)?y.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(y=>y.file).filter(Boolean)).size,s=o.length,c=`${s} data-testid attribute${s===1?"":"s"}`,d=`${r} source file${r===1?"":"s"}`,m=`${t}/CAPTURE-TESTID-REQUESTS.md`,h=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${c} requested across ${d}.`,"\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.","",xs,`Read ${m} and ${h}. They list ${c} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",xs]}import{writeFileSync as zl}from"node:fs";import{devHintsGuidePath as Yl,hintsDir as Vl,ensureDir as Xl}from"document360-engine";var $s="-".repeat(64),Kl=1;function ho(){return`# Dev \u2192 Docs hints \u2014 protocol guide
64
64
 
65
65
  <!-- Guide version: ${Kl} \xB7 maintained by document360-writer (/devhints). -->
66
66
 
@@ -119,14 +119,14 @@ Prose: what you built and the gotchas a code diff would miss \u2014 e.g. "the bu
119
119
  - Keep the body about user-facing intent, not implementation. Don't propose docs structure.
120
120
 
121
121
  That's it \u2014 drop the file and keep building. The docs agent picks it up on its next analysis run.
122
- `}async function bs(e,t){Xl(Vl(t.cwd)),zl(Yl(t.cwd),ko());for(let n of wo())console.log(n);return{kind:"continue"}}function wo(){return["\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md and created the .d360-writer/hints/ inbox.","","\u{1F4CB} One-time setup \u2014 connect this repo's coding agent to the docs agent."," Add the block below to your SOURCE repo's agent memory (CLAUDE.md / AGENTS.md), then commit"," .d360-writer/DEV-HINTS-GUIDE.md so teammates' agents get the same instruction:","",$s,"## Documentation hints (for the docs agent)","","When you ship a user-facing change (new/changed/removed screen, button, flow, setting, API field,","CLI flag, or permission), record a doc hint so the documentation team's agent can update the help","center. How: read `.d360-writer/DEV-HINTS-GUIDE.md` and follow it \u2014 create one markdown file under","`.d360-writer/hints/`. Do this as part of finishing the feature. Skip it only for changes with no","user-visible effect (refactors, tests, build, deps).",$s,"","Then keep building as usual. On its next analysis run (/audit), the docs agent reads open hints,","verifies each against your code, writes/updates the docs, and marks the hint consumed."]}q();import{existsSync as Jl,rmSync as Ql}from"node:fs";import{basename as vs,resolve as Cs}from"node:path";import{execFileSync as Zl}from"node:child_process";import{input as ec}from"@inquirer/prompts";import{readProjectConfig as tc}from"document360-engine";var nc=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"];function yo(e){let t=null;try{t=tc(e)}catch{t=null}let n=s=>s?.replace(/\\/g,"/").replace(/\/+$/,""),o=n(t?.docsDir)??"user-docs",r=new Set([o]);for(let s of[n(t?.captureDir),n(t?.outputDir)])s&&s!==o&&!s.startsWith(`${o}/`)&&r.add(s);return[...r,...nc].filter(s=>Jl(Cs(e,s)))}function xo(e,t){let n=[],o=[];for(let r of t)try{Ql(Cs(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}return{removed:n,failed:o}}function oc(e){try{return Zl("git",["status","--porcelain","--",".d360-writer/hints"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
123
- `).filter(n=>n.trim()&&/\.md\s*$/.test(n)).length}catch{return 0}}function $o(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=oc(e);return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(o=>` \u2022 ${o}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${vs(e)}`]}async function Ps(e,t){let n=yo(t.cwd);for(let d of $o(t.cwd,n))console.log(n.length===0?f(d):d);if(n.length===0)return{kind:"continue"};let o=vs(t.cwd);if((await t.withPausedInput(()=>ec({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(O("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let{removed:s,failed:c}=xo(t.cwd,n);console.log(_(`\u2713 Reset complete \u2014 removed ${s.length} item${s.length===1?"":"s"}. The repo is back to its original state.`));for(let d of c)console.log(b(` \u2717 ${d.path}: ${d.error}`));return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}var Ss={help:_n,"?":_n,clear:hr,exit:Nn,quit:Nn,init:br,mcp:Jt,publish:Rr,audit:en,scope:Ar,sync:Lr,convert:Gr,write:Xr,resume:Qr,rename:Zr,profile:ts,model:rs,doctor:Pt,workspace:cs,project:fs,"allow-prod":ms,login:gs,logout:hs,screenshot:sn,"capture-setup":St,devhints:bs,reset:Ps};function Ts(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}q();var rc={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"},js=160,vo=200,As=40;function ce(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Rs(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}: ${ce(typeof r=="string"?r:JSON.stringify(r),As)}`);return t.length>4&&n.push("\u2026"),ce(n.join(", "),js)}var De=e=>typeof e=="string"&&e?e:null,bo=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function sc(e){let t=De(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 ic(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=De(t.title);if(!o)return null;let r=sc(t.local_path);return n("Create article",`"${ce(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=De(t.title),r=bo(t.article_id);return n("Update article",o?`"${ce(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",bo(t.article_id)?`id ${bo(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",De(t.name)?`"${ce(De(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=De(t.file_path);return n("Upload image",o?ce(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function an(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),c=s.join("__");if(r==="document360"){let h=ic(c,t);if(h)return h}let d=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${d}`,sep:" ",arg:Rs(t)}}let n=rc[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:ce(o,js)}:{title:e,sep:"",arg:Rs(t)}}function ac(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 lc(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(ac).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>ce(r,vo))]}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}: ${ce(String(r),As)}`);return n.length>0?[ce(n.join(" \xB7 "),vo)]:null}return null}function cc(e){let t=De(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function uc(e,t,n){switch(e){case"d360_create_article":{let o=cc(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=De(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 ${ce(o[0],120)}`:""}`]}default:return null}}function ln(e,t=4,n,o){let r=e.replace(/\r\n/g,`
122
+ `}async function bs(e,t){Xl(Vl(t.cwd)),zl(Yl(t.cwd),ho());for(let n of ko())console.log(n);return{kind:"continue"}}function ko(){return["\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md and created the .d360-writer/hints/ inbox.","","\u{1F4CB} One-time setup \u2014 connect this repo's coding agent to the docs agent."," Add the block below to your SOURCE repo's agent memory (CLAUDE.md / AGENTS.md), then commit"," .d360-writer/DEV-HINTS-GUIDE.md so teammates' agents get the same instruction:","",$s,"## Documentation hints (for the docs agent)","","When you ship a user-facing change (new/changed/removed screen, button, flow, setting, API field,","CLI flag, or permission), record a doc hint so the documentation team's agent can update the help","center. How: read `.d360-writer/DEV-HINTS-GUIDE.md` and follow it \u2014 create one markdown file under","`.d360-writer/hints/`. Do this as part of finishing the feature. Skip it only for changes with no","user-visible effect (refactors, tests, build, deps).",$s,"","Then keep building as usual. On its next analysis run (/audit), the docs agent reads open hints,","verifies each against your code, writes/updates the docs, and marks the hint consumed."]}q();import{existsSync as Jl,rmSync as Ql}from"node:fs";import{basename as vs,resolve as Cs}from"node:path";import{execFileSync as Zl}from"node:child_process";import{input as ec}from"@inquirer/prompts";import{readProjectConfig as tc}from"document360-engine";var nc=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"];function wo(e){let t=null;try{t=tc(e)}catch{t=null}let n=s=>s?.replace(/\\/g,"/").replace(/\/+$/,""),o=n(t?.docsDir)??"user-docs",r=new Set([o]);for(let s of[n(t?.captureDir),n(t?.outputDir)])s&&s!==o&&!s.startsWith(`${o}/`)&&r.add(s);return[...r,...nc].filter(s=>Jl(Cs(e,s)))}function yo(e,t){let n=[],o=[];for(let r of t)try{Ql(Cs(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}return{removed:n,failed:o}}function oc(e){try{return Zl("git",["status","--porcelain","--",".d360-writer/hints"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
123
+ `).filter(n=>n.trim()&&/\.md\s*$/.test(n)).length}catch{return 0}}function xo(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=oc(e);return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(o=>` \u2022 ${o}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${vs(e)}`]}async function Ps(e,t){let n=wo(t.cwd);for(let d of xo(t.cwd,n))console.log(n.length===0?f(d):d);if(n.length===0)return{kind:"continue"};let o=vs(t.cwd);if((await t.withPausedInput(()=>ec({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(O("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let{removed:s,failed:c}=yo(t.cwd,n);console.log(_(`\u2713 Reset complete \u2014 removed ${s.length} item${s.length===1?"":"s"}. The repo is back to its original state.`));for(let d of c)console.log(b(` \u2717 ${d.path}: ${d.error}`));return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}var Ss={help:In,"?":In,clear:hr,exit:_n,quit:_n,init:br,mcp:Jt,publish:Rr,audit:en,scope:Ar,sync:Lr,convert:Gr,write:Xr,resume:Qr,rename:Zr,profile:ts,model:rs,doctor:Pt,workspace:cs,project:fs,"allow-prod":ms,login:gs,logout:hs,screenshot:sn,"capture-setup":St,devhints:bs,reset:Ps};function Ts(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}q();var rc={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"},js=160,bo=200,As=40;function ce(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Rs(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}: ${ce(typeof r=="string"?r:JSON.stringify(r),As)}`);return t.length>4&&n.push("\u2026"),ce(n.join(", "),js)}var De=e=>typeof e=="string"&&e?e:null,$o=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function sc(e){let t=De(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 ic(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=De(t.title);if(!o)return null;let r=sc(t.local_path);return n("Create article",`"${ce(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=De(t.title),r=$o(t.article_id);return n("Update article",o?`"${ce(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",$o(t.article_id)?`id ${$o(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",De(t.name)?`"${ce(De(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=De(t.file_path);return n("Upload image",o?ce(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function an(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),c=s.join("__");if(r==="document360"){let h=ic(c,t);if(h)return h}let d=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${d}`,sep:" ",arg:Rs(t)}}let n=rc[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:ce(o,js)}:{title:e,sep:"",arg:Rs(t)}}function ac(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 lc(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(ac).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>ce(r,bo))]}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}: ${ce(String(r),As)}`);return n.length>0?[ce(n.join(" \xB7 "),bo)]:null}return null}function cc(e){let t=De(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function uc(e,t,n){switch(e){case"d360_create_article":{let o=cc(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=De(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 ${ce(o[0],120)}`:""}`]}default:return null}}function ln(e,t=4,n,o){let r=e.replace(/\r\n/g,`
124
124
  `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=uc(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let s=lc(r)??r.split(`
125
- `);return{lines:s.slice(0,t).map(c=>ce(c,vo)),hidden:Math.max(0,s.length-t)}}function cn(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function un(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 dn(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 bc=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function vc(e,t,n,o){if(bc.test(e))try{let r=_s(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=un(t,n),d=dn(n);e.endsWith("publish_article")&&d&&console.log(j(` \u2B95 Live: ${d}`)),c&&s&&console.log(j(` \u2B95 Preview: ${cn(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function Ns(e=process.cwd(),t="auto",n){let o=pc(t);o.kind==="none"&&(console.error(""),console.error(b("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${j("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${j('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${j("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${j("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Cc(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=Co({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},d=dc({input:process.stdin,output:process.stdout}),m=[],h=null,y=!1;d.on("line",v=>{if(h){let $=h;h=null,$(v)}else m.push(v)}),d.on("close",()=>{if(y=!0,h){let v=h;h=null,v(null)}});function D(){return m.length>0?Promise.resolve(m.shift()):y?Promise.resolve(null):(process.stdout.write(j("> ")),new Promise(v=>{h=v}))}let x={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=Co({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setModel:async v=>s.setModel(v),withPausedInput:async v=>{d.pause();try{return await v()}finally{d.resume()}}};try{for(;;){let v=await D();if(v===null)break;let $=v.trim();if($){if($.startsWith("/")){let I=Ts($);if(!I)continue;let N=Ss[I.name];if(!N){console.log(b(`Unknown command: /${I.name}`)),console.log(f("Type /help for the list."));continue}let F=await N(I.args,x);if(F.kind==="exit")break;if(F.kind==="clear"){x.restartAgent();continue}if(F.kind==="allow-prod"){r=!0,x.restartAgent(),console.log(_("\u2713 Production writes authorized for this session.")),console.log("");continue}if(F.kind==="resume"){s.close(),s=Co({cwd:e,resume:F.uuid,profileName:n,allowProdWrites:r});let Q=fc(F.uuid);c={uuid:F.uuid,firstPrompt:Q?.firstPrompt??null,titleFired:!0},Is(F.uuid),console.log(_(`\u2713 Resumed "${F.name}"`)),console.log("");continue}F.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=F.display??F.prompt),await Ds(s,F.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=$),await Ds(s,$,o,c,e)}}}finally{s.close(),d.close()}}function Cc(e,t){console.log(""),console.log(ht("document360-writer")),console.log(f(` cwd: ${e}`));let n=wc(e);console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(Pc(e,t)),yc(e)||console.log(O(" First run: /init \u2192 /login \u2192 /workspace, then ask for a docs analysis.")),console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Pc(e,t){try{let n=_s(e,t),o=n.production?O(" \u26A0 PRODUCTION"):"",r=$c(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Es(r.idToken)??{},...Es(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return xc(r)&&!r.refreshToken?O(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function Sc(){console.error(""),console.error(`Sign in with your Claude subscription: run ${j("claude")} once, then retry.`),console.error(` (No Claude Code? ${j("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${j("https://console.anthropic.com/settings/keys")}`)}function Tc(e,t,n){e.uuid=t;let o=new Date().toISOString();hc({uuid:t,name:gc(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o})}function Rc(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||kc(o,t).then(r=>{r&&mc(n,r)}).catch(()=>{})}async function Ds(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))jc(c,o,r,n,s)}function jc(e,t,n,o,r){switch(e.type){case"session":t.uuid||Tc(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=an(e.name,e.input);s&&(process.stdout.write(`
125
+ `);return{lines:s.slice(0,t).map(c=>ce(c,bo)),hidden:Math.max(0,s.length-t)}}function cn(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function un(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 dn(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 bc=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function vc(e,t,n,o){if(bc.test(e))try{let r=_s(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=un(t,n),d=dn(n);e.endsWith("publish_article")&&d&&console.log(j(` \u2B95 Live: ${d}`)),c&&s&&console.log(j(` \u2B95 Preview: ${cn(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function Ns(e=process.cwd(),t="auto",n){let o=pc(t);o.kind==="none"&&(console.error(""),console.error(b("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${j("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${j('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${j("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${j("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Cc(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=vo({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},d=dc({input:process.stdin,output:process.stdout}),m=[],h=null,y=!1;d.on("line",v=>{if(h){let $=h;h=null,$(v)}else m.push(v)}),d.on("close",()=>{if(y=!0,h){let v=h;h=null,v(null)}});function D(){return m.length>0?Promise.resolve(m.shift()):y?Promise.resolve(null):(process.stdout.write(j("> ")),new Promise(v=>{h=v}))}let x={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=vo({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setModel:async v=>s.setModel(v),withPausedInput:async v=>{d.pause();try{return await v()}finally{d.resume()}}};try{for(;;){let v=await D();if(v===null)break;let $=v.trim();if($){if($.startsWith("/")){let I=Ts($);if(!I)continue;let N=Ss[I.name];if(!N){console.log(b(`Unknown command: /${I.name}`)),console.log(f("Type /help for the list."));continue}let F=await N(I.args,x);if(F.kind==="exit")break;if(F.kind==="clear"){x.restartAgent();continue}if(F.kind==="allow-prod"){r=!0,x.restartAgent(),console.log(_("\u2713 Production writes authorized for this session.")),console.log("");continue}if(F.kind==="resume"){s.close(),s=vo({cwd:e,resume:F.uuid,profileName:n,allowProdWrites:r});let Q=fc(F.uuid);c={uuid:F.uuid,firstPrompt:Q?.firstPrompt??null,titleFired:!0},Is(F.uuid),console.log(_(`\u2713 Resumed "${F.name}"`)),console.log("");continue}F.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=F.display??F.prompt),await Ds(s,F.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=$),await Ds(s,$,o,c,e)}}}finally{s.close(),d.close()}}function Cc(e,t){console.log(""),console.log(ht("document360-writer")),console.log(f(` cwd: ${e}`));let n=wc(e);console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(Pc(e,t)),yc(e)||console.log(O(" First run: /init \u2192 /login \u2192 /workspace, then ask for a docs analysis.")),console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Pc(e,t){try{let n=_s(e,t),o=n.production?O(" \u26A0 PRODUCTION"):"",r=$c(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Es(r.idToken)??{},...Es(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return xc(r)&&!r.refreshToken?O(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function Sc(){console.error(""),console.error(`Sign in with your Claude subscription: run ${j("claude")} once, then retry.`),console.error(` (No Claude Code? ${j("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${j("https://console.anthropic.com/settings/keys")}`)}function Tc(e,t,n){e.uuid=t;let o=new Date().toISOString();hc({uuid:t,name:gc(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o})}function Rc(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||kc(o,t).then(r=>{r&&mc(n,r)}).catch(()=>{})}async function Ds(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))jc(c,o,r,n,s)}function jc(e,t,n,o,r){switch(e.type){case"session":t.uuid||Tc(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=an(e.name,e.input);s&&(process.stdout.write(`
126
126
 
127
127
  `),console.log(`${_("\u25CF")} ${Pe(s.title)}${s.arg!==null?Z(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=He(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=d=>d===1?"":"s";console.log(Z(` \u23BF Added ${s.added} line${c(s.added)}, removed ${s.removed} line${c(s.removed)}`));for(let d of s.lines)console.log(d);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=ln(e.output,4,e.isError?void 0:s.name,s.input),d=e.isError?b:Z;c.lines.forEach((m,h)=>console.log(d((h===0?" \u23BF ":" ")+m))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||vc(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
128
- `),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&&(Is(t.uuid),t.titleFired||Rc(t,n));break;case"error":console.error(""),console.error(b(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Sc();break}}import{render as Ru}from"ink";import{resolveAuth as ju}from"document360-engine";import{useCallback as V,useEffect as _e,useMemo as wn,useRef as J,useState as B}from"react";import{Box as K,Text as C,useApp as Uc,useInput as Wc,useStdout as Hc}from"ink";import{existsSync as Zs,readFileSync as ei,readdirSync as ui,writeFileSync as Fc}from"node:fs";import{basename as Rt,isAbsolute as Bc,join as jt}from"node:path";import{createSession as ti,loginPkce as qc,toStoredTokens as Gc,saveTokens as zc,getAccessToken as Yc,resolveActiveProfile as ue,resolveProjectId as Vc,getArticle as Xc,decodeJwtClaims as at,isExpired as Ie,loadTokens as Be,clearTokens as Kc,clearProfileProject as Jc,setTitle as Qc,slugify as Zc,touchSession as jo,upsertSession as eu,generateTitle as ni,findByName as tu,listSessions as nu,renameSession as ou,suggestNextAction as ru,readProjectConfig as se,writeProjectConfig as su,resolveModelSetting as _o,loadProfileMap as oi,applyPull as iu,computeSyncStatus as Ao,planPull as au,inventoryRepo as lu,knownEnvironments as cu,resolveEnvironment as uu,planPartitions as ri,partitionEvenly as du,screenshotPlaceholderIds as pu,trackedArticlePaths as fu,runPartitioned as Eo,estimateBulkCost as si,resolveModelForOperation as Do,readDocsPlan as mu,ensureDir as gu,hintsDir as hu,devHintsGuidePath as ku}from"document360-engine";import{existsSync as Ac,mkdirSync as Ec,readFileSync as Dc,writeFileSync as Ic}from"node:fs";import{join as Ms}from"node:path";import{writerDir as _c}from"document360-engine";function Ls(e){return Ms(_c(e),".sessions")}function Os(e,t){return Ms(Ls(e),`${t}.json`)}function Us(e,t,n){try{Ec(Ls(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Ic(Os(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Po(e,t){try{let n=Os(e,t);if(!Ac(n))return[];let o=JSON.parse(Dc(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Nc=e=>`\x1B]0;${e}\x07`,Mc=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Ws(e){process.stdout.isTTY&&process.stdout.write(e)}function Tt(e){Ws(Nc(e))}function pn(e){Ws(Mc(e))}var fn=["\xB7 "," \xB7"],So="\u{1F7E3}";rn();var Lc=/^(?:\d+[.)]|[-*•])\s+/;function Hs(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
129
- `)){let c=s.trim().replace(Lc,""),d=c.match(/^`([^`]+)`$/);d&&(c=d[1].trim());let m=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!m||!o.has(m[1].toLowerCase()))continue;let h=`/${m[1].toLowerCase()}${m[2]?` ${m[2]}`:""}`;if(r.includes(h)||r.push(h),r.length>=n)break}return r}q();function mn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Fe(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function To(e){return e.replace(/^[\w.-]+\//,"")}var gn=16,Fs={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Ro(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Bs(e,t){let n=Ro(t);return e.some(r=>r.trim()===t.trim()||!!n&&Ro(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&Ro(r)===n)):[]}var Oc=/\[Pasted text #\d+ \+\d+ lines?\]/g;function qs(e){return e.replace(/\r\n?/g,`
128
+ `),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&&(Is(t.uuid),t.titleFired||Rc(t,n));break;case"error":console.error(""),console.error(b(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Sc();break}}import{render as Ru}from"ink";import{resolveAuth as ju}from"document360-engine";import{useCallback as V,useEffect as _e,useMemo as Ro,useRef as J,useState as B}from"react";import{Box as K,Text as C,useApp as Uc,useInput as Wc,useStdout as Hc}from"ink";import{existsSync as Zs,readFileSync as ei,readdirSync as ui,writeFileSync as Fc}from"node:fs";import{basename as Rt,isAbsolute as Bc,join as jt}from"node:path";import{createSession as ti,loginPkce as qc,toStoredTokens as Gc,saveTokens as zc,getAccessToken as Yc,resolveActiveProfile as ue,resolveProjectId as Vc,getArticle as Xc,decodeJwtClaims as at,isExpired as Ie,loadTokens as Be,clearTokens as Kc,clearProfileProject as Jc,setTitle as Qc,slugify as Zc,touchSession as jo,upsertSession as eu,generateTitle as ni,findByName as tu,listSessions as nu,renameSession as ou,suggestNextAction as ru,readProjectConfig as se,writeProjectConfig as su,resolveModelSetting as _o,loadProfileMap as oi,applyPull as iu,computeSyncStatus as Ao,planPull as au,inventoryRepo as lu,knownEnvironments as cu,resolveEnvironment as uu,planPartitions as ri,partitionEvenly as du,screenshotPlaceholderIds as pu,trackedArticlePaths as fu,runPartitioned as Eo,estimateBulkCost as si,resolveModelForOperation as Do,readDocsPlan as mu,ensureDir as gu,hintsDir as hu,devHintsGuidePath as ku}from"document360-engine";import{existsSync as Ac,mkdirSync as Ec,readFileSync as Dc,writeFileSync as Ic}from"node:fs";import{join as Ms}from"node:path";import{writerDir as _c}from"document360-engine";function Ls(e){return Ms(_c(e),".sessions")}function Os(e,t){return Ms(Ls(e),`${t}.json`)}function Us(e,t,n){try{Ec(Ls(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Ic(Os(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Co(e,t){try{let n=Os(e,t);if(!Ac(n))return[];let o=JSON.parse(Dc(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Nc=e=>`\x1B]0;${e}\x07`,Mc=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Ws(e){process.stdout.isTTY&&process.stdout.write(e)}function Tt(e){Ws(Nc(e))}function pn(e){Ws(Mc(e))}var fn=["\xB7 "," \xB7"],Po="\u{1F7E3}";rn();var Lc=/^(?:\d+[.)]|[-*•])\s+/;function Hs(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
129
+ `)){let c=s.trim().replace(Lc,""),d=c.match(/^`([^`]+)`$/);d&&(c=d[1].trim());let m=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!m||!o.has(m[1].toLowerCase()))continue;let h=`/${m[1].toLowerCase()}${m[2]?` ${m[2]}`:""}`;if(r.includes(h)||r.push(h),r.length>=n)break}return r}q();function mn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Fe(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function So(e){return e.replace(/^[\w.-]+\//,"")}var gn=16,Fs={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function To(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Bs(e,t){let n=To(t);return e.some(r=>r.trim()===t.trim()||!!n&&To(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&To(r)===n)):[]}var Oc=/\[Pasted text #\d+ \+\d+ lines?\]/g;function qs(e){return e.replace(/\r\n?/g,`
130
130
  `)}function Gs(e){return e.includes(`
131
131
  `)||e.length>200}function zs(e,t){let n=t.split(`
132
132
  `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Ys(e,t){return e.replace(Oc,n=>t.get(n)??n)}function Vs(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function hn(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
@@ -136,22 +136,22 @@ That's it \u2014 drop the file and keep building. The docs agent picks it up on
136
136
  `)){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 Io,jsx as S,jsxs as H}from"react/jsx-runtime";var wu={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},ii=` 1. /init \u2014 pick your Document360 environment & scaffold config
137
137
  2. /login signs in to that environment
138
138
  3. /project then /workspace \u2014 pick the project and where articles go
139
- Press 1 to start.`;function yu(e,t,n,o){let r=n.kind==="api"?"API key":n.kind==="subscription"?"subscription":"not configured",s=_o(e),c=se(e),d=(c?.docsDir??"user-docs").replace(/\/+$/,""),m=c?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${d}/ + config`,h={version:t,claude:r,model:s.model??"Claude Code default model",modelSource:wu[s.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:c!==null,mode:m};if(c===null)return h;try{let y=ue(e,o);h.profile=y.name,h.apiUrl=y.connection.apiUrl,h.prod=y.production,h.project=y.project.projectId??"(chosen at login)";let D=Be(y.name);if(D){let x={...at(D.idToken)??{},...at(D.accessToken)??{}},v=x.email??x.preferred_username??"signed in";Ie(D)?D.refreshToken&&(h.who=v,h.loggedOut=!1,h.sessionHint="session expired \u2014 refreshing\u2026"):(h.who=v,h.loggedOut=!1,h.sessionHint=`session valid until ${new Date(D.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return h}function xu(e,t){try{let n=ue(e,t),o=Be(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...at(o.idToken)??{},...at(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return Ie(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 ai=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],xn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],$u="Ask me to write or update an article\u2026";function yn({ch:e,dim:t}){let[n,o]=B(!0);return _e(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),S(C,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var bu=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function li(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var vu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ci(e){try{return ui(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Cu(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>ci(jt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&ci(jt(e,o)))}function Pu({startTime:e,chars:t}){let[n,o]=B(0);_e(()=>{let m=setInterval(()=>o(h=>h+1),120);return()=>clearInterval(m)},[]);let r=xn[n%xn.length],s=ai[Math.floor(n/16)%ai.length],c=Math.floor((Date.now()-e)/1e3),d=Math.round(t/4);return H(K,{children:[S(C,{color:G,children:` ${r} ${s}\u2026 `}),S(C,{color:"gray",children:`(${vt(c)} \xB7 ~${d} tokens \xB7 esc to interrupt)`})]})}var Su=12e4;function Tu({p:e}){let[t,n]=B(0);_e(()=>{let N=setInterval(()=>n(F=>F+1),150);return()=>clearInterval(N)},[]);let o=xn[t%xn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),d=Date.now()-e.lastAt>=Su,m=e.verb??"Converting",h=e.unit??"article",y=e.rows.reduce((N,F)=>N+F.items,0),D=m.toLowerCase(),x=e.rows,v=0;if(x.length>gn){let N=x.findIndex(Q=>Q.status==="active"||Q.status==="pending"),F=Math.max(0,Math.min(N-2,x.length-gn));v=x.slice(0,F).filter(Q=>Q.status==="done").length,x=x.slice(F,F+gn)}let $=Math.min(40,Math.max(...x.map(N=>To(N.label).length),0)),I=N=>N==="failed"?"red":N==="active"?G:void 0;return H(K,{flexDirection:"column",children:[H(K,{children:[S(C,{color:G,children:` ${o} ${m} ${y} ${h}${y===1?"":"s"} `}),S(C,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${vt(r)} \xB7 esc to stop`})]}),v>0&&S(C,{dimColor:!0,children:` \u2714 +${v} done`}),x.map(N=>H(C,{color:I(N.status),dimColor:N.status==="done"||N.status==="pending",children:[` ${Fs[N.status]} ${To(N.label).padEnd($)}`,N.status!=="pending"?` (${N.items} ${h}${N.items===1?"":"s"})`:"",N.status==="active"?` \u2190 ${D}\u2026`:""]},N.label)),d&&S(C,{color:"yellow",children:` \u26A0 no activity for ${vt(s)} \u2014 press esc to stop if it's wedged`})]})}function di({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Uc(),[s,c]=B(n),[d,m]=B(null),[h,y]=B({text:"",pos:0}),D=h.text,x=V(l=>{y(a=>{let i=typeof l=="function"?l(a.text):l;return{text:i,pos:i.length}})},[]),v=V(l=>{y(a=>({text:a.text.slice(0,a.pos)+l+a.text.slice(a.pos),pos:a.pos+l.length}))},[]),$=V(()=>{y(l=>{if(l.pos===0)return l;let a=l.text.slice(0,l.pos),i=Vs(a)??a.slice(0,-1);return{text:i+l.text.slice(l.pos),pos:i.length}})},[]),[I,N]=B(!1),[F,Q]=B(!1),[he,ne]=B(0),[ke,oe]=B(null),[lt,X]=B([]),qe=J(0),[gi,At]=B(!1),[hi,ct]=B(0),Ge=J(0),[ut,ze]=B(0),[Ye,Et]=B(null),Lo=J(new Map),ki=J(0),Ve=J([]),de=J(null);de.current===null&&(de.current=ti({cwd:e,profileName:s,allowProdWrites:!1}));let xe=J({uuid:null,firstPrompt:null,titleFired:!1}),Dt=J(new Map),dt=J(!1),$n=J([]),Te=J([]),bn=J(null),[Oo,Xe]=B(null),[Ne,Me]=B(null),[$e,Ke]=B(null),[Re,Je]=B(null),[ie,Qe]=B(null),[pe,Ze]=B(null),[be,et]=B(null),[fe,Le]=B(null),[ae,tt]=B(null),[Uo,vn]=B([]),Oe=J([]),It=J(!1),ve=J(null),[Wo,ee]=B(null),_t=J(!1),Nt=J(null),[me,Ue]=B(null),[Ho,pt]=B(0),[Fo,ft]=B(0),[wi,Bo]=B(0),Cn=wn(()=>{try{return _o(e).model??"auto"}catch{return null}},[e,wi]),{stdout:we}=Hc(),[,yi]=B(0),qo=J(`${we.columns??80}x${we.rows??24}`),je=V(()=>Math.max(20,(we.columns??80)-1),[we]),u=V(l=>{Ve.current.push(l),console.log(Gn(l,je()))},[je]);_e(()=>{let l=`d360-writer \xB7 ${Oo??Rt(e)}`;if(!I){pn(0),Tt(`${So} ${l}`);return}pn(3);let a=0;Tt(`${fn[0]} ${l}`);let i=setInterval(()=>{a=(a+1)%fn.length,Tt(`${fn[a]} ${l}`)},400);return()=>clearInterval(i)},[I,e,Oo]),_e(()=>()=>pn(0),[]),_e(()=>{if(u({kind:"banner",info:yu(e,o,t,s)}),!se(e)){u({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
140
- ${ii}`}),X(["/init"]);return}try{let l=ue(e,s),a=Be(l.name);a&&Ie(a)&&a.refreshToken?Yc({profile:l.name,connection:l.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),ne(i=>i+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),X(["/login"])}):(!a||Ie(a))&&(u({kind:"note",tone:"warn",text:`Profile "${l.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),X(["/login"]))}catch{}try{let l=se(e),a=ue(e,s),i=Be(a.name);l&&i&&!Ie(i)&&Cu(e,l.authoritativeSourceFiles)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),X(["/scope"]))}catch{}},[]),_e(()=>{let l=null,a=null,i=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let k=`${we.columns??80}x${we.rows??24}`;k!==qo.current&&(qo.current=k,yi(p=>p+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+qr(Ve.current,je())+"\x1B[?2026l")},80))},400)};return we.on("resize",i),()=>{l&&clearTimeout(l),a&&clearTimeout(a),we.off("resize",i)}},[we,je]);let We=Math.max(20,(we.columns??80)-1),Go=wn(()=>xu(e,s),[e,s,he]),Pn=wn(()=>{let l=se(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let a=jt(e,(l.docsDir??"user-docs").replace(/\/+$/,"")),i=(()=>{try{return Zs(a)&&ui(a).length>0}catch{return!1}})();try{let k=ue(e,s),p=Be(k.name);if(!(!!p&&!(Ie(p)&&!p.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${k.name}")\u2026`,isSetup:!0};if(!k.project.workspaceId&&!i)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return i?{text:$u,isSetup:!1}:{text:"Let's get started \u2014 try: write the docs for this repo",isSetup:!1}},[e,s,he]),mt=mr(D),zo=mt.length>0&&!I,Sn=d!==null?Js(d,8,We):null,Mt=fe?fe.paths.filter(l=>!fe.query||l.toLowerCase().includes(fe.query.toLowerCase())).slice(0,8):[],Lt=me?me.sessions.filter(l=>{let a=me.query.toLowerCase();return!a||l.name.toLowerCase().includes(a)||l.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],le=V((l,a)=>{de.current?.close(),de.current=ti({cwd:e,resume:l,profileName:a??s,allowProdWrites:dt.current}),l||(xe.current={uuid:null,firstPrompt:null,titleFired:!1},Xe(null)),pt(0),ft(0)},[e,s]),Yo=V((l,a,i)=>{if(bu.test(l))try{let k=ue(e,s),p=typeof a.project_id=="string"&&a.project_id||k.project.projectId,g=un(a,i),w=[],R=dn(i);l.endsWith("publish_article")&&R&&w.push(`Live: ${R}`),g&&p&&w.push(`Preview: ${cn(k.connection.portalUrl,p,g,k.project.languageCode??"en")}`),w.length>0&&u({kind:"link",lines:w})}catch{}},[e,s,u]),Ce=V(async(l,a)=>{At(!0),oe(null),X([]);let i=++qe.current;u({kind:"user",text:a?.echoDisplay&&a.display?a.display:l});let k=xe.current;k.firstPrompt||(k.firstPrompt=a?.display??l),Ge.current=Date.now(),ct(0),N(!0),Dt.current.clear();let p="",g="",w=null,R=()=>{w||(w=setTimeout(()=>{w=null,m(g.length>0?g:null)},60))},E=()=>{w&&clearTimeout(w),w=null,m(null)},L=()=>{if(g.trim()){let A=g.trimEnd();u({kind:"assistant",text:A})}g="",E()};try{for await(let A of de.current.send(l))if(A.type==="session"){if(!k.uuid){k.uuid=A.sessionId;let M=new Date().toISOString(),P=Zc(k.firstPrompt??"session");eu({uuid:A.sessionId,name:P,renamed:!1,titled:!1,cwd:e,firstPrompt:k.firstPrompt??"",createdAt:M,updatedAt:M}),Xe(P)}}else if(A.type==="text"){g+=A.delta,p+=A.delta;let M=Qs(g);if(M>0){let P=g.slice(0,M).trimEnd();P&&u({kind:"assistant",text:P}),g=g.slice(M)}R(),ct(P=>P+A.delta.length)}else if(A.type==="tool"){let M=an(A.name,A.input);M&&(L(),u({kind:"tool",title:M.title,sep:M.sep,arg:M.arg}),Dt.current.set(A.id,{name:A.name,input:A.input}))}else if(A.type==="article_diff"){let M=He(A.oldContent,A.newContent,je());M&&(L(),u({kind:"diff",added:M.added,removed:M.removed,lines:M.lines,hidden:M.hidden}))}else if(A.type==="tool_result"){A.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(A.output)&&(_t.current=!0);let M=Dt.current.get(A.id);if(M){Dt.current.delete(A.id),L();let P=ln(A.output,4,A.isError?void 0:M.name,M.input);u({kind:"tool-result",lines:P.lines,hidden:P.hidden,isError:A.isError}),A.isError||Yo(M.name,M.input,A.output)}}else if(A.type==="result"){L(),pt(P=>P+A.outputTokens),ft(P=>P+A.costUsd),u({kind:"done",seconds:Math.round((Date.now()-Ge.current)/1e3),tokens:A.outputTokens,costUsd:A.costUsd,ok:A.ok});let M=A.ok?Hs(p,yt.map(P=>P.name)):[];if(M.length>0?X(M):A.ok&&p.trim()&&ru(l,p,e).then(P=>{P&&qe.current===i&&oe(P)}).catch(()=>{}),k.uuid&&(jo(k.uuid),!k.titleFired)){k.titleFired=!0;let P=k.uuid,T=k.firstPrompt;T&&ni(T,e).then(W=>{W&&(Qc(P,W),Xe(W))}).catch(()=>{})}}else A.type==="error"&&(L(),A.kind==="auth"&&(_t.current=!0),u({kind:"note",text:`agent error: ${A.message}`,tone:"error"}))}finally{N(!1),E(),ne(A=>A+1),xe.current.uuid&&Us(e,xe.current.uuid,Ve.current),_t.current&&(_t.current=!1,Nt.current=a?.display??l,X(["/login"])),It.current&&(It.current=!1,Oe.current.length>0&&(u({kind:"note",tone:"info",text:`(${Oe.current.length} queued message(s) discarded)`}),Oe.current=[],vn([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,Yo,je]),Tn=V(l=>{let a=Be(l);if(!a||Ie(a)&&!a.refreshToken)return null;let i={...at(a.idToken)??{},...at(a.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),Rn=V((l,a)=>{if(a){let i=se(e);i&&(i.defaultProfile=l,su(i,e))}c(l),le(void 0,l),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Tn(l)||(u({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),X(["/login"])),ne(i=>i+1)},[e,u,le,Tn]),Ot=V((l,a,i)=>{Ft(e,l,a,i.id,i.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),le(),oi(e,l)||(u({kind:"note",tone:"info",text:"Setup complete. Press tab to start with a docs analysis."}),oe("analyze this repo and propose a docs structure"))},[e,u,le]),jn=V(async l=>{let a;try{a=await kt(e,l)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),X(["/workspace"]);return}if(a.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=a.workspaces.filter(p=>(p.workspace_type??"").toLowerCase()!=="apidocumentation"),k=i.length>0?i:a.workspaces;if(k.length===1){let p=k[0],g=a.workspaces.length-k.length;u({kind:"note",tone:"ok",text:`Selected the "${p.name??p.id}" workspace${g>0?" (skipped the API-documentation workspace)":""}.`}),Ot(a.profile,a.projectId,p);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${k.length} available).`}),X(["/workspace"])},[e,u,Ot]),Vo=V((l,a)=>{po(e,l,a.id),u({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),le(),jn(l)},[e,u,le,jn]),Ut=V(()=>{let l=Te.current[0];if(!l)return;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let i of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${i}`});l.overwritesLocalChanges&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let a=He(l.oldContent,l.newContent,je());u(a?{kind:"diff",added:a.added,removed:a.removed,lines:a.lines,hidden:a.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,je]),Xo=V(l=>{if(Te.current.length===0)return!1;let a=l.trim().toLowerCase();if(a==="y"||a==="yes"){let i=Te.current.shift();try{iu({cwd:e,profileName:s},i),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${i.path} (sync base advanced).`}),Te.current.length===0&&X(k=>k.length>0?k:["/sync"])}catch(k){u({kind:"note",tone:"error",text:`Pull failed: ${k.message}`})}}else if(a==="n"||a==="no"){let i=Te.current.shift();u({kind:"note",tone:"info",text:`Skipped ${i.path}.`})}else{let i=Te.current.length;return Te.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${i} article(s) left untouched).`}),!0}return Ut(),!0},[e,s,Ut,u]),Ko=V(l=>{let a=bn.current;if(!a)return!1;if(bn.current=null,oe(null),qe.current++,l.trim()!==a.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:k}=xo(e,a.targets);u({kind:"note",tone:k.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`});for(let p of k)u({kind:"note",tone:"error",text:` \u2717 ${p.path}: ${p.error}`});return u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
139
+ Press 1 to start.`;function yu(e,t,n,o){let r=n.kind==="api"?"API key":n.kind==="subscription"?"subscription":"not configured",s=_o(e),c=se(e),d=(c?.docsDir??"user-docs").replace(/\/+$/,""),m=c?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${d}/ + config`,h={version:t,claude:r,model:s.model??"Claude Code default model",modelSource:wu[s.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:c!==null,mode:m};if(c===null)return h;try{let y=ue(e,o);h.profile=y.name,h.apiUrl=y.connection.apiUrl,h.prod=y.production,h.project=y.project.projectId??"(chosen at login)";let D=Be(y.name);if(D){let x={...at(D.idToken)??{},...at(D.accessToken)??{}},v=x.email??x.preferred_username??"signed in";Ie(D)?D.refreshToken&&(h.who=v,h.loggedOut=!1,h.sessionHint="session expired \u2014 refreshing\u2026"):(h.who=v,h.loggedOut=!1,h.sessionHint=`session valid until ${new Date(D.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return h}function xu(e,t){try{let n=ue(e,t),o=Be(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...at(o.idToken)??{},...at(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return Ie(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 ai=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],yn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],$u="Ask me to write or update an article\u2026";function wn({ch:e,dim:t}){let[n,o]=B(!0);return _e(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),S(C,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var bu=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function li(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var vu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ci(e){try{return ui(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Cu(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>ci(jt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&ci(jt(e,o)))}function Pu({startTime:e,chars:t}){let[n,o]=B(0);_e(()=>{let m=setInterval(()=>o(h=>h+1),120);return()=>clearInterval(m)},[]);let r=yn[n%yn.length],s=ai[Math.floor(n/16)%ai.length],c=Math.floor((Date.now()-e)/1e3),d=Math.round(t/4);return H(K,{children:[S(C,{color:G,children:` ${r} ${s}\u2026 `}),S(C,{color:"gray",children:`(${vt(c)} \xB7 ~${d} tokens \xB7 esc to interrupt)`})]})}var Su=12e4;function Tu({p:e}){let[t,n]=B(0);_e(()=>{let N=setInterval(()=>n(F=>F+1),150);return()=>clearInterval(N)},[]);let o=yn[t%yn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),d=Date.now()-e.lastAt>=Su,m=e.verb??"Converting",h=e.unit??"article",y=e.rows.reduce((N,F)=>N+F.items,0),D=m.toLowerCase(),x=e.rows,v=0;if(x.length>gn){let N=x.findIndex(Q=>Q.status==="active"||Q.status==="pending"),F=Math.max(0,Math.min(N-2,x.length-gn));v=x.slice(0,F).filter(Q=>Q.status==="done").length,x=x.slice(F,F+gn)}let $=Math.min(40,Math.max(...x.map(N=>So(N.label).length),0)),I=N=>N==="failed"?"red":N==="active"?G:void 0;return H(K,{flexDirection:"column",children:[H(K,{children:[S(C,{color:G,children:` ${o} ${m} ${y} ${h}${y===1?"":"s"} `}),S(C,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${vt(r)} \xB7 esc to stop`})]}),v>0&&S(C,{dimColor:!0,children:` \u2714 +${v} done`}),x.map(N=>H(C,{color:I(N.status),dimColor:N.status==="done"||N.status==="pending",children:[` ${Fs[N.status]} ${So(N.label).padEnd($)}`,N.status!=="pending"?` (${N.items} ${h}${N.items===1?"":"s"})`:"",N.status==="active"?` \u2190 ${D}\u2026`:""]},N.label)),d&&S(C,{color:"yellow",children:` \u26A0 no activity for ${vt(s)} \u2014 press esc to stop if it's wedged`})]})}function di({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Uc(),[s,c]=B(n),[d,m]=B(null),[h,y]=B({text:"",pos:0}),D=h.text,x=V(l=>{y(a=>{let i=typeof l=="function"?l(a.text):l;return{text:i,pos:i.length}})},[]),v=V(l=>{y(a=>({text:a.text.slice(0,a.pos)+l+a.text.slice(a.pos),pos:a.pos+l.length}))},[]),$=V(()=>{y(l=>{if(l.pos===0)return l;let a=l.text.slice(0,l.pos),i=Vs(a)??a.slice(0,-1);return{text:i+l.text.slice(l.pos),pos:i.length}})},[]),[I,N]=B(!1),[F,Q]=B(!1),[ye,ne]=B(0),[he,oe]=B(null),[lt,X]=B([]),qe=J(0),[gi,At]=B(!1),[hi,ct]=B(0),Ge=J(0),[ut,ze]=B(0),[Ye,Et]=B(null),Lo=J(new Map),ki=J(0),Ve=J([]),de=J(null);de.current===null&&(de.current=ti({cwd:e,profileName:s,allowProdWrites:!1}));let xe=J({uuid:null,firstPrompt:null,titleFired:!1}),Dt=J(new Map),dt=J(!1),xn=J([]),Te=J([]),$n=J(null),[Oo,Xe]=B(null),[Ne,Me]=B(null),[$e,Ke]=B(null),[Re,Je]=B(null),[ie,Qe]=B(null),[pe,Ze]=B(null),[be,et]=B(null),[fe,Le]=B(null),[ae,tt]=B(null),[Uo,bn]=B([]),Oe=J([]),It=J(!1),ve=J(null),[Wo,ee]=B(null),_t=J(!1),Nt=J(null),[me,Ue]=B(null),[Ho,pt]=B(0),[Fo,ft]=B(0),[wi,Bo]=B(0),vn=Ro(()=>{try{return _o(e).model??"auto"}catch{return null}},[e,wi]),{stdout:ke}=Hc(),[,yi]=B(0),qo=J(`${ke.columns??80}x${ke.rows??24}`),je=V(()=>Math.max(20,(ke.columns??80)-1),[ke]),u=V(l=>{Ve.current.push(l),console.log(qn(l,je()))},[je]);_e(()=>{let l=`d360-writer \xB7 ${Oo??Rt(e)}`;if(!I){pn(0),Tt(`${Po} ${l}`);return}pn(3);let a=0;Tt(`${fn[0]} ${l}`);let i=setInterval(()=>{a=(a+1)%fn.length,Tt(`${fn[a]} ${l}`)},400);return()=>clearInterval(i)},[I,e,Oo]),_e(()=>()=>pn(0),[]),_e(()=>{if(u({kind:"banner",info:yu(e,o,t,s)}),!se(e)){u({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
140
+ ${ii}`}),X(["/init"]);return}try{let l=ue(e,s),a=Be(l.name);a&&Ie(a)&&a.refreshToken?Yc({profile:l.name,connection:l.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),ne(i=>i+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),X(["/login"])}):(!a||Ie(a))&&(u({kind:"note",tone:"warn",text:`Profile "${l.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),X(["/login"]))}catch{}try{let l=se(e),a=ue(e,s),i=Be(a.name);l&&i&&!Ie(i)&&Cu(e,l.authoritativeSourceFiles)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),X(["/scope"]))}catch{}},[]),_e(()=>{let l=null,a=null,i=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let k=`${ke.columns??80}x${ke.rows??24}`;k!==qo.current&&(qo.current=k,yi(p=>p+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+qr(Ve.current,je())+"\x1B[?2026l")},80))},400)};return ke.on("resize",i),()=>{l&&clearTimeout(l),a&&clearTimeout(a),ke.off("resize",i)}},[ke,je]);let We=Math.max(20,(ke.columns??80)-1),Go=Ro(()=>xu(e,s),[e,s,ye]),Cn=(()=>{let l=se(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let a=jt(e,(l.docsDir??"user-docs").replace(/\/+$/,"")),i=(()=>{try{return Zs(a)&&ui(a).length>0}catch{return!1}})();try{let k=ue(e,s),p=Be(k.name);if(!(!!p&&!(Ie(p)&&!p.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${k.name}")\u2026`,isSetup:!0};if(!k.project.workspaceId&&!i)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return i?{text:$u,isSetup:!1}:{text:"Let's get started \u2014 try: write the docs for this repo",isSetup:!1}})(),mt=mr(D),zo=mt.length>0&&!I,Pn=d!==null?Js(d,8,We):null,Mt=fe?fe.paths.filter(l=>!fe.query||l.toLowerCase().includes(fe.query.toLowerCase())).slice(0,8):[],Lt=me?me.sessions.filter(l=>{let a=me.query.toLowerCase();return!a||l.name.toLowerCase().includes(a)||l.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],le=V((l,a)=>{de.current?.close(),de.current=ti({cwd:e,resume:l,profileName:a??s,allowProdWrites:dt.current}),l||(xe.current={uuid:null,firstPrompt:null,titleFired:!1},Xe(null)),pt(0),ft(0)},[e,s]),Yo=V((l,a,i)=>{if(bu.test(l))try{let k=ue(e,s),p=typeof a.project_id=="string"&&a.project_id||k.project.projectId,g=un(a,i),w=[],R=dn(i);l.endsWith("publish_article")&&R&&w.push(`Live: ${R}`),g&&p&&w.push(`Preview: ${cn(k.connection.portalUrl,p,g,k.project.languageCode??"en")}`),w.length>0&&u({kind:"link",lines:w})}catch{}},[e,s,u]),Ce=V(async(l,a)=>{At(!0),oe(null),X([]);let i=++qe.current;u({kind:"user",text:a?.echoDisplay&&a.display?a.display:l});let k=xe.current;k.firstPrompt||(k.firstPrompt=a?.display??l),Ge.current=Date.now(),ct(0),N(!0),Dt.current.clear();let p="",g="",w=null,R=()=>{w||(w=setTimeout(()=>{w=null,m(g.length>0?g:null)},60))},E=()=>{w&&clearTimeout(w),w=null,m(null)},L=()=>{if(g.trim()){let A=g.trimEnd();u({kind:"assistant",text:A})}g="",E()};try{for await(let A of de.current.send(l))if(A.type==="session"){if(!k.uuid){k.uuid=A.sessionId;let M=new Date().toISOString(),P=Zc(k.firstPrompt??"session");eu({uuid:A.sessionId,name:P,renamed:!1,titled:!1,cwd:e,firstPrompt:k.firstPrompt??"",createdAt:M,updatedAt:M}),Xe(P)}}else if(A.type==="text"){g+=A.delta,p+=A.delta;let M=Qs(g);if(M>0){let P=g.slice(0,M).trimEnd();P&&u({kind:"assistant",text:P}),g=g.slice(M)}R(),ct(P=>P+A.delta.length)}else if(A.type==="tool"){let M=an(A.name,A.input);M&&(L(),u({kind:"tool",title:M.title,sep:M.sep,arg:M.arg}),Dt.current.set(A.id,{name:A.name,input:A.input}))}else if(A.type==="article_diff"){let M=He(A.oldContent,A.newContent,je());M&&(L(),u({kind:"diff",added:M.added,removed:M.removed,lines:M.lines,hidden:M.hidden}))}else if(A.type==="tool_result"){A.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(A.output)&&(_t.current=!0);let M=Dt.current.get(A.id);if(M){Dt.current.delete(A.id),L();let P=ln(A.output,4,A.isError?void 0:M.name,M.input);u({kind:"tool-result",lines:P.lines,hidden:P.hidden,isError:A.isError}),A.isError||Yo(M.name,M.input,A.output)}}else if(A.type==="result"){L(),pt(P=>P+A.outputTokens),ft(P=>P+A.costUsd),u({kind:"done",seconds:Math.round((Date.now()-Ge.current)/1e3),tokens:A.outputTokens,costUsd:A.costUsd,ok:A.ok});let M=A.ok?Hs(p,yt.map(P=>P.name)):[];if(M.length>0?X(M):A.ok&&p.trim()&&ru(l,p,e).then(P=>{P&&qe.current===i&&oe(P)}).catch(()=>{}),k.uuid&&(jo(k.uuid),!k.titleFired)){k.titleFired=!0;let P=k.uuid,T=k.firstPrompt;T&&ni(T,e).then(W=>{W&&(Qc(P,W),Xe(W))}).catch(()=>{})}}else A.type==="error"&&(L(),A.kind==="auth"&&(_t.current=!0),u({kind:"note",text:`agent error: ${A.message}`,tone:"error"}))}finally{N(!1),E(),ne(A=>A+1),xe.current.uuid&&Us(e,xe.current.uuid,Ve.current),_t.current&&(_t.current=!1,Nt.current=a?.display??l,X(["/login"])),It.current&&(It.current=!1,Oe.current.length>0&&(u({kind:"note",tone:"info",text:`(${Oe.current.length} queued message(s) discarded)`}),Oe.current=[],bn([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,Yo,je]),Sn=V(l=>{let a=Be(l);if(!a||Ie(a)&&!a.refreshToken)return null;let i={...at(a.idToken)??{},...at(a.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),Tn=V((l,a)=>{if(a){let i=se(e);i&&(i.defaultProfile=l,su(i,e))}c(l),le(void 0,l),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Sn(l)||(u({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),X(["/login"])),ne(i=>i+1)},[e,u,le,Sn]),Ot=V((l,a,i)=>{Ft(e,l,a,i.id,i.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),le(),oi(e,l)||(u({kind:"note",tone:"info",text:"Setup complete. Press tab to start with a docs analysis."}),oe("analyze this repo and propose a docs structure"))},[e,u,le]),Rn=V(async l=>{let a;try{a=await kt(e,l)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),X(["/workspace"]);return}if(a.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=a.workspaces.filter(p=>(p.workspace_type??"").toLowerCase()!=="apidocumentation"),k=i.length>0?i:a.workspaces;if(k.length===1){let p=k[0],g=a.workspaces.length-k.length;u({kind:"note",tone:"ok",text:`Selected the "${p.name??p.id}" workspace${g>0?" (skipped the API-documentation workspace)":""}.`}),Ot(a.profile,a.projectId,p);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${k.length} available).`}),X(["/workspace"])},[e,u,Ot]),Vo=V((l,a)=>{uo(e,l,a.id),u({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),le(),Rn(l)},[e,u,le,Rn]),Ut=V(()=>{let l=Te.current[0];if(!l)return;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let i of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${i}`});l.overwritesLocalChanges&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let a=He(l.oldContent,l.newContent,je());u(a?{kind:"diff",added:a.added,removed:a.removed,lines:a.lines,hidden:a.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,je]),Xo=V(l=>{if(Te.current.length===0)return!1;let a=l.trim().toLowerCase();if(a==="y"||a==="yes"){let i=Te.current.shift();try{iu({cwd:e,profileName:s},i),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${i.path} (sync base advanced).`}),Te.current.length===0&&X(k=>k.length>0?k:["/sync"])}catch(k){u({kind:"note",tone:"error",text:`Pull failed: ${k.message}`})}}else if(a==="n"||a==="no"){let i=Te.current.shift();u({kind:"note",tone:"info",text:`Skipped ${i.path}.`})}else{let i=Te.current.length;return Te.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${i} article(s) left untouched).`}),!0}return Ut(),!0},[e,s,Ut,u]),Ko=V(l=>{let a=$n.current;if(!a)return!1;if($n.current=null,oe(null),qe.current++,l.trim()!==a.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:k}=yo(e,a.targets);u({kind:"note",tone:k.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`});for(let p of k)u({kind:"note",tone:"error",text:` \u2717 ${p.path}: ${p.error}`});return u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
141
141
  ${ii}`}),X(["/init"]),At(!1),!0},[e,u]),Jo=V(async l=>{let a=l.slice(1).trim().split(/\s+/),i=(a[0]??"").toLowerCase(),k=a.slice(1);switch(At(!0),i){case"help":u({kind:"note",tone:"info",text:Xt().join(`
142
- `)});return;case"exit":case"quit":de.current?.close(),r();return;case"clear":le(),Ve.current=[],At(!1),oe(null),qe.current++,u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let p;try{p=ue(e,s)}catch(g){u({kind:"note",tone:"error",text:g.message});return}u({kind:"note",tone:"info",text:`Profile "${p.name}" \u2192 ${p.connection.name} (${p.connection.apiUrl})${p.production?" \u26A0 PRODUCTION":""}`}),Q(!0);try{let g=await qc(p.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},E=>u({kind:"note",tone:"info",text:E})),w=Gc(p.name,g);zc(w),In(w,p.name,E=>u({kind:"note",tone:"info",text:E})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${p.name}" as ${qt(w)}`});let R=(()=>{try{return ue(e,s)}catch{return p}})();R.project.workspaceId||(R.project.projectId?await jn(R.name):(u({kind:"note",tone:"info",text:"Next: pick the Document360 project."}),X(["/project"]))),Nt.current&&(oe(Nt.current),Nt.current=null,u({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(g){u({kind:"note",tone:"error",text:`Login failed: ${g.message}`})}finally{Q(!1),ne(g=>g+1)}return}case"allow-prod":{let p=!1;try{p=ue(e,s).production}catch{}if(!p){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}dt.current=!0,le(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let p=io(k.join(" ")),g=xe.current.uuid;if(!g){u({kind:"note",tone:"error",text:"Send a message first \u2014 sessions save once the agent replies."});return}if(!p){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=xe.current.firstPrompt??"";ni(w,e).then(R=>{R?(oe(`/rename ${R}`),u({kind:"note",tone:"info",text:`Suggestion: "${R}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}ou(g,p),Xe(p),Tt(`${So} d360-writer \xB7 ${p}`),u({kind:"note",tone:"ok",text:`Session renamed to "${p}".`});return}case"profile":{let p=k[0],g=se(e);if(!p){let w=Object.entries(g?.profiles??{});if(w.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let R=w.map(([A,M])=>({name:A,env:M.connection?.environment??"custom",prod:M.production===!0,who:Tn(A)})),E=s??g?.defaultProfile,L=Math.max(0,R.findIndex(A=>A.name===E));Ke({cursor:L,current:L,rows:R});return}if(p==="add"){let w=ao(e,k[1],k[2]);if(w){u({kind:"note",tone:"error",text:w});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${k[1]}" created (environment: ${k[2]??k[1]}).`}),Rn(k[1],!1);return}if(!g?.profiles?.[p]){u({kind:"note",tone:"error",text:`Unknown profile "${p}". Create it: /profile add ${p} <environment>`});return}Rn(p,!0);return}case"doctor":await Pt(k,{cwd:e});return;case"mcp":await Jt(k);return;case"init":{if(se(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer.json directly (or d360-writer init for the CLI wizard)."});return}let p=cu().map(g=>({name:g,apiUrl:uu(g).apiUrl}));Je({cursor:0,rows:p});return}case"resume":{let p=k.join(" ").trim(),g=nu(e).filter(E=>E.uuid!==xe.current.uuid);if(!p){if(!g.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Ue({query:"",cursor:0,sessions:g});return}let w=tu(e,p);if(!w){u({kind:"note",tone:"error",text:`No session matches "${p}".`});return}le(w.uuid),xe.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},Xe(w.name),jo(w.uuid),Ve.current=[];let R=Po(e,w.uuid);for(let E of R)u(E);u({kind:"note",tone:"ok",text:R.length?`Resumed "${w.name}" \u2014 restored ${R.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let p=k.join(" ").trim(),g;try{g=await kt(e,s)}catch(R){u({kind:"note",tone:"error",text:`Could not list workspaces: ${R.message}`});return}if(!p){let R=g.workspaces.map(L=>({id:L.id,name:L.name??L.id,type:L.workspace_type}));if(R.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let E=Math.max(0,R.findIndex(L=>L.id===g.current));Qe({cursor:E,current:E,rows:R,profile:g.profile,projectId:g.projectId,environment:g.environment});return}let w=Dn(g.workspaces,p);if(!w){u({kind:"note",tone:"error",text:`No workspace matches "${p}".`});return}Ot(g.profile,g.projectId,w);return}case"project":{let p=k.join(" ").trim(),g;try{g=await uo(e,s)}catch(R){u({kind:"note",tone:"error",text:`Could not list projects: ${R.message} (signed in? try /login)`});return}if(!p){let R=g.projects.map(L=>({id:L.id,name:L.name??L.id,sub:L.sub_domain}));if(R.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let E=R.findIndex(L=>L.id===g.current);Ze({cursor:Math.max(0,E),current:E,rows:R,profile:g.profile,environment:g.environment});return}let w=ds(g.projects,p);if(!w){u({kind:"note",tone:"error",text:`No project matches "${p}". Available: ${g.projects.map(R=>R.name??R.id).join(", ")}`});return}Vo(g.profile,w);return}case"logout":{let p;try{p=ue(e,s).name}catch(w){u({kind:"note",tone:"error",text:w.message});return}let g=Kc(p);Jc(e,p),le(),ne(w=>w+1),u({kind:"note",tone:g?"ok":"info",text:g?`\u2713 Signed out of "${p}" and cleared its project/workspace selection.`:`Profile "${p}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),X(["/login"]);return}case"publish":{if(k[0]&&k[0]!=="--all"){await Ce(Zt(k[0]),{display:`/publish ${k[0]}`,echoDisplay:!0});return}let p=k[0]==="--all";u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let g=await Ao({cwd:e,profileName:s}),w=Qt(g.entries);if(w.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let E=g.counts["unknown-base"]??0;E>0&&u({kind:"note",tone:"info",text:`(${E} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(p){await Ce($t(w.map(E=>E.path)),{display:"/publish --all",echoDisplay:!0});return}let R=w.length>1?[{path:"--all",label:`publish all ${w.length} candidates in one run`},...w]:w;et({cursor:0,rows:R})}catch(g){u({kind:"note",tone:"error",text:`Could not compute sync status: ${g.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let p=k.join(" ").trim();if(!p){let w=[];try{w=Object.keys(oi(e,ue(e,s).name)?.articles??{})}catch{}if(w.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Le({query:"",cursor:0,paths:w});return}let g=Bc(p)?p:jt(e,p);if(Zs(g)){try{u({kind:"preview",name:Rt(g),text:li(ei(g,"utf8"))})}catch(w){u({kind:"note",tone:"error",text:`Could not read ${g}: ${w.message}`})}return}if(vu.test(p)){try{let w=ue(e,s),R={profile:w.name,connection:w.connection},E=w.project.projectId??Vc(R),L=await Xc(R,E,p);u({kind:"preview",name:L.title??p,text:L.content??"*(article has no content)*"})}catch(w){u({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}u({kind:"note",tone:"error",text:`"${p}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let p=k[0]?.trim();if(!p){let E=on(_o(e));Me({cursor:E,current:E});return}let{lines:g,changed:w,effective:R}=Ct(e,p);for(let E of g)u({kind:"note",tone:E.startsWith("\u26A0")?"warn":E.startsWith("\u2713")?"ok":"info",text:E});w&&(Bo(E=>E+1),de.current?.setModel(R));return}case"convert":{if(!se(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:p,run:g}=Yn(k),w=fu(e,s);if(w.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let R=Vn(w,p);if(R.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${p}". (${w.length} are tracked overall.)`});return}let E=ri(R),L=3,A=`/convert${p?` --scope ${p}`:""} --run`,M=Do(e,"light");if(!g){let T=si({files:Xn(e,R),op:"convert",model:M.model}),W=p?`Scope: ${p} (${R.length} of ${w.length} tracked)
142
+ `)});return;case"exit":case"quit":de.current?.close(),r();return;case"clear":le(),Ve.current=[],At(!1),oe(null),qe.current++,u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let p;try{p=ue(e,s)}catch(g){u({kind:"note",tone:"error",text:g.message});return}u({kind:"note",tone:"info",text:`Profile "${p.name}" \u2192 ${p.connection.name} (${p.connection.apiUrl})${p.production?" \u26A0 PRODUCTION":""}`}),Q(!0);try{let g=await qc(p.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},E=>u({kind:"note",tone:"info",text:E})),w=Gc(p.name,g);zc(w),Dn(w,p.name,E=>u({kind:"note",tone:"info",text:E})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${p.name}" as ${qt(w)}`});let R=(()=>{try{return ue(e,s)}catch{return p}})();R.project.workspaceId||(R.project.projectId?await Rn(R.name):(u({kind:"note",tone:"info",text:"Next: pick the Document360 project."}),X(["/project"]))),Nt.current&&(oe(Nt.current),Nt.current=null,u({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(g){u({kind:"note",tone:"error",text:`Login failed: ${g.message}`})}finally{Q(!1),ne(g=>g+1)}return}case"allow-prod":{let p=!1;try{p=ue(e,s).production}catch{}if(!p){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}dt.current=!0,le(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let p=so(k.join(" ")),g=xe.current.uuid;if(!g){u({kind:"note",tone:"error",text:"Send a message first \u2014 sessions save once the agent replies."});return}if(!p){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=xe.current.firstPrompt??"";ni(w,e).then(R=>{R?(oe(`/rename ${R}`),u({kind:"note",tone:"info",text:`Suggestion: "${R}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}ou(g,p),Xe(p),Tt(`${Po} d360-writer \xB7 ${p}`),u({kind:"note",tone:"ok",text:`Session renamed to "${p}".`});return}case"profile":{let p=k[0],g=se(e);if(!p){let w=Object.entries(g?.profiles??{});if(w.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let R=w.map(([A,M])=>({name:A,env:M.connection?.environment??"custom",prod:M.production===!0,who:Sn(A)})),E=s??g?.defaultProfile,L=Math.max(0,R.findIndex(A=>A.name===E));Ke({cursor:L,current:L,rows:R});return}if(p==="add"){let w=io(e,k[1],k[2]);if(w){u({kind:"note",tone:"error",text:w});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${k[1]}" created (environment: ${k[2]??k[1]}).`}),Tn(k[1],!1);return}if(!g?.profiles?.[p]){u({kind:"note",tone:"error",text:`Unknown profile "${p}". Create it: /profile add ${p} <environment>`});return}Tn(p,!0);return}case"doctor":await Pt(k,{cwd:e});return;case"mcp":await Jt(k);return;case"init":{if(se(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer.json directly (or d360-writer init for the CLI wizard)."});return}let p=cu().map(g=>({name:g,apiUrl:uu(g).apiUrl}));Je({cursor:0,rows:p});return}case"resume":{let p=k.join(" ").trim(),g=nu(e).filter(E=>E.uuid!==xe.current.uuid);if(!p){if(!g.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Ue({query:"",cursor:0,sessions:g});return}let w=tu(e,p);if(!w){u({kind:"note",tone:"error",text:`No session matches "${p}".`});return}le(w.uuid),xe.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},Xe(w.name),jo(w.uuid),Ve.current=[];let R=Co(e,w.uuid);for(let E of R)u(E);u({kind:"note",tone:"ok",text:R.length?`Resumed "${w.name}" \u2014 restored ${R.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let p=k.join(" ").trim(),g;try{g=await kt(e,s)}catch(R){u({kind:"note",tone:"error",text:`Could not list workspaces: ${R.message}`});return}if(!p){let R=g.workspaces.map(L=>({id:L.id,name:L.name??L.id,type:L.workspace_type}));if(R.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let E=Math.max(0,R.findIndex(L=>L.id===g.current));Qe({cursor:E,current:E,rows:R,profile:g.profile,projectId:g.projectId,environment:g.environment});return}let w=En(g.workspaces,p);if(!w){u({kind:"note",tone:"error",text:`No workspace matches "${p}".`});return}Ot(g.profile,g.projectId,w);return}case"project":{let p=k.join(" ").trim(),g;try{g=await co(e,s)}catch(R){u({kind:"note",tone:"error",text:`Could not list projects: ${R.message} (signed in? try /login)`});return}if(!p){let R=g.projects.map(L=>({id:L.id,name:L.name??L.id,sub:L.sub_domain}));if(R.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let E=R.findIndex(L=>L.id===g.current);Ze({cursor:Math.max(0,E),current:E,rows:R,profile:g.profile,environment:g.environment});return}let w=ds(g.projects,p);if(!w){u({kind:"note",tone:"error",text:`No project matches "${p}". Available: ${g.projects.map(R=>R.name??R.id).join(", ")}`});return}Vo(g.profile,w);return}case"logout":{let p;try{p=ue(e,s).name}catch(w){u({kind:"note",tone:"error",text:w.message});return}let g=Kc(p);Jc(e,p),le(),ne(w=>w+1),u({kind:"note",tone:g?"ok":"info",text:g?`\u2713 Signed out of "${p}" and cleared its project/workspace selection.`:`Profile "${p}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),X(["/login"]);return}case"publish":{if(k[0]&&k[0]!=="--all"){await Ce(Zt(k[0]),{display:`/publish ${k[0]}`,echoDisplay:!0});return}let p=k[0]==="--all";u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let g=await Ao({cwd:e,profileName:s}),w=Qt(g.entries);if(w.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let E=g.counts["unknown-base"]??0;E>0&&u({kind:"note",tone:"info",text:`(${E} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(p){await Ce($t(w.map(E=>E.path)),{display:"/publish --all",echoDisplay:!0});return}let R=w.length>1?[{path:"--all",label:`publish all ${w.length} candidates in one run`},...w]:w;et({cursor:0,rows:R})}catch(g){u({kind:"note",tone:"error",text:`Could not compute sync status: ${g.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let p=k.join(" ").trim();if(!p){let w=[];try{w=Object.keys(oi(e,ue(e,s).name)?.articles??{})}catch{}if(w.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Le({query:"",cursor:0,paths:w});return}let g=Bc(p)?p:jt(e,p);if(Zs(g)){try{u({kind:"preview",name:Rt(g),text:li(ei(g,"utf8"))})}catch(w){u({kind:"note",tone:"error",text:`Could not read ${g}: ${w.message}`})}return}if(vu.test(p)){try{let w=ue(e,s),R={profile:w.name,connection:w.connection},E=w.project.projectId??Vc(R),L=await Xc(R,E,p);u({kind:"preview",name:L.title??p,text:L.content??"*(article has no content)*"})}catch(w){u({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}u({kind:"note",tone:"error",text:`"${p}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let p=k[0]?.trim();if(!p){let E=on(_o(e));Me({cursor:E,current:E});return}let{lines:g,changed:w,effective:R}=Ct(e,p);for(let E of g)u({kind:"note",tone:E.startsWith("\u26A0")?"warn":E.startsWith("\u2713")?"ok":"info",text:E});w&&(Bo(E=>E+1),de.current?.setModel(R));return}case"convert":{if(!se(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:p,run:g}=zn(k),w=fu(e,s);if(w.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let R=Yn(w,p);if(R.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${p}". (${w.length} are tracked overall.)`});return}let E=ri(R),L=3,A=`/convert${p?` --scope ${p}`:""} --run`,M=Do(e,"light");if(!g){let T=si({files:Vn(e,R),op:"convert",model:M.model}),W=p?`Scope: ${p} (${R.length} of ${w.length} tracked)
143
143
  `:"",te=`
144
- Model: ${M.model}${M.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:W+Jn(E,T,L).join(`
145
- `)+te}),X([A]);return}Ge.current=Date.now(),ct(0),N(!0);let P=new AbortController;ve.current=P,ee({verb:"Converting",total:E.length,done:0,active:[],rows:mn(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${R.length} articles across ${E.length} partitions (\u2264${L} agents at once) on ${M.model}\u2026 (esc to stop)`});try{for await(let T of Eo({cwd:e,partitions:E,promptFor:Kn,concurrency:L,profileName:s,allowProdWrites:dt.current,model:M.model,signal:P.signal}))if(T.type==="partition_status")T.status==="running"?ee(W=>W&&{...W,active:[...W.active,T.label],rows:Fe(W.rows,T.label,"active"),lastAt:Date.now()}):ee(W=>W&&{...W,active:W.active.filter(te=>te!==T.label),done:W.done+1,rows:Fe(W.rows,T.label,T.status==="done"?"done":"failed"),lastAt:Date.now()});else if(T.type==="partition_event")ee(W=>{if(!W)return W;let te={...W,lastAt:Date.now()};return T.event.type==="tool"?te.tools=W.tools+1:T.event.type==="text"&&(te.chars=W.chars+T.event.delta.length),te});else if(T.type==="run_done"){ft(U=>U+T.totalCostUsd),pt(U=>U+T.results.reduce((Y,re)=>Y+re.outputTokens,0));let W=T.aborted?"Stopped. ":"",te=t.kind==="api"?"api":"subscription";u({kind:"note",tone:T.aborted?"warn":T.ok?"ok":"warn",text:W+Qn(T.results,E,te).join(`
146
- `)})}}catch(T){u({kind:"note",tone:"error",text:`Convert run failed: ${T.message}`})}finally{ve.current=null,ee(null),N(!1),ne(T=>T+1)}return}case"write":{if(!se(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=mu(e);if(p.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:g,path:w,run:R}=eo(k),{docsDir:E,targets:L,reason:A}=so(e,p,{scope:g,path:w});if(L.length===0){u({kind:"note",tone:"warn",text:A??"Nothing to write."});return}let M=ri(L),P=5,T=Do(e,"standard");if(!R&&!!!w){let U=si({files:to(e,p,L),op:"write",model:T.model}),Y=g?`Scope: ${g} (${L.length} pending)
144
+ Model: ${M.model}${M.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:W+Kn(E,T,L).join(`
145
+ `)+te}),X([A]);return}Ge.current=Date.now(),ct(0),N(!0);let P=new AbortController;ve.current=P,ee({verb:"Converting",total:E.length,done:0,active:[],rows:mn(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${R.length} articles across ${E.length} partitions (\u2264${L} agents at once) on ${M.model}\u2026 (esc to stop)`});try{for await(let T of Eo({cwd:e,partitions:E,promptFor:Xn,concurrency:L,profileName:s,allowProdWrites:dt.current,model:M.model,signal:P.signal}))if(T.type==="partition_status")T.status==="running"?ee(W=>W&&{...W,active:[...W.active,T.label],rows:Fe(W.rows,T.label,"active"),lastAt:Date.now()}):ee(W=>W&&{...W,active:W.active.filter(te=>te!==T.label),done:W.done+1,rows:Fe(W.rows,T.label,T.status==="done"?"done":"failed"),lastAt:Date.now()});else if(T.type==="partition_event")ee(W=>{if(!W)return W;let te={...W,lastAt:Date.now()};return T.event.type==="tool"?te.tools=W.tools+1:T.event.type==="text"&&(te.chars=W.chars+T.event.delta.length),te});else if(T.type==="run_done"){ft(U=>U+T.totalCostUsd),pt(U=>U+T.results.reduce((Y,re)=>Y+re.outputTokens,0));let W=T.aborted?"Stopped. ":"",te=t.kind==="api"?"api":"subscription";u({kind:"note",tone:T.aborted?"warn":T.ok?"ok":"warn",text:W+Jn(T.results,E,te).join(`
146
+ `)})}}catch(T){u({kind:"note",tone:"error",text:`Convert run failed: ${T.message}`})}finally{ve.current=null,ee(null),N(!1),ne(T=>T+1)}return}case"write":{if(!se(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=mu(e);if(p.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:g,path:w,run:R}=Zn(k),{docsDir:E,targets:L,reason:A}=ro(e,p,{scope:g,path:w});if(L.length===0){u({kind:"note",tone:"warn",text:A??"Nothing to write."});return}let M=ri(L),P=5,T=Do(e,"standard");if(!R&&!!!w){let U=si({files:eo(e,p,L),op:"write",model:T.model}),Y=g?`Scope: ${g} (${L.length} pending)
147
147
  `:"",re=`
148
- Model: ${T.model}${T.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:Y+oo(M,U,P).join(`
149
- `)+re}),X([`/write${g?` --scope ${g}`:" --all"} --run`]);return}Ge.current=Date.now(),ct(0),N(!0);let te=new AbortController;ve.current=te,ee({verb:"Writing",total:M.length,done:0,active:[],rows:mn(M),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${L.length} article${L.length===1?"":"s"} across ${M.length} partition${M.length===1?"":"s"} (\u2264${P} agents at once) on ${T.model}${T.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let U of Eo({cwd:e,partitions:M,promptFor:Y=>no(Y,E),concurrency:P,profileName:s,allowProdWrites:dt.current,model:T.model,signal:te.signal}))if(U.type==="partition_status")U.status==="running"?ee(Y=>Y&&{...Y,active:[...Y.active,U.label],rows:Fe(Y.rows,U.label,"active"),lastAt:Date.now()}):ee(Y=>Y&&{...Y,active:Y.active.filter(re=>re!==U.label),done:Y.done+1,rows:Fe(Y.rows,U.label,U.status==="done"?"done":"failed"),lastAt:Date.now()});else if(U.type==="partition_event")ee(Y=>{if(!Y)return Y;let re={...Y,lastAt:Date.now()};return U.event.type==="tool"?re.tools=Y.tools+1:U.event.type==="text"&&(re.chars=Y.chars+U.event.delta.length),re});else if(U.type==="run_done"){ft(En=>En+U.totalCostUsd),pt(En=>En+U.results.reduce((bi,vi)=>bi+vi.outputTokens,0));let Y=U.aborted?"Stopped. ":"",re=t.kind==="api"?"api":"subscription";u({kind:"note",tone:U.aborted?"warn":U.ok?"ok":"warn",text:Y+ro(U.results,M,re).join(`
148
+ Model: ${T.model}${T.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:Y+no(M,U,P).join(`
149
+ `)+re}),X([`/write${g?` --scope ${g}`:" --all"} --run`]);return}Ge.current=Date.now(),ct(0),N(!0);let te=new AbortController;ve.current=te,ee({verb:"Writing",total:M.length,done:0,active:[],rows:mn(M),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${L.length} article${L.length===1?"":"s"} across ${M.length} partition${M.length===1?"":"s"} (\u2264${P} agents at once) on ${T.model}${T.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let U of Eo({cwd:e,partitions:M,promptFor:Y=>to(Y,E),concurrency:P,profileName:s,allowProdWrites:dt.current,model:T.model,signal:te.signal}))if(U.type==="partition_status")U.status==="running"?ee(Y=>Y&&{...Y,active:[...Y.active,U.label],rows:Fe(Y.rows,U.label,"active"),lastAt:Date.now()}):ee(Y=>Y&&{...Y,active:Y.active.filter(re=>re!==U.label),done:Y.done+1,rows:Fe(Y.rows,U.label,U.status==="done"?"done":"failed"),lastAt:Date.now()});else if(U.type==="partition_event")ee(Y=>{if(!Y)return Y;let re={...Y,lastAt:Date.now()};return U.event.type==="tool"?re.tools=Y.tools+1:U.event.type==="text"&&(re.chars=Y.chars+U.event.delta.length),re});else if(U.type==="run_done"){ft(An=>An+U.totalCostUsd),pt(An=>An+U.results.reduce((bi,vi)=>bi+vi.outputTokens,0));let Y=U.aborted?"Stopped. ":"",re=t.kind==="api"?"api":"subscription";u({kind:"note",tone:U.aborted?"warn":U.ok?"ok":"warn",text:Y+oo(U.results,M,re).join(`
150
150
  `)})}}catch(U){u({kind:"note",tone:"error",text:`Write run failed: ${U.message}`})}finally{ve.current=null,ee(null),N(!1),ne(U=>U+1)}return}case"sync":{let p=(k[0]??"status").toLowerCase();try{if(p==="status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let g=await Ao({cwd:e,profileName:s});u({kind:"note",tone:"info",text:nn(g).join(`
151
- `)});return}if(p==="pull"){let g=k[1];if(!g){u({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let w;if(g==="--all"){if(u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),w=(await Ao({cwd:e,profileName:s})).entries.filter(L=>L.status==="remote-ahead"&&L.path).map(L=>L.path),w.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing is remote-ahead \u2014 no pulls needed. (Conflicts are never bulk-pulled; pull them one by one.)"});return}}else w=[g.replace(/\\/g,"/")];let R=[];for(let E of w)R.push(await au({cwd:e,profileName:s,relPath:E}));Te.current=R,Ut();return}u({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${p} \u2014 use /sync or /sync pull <path>|--all.`})}catch(g){u({kind:"note",tone:"error",text:`Sync failed: ${g.message}`})}return}case"scope":{if(!se(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=lu(e);if(p.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}tt({cursor:0,rows:p.map(g=>({...g,checked:g.recommended}))});return}case"audit":case"capture-setup":{let g=await(i==="audit"?en:St)(k,void 0);if(g.kind==="forward-to-agent"&&g.prompt&&await Ce(g.prompt,{display:g.display,echoDisplay:!0}),i==="capture-setup"){let w=ho(e);w&&u({kind:"note",tone:"info",text:w.join(`
152
- `)})}return}case"devhints":{if(!se(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}gu(hu(e)),Fc(ku(e),ko()),u({kind:"note",tone:"info",text:wo().join(`
153
- `)});return}case"screenshot":{let p=fo(k);if(p.mode==="list"){if(!se(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:go(mo(e,p.scope),p.scope).join(`
154
- `)});return}if(p.mode==="single"){let P=await sn(k);P.kind==="forward-to-agent"&&P.prompt&&await Ce(P.prompt,{display:P.display,echoDisplay:!0});return}if(!se(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let g=p.mode==="scope"?p.scope:void 0,w=pu(e,{scope:g}).map(P=>P.id);if(w.length===0){u({kind:"note",tone:"info",text:g?`No screenshot placeholders under ${g}.`:"No screenshot placeholders found in the docs."});return}let R=6,E=du(w,3),L=Do(e,"standard");Ge.current=Date.now(),ct(0),N(!0);let A=new AbortController;ve.current=A,ee({verb:"Authoring",unit:"spec",total:E.length,done:0,active:[],rows:mn(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${w.length} screenshot spec${w.length===1?"":"s"} across ${E.length} partition${E.length===1?"":"s"} (\u2264${R} agents at once) on ${L.model}${L.forced?" (forced)":""}\u2026 (esc to stop)`});let M=!1;try{for await(let P of Eo({cwd:e,partitions:E,promptFor:ys,concurrency:R,profileName:s,allowProdWrites:dt.current,model:L.model,signal:A.signal}))if(P.type==="partition_status")P.status==="running"?ee(T=>T&&{...T,active:[...T.active,P.label],rows:Fe(T.rows,P.label,"active"),lastAt:Date.now()}):ee(T=>T&&{...T,active:T.active.filter(W=>W!==P.label),done:T.done+1,rows:Fe(T.rows,P.label,P.status==="done"?"done":"failed"),lastAt:Date.now()});else if(P.type==="partition_event")ee(T=>{if(!T)return T;let W={...T,lastAt:Date.now()};return P.event.type==="tool"?W.tools=T.tools+1:P.event.type==="text"&&(W.chars=T.chars+P.event.delta.length),W});else if(P.type==="run_done"){ft(U=>U+P.totalCostUsd),pt(U=>U+P.results.reduce((Y,re)=>Y+re.outputTokens,0));let T=P.results.filter(U=>U.ok).length,W=P.aborted?"Stopped. ":"";M=!P.aborted&&p.setup;let te=P.aborted?"":M?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";u({kind:"note",tone:P.aborted?"warn":P.ok?"ok":"warn",text:`${W}Authored specs \u2014 ${T}/${P.results.length} batches ok.${te}`})}}catch(P){u({kind:"note",tone:"error",text:`Spec authoring failed: ${P.message}`})}finally{ve.current=null,ee(null),N(!1),ne(P=>P+1)}if(M){let P=await St();P.kind==="forward-to-agent"&&P.prompt&&await Ce(P.prompt,{display:P.display,echoDisplay:!0});let T=ho(e);T&&u({kind:"note",tone:"info",text:T.join(`
155
- `)})}return}case"reset":{let p=yo(e);if(p.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}bn.current={repoName:Rt(e),targets:p},u({kind:"note",tone:"warn",text:$o(e,p).join(`
156
- `)}),oe(Rt(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Ut,u,le,Ce]),Wt=V(l=>{let a=(l??D).trim();if(x(""),Et(null),ze(0),a.startsWith("/")&&(oe(null),qe.current++,X(k=>Bs(k,a))),!a||Ko(a)||Xo(a))return;$n.current.push(a);let i=Ys(a,Lo.current);a.startsWith("/")?Jo(i):Ce(i,{display:a})},[D,Ko,Xo,Jo,Ce]),Qo=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let a=qs(l);if(Gs(a)){let i=zs(++ki.current,a);Lo.current.set(i,a),v(i)}else v(a);return}v(l)},[v]),nt=Math.max(10,We-6),Zo=wn(()=>hn(h.text,nt),[h.text,nt]),An=V(l=>y(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+l))})),[]),Ht=V(l=>y(a=>({...a,pos:Xs(hn(a.text,nt),a.pos,l)})),[nt]),gt=V(l=>y(a=>({...a,pos:Ks(hn(a.text,nt),a.pos,l)})),[nt]),xi=["\x1B[H","\x1B[1~","\x1BOH"],$i=["\x1B[F","\x1B[4~","\x1BOF"],er=V((l,a)=>a.leftArrow?(An(-1),!0):a.rightArrow?(An(1),!0):l&&xi.includes(l)?(gt("start"),!0):l&&$i.includes(l)?(gt("end"),!0):a.ctrl&&l==="a"?(gt("start"),!0):a.ctrl&&l==="e"?(gt("end"),!0):!1,[An,gt]);return Wc((l,a)=>{if(a.ctrl&&l==="c"){de.current?.close(),r();return}if(!F){if(I){if(a.escape){if(ve.current){ve.current.signal.aborted||(u({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),ve.current.abort());return}It.current||(It.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),de.current?.interrupt());return}if(a.return){let i=D.trim();if(!i)return;Oe.current.push(i),vn([...Oe.current]),x("");return}if(er(l,a))return;if(a.upArrow){Ht(-1);return}if(a.downArrow){Ht(1);return}if(a.backspace||a.delete){$();return}l&&!a.ctrl&&!a.meta&&Qo(l);return}if(Ne){if(a.upArrow){Me(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Me(i=>i&&{...i,cursor:Math.min(ye.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ye.length){Me(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=ye[Ne.cursor];Me(null);let{lines:k,changed:p,effective:g}=Ct(e,i.value??"default");for(let w of k)u({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});p&&(Bo(w=>w+1),de.current?.setModel(g));return}if(l==="s"){let i=ye[Ne.cursor];Me(null),de.current?.setModel(i.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){Me(null);return}return}if($e){if(a.upArrow){Ke(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ke(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=$e.rows.length){Ke(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return||l==="s"){let i=$e.rows[$e.cursor];Ke(null),Rn(i.name,a.return===!0);return}if(a.escape){Ke(null);return}return}if(Re){if(a.upArrow){Je(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Je(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.rows.length){Je(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=Re.rows[Re.cursor].name;if(Je(null),!xr(e,i).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${i}").`});let p=!1;try{let g=Be(i);p=!!g&&!(Ie(g)&&!g.refreshToken)}catch{}p?(u({kind:"note",tone:"info",text:`Already signed in to ${i} \u2014 next: pick a workspace.`}),X(["/workspace"])):(u({kind:"note",tone:"info",text:`Next: sign in to Document360 (${i}).`}),X(["/login"])),ne(g=>g+1);return}if(a.escape){Je(null);return}return}if(ie){if(a.upArrow){Qe(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Qe(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ie.rows.length){Qe(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=ie.rows[ie.cursor],{profile:k,projectId:p}=ie;Qe(null),Ot(k,p,i);return}if(a.escape){Qe(null);return}return}if(pe){if(a.upArrow){Ze(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ze(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=pe.rows.length){Ze(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=pe.rows[pe.cursor],{profile:k}=pe;Ze(null),Vo(k,i);return}if(a.escape){Ze(null);return}return}if(ae){if(a.upArrow){tt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){tt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l===" "){tt(i=>i&&{...i,rows:i.rows.map((k,p)=>p===i.cursor?{...k,checked:!k.checked}:k)});return}if(a.return){let i=ae.rows.filter(k=>k.checked).map(k=>k.path);if(tt(null),i.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Ln(e,i),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer.json`});for(let k of i)u({kind:"note",tone:"info",text:` ${k}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){tt(null);return}return}if(be){if(a.upArrow){et(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){et(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=be.rows.length){et(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=be.rows[be.cursor],k=be.rows.filter(p=>p.path!=="--all").map(p=>p.path);et(null),Ce(i.path==="--all"?$t(k):Zt(i.path),{display:i.path==="--all"?"/publish --all":`/publish ${i.path}`,echoDisplay:!0});return}if(a.escape){et(null);return}return}if(fe){if(a.escape){Le(null);return}if(a.upArrow){Le(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Le(i=>i&&{...i,cursor:Math.min(Math.max(0,Mt.length-1),i.cursor+1)});return}if(a.return){let i=Mt[fe.cursor];if(i){Le(null);try{u({kind:"preview",name:Rt(i),text:li(ei(jt(e,i),"utf8"))})}catch(k){u({kind:"note",tone:"error",text:`Could not read ${i}: ${k.message}`})}}return}if(a.backspace||a.delete){Le(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){Le(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(me){if(a.escape){Ue(null);return}if(a.upArrow){Ue(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ue(i=>i&&{...i,cursor:Math.min(Math.max(0,Lt.length-1),i.cursor+1)});return}if(a.return){let i=Lt[me.cursor];if(i){Ue(null),le(i.uuid),xe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},Xe(i.name),jo(i.uuid),Ve.current=[];let k=Po(e,i.uuid);for(let p of k)u(p);u({kind:"note",tone:"ok",text:k.length?`Resumed "${i.name}" \u2014 restored ${k.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){Ue(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){Ue(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(a.tab&&!D&&ke){x(ke),oe(null),qe.current++;return}if(!D&&lt.length>0&&l&&/^[1-9]$/.test(l)){let i=lt[Number(l)-1];if(i){x(i);return}}if(!er(l,a)){if(zo){if(a.upArrow){ze(i=>Math.max(0,i-1));return}if(a.downArrow){ze(i=>Math.min(mt.length-1,i+1));return}if(a.tab){x("/"+(mt[ut]?.name??"")+" "),ze(0);return}if(a.return){let i=mt[ut];if(i){let k=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(gr(i.usage)&&!k){x("/"+i.name+" "),ze(0);return}Wt("/"+i.name+(k?" "+k:""));return}}}else{if(a.upArrow){if(D!==""&&Ye===null){Ht(-1);return}let i=$n.current;if(!i.length)return;let k=Ye===null?i.length-1:Math.max(0,Ye-1);Et(k),x(i[k]??"");return}if(a.downArrow){if(D!==""&&Ye===null){Ht(1);return}let i=$n.current;if(Ye===null)return;let k=Ye+1;k>=i.length?(Et(null),x("")):(Et(k),x(i[k]??""));return}}if(a.return){Wt();return}if(a.backspace||a.delete){$();return}if(a.escape){x(""),ze(0),oe(null),X([]);return}l&&!a.ctrl&&!a.meta&&Qo(l)}}}),_e(()=>{if(I||F)return;let l=Oe.current.shift();l!==void 0&&(vn([...Oe.current]),Wt(l))},[I,F,Wt]),H(K,{flexDirection:"column",width:We,children:[Sn!==null&&H(K,{marginTop:1,flexDirection:"column",children:[Sn.truncated&&S(C,{dimColor:!0,children:"\u2026"}),S(C,{children:Sn.text})]}),I&&(Wo?S(Tu,{p:Wo}):S(Pu,{startTime:Ge.current,chars:hi})),S(K,{borderStyle:"round",borderColor:Go.prod?"yellow":G,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?Zo.map((l,a)=>{let i=h.text.slice(l.start,l.end),k=a===kn(Zo,h.pos),p=Math.min(h.pos,l.end)-l.start;return H(C,{children:[S(C,{color:G,children:a===0?"> ":" "}),k?H(Io,{children:[i.slice(0,p),S(yn,{ch:i[p]??" "}),i.slice(p+1)]}):i||" "]},`${a}-${l.start}`)}):H(C,{children:[S(C,{color:G,children:"> "}),ke&&!I?H(Io,{children:[S(yn,{ch:ke[0],dim:!0}),S(C,{color:"gray",children:ke.slice(1)}),S(C,{dimColor:!0,children:" (tab)"})]}):Pn.isSetup||!gi?H(Io,{children:[S(yn,{ch:Pn.text[0],dim:!0}),S(C,{color:"gray",children:Pn.text.slice(1)})]}):S(yn,{ch:" "})]})}),Uo.length>0&&S(K,{flexDirection:"column",paddingX:1,children:Uo.map((l,a)=>S(C,{color:"gray",children:`\u29D7 queued: ${l}`},`${a}-${l.slice(0,24)}`))}),Ne?H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Select model"}),S(C,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),ye.map((l,a)=>H(C,{color:a===Ne.cursor?G:void 0,children:[a===Ne.cursor?"\u276F ":" ",`${a+1}. ${l.label}${a===Ne.current?" \u2714":""}`.padEnd(16),S(C,{color:"gray",children:l.desc})]},l.label)),S(C,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):$e?H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Switch connection profile"}),$e.rows.map((l,a)=>H(C,{color:a===$e.cursor?G:void 0,children:[a===$e.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===$e.current?" \u2714":""}`.padEnd(20),S(C,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?S(C,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),S(C,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Re?H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Pick your Document360 environment"}),Re.rows.map((l,a)=>H(C,{color:a===Re.cursor?G:void 0,children:[a===Re.cursor?"\u276F ":" ",`${a+1}. ${l.name}`.padEnd(16),S(C,{color:"gray",children:l.apiUrl})]},l.name)),S(C,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ie?H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Switch workspace"}),S(C,{dimColor:!0,children:`environment ${ie.environment} \xB7 project ${ie.projectId.slice(0,8)}\u2026`}),ie.rows.map((l,a)=>H(C,{color:a===ie.cursor?G:void 0,children:[a===ie.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===ie.current?" \u2714":""}`.padEnd(30),S(C,{color:"gray",children:l.type??""})]},l.id)),S(C,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):pe?H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Choose project"}),S(C,{dimColor:!0,children:`environment ${pe.environment}`}),pe.rows.map((l,a)=>H(C,{color:a===pe.cursor?G:void 0,children:[a===pe.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===pe.current?" \u2714":""}`.padEnd(30),S(C,{color:"gray",children:l.sub??""})]},l.id)),S(C,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ae?(()=>{let a=Math.min(Math.max(0,ae.cursor-Math.floor(7)),Math.max(0,ae.rows.length-14)),i=ae.rows.slice(a,a+14),k=ae.rows.filter(p=>p.checked).length;return H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:`Which folders back the user docs? (${k} selected of ${ae.rows.length})`}),a>0?S(C,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((p,g)=>{let w=a+g;return H(C,{color:w===ae.cursor?G:void 0,children:[w===ae.cursor?"\u276F ":" ",p.checked?"\u25C9 ":"\u25CB ",p.path.padEnd(Math.min(48,We-34)),S(C,{color:"gray",children:tn(p)})]},p.path)}),a+14<ae.rows.length?S(C,{dimColor:!0,children:` \u2193 ${ae.rows.length-a-14} more`}):null,S(C,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():be?H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Publish which article?"}),be.rows.map((l,a)=>H(C,{color:a===be.cursor?G:void 0,children:[a===be.cursor?"\u276F ":" ",`${a+1}. ${l.path}`.padEnd(Math.min(56,We-30)),S(C,{color:"gray",children:l.label})]},l.path)),S(C,{dimColor:!0,children:"enter publish (draft) \xB7 esc cancel"})]}):fe?H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:`Preview article${fe.query?` \u2014 filter: ${fe.query}`:" (type to filter)"}`}),Mt.length===0?S(C,{color:"gray",children:"no articles match"}):Mt.map((l,a)=>H(C,{color:a===fe.cursor?G:void 0,children:[a===fe.cursor?"\u276F ":" ",l]},l)),S(C,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):me?H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:`Resume session${me.query?` \u2014 filter: ${me.query}`:" (type to filter)"}`}),Lt.length===0?S(C,{color:"gray",children:"no sessions match"}):Lt.map((l,a)=>H(C,{color:a===me.cursor?G:void 0,children:[a===me.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),S(C,{color:a===me.cursor?G:"gray",children:l.firstPrompt.slice(0,Math.max(10,We-40))})]},l.uuid)),S(C,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):zo?S(K,{flexDirection:"column",children:mt.map((l,a)=>H(C,{color:a===ut?G:void 0,children:[a===ut?"\u276F ":" ",l.usage.padEnd(22)," ",S(C,{color:a===ut?G:"gray",children:l.name==="model"&&Cn?`${l.desc} (currently ${Cn})`:l.desc})]},l.name))}):!D&&lt.length>0?H(K,{flexDirection:"column",paddingX:1,children:[lt.map((l,a)=>H(C,{children:[S(C,{color:G,children:a+1})," ",l.slice(0,Math.max(20,We-5))]},l)),S(C,{dimColor:!0,children:`press 1-${lt.length} to fill the command \xB7 esc dismiss`})]}):S(K,{paddingX:1,children:H(C,{color:"gray",children:[Go.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Cn??"model n/a"}${t.kind==="api"?Fo>0?` \xB7 ${ge(Fo)}`:"":Ho>0?` \xB7 ${it(Ho)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}q();import{jsx as Au}from"react/jsx-runtime";async function pi(e=process.cwd(),t="auto",n,o="0.0.0"){let r=ju(t);r.kind==="none"&&(console.error(""),console.error(b("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${j("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${j("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Ru(Au(di,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
151
+ `)});return}if(p==="pull"){let g=k[1];if(!g){u({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let w;if(g==="--all"){if(u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),w=(await Ao({cwd:e,profileName:s})).entries.filter(L=>L.status==="remote-ahead"&&L.path).map(L=>L.path),w.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing is remote-ahead \u2014 no pulls needed. (Conflicts are never bulk-pulled; pull them one by one.)"});return}}else w=[g.replace(/\\/g,"/")];let R=[];for(let E of w)R.push(await au({cwd:e,profileName:s,relPath:E}));Te.current=R,Ut();return}u({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${p} \u2014 use /sync or /sync pull <path>|--all.`})}catch(g){u({kind:"note",tone:"error",text:`Sync failed: ${g.message}`})}return}case"scope":{if(!se(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=lu(e);if(p.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}tt({cursor:0,rows:p.map(g=>({...g,checked:g.recommended}))});return}case"audit":case"capture-setup":{let g=await(i==="audit"?en:St)(k,void 0);if(g.kind==="forward-to-agent"&&g.prompt&&await Ce(g.prompt,{display:g.display,echoDisplay:!0}),i==="capture-setup"){let w=go(e);w&&u({kind:"note",tone:"info",text:w.join(`
152
+ `)})}return}case"devhints":{if(!se(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}gu(hu(e)),Fc(ku(e),ho()),u({kind:"note",tone:"info",text:ko().join(`
153
+ `)});return}case"screenshot":{let p=po(k);if(p.mode==="list"){if(!se(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:mo(fo(e,p.scope),p.scope).join(`
154
+ `)});return}if(p.mode==="single"){let P=await sn(k);P.kind==="forward-to-agent"&&P.prompt&&await Ce(P.prompt,{display:P.display,echoDisplay:!0});return}if(!se(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let g=p.mode==="scope"?p.scope:void 0,w=pu(e,{scope:g}).map(P=>P.id);if(w.length===0){u({kind:"note",tone:"info",text:g?`No screenshot placeholders under ${g}.`:"No screenshot placeholders found in the docs."});return}let R=6,E=du(w,3),L=Do(e,"standard");Ge.current=Date.now(),ct(0),N(!0);let A=new AbortController;ve.current=A,ee({verb:"Authoring",unit:"spec",total:E.length,done:0,active:[],rows:mn(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${w.length} screenshot spec${w.length===1?"":"s"} across ${E.length} partition${E.length===1?"":"s"} (\u2264${R} agents at once) on ${L.model}${L.forced?" (forced)":""}\u2026 (esc to stop)`});let M=!1;try{for await(let P of Eo({cwd:e,partitions:E,promptFor:ys,concurrency:R,profileName:s,allowProdWrites:dt.current,model:L.model,signal:A.signal}))if(P.type==="partition_status")P.status==="running"?ee(T=>T&&{...T,active:[...T.active,P.label],rows:Fe(T.rows,P.label,"active"),lastAt:Date.now()}):ee(T=>T&&{...T,active:T.active.filter(W=>W!==P.label),done:T.done+1,rows:Fe(T.rows,P.label,P.status==="done"?"done":"failed"),lastAt:Date.now()});else if(P.type==="partition_event")ee(T=>{if(!T)return T;let W={...T,lastAt:Date.now()};return P.event.type==="tool"?W.tools=T.tools+1:P.event.type==="text"&&(W.chars=T.chars+P.event.delta.length),W});else if(P.type==="run_done"){ft(U=>U+P.totalCostUsd),pt(U=>U+P.results.reduce((Y,re)=>Y+re.outputTokens,0));let T=P.results.filter(U=>U.ok).length,W=P.aborted?"Stopped. ":"";M=!P.aborted&&p.setup;let te=P.aborted?"":M?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";u({kind:"note",tone:P.aborted?"warn":P.ok?"ok":"warn",text:`${W}Authored specs \u2014 ${T}/${P.results.length} batches ok.${te}`})}}catch(P){u({kind:"note",tone:"error",text:`Spec authoring failed: ${P.message}`})}finally{ve.current=null,ee(null),N(!1),ne(P=>P+1)}if(M){let P=await St();P.kind==="forward-to-agent"&&P.prompt&&await Ce(P.prompt,{display:P.display,echoDisplay:!0});let T=go(e);T&&u({kind:"note",tone:"info",text:T.join(`
155
+ `)})}return}case"reset":{let p=wo(e);if(p.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}$n.current={repoName:Rt(e),targets:p},u({kind:"note",tone:"warn",text:xo(e,p).join(`
156
+ `)}),oe(Rt(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Ut,u,le,Ce]),Wt=V(l=>{let a=(l??D).trim();if(x(""),Et(null),ze(0),a.startsWith("/")&&(oe(null),qe.current++,X(k=>Bs(k,a))),!a||Ko(a)||Xo(a))return;xn.current.push(a);let i=Ys(a,Lo.current);a.startsWith("/")?Jo(i):Ce(i,{display:a})},[D,Ko,Xo,Jo,Ce]),Qo=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let a=qs(l);if(Gs(a)){let i=zs(++ki.current,a);Lo.current.set(i,a),v(i)}else v(a);return}v(l)},[v]),nt=Math.max(10,We-6),Zo=Ro(()=>hn(h.text,nt),[h.text,nt]),jn=V(l=>y(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+l))})),[]),Ht=V(l=>y(a=>({...a,pos:Xs(hn(a.text,nt),a.pos,l)})),[nt]),gt=V(l=>y(a=>({...a,pos:Ks(hn(a.text,nt),a.pos,l)})),[nt]),xi=["\x1B[H","\x1B[1~","\x1BOH"],$i=["\x1B[F","\x1B[4~","\x1BOF"],er=V((l,a)=>a.leftArrow?(jn(-1),!0):a.rightArrow?(jn(1),!0):l&&xi.includes(l)?(gt("start"),!0):l&&$i.includes(l)?(gt("end"),!0):a.ctrl&&l==="a"?(gt("start"),!0):a.ctrl&&l==="e"?(gt("end"),!0):!1,[jn,gt]);return Wc((l,a)=>{if(a.ctrl&&l==="c"){de.current?.close(),r();return}if(!F){if(I){if(a.escape){if(ve.current){ve.current.signal.aborted||(u({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),ve.current.abort());return}It.current||(It.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),de.current?.interrupt());return}if(a.return){let i=D.trim();if(!i)return;Oe.current.push(i),bn([...Oe.current]),x("");return}if(er(l,a))return;if(a.upArrow){Ht(-1);return}if(a.downArrow){Ht(1);return}if(a.backspace||a.delete){$();return}l&&!a.ctrl&&!a.meta&&Qo(l);return}if(Ne){if(a.upArrow){Me(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Me(i=>i&&{...i,cursor:Math.min(we.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=we.length){Me(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=we[Ne.cursor];Me(null);let{lines:k,changed:p,effective:g}=Ct(e,i.value??"default");for(let w of k)u({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});p&&(Bo(w=>w+1),de.current?.setModel(g));return}if(l==="s"){let i=we[Ne.cursor];Me(null),de.current?.setModel(i.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){Me(null);return}return}if($e){if(a.upArrow){Ke(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ke(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=$e.rows.length){Ke(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return||l==="s"){let i=$e.rows[$e.cursor];Ke(null),Tn(i.name,a.return===!0);return}if(a.escape){Ke(null);return}return}if(Re){if(a.upArrow){Je(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Je(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.rows.length){Je(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=Re.rows[Re.cursor].name;if(Je(null),!xr(e,i).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${i}").`});let p=!1;try{let g=Be(i);p=!!g&&!(Ie(g)&&!g.refreshToken)}catch{}p?(u({kind:"note",tone:"info",text:`Already signed in to ${i} \u2014 next: pick a workspace.`}),X(["/workspace"])):(u({kind:"note",tone:"info",text:`Next: sign in to Document360 (${i}).`}),X(["/login"])),ne(g=>g+1);return}if(a.escape){Je(null);return}return}if(ie){if(a.upArrow){Qe(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Qe(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ie.rows.length){Qe(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=ie.rows[ie.cursor],{profile:k,projectId:p}=ie;Qe(null),Ot(k,p,i);return}if(a.escape){Qe(null);return}return}if(pe){if(a.upArrow){Ze(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ze(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=pe.rows.length){Ze(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=pe.rows[pe.cursor],{profile:k}=pe;Ze(null),Vo(k,i);return}if(a.escape){Ze(null);return}return}if(ae){if(a.upArrow){tt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){tt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l===" "){tt(i=>i&&{...i,rows:i.rows.map((k,p)=>p===i.cursor?{...k,checked:!k.checked}:k)});return}if(a.return){let i=ae.rows.filter(k=>k.checked).map(k=>k.path);if(tt(null),i.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Mn(e,i),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer.json`});for(let k of i)u({kind:"note",tone:"info",text:` ${k}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){tt(null);return}return}if(be){if(a.upArrow){et(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){et(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=be.rows.length){et(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=be.rows[be.cursor],k=be.rows.filter(p=>p.path!=="--all").map(p=>p.path);et(null),Ce(i.path==="--all"?$t(k):Zt(i.path),{display:i.path==="--all"?"/publish --all":`/publish ${i.path}`,echoDisplay:!0});return}if(a.escape){et(null);return}return}if(fe){if(a.escape){Le(null);return}if(a.upArrow){Le(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Le(i=>i&&{...i,cursor:Math.min(Math.max(0,Mt.length-1),i.cursor+1)});return}if(a.return){let i=Mt[fe.cursor];if(i){Le(null);try{u({kind:"preview",name:Rt(i),text:li(ei(jt(e,i),"utf8"))})}catch(k){u({kind:"note",tone:"error",text:`Could not read ${i}: ${k.message}`})}}return}if(a.backspace||a.delete){Le(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){Le(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(me){if(a.escape){Ue(null);return}if(a.upArrow){Ue(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ue(i=>i&&{...i,cursor:Math.min(Math.max(0,Lt.length-1),i.cursor+1)});return}if(a.return){let i=Lt[me.cursor];if(i){Ue(null),le(i.uuid),xe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},Xe(i.name),jo(i.uuid),Ve.current=[];let k=Co(e,i.uuid);for(let p of k)u(p);u({kind:"note",tone:"ok",text:k.length?`Resumed "${i.name}" \u2014 restored ${k.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){Ue(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){Ue(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(a.tab&&!D&&he){x(he),oe(null),qe.current++;return}if(!D&&lt.length>0&&l&&/^[1-9]$/.test(l)){let i=lt[Number(l)-1];if(i){x(i);return}}if(!er(l,a)){if(zo){if(a.upArrow){ze(i=>Math.max(0,i-1));return}if(a.downArrow){ze(i=>Math.min(mt.length-1,i+1));return}if(a.tab){x("/"+(mt[ut]?.name??"")+" "),ze(0);return}if(a.return){let i=mt[ut];if(i){let k=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(gr(i.usage)&&!k){x("/"+i.name+" "),ze(0);return}Wt("/"+i.name+(k?" "+k:""));return}}}else{if(a.upArrow){if(D!==""&&Ye===null){Ht(-1);return}let i=xn.current;if(!i.length)return;let k=Ye===null?i.length-1:Math.max(0,Ye-1);Et(k),x(i[k]??"");return}if(a.downArrow){if(D!==""&&Ye===null){Ht(1);return}let i=xn.current;if(Ye===null)return;let k=Ye+1;k>=i.length?(Et(null),x("")):(Et(k),x(i[k]??""));return}}if(a.return){Wt();return}if(a.backspace||a.delete){$();return}if(a.escape){x(""),ze(0),oe(null),X([]);return}l&&!a.ctrl&&!a.meta&&Qo(l)}}}),_e(()=>{if(I||F)return;let l=Oe.current.shift();l!==void 0&&(bn([...Oe.current]),Wt(l))},[I,F,Wt]),H(K,{flexDirection:"column",width:We,children:[Pn!==null&&H(K,{marginTop:1,flexDirection:"column",children:[Pn.truncated&&S(C,{dimColor:!0,children:"\u2026"}),S(C,{children:Pn.text})]}),I&&(Wo?S(Tu,{p:Wo}):S(Pu,{startTime:Ge.current,chars:hi})),S(K,{borderStyle:"round",borderColor:Go.prod?"yellow":G,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?Zo.map((l,a)=>{let i=h.text.slice(l.start,l.end),k=a===kn(Zo,h.pos),p=Math.min(h.pos,l.end)-l.start;return H(C,{children:[S(C,{color:G,children:a===0?"> ":" "}),k?H(Io,{children:[i.slice(0,p),S(wn,{ch:i[p]??" "}),i.slice(p+1)]}):i||" "]},`${a}-${l.start}`)}):H(C,{children:[S(C,{color:G,children:"> "}),he&&!I?H(Io,{children:[S(wn,{ch:he[0],dim:!0}),S(C,{color:"gray",children:he.slice(1)}),S(C,{dimColor:!0,children:" (tab)"})]}):Cn.isSetup||!gi?H(Io,{children:[S(wn,{ch:Cn.text[0],dim:!0}),S(C,{color:"gray",children:Cn.text.slice(1)})]}):S(wn,{ch:" "})]})}),Uo.length>0&&S(K,{flexDirection:"column",paddingX:1,children:Uo.map((l,a)=>S(C,{color:"gray",children:`\u29D7 queued: ${l}`},`${a}-${l.slice(0,24)}`))}),Ne?H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Select model"}),S(C,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),we.map((l,a)=>H(C,{color:a===Ne.cursor?G:void 0,children:[a===Ne.cursor?"\u276F ":" ",`${a+1}. ${l.label}${a===Ne.current?" \u2714":""}`.padEnd(16),S(C,{color:"gray",children:l.desc})]},l.label)),S(C,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):$e?H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Switch connection profile"}),$e.rows.map((l,a)=>H(C,{color:a===$e.cursor?G:void 0,children:[a===$e.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===$e.current?" \u2714":""}`.padEnd(20),S(C,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?S(C,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),S(C,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Re?H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Pick your Document360 environment"}),Re.rows.map((l,a)=>H(C,{color:a===Re.cursor?G:void 0,children:[a===Re.cursor?"\u276F ":" ",`${a+1}. ${l.name}`.padEnd(16),S(C,{color:"gray",children:l.apiUrl})]},l.name)),S(C,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ie?H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Switch workspace"}),S(C,{dimColor:!0,children:`environment ${ie.environment} \xB7 project ${ie.projectId.slice(0,8)}\u2026`}),ie.rows.map((l,a)=>H(C,{color:a===ie.cursor?G:void 0,children:[a===ie.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===ie.current?" \u2714":""}`.padEnd(30),S(C,{color:"gray",children:l.type??""})]},l.id)),S(C,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):pe?H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Choose project"}),S(C,{dimColor:!0,children:`environment ${pe.environment}`}),pe.rows.map((l,a)=>H(C,{color:a===pe.cursor?G:void 0,children:[a===pe.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===pe.current?" \u2714":""}`.padEnd(30),S(C,{color:"gray",children:l.sub??""})]},l.id)),S(C,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ae?(()=>{let a=Math.min(Math.max(0,ae.cursor-Math.floor(7)),Math.max(0,ae.rows.length-14)),i=ae.rows.slice(a,a+14),k=ae.rows.filter(p=>p.checked).length;return H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:`Which folders back the user docs? (${k} selected of ${ae.rows.length})`}),a>0?S(C,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((p,g)=>{let w=a+g;return H(C,{color:w===ae.cursor?G:void 0,children:[w===ae.cursor?"\u276F ":" ",p.checked?"\u25C9 ":"\u25CB ",p.path.padEnd(Math.min(48,We-34)),S(C,{color:"gray",children:tn(p)})]},p.path)}),a+14<ae.rows.length?S(C,{dimColor:!0,children:` \u2193 ${ae.rows.length-a-14} more`}):null,S(C,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():be?H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Publish which article?"}),be.rows.map((l,a)=>H(C,{color:a===be.cursor?G:void 0,children:[a===be.cursor?"\u276F ":" ",`${a+1}. ${l.path}`.padEnd(Math.min(56,We-30)),S(C,{color:"gray",children:l.label})]},l.path)),S(C,{dimColor:!0,children:"enter publish (draft) \xB7 esc cancel"})]}):fe?H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:`Preview article${fe.query?` \u2014 filter: ${fe.query}`:" (type to filter)"}`}),Mt.length===0?S(C,{color:"gray",children:"no articles match"}):Mt.map((l,a)=>H(C,{color:a===fe.cursor?G:void 0,children:[a===fe.cursor?"\u276F ":" ",l]},l)),S(C,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):me?H(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:`Resume session${me.query?` \u2014 filter: ${me.query}`:" (type to filter)"}`}),Lt.length===0?S(C,{color:"gray",children:"no sessions match"}):Lt.map((l,a)=>H(C,{color:a===me.cursor?G:void 0,children:[a===me.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),S(C,{color:a===me.cursor?G:"gray",children:l.firstPrompt.slice(0,Math.max(10,We-40))})]},l.uuid)),S(C,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):zo?S(K,{flexDirection:"column",children:mt.map((l,a)=>H(C,{color:a===ut?G:void 0,children:[a===ut?"\u276F ":" ",l.usage.padEnd(22)," ",S(C,{color:a===ut?G:"gray",children:l.name==="model"&&vn?`${l.desc} (currently ${vn})`:l.desc})]},l.name))}):!D&&lt.length>0?H(K,{flexDirection:"column",paddingX:1,children:[lt.map((l,a)=>H(C,{children:[S(C,{color:G,children:a+1})," ",l.slice(0,Math.max(20,We-5))]},l)),S(C,{dimColor:!0,children:`press 1-${lt.length} to fill the command \xB7 esc dismiss`})]}):S(K,{paddingX:1,children:H(C,{color:"gray",children:[Go.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${vn??"model n/a"}${t.kind==="api"?Fo>0?` \xB7 ${ge(Fo)}`:"":Ho>0?` \xB7 ${it(Ho)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}q();import{jsx as Au}from"react/jsx-runtime";async function pi(e=process.cwd(),t="auto",n,o="0.0.0"){let r=ju(t);r.kind==="none"&&(console.error(""),console.error(b("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${j("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${j("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Ru(Au(di,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
157
157
  `),process.exit(0)}var _u=Du(import.meta.url),fi=_u("../package.json"),Se=new Eu;function No(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Se.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{No(e),await Gt({profile:e.profile,manual:e.manual})});Se.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{No(e),await ur({profile:e.profile})});Se.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{No(e),await cr({profile:e.profile})});var Mo=Se.command("profile").description("Manage connection profiles for the current repo");Mo.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>zt(process.cwd()));Mo.command("use <name>").description("Set the default profile for this repo").action(e=>Yt(process.cwd(),e));Mo.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Vt(process.cwd(),e));var mi=Se.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");mi.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>ot(process.cwd(),e.profile));mi.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await rr(process.cwd(),e,t.profile)});Se.command("logs").description("Show the Document360 API log files (send these to support when reporting a problem)").action(()=>pr());Se.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(rn(),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});Se.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(fi.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(Iu.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 fr(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 Ns(e.cwd,e.auth,e.profile):await pi(e.cwd,e.auth,e.profile,fi.version)});Se.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.47",
3
+ "version": "0.4.48",
4
4
  "description": "Standalone documentation agent CLI. Reads your code, writes your docs. Specialized for Document360 publishing.",
5
5
  "type": "module",
6
6
  "bin": {