document360-writer 0.5.71 → 0.5.73
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.
- package/dist/cli.js +104 -104
- package/dist/lib/categoryChoices.d.ts +23 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Fc=Object.defineProperty;var Ln=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var hi=(e,t)=>{for(var n in t)Fc(e,n,{get:t[n],enumerable:!0})};import Ge from"picocolors";var B,Hc,qc,Bc,gi,en,f,$,U,N,L,ie,Pe,H=Ln(()=>{"use strict";B="#7f56d9",[Hc,qc,Bc]=[127,86,217],gi=e=>Ge.isColorSupported?`\x1B[38;2;${Hc};${qc};${Bc}m${e}\x1B[39m`:e,en=e=>Ge.bold(gi(e)),f=e=>Ge.dim(e),$=e=>Ge.red(e),U=e=>Ge.yellow(e),N=e=>Ge.green(e),L=gi,ie=e=>Ge.gray(e),Pe=e=>Ge.bold(e)});import{existsSync as zn,writeFileSync as on,readFileSync as Su,readdirSync as Du}from"node:fs";import{join as ju}from"node:path";import{devHintsGuidePath as Xn,hintsDir as Ii,architectureDir as Li,messagesDir as ur,creatorNotesPath as _i,devhintsStatePath as Mi,ensureDir as Yn,writeMessage as Au,listOpenForDev as Eu}from"document360-engine";function Ui(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
4
|
<!-- devhints script v${re} \xB7 maintained by document360-writer (/devhints). -->
|
|
5
5
|
|
|
@@ -168,7 +168,7 @@ whenever \`git status\` shows changes under \`.d360-writer/\`, commit them (e.g.
|
|
|
168
168
|
\`git add .d360-writer && git commit -m "docs: sync d360-writer output"\`) before you push. The docs agent
|
|
169
169
|
will remind you when it leaves changes, but it's your call to commit them. Without this, the team's docs
|
|
170
170
|
and \u2014 critically \u2014 the sync map are stranded on one machine.
|
|
171
|
-
`}function
|
|
171
|
+
`}function Nu(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
|
|
172
172
|
|
|
173
173
|
<!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
|
|
174
174
|
The builder agent reads this FIRST and treats it as authoritative when writing the architecture
|
|
@@ -182,60 +182,60 @@ Anything only a human knows that would help document this product. For example:
|
|
|
182
182
|
- Gotchas or non-obvious behavior.
|
|
183
183
|
|
|
184
184
|
(Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
|
|
185
|
-
`}function
|
|
186
|
-
`)}
|
|
187
|
-
`)}function
|
|
188
|
-
`)}function
|
|
189
|
-
`)}),n.notifiedBuilder=!0))}catch{}return n}function
|
|
190
|
-
`)}function
|
|
191
|
-
`),"utf8")}async function cr(){let e=process.cwd(),t=Li(e);if(Lt(t)&&!await Pu({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Hi(e)??_i(e),o=await nn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await nn({message:"Capture directory (where document360-capture .spec.ts files live):",default:Ui}),s=await nn({message:"Screenshot output directory:",default:Wi}),l=await nn({message:"Default connection profile name:",default:"berlin"}),p=await nn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),y={projectId:o,docsDir:Mi,captureDir:r,outputDir:s,profiles:{[l]:{connection:{environment:p},production:!1}},defaultProfile:l,authoritativeSourceFiles:qi(e)},g=Du(e);g?.terminologyGlossary&&(y.terminologyGlossary=g.terminologyGlossary),Oi(y,e),Fi(e);let b=It(e);console.log(""),console.log(A(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${L(`d360-writer login --profile ${l}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let S of Ot(b))console.log(S);return console.log(""),console.log(`${f("Then ask:")} ${L('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Hi(e){let t=Xn(e,"package.json");if(!Lt(t))return null;try{return JSON.parse(Ru(t,"utf8")).name??null}catch{return null}}function qi(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Lt(Xn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Xn(e,n);Lt(o)&&!Au(o)&&t.push(n)}return t}function Au(e){try{return Tu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Qn=In(()=>{"use strict";H();ct()});var Wa={};li(Wa,{doctorCommand:()=>un,renderDoctorChecks:()=>Ua,runDoctorChecks:()=>Ma});import{existsSync as ip}from"node:fs";import{d360GetAll as ap,getAccessToken as lp,isExpired as es,loadProfileMap as cp,loadTokens as up,packageSkillsDir as Oa,projectConfigPath as dp,readProjectConfig as pp,DEFAULT_DOCS_DIR as fp,fetchManifestSummary as mp,resolveActiveProfile as hp,classifyClaudeAuth as gp,CLAUDE_CODE_SETUP_HINT as La,resolveModelSetting as yp,probeModel as wp,detectAppType as kp,playbookSkillName as bp,D360AuthError as xp}from"document360-engine";async function Ma(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=gp();o.state==="ready"?t.push({level:"ok",label:`Claude auth: ${o.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):o.state==="maybe"?t.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${La}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:La});let r=yp(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let P=await wp(e,r.model??void 0);P.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(P.latencyMs/1e3).toFixed(1)}s`}):P.timedOut?t.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):t.push({level:"fail",label:`Model call failed \u2014 ${P.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let s=pp(e);if(!s)return t.push({level:"fail",label:`No ${dp(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let l=(s.docsDir??fp).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 ${l}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let y=s.appType??kp(e);if(y){let P=s.appType?"from config":"auto-detected",C=y==="web"||y==="cli";t.push({level:"ok",label:`Genre: ${y} (${P})${C?` \u2192 ${bp(y)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else t.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let g;try{g=hp(e),t.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(P){return t.push({level:"fail",label:`Profile config: ${P.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let b=up(g.name);b?es(b)&&!b.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):es(b)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(b.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${g.name})`}),t.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let S=cp(e,g.name);S?S.projectId&&g.project.projectId&&S.projectId!==g.project.projectId?t.push({level:"fail",label:`Category map projectId (${S.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(S.articles).length} articles, ${Object.keys(S.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),t.push(ip(Oa())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Oa()}`,fix:"Reinstall document360-writer (broken install)"});let x=Oe(e);if(x.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${re})`}):x.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${x.completedVersion}, current is v${re}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),b&&(!es(b)||b.refreshToken)){let P={profile:g.name,connection:g.connection};try{await lp(P);let j=await ap(P,"/v3/projects");t.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${j.length} project(s) visible`})}catch(j){t.push({level:"fail",label:`API call failed: ${j.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let C=S?.projectId??g.project.projectId;if(C&&g.project.workspaceId)try{let j=await mp(P,C,g.project.workspaceId);if(j){let I=(j.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${g.connection.name} (${j.languages?.length??0} language${(j.languages?.length??0)===1?"":"s"}) \xB7 hash ${I||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${g.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(j){j instanceof xp||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(j.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??C})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):t.push({level:"warn",label:`Workspace sync manifest: probe failed (${j.message.slice(0,80)})`})}}return t}function Ua(e){let t=[""];for(let r of e){let s=r.level==="ok"?A("\u2713"):r.level==="warn"?U("\u26A0"):$("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${L(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?A(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function un(e,t){console.log(f("Running checks\u2026"));for(let n of Ua(await Ma(t.cwd)))console.log(n);return{kind:"continue"}}var ao=In(()=>{"use strict";ct();H()});import{Command as wh}from"commander";import{createRequire as kh}from"node:module";import{AUTH_MODES as bh}from"document360-engine";import{input as Kc}from"@inquirer/prompts";import{loginPkce as Xc,refreshTokens as Qc,toStoredTokens as hi,clearTokens as Jc,decodeJwtClaims as mi,isExpired as Zc,loadTokens as eu,saveTokens as gi,resolveActiveProfile as Mn,setProfileProject as tu,readProjectConfig as nu}from"document360-engine";H();import{select as Oc}from"@inquirer/prompts";import{resolveActiveProfile as Lc,setProfileProject as Mc,resolveProjectId as Uc,listWorkspaces as Wc}from"document360-engine";async function Zt(e,t){let n=Lc(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Uc(o);return{workspaces:await Wc(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var ui=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function er(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function _n(e,t,n,o,r){Mc(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function di(e,t,n){let o;try{o=await Zt(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=er(o.workspaces,t);return r?(_n(e,o.profile,o.projectId,r.id,r.name),console.log(A(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Et(e,t){let n;try{n=await Zt(e,t)}catch(g){console.log($(`Could not list workspaces: ${g.message}`));return}let{workspaces:o,projectId:r,profile:s,current:l}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===l?L("\u25CF"):" "} ${ui(g)} ${f(g.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Oc({message:"Select the Document360 workspace for this repo:",choices:o.map(g=>({name:`${ui(g)}${g.id===l?" (current)":""}`,value:g.id}))}),y=o.find(g=>g.id===p);_n(e,s,r,p,y?.name),console.log(A(`\u2713 Workspace set to "${y?.name??p}" for profile "${s}".`))}H();import{select as Fc}from"@inquirer/prompts";import{resolveActiveProfile as Hc,setProfileProject as qc,listProjects as Bc}from"document360-engine";async function Ge(e,t){let n=Hc(e,t),o={profile:n.name,connection:n.connection};return{projects:await Bc(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var pi=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function tr(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 On(e,t,n,o){qc(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function fi(e,t,n){let o;try{o=await Ge(e,n)}catch(s){return console.log($(`Could not list projects: ${s.message}`)),1}let r=tr(o.projects,t);return r?(On(e,o.profile,r.id,r.name),console.log(A(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log($(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Ln(e,t){let n;try{n=await Ge(e,t)}catch(y){console.log($(`Could not list projects: ${y.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 y of o)console.log(` ${y.id===s?L("\u25CF"):" "} ${pi(y)} ${f(y.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let l=await Fc({message:"Select the Document360 project for this repo:",choices:o.map(y=>({name:`${pi(y)}${y.id===s?" (current)":""}`,value:y.id}))}),p=o.find(y=>y.id===l);On(e,r,l,p?.name),console.log(A(`\u2713 Project set to "${p?.name??l}" for profile "${r}". Next: pick a workspace.`))}H();import Gc from"picocolors";function Yc(e=process.env){return e.FORCE_HYPERLINK==="0"||!Gc.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 Vc(e,t=e,n){return Yc(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var zc=/https?:\/\/[^\s\x1b]+/g;function en(e,t){return e.replace(zc,n=>Vc(n,n,t))}function yi(e){return{...mi(e.idToken)??{},...mi(e.accessToken)??{}}}function Un(e){let t=yi(e),n=t.email??t.preferred_username??t.sub??"unknown",o=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${n}${o}`}async function Wn(e){let t=Mn(process.cwd(),e.profile),n=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Xc(n,{manual:e.manual,promptForRedirect:s=>Kc({message:s})},s=>console.log(en(s))),r=hi(t.name,o);if(gi(r),await nr(r,t.name,s=>console.log(f(s))),console.log(""),console.log(A(`\u2713 Logged in to "${t.name}" as ${Un(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{nu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Et(process.cwd(),t.name))}catch{}}async function nr(e,t,n){let r=yi(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Mn(process.cwd(),t).project.projectId)return;let l;try{let{projects:p}=await Ge(process.cwd(),t);l=p.find(y=>y.id===r)?.name}catch{}tu(process.cwd(),t,{projectId:r,projectName:l}),n(` Project "${l??r}" written to profile "${t}".`)}catch{}}async function wi(e){let t=Mn(process.cwd(),e.profile),n=t.connection,o=eu(t.name);if(!o){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${L(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Un(o)}`),Zc(o))if(o.refreshToken)try{let r=hi(t.name,await Qc(n,o.refreshToken));gi(r),console.log(A(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(U(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(U("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function ki(e){let t=Mn(process.cwd(),e.profile);Jc(t.name)?console.log(A(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}H();import{readProjectConfig as bi,writeProjectConfig as ou,resolveActiveProfile as ru,loadTokens as su,isExpired as iu}from"document360-engine";function Fn(e){let t=bi(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?L("\u25CF "):" ",s=o.production?U(" \u26A0 PRODUCTION"):"",l=o.connection.environment??"(inline)",p=su(n),y=p?iu(p)&&!p.refreshToken?U("expired"):f("logged in"):f("not logged in");console.log(`${r}${L(n)} \u2192 ${l}${s} [${y}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Hn(e,t){let n=bi(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log($(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,ou(n,e);let o=n.profiles[t].production?U(" \u26A0 PRODUCTION"):"";console.log(A(`\u2713 Default profile is now "${t}"${o}`))}function qn(e,t){try{let n=ru(e,t);console.log(""),console.log(`Profile ${L(n.name)}${n.production?U(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}H();import{existsSync as au,readdirSync as lu,statSync as xi}from"node:fs";import{join as $i}from"node:path";import{apiLogDir as cu}from"document360-engine";function vi(){let e=cu();if(console.log(""),console.log(`Document360 API logs: ${L(e)}`),!au(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=lu(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(xi($i(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(xi($i(e,r)).size/1024).toFixed(1);console.log(` ${$(r)} ${f(`${s} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}H();import{createSession as uu,resolveAuth as du,findByName as pu,slugify as fu,touchSession as mu,upsertSession as hu,resolveActiveProfile as gu}from"document360-engine";async function Ci(e,t,n,o,r,s){let l=du(n);l.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),process.exit(2)),l.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=gu(e,r)}catch(x){console.error($(`Document360 profile error: ${x.message}`)),process.exit(2)}p.production&&(console.error(U(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let y;if(o){let x=pu(e,o);x||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),y=x.uuid,console.error(f(`Resuming "${x.name}"`))}let g=uu({cwd:e,resume:y,profileName:r,allowProdWrites:s===!0}),b=y??null,S=1;for await(let x of g.send(t))switch(x.type){case"session":if(!b){b=x.sessionId;let P=new Date().toISOString();hu({uuid:b,name:fu(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(ie(` \u2699 ${x.name}`));break;case"result":S=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($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${x.message}`)),process.exit(1)}b&&mu(b),process.stdout.write(`
|
|
192
|
-
`),process.exit(
|
|
185
|
+
`}function Ot(e){Yn(Ii(e)),Yn(Li(e)),Yn(ur(e));for(let n of[Ii(e),ur(e)]){let o=ju(n,".gitkeep");zn(o)||on(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
186
|
+
`)}zn(_i(e))||on(_i(e),Nu()),on(Xn(e),Ui());let t=_e(e);return Fi(e,new Date().toISOString()),t}async function Wi(e,t){for(let n of Mt(Ot(t.cwd)))console.log(n);return{kind:"continue"}}function ct(){return[`This is document360-writer's dev hand-off setup (v${re}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20134). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current \u2014 and SURFACE each hint drop in"," your reply (name the file + the one-line surface), never silently; NEVER write or publish the"," user-facing articles yourself (that is the docs agent's job \u2014 you only hand off); AND each session,"," check `.d360-writer/messages/` for open questions from the docs agent and answer them \u2014 all per"," `.d360-writer/DEV-HINTS-GUIDE.md`. If that section is already there, leave it (refine in place only if"," wrong) \u2014 do NOT add a duplicate. Then commit `.d360-writer/` and the memory-file change ONLY if"," something actually changed.","4. Two-way messages (Part 3): check `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each \u2014 fold durable facts into the architecture brief and/or drop"," a reply (`from: dev`, `kind: answer`, `re: <id>`) \u2014 then set the question's frontmatter `status: done`."," If there are none, continue.","5. Then STOP and ask me for tribal knowledge \u2014 present it as a clearly-marked, standalone prompt on its"," own line (NOT buried in prose) and WAIT for my reply before doing anything else. Use this shape:",' "\u23F8 YOUR INPUT NEEDED \u2014 Any tribal knowledge that would help document this product? (folder map,',` terminology, what to prioritize or skip, gotchas.) Type it below, or reply 'none' / 'carry on' to skip."`," If I give you anything, phrase it clearly and append it to `.d360-writer/architecture/CREATOR-NOTES.md`"," (keep the existing header comment and every note already there; only add). If I say 'none'/'carry on', continue.",`6. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${re},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","7. When everything is done, print the completion line, THEN the next command as its own copy-paste"," block so it is unmistakable. Pick the matching first line:",' \u2022 first-time setup: "\u2705 Setup complete. Now switch to the document360-writer terminal and paste this:"',' \u2022 a refresh (brief/notes already existed): "\u2705 Hand-off refreshed. Back in the document360-writer terminal, paste this:"'," Then, on its OWN line, fenced as a code block so it copies cleanly:"," ```"," write the docs for this repo"," ```"].join(`
|
|
187
|
+
`)}function dr(e){try{let t=Su(Mi(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Fi(e,t){let o={...dr(e)??{},emittedVersion:re,emittedAt:t};on(Mi(e),`${JSON.stringify(o,null,2)}
|
|
188
|
+
`)}function Lt(e){try{return Du(Li(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function _e(e){let n=dr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<re?"stale":"current",completedVersion:n}}function Kn(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:re};try{if(!zn(Xn(e)))return n;let o=dr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;re>r&&(Yn(ur(e)),on(Xn(e),Ui()),Fi(e,t),n.guideRefreshed=!0),re>s&&(Eu(e).some(p=>p.kind==="request"&&p.subject.startsWith(Oi))||(Au(e,{id:`onb${re}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Oi}${re})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${re}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",ct()].join(`
|
|
189
|
+
`)}),n.notifiedBuilder=!0))}catch{}return n}function Qn(e){if(!zn(Xn(e)))return[];let t=_e(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${re}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,_t,ct(),_t,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function pr(){return['document360-writer (its "docs agent") has been removed from this repository. Please undo its dev\u2192docs',"hand-off setup and restore this repo to how it was before \u2014 in order:","","1. In this repo's agent-memory file (CLAUDE.md, or AGENTS.md \u2014 whichever it edited), REMOVE the",' "Documentation hand-off" section that was added (the rule about dropping hint files in'," `.d360-writer/hints/`, keeping `.d360-writer/architecture/` current, and checking"," `.d360-writer/messages/`). Leave everything else in that file untouched.","2. The `.d360-writer/` folder is already deleted on disk. If it was committed, remove it from version"," control too \u2014 `git rm -r --cached .d360-writer` (if it still resolves) \u2014 and commit the deletions.","3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
|
|
190
|
+
`)}function Jn(){return['\u{1F9F9} One leftover: your builder still has the "Documentation hand-off" rule in its CLAUDE.md / AGENTS.md'," (reset only clears d360-writer's own .d360-writer/ folder \u2014 never your repo's files)."," To restore it, paste this prompt into your repo's coding agent (Claude Code / Codex / Cursor):",_t,pr(),_t]}function Mt(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${re}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",_t,ct(),_t,"","That one run writes the architecture brief, adds the ongoing rule to your agent memory (CLAUDE.md / AGENTS.md)","and commits it so teammates inherit it, answers any open questions the writer left, and asks you for tribal","knowledge \u2014 no manual file edits. It also sets up the two-way channel: the writer can ask you questions","(`/inbox` on its side), and you can ask it to document a session on demand (Part 4 of the guide).","","When it finishes, come back to THIS terminal and run:"," write the docs for this repo"]}var _t,re,Oi,ut=Ln(()=>{"use strict";_t="-".repeat(64),re=6;Oi="Re-run dev\u2194docs onboarding (protocol v"});var Qi={};hi(Qi,{initCommand:()=>mr,scaffoldInit:()=>fr});import{input as rn,confirm as Iu}from"@inquirer/prompts";import{basename as Hi,join as Zn}from"node:path";import{existsSync as Ut,readFileSync as _u,readdirSync as Ou,writeFileSync as Lu}from"node:fs";import{writeProjectConfig as qi,readProjectConfig as Mu,projectConfigPath as Bi,writerDir as Uu,DEFAULT_DOCS_DIR as Gi,DEFAULT_CAPTURE_DIR as Vi,DEFAULT_OUTPUT_DIR as Yi}from"document360-engine";function fr(e,t="berlin"){let n=Bi(e);if(Ut(n))return{created:!1,path:n,profileName:""};let o={projectId:Xi(e)??Hi(e),docsDir:Gi,captureDir:Vi,outputDir:Yi,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Ki(e)};return qi(o,e),zi(e),{created:!0,path:n,profileName:t}}function zi(e){let t=Zn(Uu(e),".gitignore");Ut(t)||Lu(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
191
|
+
`),"utf8")}async function mr(){let e=process.cwd(),t=Bi(e);if(Ut(t)&&!await Iu({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Xi(e)??Hi(e),o=await rn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await rn({message:"Capture directory (where document360-capture .spec.ts files live):",default:Vi}),s=await rn({message:"Screenshot output directory:",default:Yi}),l=await rn({message:"Default connection profile name:",default:"berlin"}),p=await rn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:Gi,captureDir:r,outputDir:s,profiles:{[l]:{connection:{environment:p},production:!1}},defaultProfile:l,authoritativeSourceFiles:Ki(e)},y=Mu(e);y?.terminologyGlossary&&(g.terminologyGlossary=y.terminologyGlossary),qi(g,e),zi(e);let k=Ot(e);console.log(""),console.log(N(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${L(`d360-writer login --profile ${l}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let j of Mt(k))console.log(j);return console.log(""),console.log(`${f("Then ask:")} ${L('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Xi(e){let t=Zn(e,"package.json");if(!Ut(t))return null;try{return JSON.parse(_u(t,"utf8")).name??null}catch{return null}}function Ki(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Ut(Zn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Zn(e,n);Ut(o)&&!Wu(o)&&t.push(n)}return t}function Wu(e){try{return Ou(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var eo=Ln(()=>{"use strict";H();ut()});var Xa={};hi(Xa,{doctorCommand:()=>pn,renderDoctorChecks:()=>za,runDoctorChecks:()=>Ya});import{existsSync as vp}from"node:fs";import{d360GetAll as Cp,getAccessToken as Pp,isExpired as as,loadProfileMap as Rp,loadTokens as Tp,packageSkillsDir as Ga,projectConfigPath as Sp,readProjectConfig as Dp,DEFAULT_DOCS_DIR as jp,fetchManifestSummary as Ap,resolveActiveProfile as Ep,classifyClaudeAuth as Np,CLAUDE_CODE_SETUP_HINT as Va,resolveModelSetting as Ip,probeModel as _p,detectAppType as Op,playbookSkillName as Lp,D360AuthError as Mp}from"document360-engine";async function Ya(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=Np();o.state==="ready"?t.push({level:"ok",label:`Claude auth: ${o.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):o.state==="maybe"?t.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${Va}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Va});let r=Ip(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let P=await _p(e,r.model??void 0);P.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(P.latencyMs/1e3).toFixed(1)}s`}):P.timedOut?t.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):t.push({level:"fail",label:`Model call failed \u2014 ${P.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let s=Dp(e);if(!s)return t.push({level:"fail",label:`No ${Sp(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let l=(s.docsDir??jp).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 ${l}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let g=s.appType??Op(e);if(g){let P=s.appType?"from config":"auto-detected",C=g==="web"||g==="cli";t.push({level:"ok",label:`Genre: ${g} (${P})${C?` \u2192 ${Lp(g)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else t.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let y;try{y=Ep(e),t.push({level:"ok",label:`Profile: ${y.name} (${y.connection.name})${y.production?" \u26A0 PRODUCTION":""}`})}catch(P){return t.push({level:"fail",label:`Profile config: ${P.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=Tp(y.name);k?as(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):as(k)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(k.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${y.name})`}),t.push(y.project.workspaceId?{level:"ok",label:`Workspace: ${y.project.workspaceName??y.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let j=Rp(e,y.name);j?j.projectId&&y.project.projectId&&j.projectId!==y.project.projectId?t.push({level:"fail",label:`Category map projectId (${j.projectId}) \u2260 profile projectId (${y.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(j.articles).length} articles, ${Object.keys(j.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${y.name}" (created on first /publish)`}),t.push(vp(Ga())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Ga()}`,fix:"Reinstall document360-writer (broken install)"});let x=_e(e);if(x.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${re})`}):x.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${x.completedVersion}, current is v${re}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!as(k)||k.refreshToken)){let P={profile:y.name,connection:y.connection};try{await Pp(P);let E=await Cp(P,"/v3/projects");t.push({level:"ok",label:`API reachable (${y.connection.apiUrl}) \u2014 ${E.length} project(s) visible`})}catch(E){t.push({level:"fail",label:`API call failed: ${E.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let C=j?.projectId??y.project.projectId;if(C&&y.project.workspaceId)try{let E=await Ap(P,C,y.project.workspaceId);if(E){let I=(E.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${y.connection.name} (${E.languages?.length??0} language${(E.languages?.length??0)===1?"":"s"}) \xB7 hash ${I||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${y.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(E){E instanceof Mp||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(E.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${y.project.projectName??C})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):t.push({level:"warn",label:`Workspace sync manifest: probe failed (${E.message.slice(0,80)})`})}}return t}function za(e){let t=[""];for(let r of e){let s=r.level==="ok"?N("\u2713"):r.level==="warn"?U("\u26A0"):$("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${L(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?N(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function pn(e,t){console.log(f("Running checks\u2026"));for(let n of za(await Ya(t.cwd)))console.log(n);return{kind:"continue"}}var po=Ln(()=>{"use strict";ut();H()});import{Command as _h}from"commander";import{createRequire as Oh}from"node:module";import{AUTH_MODES as Lh}from"document360-engine";import{input as ru}from"@inquirer/prompts";import{loginPkce as su,refreshTokens as iu,toStoredTokens as $i,clearTokens as au,decodeJwtClaims as xi,isExpired as lu,loadTokens as cu,saveTokens as vi,resolveActiveProfile as Fn,setProfileProject as uu,readProjectConfig as du}from"document360-engine";H();import{select as Gc}from"@inquirer/prompts";import{resolveActiveProfile as Vc,setProfileProject as Yc,resolveProjectId as zc,listWorkspaces as Xc}from"document360-engine";async function tn(e,t){let n=Vc(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??zc(o);return{workspaces:await Xc(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var yi=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function sr(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function Mn(e,t,n,o,r){Yc(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function wi(e,t,n){let o;try{o=await tn(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=sr(o.workspaces,t);return r?(Mn(e,o.profile,o.projectId,r.id,r.name),console.log(N(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function It(e,t){let n;try{n=await tn(e,t)}catch(y){console.log($(`Could not list workspaces: ${y.message}`));return}let{workspaces:o,projectId:r,profile:s,current:l}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let y of o)console.log(` ${y.id===l?L("\u25CF"):" "} ${yi(y)} ${f(y.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Gc({message:"Select the Document360 workspace for this repo:",choices:o.map(y=>({name:`${yi(y)}${y.id===l?" (current)":""}`,value:y.id}))}),g=o.find(y=>y.id===p);Mn(e,s,r,p,g?.name),console.log(N(`\u2713 Workspace set to "${g?.name??p}" for profile "${s}".`))}H();import{select as Kc}from"@inquirer/prompts";import{resolveActiveProfile as Qc,setProfileProject as Jc,listProjects as Zc}from"document360-engine";async function Ve(e,t){let n=Qc(e,t),o={profile:n.name,connection:n.connection};return{projects:await Zc(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ki=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function ir(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 Un(e,t,n,o){Jc(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function bi(e,t,n){let o;try{o=await Ve(e,n)}catch(s){return console.log($(`Could not list projects: ${s.message}`)),1}let r=ir(o.projects,t);return r?(Un(e,o.profile,r.id,r.name),console.log(N(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log($(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Wn(e,t){let n;try{n=await Ve(e,t)}catch(g){console.log($(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===s?L("\u25CF"):" "} ${ki(g)} ${f(g.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let l=await Kc({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${ki(g)}${g.id===s?" (current)":""}`,value:g.id}))}),p=o.find(g=>g.id===l);Un(e,r,l,p?.name),console.log(N(`\u2713 Project set to "${p?.name??l}" for profile "${r}". Next: pick a workspace.`))}H();import eu from"picocolors";function tu(e=process.env){return e.FORCE_HYPERLINK==="0"||!eu.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 nu(e,t=e,n){return tu(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var ou=/https?:\/\/[^\s\x1b]+/g;function nn(e,t){return e.replace(ou,n=>nu(n,n,t))}function Ci(e){return{...xi(e.idToken)??{},...xi(e.accessToken)??{}}}function Hn(e){let t=Ci(e),n=t.email??t.preferred_username??t.sub??"unknown",o=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${n}${o}`}async function qn(e){let t=Fn(process.cwd(),e.profile),n=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await su(n,{manual:e.manual,promptForRedirect:s=>ru({message:s})},s=>console.log(nn(s))),r=$i(t.name,o);if(vi(r),await ar(r,t.name,s=>console.log(f(s))),console.log(""),console.log(N(`\u2713 Logged in to "${t.name}" as ${Hn(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{du(process.cwd())?.profiles?.[t.name]&&(console.log(""),await It(process.cwd(),t.name))}catch{}}async function ar(e,t,n){let r=Ci(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Fn(process.cwd(),t).project.projectId)return;let l;try{let{projects:p}=await Ve(process.cwd(),t);l=p.find(g=>g.id===r)?.name}catch{}uu(process.cwd(),t,{projectId:r,projectName:l}),n(` Project "${l??r}" written to profile "${t}".`)}catch{}}async function Pi(e){let t=Fn(process.cwd(),e.profile),n=t.connection,o=cu(t.name);if(!o){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${L(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Hn(o)}`),lu(o))if(o.refreshToken)try{let r=$i(t.name,await iu(n,o.refreshToken));vi(r),console.log(N(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(U(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(U("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function Ri(e){let t=Fn(process.cwd(),e.profile);au(t.name)?console.log(N(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}H();import{readProjectConfig as Ti,writeProjectConfig as pu,resolveActiveProfile as fu,loadTokens as mu,isExpired as hu}from"document360-engine";function Bn(e){let t=Ti(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?L("\u25CF "):" ",s=o.production?U(" \u26A0 PRODUCTION"):"",l=o.connection.environment??"(inline)",p=mu(n),g=p?hu(p)&&!p.refreshToken?U("expired"):f("logged in"):f("not logged in");console.log(`${r}${L(n)} \u2192 ${l}${s} [${g}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Gn(e,t){let n=Ti(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log($(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,pu(n,e);let o=n.profiles[t].production?U(" \u26A0 PRODUCTION"):"";console.log(N(`\u2713 Default profile is now "${t}"${o}`))}function Vn(e,t){try{let n=fu(e,t);console.log(""),console.log(`Profile ${L(n.name)}${n.production?U(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}H();import{existsSync as gu,readdirSync as yu,statSync as Si}from"node:fs";import{join as Di}from"node:path";import{apiLogDir as wu}from"document360-engine";function ji(){let e=wu();if(console.log(""),console.log(`Document360 API logs: ${L(e)}`),!gu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=yu(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Si(Di(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Si(Di(e,r)).size/1024).toFixed(1);console.log(` ${$(r)} ${f(`${s} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}H();import{createSession as ku,resolveAuth as bu,findByName as xu,slugify as $u,touchSession as vu,upsertSession as Cu,resolveActiveProfile as Pu}from"document360-engine";async function Ai(e,t,n,o,r,s){let l=bu(n);l.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),process.exit(2)),l.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Pu(e,r)}catch(x){console.error($(`Document360 profile error: ${x.message}`)),process.exit(2)}p.production&&(console.error(U(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let g;if(o){let x=xu(e,o);x||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),g=x.uuid,console.error(f(`Resuming "${x.name}"`))}let y=ku({cwd:e,resume:g,profileName:r,allowProdWrites:s===!0}),k=g??null,j=1;for await(let x of y.send(t))switch(x.type){case"session":if(!k){k=x.sessionId;let P=new Date().toISOString();Cu({uuid:k,name:$u(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(ie(` \u2699 ${x.name}`));break;case"result":j=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($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${x.message}`)),process.exit(1)}k&&vu(k),process.stdout.write(`
|
|
192
|
+
`),process.exit(j)}import{createInterface as Kf}from"node:readline/promises";import{createSession as js,resolveAuth as Qf,getSession as Jf,setTitle as Zf,slugify as em,touchSession as jl,upsertSession as tm,generateTitle as nm,resolveActiveProfile as Al,resolveModelSetting as om,readProjectConfig as rm,resolveAndPersistAppType as sm,decodeJwtClaims as Sl,isExpired as im,loadTokens as am}from"document360-engine";var Re=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --all to author capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then run d360-capture in your app's repo \u2014 it signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot --list",s:"See capture status \u2014 which specs exist and which are done."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"d360-capture is a separate Playwright CLI \u2014 run it in the app's repo (needs its URL + a login)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"Author capture specs (--all / --list)."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function Ru(e){switch(e.t){case"head":return e.s;case"text":return` ${e.s}`;case"dim":return` ${e.s}`;case"sub":return e.s;case"good":return` ${e.s}`;case"step":return` ${e.n}. ${e.s}`;case"cmd":return` ${e.name.padEnd(20)} ${e.s}`;case"gap":return""}}function Ei(){let e=["document360-writer \u2014 help",""];for(let t of Re){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push(Ru(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function lr(){console.log("");for(let e of Ei())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}H();import{getSession as Tu}from"document360-engine";async function Ni(e,t){let n=t.currentUuid(),o=n?Tu(n):void 0;return console.log(o?f(`
|
|
193
193
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
194
194
|
`):f(`
|
|
195
195
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
196
|
-
`)),{kind:"clear"}}async function
|
|
196
|
+
`)),{kind:"clear"}}async function cr(){return{kind:"exit"}}eo();H();import{readMcpConfig as hr,writeMcpConfig as Ji}from"document360-engine";async function to(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Fu(),{kind:"continue"}):t==="add"?(Hu(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(qu(e.slice(1)),{kind:"continue"}):(console.log($(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Fu(){let e=hr(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
|
|
197
197
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
198
|
-
`));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(` ${L(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(` ${L(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function
|
|
199
|
-
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(
|
|
200
|
-
`)}),W=Math.max(...I.map(fe=>fe.length)),J=[];for(let fe=0;fe<W;fe++)J.push(p.map((oe,
|
|
201
|
-
`)},P=[
|
|
202
|
-
`)}function
|
|
203
|
-
`);return
|
|
204
|
-
|
|
205
|
-
`)
|
|
206
|
-
`);case"table":return
|
|
207
|
-
|
|
208
|
-
`)}H();import
|
|
209
|
-
`);let r=2,s=3,l=
|
|
210
|
-
`);let
|
|
211
|
-
`)}var
|
|
212
|
-
`).flatMap(
|
|
213
|
-
`)),
|
|
214
|
-
`+p.map((
|
|
198
|
+
`));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(` ${L(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(` ${L(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Hu(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log($("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log($(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=hr(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let l={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let g=o[++p],y=g?.match(/^([^:=]+)[:=](.+)$/);if(!y){console.log($(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}l[y[1].trim()]=y[2].trim()}else{console.log($(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(l).length>0?l:void 0}}r.servers[t]=s,Ji(r),console.log(""),console.log(N(`\u2713 Registered "${t}" (${n})`)),console.log(U(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function qu(e){let t=e[0];if(!t){console.log($("Usage: /mcp remove <name>"));return}let n=hr();if(!n.servers[t]){console.log($(`No server named "${t}".`));return}delete n.servers[t],Ji(n),console.log(N(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}H();import{readFileSync as rd}from"node:fs";import{join as sd}from"node:path";import{select as id}from"@inquirer/prompts";import{computeSyncStatus as Cr,planPartitions as ad,relatedArticlePaths as ld,resolveModelForOperation as cd,runPartitioned as ud,loadProfileMap as dd,resolveActiveProfile as pd,resolveCrossLinks as fd,applyStructureOrder as la,orderSyncLine as ca,applyRelatedArticles as ua,relatedSyncLine as da}from"document360-engine";import X from"picocolors";import ra from"wrap-ansi";import xr from"string-width";H();import Ye from"picocolors";import gr from"wrap-ansi";import yr from"string-width";var Zi=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),ea=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),ta=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Bu(e){let t=e.replace(/\r/g,"").split(`
|
|
199
|
+
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(Zi(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&ea(t[o+1])){let p=ta(r);o+=2;let g=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)g.push(ta(t[o++]));n.push({kind:"table",header:p,rows:g});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let g=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(g),text:g.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let l=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Zi(t[o])&&!(t[o].includes("|")&&o+1<t.length&&ea(t[o+1]));)l.push(t[o++]);n.push({kind:"para",text:l.join(" ")})}return n}function wr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ye.bold(t.slice(2,-2)):t.startsWith("`")?L(t.slice(1,-1)):Ye.italic(t.slice(1,-1)))}var Gu=(e,t)=>e+" ".repeat(Math.max(0,t-yr(e)));function Vu(e,t,n){let o=e.length,r=e.map((C,E)=>Math.max(yr(C),...t.map(I=>yr(I[E]??"")))),s=Math.max(24,n),l=3*o+1,p=[...r],g=()=>p.reduce((C,E)=>C+E,0)+l,y=0;for(;g()>s&&y++<1e4;){let C=-1,E=6;for(let I=0;I<o;I++)p[I]>E&&(E=p[I],C=I);if(C===-1)break;p[C]-=1}let k=(C,E,I)=>Ye.gray(C+p.map(W=>"\u2500".repeat(W+2)).join(E)+I),j=Ye.gray("\u2502"),x=(C,E)=>{let I=p.map((fe,oe)=>{let Se=C[oe]??"",ue=E?Ye.bold(Se):wr(Se);return gr(ue,fe,{hard:!0}).split(`
|
|
200
|
+
`)}),W=Math.max(...I.map(fe=>fe.length)),J=[];for(let fe=0;fe<W;fe++)J.push(p.map((oe,Se)=>`${j} ${Gu(I[Se][fe]??"",oe)} `).join("")+j);return J.join(`
|
|
201
|
+
`)},P=[k("\u250C","\u252C","\u2510"),x(e,!0)];return P.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((C,E)=>{P.push(x(C,!1)),P.push(E===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),P.join(`
|
|
202
|
+
`)}function Yu(e,t){switch(e.kind){case"heading":return Ye.bold(e.text);case"hr":return Ye.gray("\u2500".repeat(t));case"para":return gr(wr(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",s=" ".repeat(2+r.length+1),[l="",...p]=gr(wr(o.text),Math.max(10,t-s.length)).split(`
|
|
203
|
+
`);return` ${r} ${l}`+p.map(g=>`
|
|
204
|
+
${s}${g}`).join("")}).join(`
|
|
205
|
+
`)}case"code":return e.lines.map(n=>Ye.gray(" "+n)).join(`
|
|
206
|
+
`);case"table":return Vu(e.header,e.rows,t)}}function kr(e,t){let n=Math.max(20,t);return Bu(e).map(o=>Yu(o,n)).join(`
|
|
207
|
+
|
|
208
|
+
`)}H();import zu from"picocolors";var Xu=[127,86,217],Ku=[22,38,43],na={T:Xu,E:Ku},sn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],br=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Qu=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function oa(){if(!zu.isColorSupported)return[];let e=sn[0].length,t=[];for(let n=0;n<sn.length;n+=2){let o="";for(let r=0;r<e;r++){let s=na[sn[n][r]],l=n+1<sn.length?na[sn[n+1][r]]:void 0;s&&l?o+=`${br(s)}${Qu(l)}\u2580\x1B[49m\x1B[39m`:s?o+=`${br(s)}\u2580\x1B[39m`:l?o+=`${br(l)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function an(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function he(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function ze(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Wt=(e,t)=>` ${e.padEnd(13)}${t}`;function Ju(e,t){let n=[en("\u270E document360-writer")+X.gray(` v${e.version}`),X.gray(" Reads your code, writes your docs."),"",Wt("Claude:",`${e.claude}${X.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Wt("Document360:",e.configured?e.loggedOut?X.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?X.gray(` (${e.sessionHint})`):""}`:X.yellow("not set up \u2014 run /init")),Wt("Profile:",e.configured?`${e.profile}${X.gray(` (${e.apiUrl})`)}${e.prod?X.bold(X.yellow(" \u26A0 PRODUCTION")):""}`:X.gray("\u2014 (run /init)")),Wt("Project:",e.project),Wt("Mode:",X.gray(e.mode)),Wt("cwd:",X.gray(e.cwd))],o=oa();if(o.length===0)return n.join(`
|
|
209
|
+
`);let r=2,s=3,l=xr(o[0]);if(!(t>=r+l+s+Math.max(...n.map(k=>xr(k)))))return[...o.map(k=>" "+k),...n].join(`
|
|
210
|
+
`);let g=Math.max(0,Math.floor((n.length-o.length)/2)),y=[];for(let k=0;k<Math.max(o.length+g,n.length);k++){let j=o[k-g]??" ".repeat(l);y.push((" ".repeat(r)+j+" ".repeat(s)+(n[k]??"")).trimEnd())}return y.join(`
|
|
211
|
+
`)}var Zu={error:X.red,warn:X.yellow,ok:X.green,info:X.gray};function $r(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Ju(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),l=50,p=e.text.split(`
|
|
212
|
+
`).flatMap(y=>ra(y,s,{hard:!0}).split(`
|
|
213
|
+
`)),g=Math.max(0,p.length-l);return g>0&&(p=[...p.slice(0,l),X.dim(`\u2026 +${g} more lines`)]),`
|
|
214
|
+
`+p.map((y,k)=>o+(k===0?L(" \u276F "):" ")+y+" ".repeat(Math.max(0,s-xr(y))+1)+r).join(`
|
|
215
215
|
`)}case"assistant":return`
|
|
216
|
-
`+
|
|
217
|
-
`+
|
|
218
|
-
`)}case"diff":{let o=l=>l===1?"":"s",s=[
|
|
219
|
-
`)}case"link":return e.lines.map(o=>L(
|
|
216
|
+
`+kr(e.text,n);case"tool":{let o=e.arg!==null?X.gray(`${e.sep}(${e.arg})`):"";return`
|
|
217
|
+
`+ra(X.green("\u25CF ")+X.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?X.red:X.gray,r=e.lines.map((s,l)=>o((l===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(X.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
218
|
+
`)}case"diff":{let o=l=>l===1?"":"s",s=[X.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(X.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
|
|
219
|
+
`)}case"link":return e.lines.map(o=>L(nn(` \u2B95 ${o}`))).join(`
|
|
220
220
|
`);case"preview":return`
|
|
221
|
-
`+
|
|
222
|
-
|
|
223
|
-
`+
|
|
224
|
-
`+
|
|
225
|
-
`+(e.ok?
|
|
226
|
-
`)}import{resolveActiveProfile as
|
|
227
|
-
`)}var
|
|
228
|
-
`)}function
|
|
229
|
-
`),display:"/audit"}}H();import{checkbox as
|
|
221
|
+
`+en(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
222
|
+
|
|
223
|
+
`+kr(e.text,n);case"note":return`
|
|
224
|
+
`+Zu[e.tone](nn(e.text));case"done":return`
|
|
225
|
+
`+(e.ok?X.magenta("\u2736 "):X.red("\u2736 "))+X.gray(`Cooked for ${an(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${he(e.costUsd)}`:""))}}function sa(e,t){return e.map(n=>$r(n,t)).join(`
|
|
226
|
+
`)}import{resolveActiveProfile as ed,loadTokens as td,isExpired as nd,decodeJwtClaims as ia}from"document360-engine";function od(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Oe(e,t){try{let n=ed(e,t),o=td(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(nd(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let l={...ia(o.idToken)??{},...ia(o.accessToken)??{}}.doc360_project_id;if(typeof l=="string"&&l&&l!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${od(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var ln=3;function Pr(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(`
|
|
227
|
+
`)}var aa={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function cn(e){return e.filter(t=>t.path!==null&&t.status in aa&&!t.link).map(t=>({path:t.path,label:aa[t.status]}))}function no(e){return e.filter(t=>t.link).length}function Rr(e,t){try{let n=dd(e,pd(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=fd(rd(sd(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages not published yet \u2014 they show as plain text for now and turn into live links once those pages are published.`}catch{return null}}function md(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=t.replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}function pa(e){let t=[];e.length>1&&t.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(o=>o.path),indent:!1});let n=new Map;for(let o of e){let r=o.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),s=n.get(r);s?s.push(o):n.set(r,[o])}for(let o of[...n.keys()].sort()){let r=n.get(o).sort((s,l)=>s.path.localeCompare(l.path));t.push({kind:"category",label:`${md(o)} (${r.length})`,paths:r.map(s=>s.path),indent:!1});for(let s of r){let l=s.path.replace(/\\/g,"/").split("/").pop()??s.path;t.push({kind:"article",label:l,paths:[s.path],indent:!0,note:s.label})}}return t}function oo(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(`
|
|
228
|
+
`)}function Tr(e,t,n){let o=x=>t[x.index]?.paths.length??0,r=e.filter(x=>x.ok),s=e.filter(x=>!x.ok),l=e.reduce((x,P)=>x+o(P),0),p=r.reduce((x,P)=>x+o(P),0),g=n==="api"?`${he(e.reduce((x,P)=>x+P.costUsd,0))} total`:ze(e.reduce((x,P)=>x+P.outputTokens,0)),y=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,k=x=>`${x} article${x===1?"":"s"}`,j=[];if(s.length===0)j.push(`Published ${k(l)} (${y}) successfully \xB7 ${g}.`),j.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{j.push(`Published ${p}/${k(l)} (${y}) \xB7 ${g}.`),j.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let x of s)j.push(` \u2717 ${x.label}${x.error?` \u2014 ${x.error}`:""}`)}return j}async function vr(e,t){let n=ad(t),{model:o}=cd(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${ln} agents at once) on ${o}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let r of ud({cwd:e.cwd,partitions:n,promptFor:s=>oo(s.paths),concurrency:ln,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:o}))if(r.type==="partition_status")r.status==="running"?console.log(f(` \u25B8 ${r.label} \u2014 publishing\u2026`)):r.status==="done"?console.log(N(` \u2713 ${r.label}`)):console.log($(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let s=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of Tr(r.results,n,s))console.log(r.ok?N(p):U(p));let l=Rr(e.cwd,e.profileName);l&&console.log(f(l));try{let p=ca(await la({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}try{let p=da(await ua({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}}}catch(r){console.log($(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function ro(e,t,n){let o=ld(e,n);if(o.length===0)return[];let r=new Set(cn((await Cr({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function fa(e,t){let n=Oe(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await ro(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(N("\u2713 All related articles are already published.")),{kind:"continue"}):await vr(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await Cr({cwd:t?.cwd??process.cwd()}),s=cn(r.entries),l=no(r.entries);if(l>0&&console.log(U(`\u26A0 ${l} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),s.length===0){if(console.log(N(l>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let p=ca(await la({cwd:t.cwd,profileName:t.profileName}));p&&console.log(f(p));let g=da(await ua({cwd:t.cwd,profileName:t.profileName}));g&&console.log(f(g))}catch{}return{kind:"continue"}}return t?await vr(t,s.map(p=>p.path)):{kind:"forward-to-agent",prompt:oo(s.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log($(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let s=await Cr({cwd:t?.cwd??process.cwd()});r=cn(s.entries);let l=no(s.entries);l>0&&console.log(U(`\u26A0 ${l} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`))}catch(s){return console.log($(`Could not compute sync status: ${s.message}`)),console.log(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(N("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(f(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${f(`(${s.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>id({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await vr(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Pr(o),display:`/publish ${o}`}}async function un(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
|
|
229
|
+
`),display:"/audit"}}H();import{checkbox as hd}from"@inquirer/prompts";import{inventoryRepo as gd,readProjectConfig as ma,writeProjectConfig as yd}from"document360-engine";function Sr(e,t){let n=ma(e);n&&(n.authoritativeSourceFiles=t,yd(n,e))}function so(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 ha(e,t){let n=t?.cwd??process.cwd();if(!ma(n))return console.log($("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=gd(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(L("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(so(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>hd({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${so(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"};Sr(n,r),console.log(N(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}H();import{confirm as vd}from"@inquirer/prompts";import{applyPull as jr,computeSyncStatus as ba,compareRemoteSources as Cd,planPull as xa,planImport as Pd,applyImport as Rd,establishBaselines as Td,rebaselineServerMeta as Sd,D360AuthError as Dd}from"document360-engine";H();var ga=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:$,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:U,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:L,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:$,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:$,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ie,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:f,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:f,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:ie,mark:"\xB7"}];function wd(e){return e.path?e.path:`${e.title??"(untitled)"} ${ie(`[${e.articleId}]`)}`}function kd(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60);return`${n}m ${Math.round(t-n*60)}s`}function io(e,t){let n=[],o=e.entries.filter(k=>k.link);if(o.length>0){n.push(""),n.push(Pe("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let k of o)n.push(` ${U("~")} ${U(k.path??"")} ${ie(`\u2192 "${k.link.title}"`)}`)}for(let k of ga){let j=e.entries.filter(x=>x.status===k.status&&!(k.status==="untracked-local"&&x.link));if(j.length!==0){n.push(""),n.push(Pe(k.header));for(let x of j)n.push(` ${k.paint(k.mark)} ${k.paint(wd(x))}${x.detail?ie(` (${x.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let l={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},p=o.length,g=s===r?N("\u2713 everything up to date"):[r>0?N(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...ga.map(k=>{let j=(e.counts[k.status]??0)-(k.status==="untracked-local"?p:0);return j>0?`${j} ${l[k.status]}`:null})].filter(Boolean).join(ie(" \xB7 ")),y=t!==void 0?` \xB7 synced in ${kd(t)}`:"";return n.push(g+ie(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${y}`)),n}import{structuredPatch as bd}from"diff";import ya from"picocolors";var wa=80,xd="\x1B[48;2;74;28;28m",$d="\x1B[48;2;24;66;24m",ka="\x1B[49m",Dr=e=>String(e).padStart(5);function dt(e,t,n){let o=x=>{let P=x.replace(/\r\n/g,`
|
|
230
230
|
`);return P.endsWith(`
|
|
231
231
|
`)||P===""?P:P+`
|
|
232
|
-
`},r=o(e),s=o(t);if(r===s)return null;let l=Math.max(20,n-10),p=
|
|
232
|
+
`},r=o(e),s=o(t);if(r===s)return null;let l=Math.max(20,n-10),p=bd("a","b",r,s,"","",{context:3}),g=0,y=0,k=[];p.hunks.forEach((x,P)=>{P>0&&k.push(ya.gray(" \u2026"));let C=x.oldStart,E=x.newStart;for(let I of x.lines){let W=I[0],J=I.slice(1).slice(0,l);W==="-"?(y++,k.push(`${xd}${Dr(C++)} - ${J}${ka}`)):W==="+"?(g++,k.push(`${$d}${Dr(E++)} + ${J}${ka}`)):(k.push(ya.gray(Dr(E))+" "+J),C++,E++)}});let j=k.slice(0,wa);return{added:g,removed:y,lines:j,hidden:Math.max(0,k.length-wa)}}async function $a(e,t){let n=Oe(t.cwd,t.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await jd(t),{kind:"continue"};if(o==="--baseline")return await Ad(t,e.filter(l=>l!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Ed(t),{kind:"continue"};if(o)return console.log($(`Unknown option: ${o}`)),console.log(f("Usage: /pull pull portal edits + import new portal articles")),console.log(f(" /pull <path> pull one article (or resolve a conflict)")),console.log(f(" /pull --status drift report only (no writes)")),console.log(f(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Nd(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await Ar({cwd:t.cwd,profileName:t.profileName});for(let l of Er(s))console.log(l.tone==="ok"?N(l.text):l.tone==="warn"?U(l.text):f(l.text));console.log("")}catch(r){r instanceof Dd?console.log($(r.message)):console.log($(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Ar(e){let t=await ba({cwd:e.cwd,profileName:e.profileName}),n={pulled:[],imported:[],conflicts:[],toPublish:0,failed:[]};for(let o of t.entries)if(o.status==="remote-ahead"&&o.path)try{let r=await xa({cwd:e.cwd,profileName:e.profileName,relPath:o.path});jr({cwd:e.cwd,profileName:e.profileName},r),n.pulled.push(o.path)}catch(r){n.failed.push({ref:o.path,error:r.message})}else if(o.status==="untracked-remote"&&o.articleId)try{let r=await Pd({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Rd({cwd:e.cwd,profileName:e.profileName},r),n.imported.push({title:r.title,path:r.path})}catch(r){n.failed.push({ref:o.title??o.articleId,error:r.message})}else o.status==="conflict"&&o.path?n.conflicts.push(o.path):(o.status==="local-ahead"||o.status==="untracked-local"&&!o.link)&&o.path&&n.toPublish++;return n}var ao=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,pt=e=>e===1?"":"s";function Er(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${pt(e.pulled.length)} into local: ${ao(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${pt(e.imported.length)}: ${ao(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${pt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${pt(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Take the portal copy: /pull <path> \xB7 keep yours: /publish <path>. (${ao(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${pt(e.failed.length)} failed: ${ao(e.failed.map(n=>n.ref))}`}),t.length===0&&t.push({tone:"ok",text:"\u2713 Already in sync with Document360 \u2014 nothing to pull."}),t}async function jd(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await ba({cwd:e.cwd,profileName:e.profileName});for(let o of io(n,Date.now()-t))console.log(o);console.log("")}async function Ad(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(f(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Td({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Sd({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(N("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(N(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(N(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(U(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(f(` - ${s.path} (${s.reason})`))}}async function Ed(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Cd({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Pe(String(t.legacyCount))} \xB7 Manifest: ${Pe(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(N("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log($(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(U(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(U(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(f(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Nd(e,t){let n=t.replace(/\\/g,"/"),o=await xa({cwd:e.cwd,profileName:e.profileName,relPath:n});console.log(""),console.log(`${L("\u25CF")} ${Pe(o.title)} ${ie(`(${o.path})`)}`);for(let l of o.notes)console.log(U(` \u26A0 ${l}`));o.overwritesLocalChanges&&console.log(U(" \u26A0 This OVERWRITES local edits made since the last sync."));let r=dt(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(f(" Local file already matches the remote content \u2014 advancing the sync base only.")),jr({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ie(` \u23BF Added ${r.added} line${pt(r.added)}, removed ${r.removed} line${pt(r.removed)}`));for(let l of r.lines)console.log(l);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>vd({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}jr({cwd:e.cwd,profileName:e.profileName},o),console.log(N(` \u2713 Pulled ${o.path} (sync base advanced).`))}H();import{statSync as Id}from"node:fs";import{resolve as _d}from"node:path";import{estimateBulkCost as Od,planPartitions as Ld,readProjectConfig as Md,resolveModelForOperation as Ud,runPartitioned as Wd,trackedArticlePaths as Fd}from"document360-engine";var Nr=3;function Ir(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 _r(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Or(e,t){return t.map(n=>{let o=0;try{o=Id(_d(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Lr(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:
|
|
233
233
|
- 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.
|
|
234
234
|
- 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.
|
|
235
235
|
- 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.
|
|
236
236
|
- Work only on these files:
|
|
237
237
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
238
|
-
`)}function
|
|
238
|
+
`)}function Mr(e,t,n){let o=e.reduce((p,g)=>p+g.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${he(r)}\u2013${he(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Ur(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),l=e.reduce((C,E)=>C+o(E),0),p=r.reduce((C,E)=>C+o(E),0),g=e.reduce((C,E)=>C+E.costUsd,0),y=e.reduce((C,E)=>C+E.outputTokens,0),k=n==="api"?`${he(g)} total`:ze(y),j=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Converted ${x(l)} (${j}) successfully \xB7 ${k}.`);else{P.push(`Converted ${p}/${x(l)} (${j}) \xB7 ${k}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}async function va(e,t){if(!Md(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Ir(e),r=Fd(t.cwd,t.profileName);if(r.length===0)return console.log($("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=_r(r,n);if(s.length===0)return console.log($(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let l=Ld(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:g,forced:y}=Ud(t.cwd,"light");if(!o){let k=Od({files:Or(t.cwd,s),op:"convert",model:g});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let j of Mr(l,k,Nr))console.log(j);return console.log(f(`Model: ${g}${y?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${l.length} partitions (\u2264${Nr} agents at once) on ${g}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let k of Wd({cwd:t.cwd,partitions:l,promptFor:Lr,concurrency:Nr,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:g}))if(k.type==="partition_status")k.status==="running"?console.log(f(` \u25B8 ${k.label} \u2014 converting\u2026`)):k.status==="done"?console.log(N(` \u2713 ${k.label}`)):console.log($(` \u2717 ${k.label}`));else if(k.type==="run_done"){console.log("");let j=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let x of Ur(k.results,l,j))console.log(k.ok?N(x):U(x))}}catch(k){console.log($(`Convert run failed: ${k.message}`))}return console.log(""),{kind:"continue"}}H();import{statSync as Ra}from"node:fs";import{resolve as Ta}from"node:path";import{estimateBulkCost as Kd,lintDocs as Qd,planPartitions as Jd,readDocsPlan as Zd,readProjectConfig as Sa,DEFAULT_DOCS_DIR as ep,resolveModelForOperation as tp,runPartitioned as np}from"document360-engine";import{readProjectConfig as Hd,loadProfileMap as qd,resolveActiveProfile as Bd,desiredCategoryOrder as Gd,desiredArticleOrder as Vd,DEFAULT_DOCS_DIR as Yd}from"document360-engine";var Wr=e=>e.replace(/\\/g,"/"),zd=e=>Wr(e).split("/").pop()??e;function Xd(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function Fr(e,t){try{let n=Hd(e);if(!n)return[];let o=Bd(e,t),r=qd(e,o.name);if(!r)return[];let s=Wr(n.docsDir??Yd).replace(/\/+$/,""),l=new Map;for(let g of Vd(r))l.set(g.categoryPath,(l.get(g.categoryPath)??0)+1);let p=[];for(let g of Gd(r)){let y=Wr(g.path),k=y.startsWith(`${s}/`)?y.slice(s.length+1):y===s?"":y;k&&p.push({token:k,label:Xd(zd(y)),count:l.get(g.path)??0})}return p}catch{return[]}}function Ca(e,t){let n=Fr(e,t);return n.length===0?["No categories yet \u2014 author some articles first, then scope to one."]:["Which category? Re-run with one of:",...n.map(o=>` --scope ${o.token} (${o.label} \xB7 ${o.count} article${o.count===1?"":"s"})`)]}function lo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Pa(e,t){let n=e.indexOf("--scope");if(n===-1)return["--scope",t,...e];let o=e[n+1],r=[...e];return o===void 0||o.startsWith("-")?r.splice(n+1,0,t):r[n+1]=t,r}var op=3,rp=8;function Hr(e){return e===void 0||!Number.isFinite(e)?op:Math.max(1,Math.min(Math.floor(e),rp))}function qr(e){let t,n,o=!1,r=!1,s,l=g=>{let y=Number(g);return g!==void 0&&Number.isFinite(y)?y:void 0};for(let g=0;g<e.length;g++){let y=e[g];if(y==="--preview"||y==="--dry-run")o=!0;else if(y==="--rewrite"||y==="--force")r=!0;else{if(y==="--run"||y==="--yes"||y==="--all")continue;y==="--scope"?t=e[++g]:y?.startsWith("--scope=")?t=y.slice(8):y==="--concurrency"?s=l(e[++g]):y?.startsWith("--concurrency=")?s=l(y.slice(14)):y&&!y.startsWith("--")&&(n=y)}}let p=g=>g?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function sp(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function ip(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Br(e,t,n){return n.filter(o=>{try{return Ra(Ta(e,t,o)).size===0}catch{return!0}})}function Gr(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let l of o.get(r)?.sources??[])try{s+=Ra(Ta(e,l)).size}catch{}return{path:r,bytes:s}})}function Vr(e,t,n={}){let o=n.rewrite?`- Some or all of these articles ALREADY EXIST on disk \u2014 this is a re-author (rewrite/upgrade), NOT a first draft. For any that exist, do NOT preserve or lightly-edit the current file: RE-AUTHOR it from scratch against the plan + sources + the active doc-type playbook standard. The existing file is what you're replacing \u2014 its structure is NOT the target; match only the project's voice/terminology.
|
|
239
239
|
`:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
240
240
|
- 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).
|
|
241
241
|
- 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.
|
|
@@ -244,75 +244,75 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
|
244
244
|
- 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.
|
|
245
245
|
Articles:
|
|
246
246
|
`+e.paths.map(r=>`- ${r}`).join(`
|
|
247
|
-
`)}function
|
|
248
|
-
`)}var
|
|
249
|
-
`)}var
|
|
247
|
+
`)}function Yr(e,t,n){let o=e.reduce((l,p)=>l+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(l=>` \u2022 ${l.label} \u2014 ${l.paths.length} article${l.paths.length===1?"":"s"}`),"",`Estimated cost: ${he(r)}\u2013${he(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function zr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),l=e.reduce((C,E)=>C+o(E),0),p=r.reduce((C,E)=>C+o(E),0),g=e.reduce((C,E)=>C+E.costUsd,0),y=e.reduce((C,E)=>C+E.outputTokens,0),k=n==="api"?`${he(g)} total`:ze(y),j=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Wrote ${x(l)} (${j}) successfully \xB7 ${k}.`),P.push("Next \u2014 push them to Document360:"),P.push("/publish --all"),P.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{P.push(`Wrote ${p}/${x(l)} (${j}) \xB7 ${k}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}function Xr(e,t,n){try{let o=Qd({cwd:e,paths:n.map(s=>`${t}/${s}`)});if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 /check --fix corrects them.`}catch{return null}}function Kr(e,t,n){let o=(Sa(e)?.docsDir??ep).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=sp(n.path,o);return r.includes(p)?{docsDir:o,targets:[p],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${p}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=ip(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let l=Br(e,o,s);if(l.length===0){let p=n.scope?` under "${n.scope}"`:"",g=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${g} --rewrite to regenerate them all.`}}return{docsDir:o,targets:l,planCount:r.length}}async function Da(e,t){if(!Sa(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};if(lo(e)){for(let W of Ca(t.cwd,t.profileName))console.log(f(W));return{kind:"continue"}}let n=Zd(t.cwd);if(n.length===0)return console.log($("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:l,rewrite:p}=qr(e),{docsDir:g,targets:y,reason:k,rewriting:j}=Kr(t.cwd,n,{scope:o,path:r,rewrite:p});if(y.length===0)return console.log(k?U(k):U("Nothing to write.")),{kind:"continue"};j&&console.log(U(`--rewrite: regenerating ${y.length} already-written article${y.length===1?"":"s"} (overwrites them; git has your baseline).`));let x=Jd(y),P=Hr(l),{model:C,forced:E}=tp(t.cwd,"standard"),I=!!r;if(s&&!I){let W=Kd({files:Gr(t.cwd,n,y),op:"write",model:C});o&&console.log(f(`Scope: ${o} (${y.length} pending).`));for(let J of Yr(x,W,P))console.log(J);return console.log(f(`Model: ${C}${E?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${y.length} article${y.length===1?"":"s"} across ${x.length} partition${x.length===1?"":"s"} (\u2264${P} agents at once) on ${C}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let W of np({cwd:t.cwd,partitions:x,promptFor:J=>Vr(J,g,{rewrite:j||I}),concurrency:P,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(W.type==="partition_status")W.status==="running"?console.log(f(` \u25B8 ${W.label} \u2014 writing\u2026`)):W.status==="done"?console.log(N(` \u2713 ${W.label}`)):console.log($(` \u2717 ${W.label}`));else if(W.type==="run_done"){console.log("");let J=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let oe of zr(W.results,x,J))console.log(W.ok?N(oe):U(oe));let fe=Xr(t.cwd,g,y);fe&&console.log(U(fe))}}catch(W){console.log($(`Write run failed: ${W.message}`))}return console.log(""),{kind:"continue"}}H();import{existsSync as ap,readdirSync as ja,statSync as Aa}from"node:fs";import{join as Ea}from"node:path";import{inputDir as lp,readProjectConfig as cp}from"document360-engine";var Na=/\.(md|markdown|pdf|txt)$/i;function Qr(e){let t=lp(e);if(!ap(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of ja(t)){let s=Ea(t,r),l=!1;try{l=Aa(s).isDirectory()}catch{continue}if(l){if(r.startsWith("."))continue;let p=up(s);p>0&&n.push({name:r,docCount:p})}else Na.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function up(e){let t=0;for(let n of ja(e))try{Aa(Ea(e,n)).isFile()&&Na.test(n)&&t++}catch{}return t}function Jr(e,t){let n=t.trim().toLowerCase();return n?e.find(o=>o.name.toLowerCase()===n)?.name??e.find(o=>o.name.toLowerCase().startsWith(n))?.name??e.find(o=>o.name.toLowerCase().includes(n))?.name??null:null}function co(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in .d360-writer/input/${e}/`:t?`the input docs in .d360-writer/input/ relevant to: "${t}"`:"the input docs in .d360-writer/input/"}.`,t&&!e?`Use "${t}" as the feature framing.`:"","","Follow the skill: (1) read those PRDs/specs as the primary source (intent, user-facing surface,","terminology, user stories, prerequisites); (2) locate and read the CODE that implements that surface","to pin exact UI strings/routes/states \u2014 never fabricate; flag anything the PRD claims that you","cannot find in source; (3) propose a tight feature-scoped article set (\u22483\u20135) and pin it to",".d360-writer/plan.json + AGENT-PLAN.md, with each article's `sources` listing BOTH the PRD file(s)","AND the grounding code files; (4) flag overlaps with existing articles (do not merge). Then stop and","offer /write. Do NOT write the articles in this turn."].filter(Boolean).join(`
|
|
248
|
+
`)}var Zr="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Ia(e,t){let n=t?.cwd??process.cwd();if(!cp(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Qr(n);if(o.length===0&&r===0)return console.log(f(Zr)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let g of o)console.log(` ${g.name} ${f(`(${g.docCount} doc${g.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:co(p),display:p?`/draft ${p}`:"/draft"}}let l=Jr(o,s);return{kind:"forward-to-agent",prompt:co(l??"",l?void 0:s),display:`/draft ${s}`}}H();import{listOpenForDocs as dp,readProjectConfig as pp}from"document360-engine";function es(e){try{return dp(e).filter(t=>t.kind==="request").length}catch{return 0}}function ts(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function ns(e,t=!1){let n=["Run the document-handoff skill.",""];return e?n.push(`The builder hand-off (what was shipped this session): "${e}".`,"Treat this as the Stage 1 hand-off: ground it in the cited/changed code + the architecture brief,","then decide and APPLY the right doc action \u2014 a new section, a new article, an update to existing","article(s), or a retirement, or a mix. No fixed shape; pick the smallest set that keeps the docs correct."):n.push("No description was given \u2014 call d360_inbox and act on the OPEN `request` messages the builder left:","for each, run the document-handoff flow (ground \u2192 decide \u2192 apply) and mark the request `status: done`","with `resulting_articles` when finished."),n.push("","Draft only \u2014 do not publish. If you would create multiple new articles (a section), call","d360_estimate_cost and present the count + cost band first, then wait for the go-ahead."),t&&n.push("","After the drafts exist and the user confirms any bulk gate, publish the new/updated articles to","Document360 (the publish-to-d360 skill). On a production profile, respect the write-guard."),n.join(`
|
|
249
|
+
`)}var os="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function _a(e,t){let n=t?.cwd??process.cwd();if(!pp(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=ts(e);if(!r&&es(n)===0)return console.log(f(os)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:ns(r,o),display:s}}H();import{search as fp}from"@inquirer/prompts";import{findByName as mp,getSession as hp,listSessions as gp,relativeTime as La}from"document360-engine";async function Ma(e,t){let n=gp(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=mp(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),Oa(n),{kind:"continue"})}if(!process.stdin.isTTY)return Oa(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>fp({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let l=(s??"").toLowerCase();return n.filter(p=>!l||p.name.toLowerCase().includes(l)||p.firstPrompt.toLowerCase().includes(l)).map(p=>({name:`${p.name} ${La(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=hp(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Oa(e){console.log("");for(let t of e.slice(0,15))console.log(` ${L(t.name)} ${f(La(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}H();import{renameSession as yp}from"document360-engine";function rs(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 Ua(e,t){let n=rs(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(yp(o,n)?console.log(N(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(N(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Wa,readProjectConfig as wp,writeProjectConfig as kp}from"document360-engine";H();function ss(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=wp(e);if(!o)return"No .d360-writer/config.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return Wa().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},kp(o,e),null):`Unknown environment "${r}". Known: ${Wa().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function Fa(e,t){let n=e[0];if(!n)return Bn(t.cwd),{kind:"continue"};if(n==="add"){let o=ss(t.cwd,e[1],e[2]);return o?(console.log($(o)),{kind:"continue"}):(console.log(N(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${L(`/profile ${e[1]}`)} then ${L("/login")}`),{kind:"continue"})}return Gn(t.cwd,n),Vn(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}H();import{select as bp}from"@inquirer/prompts";import{readProjectConfig as xp,readUserConfig as Ha,resolveModelSetting as is,writeUserConfig as qa}from"document360-engine";var Ee=[{value:null,label:"Auto",desc:"Engine right-sizes per task \u2014 Sonnet for routine work, Opus for analysis (recommended)"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus 4.8 \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet 4.6 \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku 4.5 \xB7 fastest for quick answers"}];function uo(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=Ee.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function $p(e){switch(e.source){case"project":return".d360-writer/config.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"claude-settings":return"Claude Code's own settings (~/.claude/settings.json)";case"claude-default":return"Claude Code default (no override configured)"}}function dn(e,t){let n=()=>{let s=is(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Ha();return s.defaultModel?(delete s.defaultModel,qa(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${is(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}}qa({...Ha(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=xp(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer/config.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function Ba(e,t){let n=e[0]?.trim();if(!n){let l=is(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${L(l.model??"Claude Code default")}`),console.log(f(` source: ${$p(l)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=uo(l),g;try{g=await t.withPausedInput(()=>bp({message:`Select model (current: ${l.model??"Claude Code default"})`,default:Ee[p].value,choices:Ee.map((x,P)=>({name:`${x.label}${P===p?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:y,changed:k,effective:j}=dn(t.cwd,g??"default");for(let x of y)console.log(x.startsWith("\u26A0")?U(x):x.startsWith("\u2713")?N(x):f(x));return k&&await t.setModel(j),{kind:"continue"}}let{lines:o,changed:r,effective:s}=dn(t.cwd,n);for(let l of o)console.log(l.startsWith("\u26A0")?U(l):l.startsWith("\u2713")?N(l):f(l));return r&&await t.setModel(s),{kind:"continue"}}po();async function Ka(e,t){return await t.withPausedInput(()=>It(t.cwd)),{kind:"clear"}}async function Qa(e,t){return await t.withPausedInput(()=>Wn(t.cwd,t.profileName)),{kind:"clear"}}H();import{resolveActiveProfile as Up}from"document360-engine";async function Ja(e,t){let n=!1;try{n=Up(t.cwd).production}catch{}return n?(console.log(U("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}H();var Za=async(e,t)=>{try{await t.withPausedInput(()=>qn({}))}catch(n){console.log($(`Login failed: ${n.message}`))}return{kind:"continue"}};H();import{resolveActiveProfile as Wp,clearTokens as Fp,clearProfileProject as Hp}from"document360-engine";async function el(e,t){let n;try{n=Wp(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let o=Fp(n);return Hp(t.cwd,n),console.log(o?N(`\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 tl}from"node:fs";import{isAbsolute as qp,join as Bp,resolve as Gp}from"node:path";import{readProjectConfig as Vp,screenshotPlaceholderIds as Yp,DEFAULT_CAPTURE_DIR as zp,DEFAULT_OUTPUT_DIR as Xp}from"document360-engine";var nl=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function ls(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?nl(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:nl(o),setup:t}:{mode:"single",id:o}}function cs(e,t){let n=Vp(e),o=n?.captureDir??zp,r=n?.outputDir??Xp,s=(l,p)=>qp(l)?Bp(l,p):Gp(e,l,p);return Yp(e,{scope:t}).map(({id:l,file:p})=>{let g=tl(s(r,`${l}.png`))?"captured":tl(s(o,`${l}.spec.ts`))?"spec":"placeholder";return{id:l,file:p,state:g}})}var Kp={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Qp={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function us(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 l of e.filter(p=>p.file===s))r.push(` ${Kp[l.state]} ${l.id.padEnd(34)} ${Qp[l.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function ol(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(`
|
|
250
250
|
`),"","For each: locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir); read the product source for","EXACT routes + stable data-testid selectors (never guess); enter the prepared context via","captureScope(); guard data prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts","(skip-with-TODO if a stable selector is missing). Do NOT run other skills. Report the specs you","wrote and any TODO data-testids."].join(`
|
|
251
|
-
`)}async function
|
|
251
|
+
`)}async function fo(e,t){let n=ls(e);if(n.mode==="list"){let l=t?.cwd??process.cwd();for(let p of us(cs(l,n.scope),n.scope))console.log(p);return{kind:"continue"}}if(n.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${n.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${n.id}.spec.ts. Report the spec path and any TODO data-testids or data to stage.`].join(`
|
|
252
252
|
`),display:`/screenshot ${n.id}`};let r=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${n.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${n.scope}`:"every <!-- SCREENSHOT --> placeholder across the docs tree (the configured docsDir)"}.`,"Follow that skill exactly for each: read the SCREENSHOT block; read the product source for EXACT routes","and stable data-testid selectors (never guess); enter the prepared context via captureScope(); guard data",`prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts.${n.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`].join(`
|
|
253
|
-
`),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as
|
|
254
|
-
`),display:"/capture-setup"}}var
|
|
255
|
-
`)}async function
|
|
256
|
-
`)}var
|
|
257
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
253
|
+
`),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as Jp,readFileSync as Zp}from"node:fs";import{isAbsolute as ef,join as tf,resolve as nf}from"node:path";import{readProjectConfig as of,DEFAULT_CAPTURE_DIR as rf}from"document360-engine";async function fn(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-SETUP.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
|
|
254
|
+
`),display:"/capture-setup"}}var rl="-".repeat(64);function ds(e){let t=rf;try{let k=of(e);k?.captureDir&&(t=k.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=ef(t)?tf(t,"CAPTURE-TESTID-REQUESTS.json"):nf(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Jp(n))return null;let o;try{let k=JSON.parse(Zp(n,"utf8").replace(/^/,""));o=Array.isArray(k?.requests)?k.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(k=>k.file).filter(Boolean)).size,s=o.length,l=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,g=`${t}/CAPTURE-TESTID-REQUESTS.md`,y=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${l} requested across ${p}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",rl,`Read ${g} and ${y}. They list ${l} 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.",rl]}ut();H();import{listOpenForDocs as sf,readProjectConfig as af}from"document360-engine";function ps(e){try{return sf(e).length}catch{return 0}}function fs(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape."," \u2022 answer (a reply to a question you asked; `re` = your question id) \u2192 fold the fact into the affected"," article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only \u2014 do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
|
|
255
|
+
`)}async function sl(e,t){let n=t?.cwd??process.cwd();return af(n)?ps(n)===0?(console.log(f("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:fs(),display:"/inbox"}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}H();import{listOpenHints as lf,listOpenForDocs as cf,readProjectConfig as uf,computeSyncStatus as df,planPull as pf,applyPull as ff,planImport as mf,applyImport as hf}from"document360-engine";function Ft(e){let t=0,n=0,o=0;try{t=lf(e).length}catch{}try{let r=cf(e);n=r.filter(s=>s.kind==="request").length,o=r.filter(s=>s.kind==="answer").length}catch{}return{hints:t,requests:n,answers:o}}function Ht(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),t.length?t.join(", "):null}function hs(e){return{publish:e.includes("--publish")}}function gs({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.","2. Gather the pending work: d360_pending_hints (the builder's per-change hints) AND d360_inbox (open requests + answers).","3. Gather PORTAL FEEDBACK: call d360_setup_feedback once (idempotent \u2014 it creates the hidden feedback category + seed articles if this workspace has none, else no-ops), then d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY \u2014 triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","4. Decide the right doc actions across ALL of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief, and address each feedback item (improve the doc it points at \u2014 as a draft).","5. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the loop:"," \u2022 stamp consumed hints, and mark handled messages status: done with resulting_articles;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article \u2014 `**d360-writer response:** \u2713 actioned in <article> \u2014 <date>` (or `declined \u2014 <reason>`) \u2014 NEVER overwriting the person's own text \u2014 then call d360_feedback_done(article_id, resulting_articles);"," \u2022 EXCEPT the Creator-notes item (is_creator_notes:true): do NOT reply in it \u2014 instead fold its content into `.d360-writer/architecture/CREATOR-NOTES.md` as an appended, dated `## From portal Creator notes (<date>)` section (preserve every existing note + human edit), then call d360_feedback_done for it.","8. Push the drafts to Document360.","9. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs \u2014 only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)"];return t.push(e?"10. Then publish the new/updated articles live (publish-to-d360 skill), respecting the production write-guard.":"Leave everything as DRAFTS for review \u2014 do not publish live (run /publish when you want them live)."),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (plus the d360_ask_builder question you left for it)."),t.join(`
|
|
256
|
+
`)}var gf={status:df,plan:pf,apply:ff,planImport:mf,applyImport:hf};async function ys(e,t=gf){let n={pulled:[],imported:[],conflicts:[],failed:[]},o;try{o=await t.status({cwd:e.cwd,profileName:e.profileName})}catch(r){return n.error=r.message,n}for(let r of o.entries)if(r.status==="conflict"&&r.path)n.conflicts.push(r.path);else if(r.status==="untracked-remote"&&r.articleId)try{let s=await t.planImport({cwd:e.cwd,profileName:e.profileName,articleId:r.articleId});t.applyImport({cwd:e.cwd,profileName:e.profileName},s),n.imported.push(s.path)}catch(s){n.failed.push({path:r.title??r.articleId,error:s.message})}else if(r.status==="remote-ahead"&&r.path)try{let s=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},s),n.pulled.push(r.path)}catch(s){n.failed.push({path:r.path,error:s.message})}return n}var ms=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,mo=e=>e===1?"":"s";function ws(e){if(e.error)return[`\u26A0 Couldn't check Document360 for portal changes (${e.error.slice(0,100)}) \u2014 proceeding; the agent will re-check.`];let t=[];return e.pulled.length&&t.push(`\u2713 Pulled ${e.pulled.length} portal edit${mo(e.pulled.length)} into local: ${ms(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${mo(e.imported.length)} into local drafts: ${ms(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${mo(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${ms(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${mo(e.failed.length)} failed \u2014 left for /pull.`),t}async function il(e,t){let n=t?.cwd??process.cwd();if(!uf(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Oe(n,t?.profileName);if(!o.ok)return console.log($(o.reason)),{kind:"continue"};let{publish:r}=hs(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await ys({cwd:n,profileName:t?.profileName});for(let p of ws(s))console.log(p.startsWith("\u2713")?N(p):p.startsWith("\u2139")?f(p):U(p));let l=Ht(Ft(n));return console.log(f(l?`Catching up on ${l}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:gs({publish:r}),display:`/catch-up${r?" --publish":""}`}}H();import{spawn as yf}from"node:child_process";var ft="document360-writer",ho=`npm i -g ${ft}@latest`;async function go(){let e=process.platform==="win32";return new Promise(t=>{try{let n=yf(`npm i -g ${ft}@latest`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});n.on("error",o=>t({ok:!1,output:String(o)})),n.on("close",o=>t({ok:o===0,output:""})),e||n.unref()}catch(n){t({ok:!1,output:String(n)})}})}async function al(){return console.log(f(`Updating ${ft}\u2026`)),(await go()).ok?console.log(N("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log($(`Update failed \u2014 run manually: ${ho}`)),{kind:"continue"}}H();ut();import{existsSync as ks,rmSync as wf}from"node:fs";import{basename as ll,resolve as bs}from"node:path";import{execFileSync as kf}from"node:child_process";import{input as bf}from"@inquirer/prompts";import{readProjectConfig as xf,devHintsGuidePath as $f}from"document360-engine";var vf=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Cf=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),yo=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),cl=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function ul(e){let t=yo(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:cl(t)?!0:Cf.has(t)}function xs(e){let t=null;try{t=xf(e)}catch{t=null}let n=new Set(vf);for(let o of[yo(t?.docsDir),yo(t?.captureDir),yo(t?.outputDir)])o&&cl(o)&&n.add(o);return[...n].filter(o=>ul(o)&&ks(bs(e,o)))}function $s(e,t){let n=[],o=[];for(let r of t){if(!ul(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{wf(bs(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function dl(e,t){try{return kf("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
257
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Pf(e){return dl(e,".d360-writer/hints")}function Rf(e){return dl(e,".d360-writer/messages")}function vs(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Pf(e),o=Rf(e),r=ks(bs(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(s=>` \u2022 ${s}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o>0?[`\u26A0 ${o} message(s) under .d360-writer/messages/ are not committed \u2014 commit them first or they're gone.`]:[],...r?["Note: a repo-root user-docs/ is NOT touched (only .d360-writer/ is removed)."]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${ll(e)}`]}async function pl(e,t){let n=xs(t.cwd);for(let g of vs(t.cwd,n))console.log(n.length===0?f(g):g);if(n.length===0)return{kind:"continue"};let o=ll(t.cwd);if((await t.withPausedInput(()=>bf({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(U("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=ks($f(t.cwd)),{removed:l,failed:p}=$s(t.cwd,n);console.log(N(`\u2713 Reset complete \u2014 removed ${l.length} item${l.length===1?"":"s"}. The repo is back to its original state.`));for(let g of p)console.log($(` \u2717 ${g.path}: ${g.error}`));if(s){for(let g of Jn())console.log(g);console.log(f("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}H();import{lintDocs as Tf}from"document360-engine";function wo(e){if(e.length===0)return["\u2713 No issues found \u2014 no leaked internals, unknown commands, stale version facts, or AI-tells in the docs."];let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}let n=[`\u26A0 ${e.length} doc issue${e.length===1?"":"s"} in ${t.size} article${t.size===1?"":"s"} (leaked internals / unknown commands / stale facts / AI-tells):`];for(let[o,r]of t){n.push(` ${o}`);for(let s of r)n.push(` L${s.line}: "${s.term}" \u2014 ${s.message}`)}return n}function Cs(e){let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}return["The documentation quality check found issues in already-written articles. FIX each one by EDITING the","article in place \u2014 do not rewrite whole articles, just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","How to fix, by issue type:","- internal-leak (an agent codename, an internal skill name, or a d360_* tool name): this is the"," documentation engine's own machinery and must NOT appear in user docs. Reword the sentence to describe"," the behavior in plain user terms, or delete the internal aside. Do NOT swap it for another internal term.","- unknown-command: the named /command or --flag does not exist in the product source. Find the correct"," command/flag in the source and use it; if there is no real equivalent, remove the claim.","- stale-fact: the version contradicts the product's package.json engines \u2014 correct it to the real value.","- ai-tell: a machine-sounding buzzword (e.g. delve, leverage, furthermore, robust). Rewrite the phrase in"," plain, direct developer language; preserve the meaning; do NOT swap one buzzword for another.","","Rules: edit ONLY the listed articles; do not touch others; do not publish; introduce no new internal","nouns, invented commands, or wrong facts. When done, every listed issue should be gone.","","Issues:",[...t.entries()].map(([o,r])=>[o,...r.map(s=>` - L${s.line} [${s.kind}]: "${s.term}" \u2014 ${s.message}`)].join(`
|
|
258
258
|
`)).join(`
|
|
259
259
|
`)].join(`
|
|
260
|
-
`)}async function
|
|
261
|
-
`);return{prompt:
|
|
262
|
-
`),display:`/reorder${n?` ${n}`:""}`}}async function
|
|
263
|
-
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let l=
|
|
264
|
-
`);return{lines:s.slice(0,t).map(l=>
|
|
265
|
-
|
|
266
|
-
`),console.log(`${
|
|
267
|
-
`),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&&(
|
|
268
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){
|
|
269
|
-
`)}import{existsSync as
|
|
270
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var
|
|
271
|
-
`)){let l=s.trim().replace(
|
|
272
|
-
`)}function
|
|
273
|
-
`)}function
|
|
274
|
-
`)||e.length>200}function
|
|
275
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function
|
|
276
|
-
`)){if(s.length===0)o.push({start:r,end:r});else for(let l=0;l<s.length;l+=n)o.push({start:r+l,end:r+Math.min(l+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function
|
|
277
|
-
`),s=0;for(let l=r.length-1;l>=0;l--){let p=r[l];if(s+=Math.max(1,Math.ceil(p.length/o)),s>=t){let
|
|
278
|
-
`),truncated:l>0||
|
|
279
|
-
`)){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
|
|
260
|
+
`)}async function fl(e,t){let n=e.includes("--fix"),o=e.find(l=>!l.startsWith("--")),r=o?` ${o}`:"",s=Tf({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(N("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:Cs(s),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let l of wo(s))console.log(s.length===0?N(l):U(l));return s.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}H();import{lintDocs as Nf,loadStyleGuide as If,buildReviewPrompt as _f,readProjectConfig as Of,DEFAULT_DOCS_DIR as Lf}from"document360-engine";H();import{readProjectConfig as Sf,loadProfileMap as Df,resolveActiveProfile as jf,desiredCategoryOrder as Af,desiredArticleOrder as Ef}from"document360-engine";function ml(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var hl=e=>e.replace(/\\/g,"/").split("/").pop()??e;function mn(e,t){try{if(!Sf(e))return[];let n=jf(e,t),o=Df(e,n.name);if(!o)return[];let r=new Map;for(let l of Ef(o)){let p=r.get(l.categoryPath);p?p.push(l):r.set(l.categoryPath,[l])}let s=[];for(let l of Af(o)){s.push(ml(hl(l.path)));for(let p of(r.get(l.path)??[]).sort((g,y)=>g.order-y.order))s.push(` ${ml(hl(p.path))}`)}return s}catch{return[]}}async function gl(e,t){let n=mn(t.cwd,t.profileName);if(n.length===0)return console.log(f("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(L("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Ps(e,t){let n=Of(e);if(!n)return null;let o=(n.docsDir??Lf).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(k=>!k.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),l=Nf({cwd:e}),p=s?l.filter(k=>k.path===`${o}/${s}`||k.path.startsWith(`${o}/${s}/`)):l,g=s?"":mn(e).join(`
|
|
261
|
+
`);return{prompt:_f({docsRoot:o,scope:s,styleGuide:If(e),deterministicFindings:p,fix:r,structure:g||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function yl(e,t){let n=Ps(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}H();import{readProjectConfig as Mf}from"document360-engine";function Rs(e,t){if(!Mf(e))return null;let n=t.find(r=>!r.startsWith("--"));return{prompt:[`Reorder the articles within ${n?`the "${n}" category`:"each category"} to the best reading order.`,"Follow the manage-structure skill: decide the ideal order with senior-editor judgment per the doc-genre","playbook (overview / mental-model first; reference and troubleshooting/FAQ last), then APPLY it with the","d360_reorder_articles tool \u2014 one category at a time, all paths in the same category folder. Do not rename","files or edit the map by hand; the tool handles it. Report the new order, and remind me it reaches","Document360 on the next /publish."].join(`
|
|
262
|
+
`),display:`/reorder${n?` ${n}`:""}`}}async function wl(e,t){let n=Rs(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}H();import{readProjectConfig as Uf,writeProjectConfig as kl,isAppType as Wf,playbookSkillName as Ff,detectAppType as bl}from"document360-engine";var xl=["web","cli","service","library"],Hf=new Set(["web","cli"]);function Ts(e){return Hf.has(e)?`${Ff(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function $l(e,t){let n=t.cwd,o=Uf(n);if(!o)return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??bl(n);if(s){let l=o.appType?"set in config":"auto-detected";console.log(`${L("Genre:")} ${s} (${l}) \u2014 ${Ts(s)}`)}else console.log(U("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${xl.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(f("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...l}=o;kl(l,n);let p=bl(n);return console.log(N(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${Ts(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return Wf(r)?(kl({...o,appType:r},n),console.log(N(`\u2713 Genre set to ${r} \u2014 ${Ts(r)} (applies from your next command).`)),{kind:"continue"}):(console.log($(`Unknown genre "${r}". Choose one of: ${xl.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}var vl={help:lr,"?":lr,clear:Ni,exit:cr,quit:cr,init:mr,mcp:to,publish:fa,audit:un,scope:ha,pull:$a,convert:va,write:Da,draft:Ia,document:_a,resume:Ma,rename:Ua,profile:Fa,model:Ba,doctor:pn,workspace:Ka,project:Qa,"allow-prod":Ja,login:Za,logout:el,screenshot:fo,"capture-setup":fn,devhints:Wi,inbox:sl,"catch-up":il,update:al,reset:pl,check:fl,review:yl,reorder:wl,structure:gl,genre:$l};function Cl(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}ut();H();var qf={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"},Rl=160,Ds=200,Tl=40;function we(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Pl(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}: ${we(typeof r=="string"?r:JSON.stringify(r),Tl)}`);return t.length>4&&n.push("\u2026"),we(n.join(", "),Rl)}var Xe=e=>typeof e=="string"&&e?e:null,Ss=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Bf(e){let t=Xe(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 Gf(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Xe(t.title);if(!o)return null;let r=Bf(t.local_path);return n("Create article",`"${we(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Xe(t.title),r=Ss(t.article_id);return n("Update article",o?`"${we(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Ss(t.article_id)?`id ${Ss(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",Xe(t.name)?`"${we(Xe(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Xe(t.file_path);return n("Upload image",o?we(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function ko(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),l=s.join("__");if(r==="document360"){let y=Gf(l,t);if(y)return y}let p=l.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Pl(t)}}let n=qf[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:we(o,Rl)}:{title:e,sep:"",arg:Pl(t)}}function Vf(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 Yf(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Vf).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>we(r,Ds))]}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}: ${we(String(r),Tl)}`);return n.length>0?[we(n.join(" \xB7 "),Ds)]:null}return null}function zf(e){let t=Xe(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Xf(e,t,n){switch(e){case"d360_create_article":{let o=zf(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=Xe(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 ${we(o[0],120)}`:""}`]}default:return null}}function bo(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
263
|
+
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let l=Xf(n.slice(18),o,r);if(l)return{lines:l,hidden:0}}let s=Yf(r)??r.split(`
|
|
264
|
+
`);return{lines:s.slice(0,t).map(l=>we(l,Ds)),hidden:Math.max(0,s.length-t)}}function xo(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function $o(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 vo(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 lm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function cm(e,t,n,o){if(lm.test(e))try{let r=Al(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,l=$o(t,n),p=vo(n);e.endsWith("publish_article")&&p&&console.log(L(` \u2B95 Live: ${p}`)),l&&s&&console.log(L(` \u2B95 Preview: ${xo(r.connection.portalUrl,s,l,r.project.languageCode??"en")}`))}catch{}}async function El(e=process.cwd(),t="auto",n){let o=Qf(t);o.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${L("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${L('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),um(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=js({cwd:e,profileName:n,allowProdWrites:r}),l={uuid:null,firstPrompt:null,titleFired:!1},p=Kf({input:process.stdin,output:process.stdout}),g=[],y=null,k=!1;p.on("line",P=>{if(y){let C=y;y=null,C(P)}else g.push(P)}),p.on("close",()=>{if(k=!0,y){let P=y;y=null,P(null)}});function j(){return g.length>0?Promise.resolve(g.shift()):k?Promise.resolve(null):(process.stdout.write(L("> ")),new Promise(P=>{y=P}))}let x={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=js({cwd:e,profileName:n,allowProdWrites:r}),l={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>l.uuid,setPendingName:P=>{l.pendingName=P},setModel:async P=>s.setModel(P),withPausedInput:async P=>{p.pause();try{return await P()}finally{p.resume()}}};try{for(;;){let P=await j();if(P===null)break;let C=P.trim();if(C){if(C.startsWith("/")){let E=Cl(C);if(!E)continue;let I=vl[E.name];if(!I){console.log($(`Unknown command: /${E.name}`)),console.log(f("Type /help for the list."));continue}let W=await I(E.args,x);if(W.kind==="exit")break;if(W.kind==="clear"){x.restartAgent();continue}if(W.kind==="allow-prod"){r=!0,x.restartAgent(),console.log(N("\u2713 Production writes authorized for this session.")),console.log("");continue}if(W.kind==="resume"){s.close(),s=js({cwd:e,resume:W.uuid,profileName:n,allowProdWrites:r});let J=Jf(W.uuid);l={uuid:W.uuid,firstPrompt:J?.firstPrompt??null,titleFired:!0},jl(W.uuid),console.log(N(`\u2713 Resumed "${W.name}"`)),console.log("");continue}W.kind==="forward-to-agent"&&(l.firstPrompt||(l.firstPrompt=W.display??W.prompt),await Dl(s,W.prompt,o,l,e));continue}l.firstPrompt||(l.firstPrompt=C),await Dl(s,C,o,l,e)}}}finally{s.close(),p.close()}}function um(e,t){console.log(""),console.log(en("document360-writer")),console.log(f(` cwd: ${e}`));let n=om(e);if(console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(dm(e,t)),!rm(e))console.log(U(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{try{Kn(e);for(let o of Qn(e))console.log(U(` ${o}`))}catch{}try{let o=sm(e);o.persisted&&o.appType?console.log(f(` \u2713 Detected a ${o.appType} app \u2014 enabled the ${o.appType}-doc-playbook (change with /genre).`)):o.source==="unknown"&&console.log(U(" Couldn't classify this repo \u2014 run /genre <web|cli|service|library> so the docs use the right playbook."))}catch{}try{let o=Ht(Ft(e));o&&console.log(U(` \u{1F4CB} ${o} from the repo's coding agent \u2014 run /catch-up.`))}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function dm(e,t){try{let n=Al(e,t),o=n.production?U(" \u26A0 PRODUCTION"):"",r=am(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Sl(r.idToken)??{},...Sl(r.accessToken)??{}},l=s.email??s.preferred_username??"signed in";return im(r)&&!r.refreshToken?U(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${l} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function pm(){console.error(""),console.error(`Sign in with your Claude subscription: run ${L("claude")} once, then retry.`),console.error(` (No Claude Code? ${L("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${L("https://console.anthropic.com/settings/keys")}`)}function fm(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;tm({uuid:t,name:r??em(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function mm(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||nm(o,t).then(r=>{r&&Zf(n,r)}).catch(()=>{})}async function Dl(e,t,n,o,r){let s=new Map;for await(let l of e.send(t))hm(l,o,r,n,s)}function hm(e,t,n,o,r){switch(e.type){case"session":t.uuid||fm(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=ko(e.name,e.input);s&&(process.stdout.write(`
|
|
265
|
+
|
|
266
|
+
`),console.log(`${N("\u25CF")} ${Pe(s.title)}${s.arg!==null?ie(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=dt(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let l=p=>p===1?"":"s";console.log(ie(` \u23BF Added ${s.added} line${l(s.added)}, removed ${s.removed} line${l(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(f(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let l=bo(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?$:ie;l.lines.forEach((g,y)=>console.log(p((y===0?" \u23BF ":" ")+g))),l.hidden>0&&console.log(f(` \u2026 +${l.hidden} lines`)),e.isError||cm(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
|
|
267
|
+
`),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&&(jl(t.uuid),t.titleFired||mm(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&pm();break}}import{render as Ah}from"ink";import{resolveAuth as Eh}from"document360-engine";import{useCallback as z,useEffect as ke,useMemo as Os,useRef as Q,useState as q}from"react";import{Box as ee,Text as D,useApp as Nm,useInput as Im,useStdout as _m}from"ink";import{existsSync as Ke,readFileSync as Ls,readdirSync as Oo}from"node:fs";import{spawnSync as Om}from"node:child_process";import{basename as gn,isAbsolute as Lm,join as ht}from"node:path";import{createSession as lc,classifyClaudeAuth as Fs,CLAUDE_CODE_SETUP_HINT as Mm,loginPkce as Um,toStoredTokens as Wm,saveTokens as Fm,getAccessToken as Hm,resolveActiveProfile as pe,resolveProjectId as qm,getArticle as Bm,decodeJwtClaims as Bt,isExpired as Ue,loadTokens as Qe,clearTokens as Gm,clearProfileProject as Vm,setTitle as Ym,slugify as zm,touchSession as Ms,upsertSession as Xm,generateTitle as cc,findByName as Km,listSessions as Qm,renameSession as Jm,suggestNextAction as Zm,readProjectConfig as Z,writeProjectConfig as uc,resolveAndPersistAppType as eh,resolveModelSetting as Hs,loadProfileMap as _o,applyPull as th,computeSyncStatus as dc,countLocalAhead as nh,lintDocs as pc,compareRemoteSources as oh,planPull as rh,establishBaselines as sh,rebaselineServerMeta as ih,inventoryRepo as ah,knownEnvironments as lh,resolveEnvironment as ch,planPartitions as Us,partitionEvenly as uh,screenshotPlaceholderIds as dh,trackedArticlePaths as ph,runPartitioned as Eo,estimateBulkCost as fc,resolveModelForOperation as No,readDocsPlan as mc,checkForUpdate as fh,detectInstallKind as mh,isSelfUpdatable as hh,devHintsGuidePath as qs,toolFeedbackPath as gh,reconcileToolFeedback as yh,DEFAULT_DOCS_DIR as yn,setProfileProject as wh,writeCrashLog as kh,applyStructureOrder as hc,orderSyncLine as gc,applyRelatedArticles as yc,relatedSyncLine as wc}from"document360-engine";ut();import{spawn as Nl}from"node:child_process";function gm(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function ym(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?Nl([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Nl(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",l=>o(l===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function Il(e){for(let[t,n]of gm())if(await ym(t,n,e))return!0;return!1}var wm=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function As(e,t){if(t.closed)return e;let n=e.split(`
|
|
268
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){wm.test(s)&&(t.cueSeen=!0);continue}let l=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);l?(n[r]=`${l[1]}${++t.num}. ${l[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
|
|
269
|
+
`)}import{existsSync as km,mkdirSync as bm,readFileSync as xm,writeFileSync as $m}from"node:fs";import{join as _l}from"node:path";import{writerDir as vm}from"document360-engine";function Ol(e){return _l(vm(e),".sessions")}function Ll(e,t){return _l(Ol(e),`${t}.json`)}function Ml(e,t,n){try{bm(Ol(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");$m(Ll(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Es(e,t){try{let n=Ll(e,t);if(!km(n))return[];let o=JSON.parse(xm(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Cm=e=>`\x1B]0;${e}\x07`,Pm=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Ul(e){process.stdout.isTTY&&process.stdout.write(e)}function qt(e){Ul(Cm(e))}function Co(e){Ul(Pm(e))}var Po=["\xB7 "," \xB7"],Ro="\u{1F7E3}";po();eo();var To=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path>] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Reports issues; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category>]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],Wl={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function Fl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Wl[n])return Wl[n];let o=To.find(r=>r.name===t);return o?o.desc:""}function Hl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return To.filter(n=>n.name.startsWith(t))}function ql(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}H();import{Box as Bl,Text as ae}from"ink";import{jsx as le,jsxs as So}from"react/jsx-runtime";function Rm({row:e}){switch(e.t){case"head":return le(ae,{color:B,bold:!0,children:e.s});case"text":return le(ae,{children:e.s});case"dim":return le(ae,{dimColor:!0,children:e.s});case"sub":return le(ae,{bold:!0,dimColor:!0,children:e.s});case"good":return le(ae,{color:"green",children:e.s});case"step":return So(ae,{children:[le(ae,{color:B,children:`${e.n}. `}),e.s]});case"cmd":return So(ae,{children:[" ",le(ae,{color:B,children:e.name.padEnd(20)}),le(ae,{dimColor:!0,children:e.s})]});case"gap":return le(ae,{children:" "})}}function Gl({tab:e,width:t}){let n=Re[e]??Re[0],o=6+Re.reduce((s,l)=>s+l.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return So(Bl,{flexDirection:"column",paddingX:1,children:[So(ae,{children:[le(ae,{color:B,bold:!0,children:"Help "}),Re.map((s,l)=>l===e?le(ae,{color:"white",backgroundColor:B,bold:!0,children:` ${s.label} `},s.key):le(ae,{dimColor:!0,children:` ${s.label} `},s.key))]}),le(ae,{color:B,children:r}),le(Bl,{flexDirection:"column",marginTop:1,children:n.rows.map((s,l)=>le(Rm,{row:s},l))}),le(ae,{dimColor:!0,children:`
|
|
270
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var Tm=/^(?:\d+[.)]|[-*•])\s+/;function Vl(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
271
|
+
`)){let l=s.trim().replace(Tm,""),p=l.match(/^`([^`]+)`$/);p&&(l=p[1].trim());let g=l.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!g||!o.has(g[1].toLowerCase()))continue;let y=`/${g[1].toLowerCase()}${g[2]?` ${g[2]}`:""}`;if(r.includes(y)||r.push(y),r.length>=n)break}return r}H();function hn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Le(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Yl(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Sm=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function zl(e,t,n){if(!Sm.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(s=>{let l=s.replace(/\\/g,"/");return r===l||r.endsWith(`/${l}`)})??null}function Ns(e){return e.replace(/^[\w.-]+\//,"")}var Do=16,Xl={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function mt(e){return typeof e=="string"?e:e.cmd}function Kl(e){return typeof e=="string"?void 0:e.desc}function Is(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Ql(e,t){let n=Is(t);return e.some(r=>mt(r).trim()===t.trim()||!!n&&Is(mt(r))===n)?e.filter(r=>mt(r).trim()!==t.trim()&&!(n&&Is(mt(r))===n)):[]}var Dm='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function jm(e,t){switch(e){case"/write":return"finish the planned articles that aren\u2019t written yet";case"/catch-up":return"write up everything your builder flagged";case"/audit":return t?"also scan the code for other changes":"check the code for anything new or missing in the docs";case"/pull":return"pull edits + new articles from Document360";case"/publish":return"push your local changes up to Document360";default:return""}}function Me(e){return e===1?"":"s"}function Am(e){switch(e){case"/write":return"it finishes the articles already planned";case"/catch-up":return"it clears everything your builder queued";case"/audit":return"it shows what the latest code changes touch";case"/pull":return"it reconciles anything changed on Document360";case"/publish":return"it pushes your local edits up to Document360";default:return"it\u2019s the most useful next step"}}function _s(e,t,n){let o=[];e.pendingWrites>0&&o.push(` \u2022 ${e.pendingWrites} planned article${Me(e.pendingWrites)} still unwritten`),e.localAhead>0&&o.push(` \u2022 ${e.localAhead} article${Me(e.localAhead)} changed locally \u2014 ready to publish`),e.pendingText&&o.push(` \u2022 your builder left ${e.pendingText}`),e.behind>0&&o.push(` \u2022 ${e.behind} code change${Me(e.behind)} since your last docs check`);let r=o.length>0?["Welcome back \u2014 where your docs stand:",...o,`I\u2019d start with ${t[0]} \u2014 ${Am(t[0])}.`]:[`Welcome back. Your ${e.tracked} tracked article${Me(e.tracked)} are all in sync.`];return r.push("",...t.map((s,l)=>` ${l+1} ${s.padEnd(9)} ${jm(s,n)}`),"Or just tell me what to write or update."),r.join(`
|
|
272
|
+
`)}function Jl(e){if(!e.ready)return{kind:"idle"};let t=!!e.pendingText;if(!e.hasDocs)return{kind:"noDocs",note:Dm,ghost:"write the docs for this repo",title:t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:null,options:t?["/catch-up","/audit"]:["/audit"]};if(e.pendingWrites>0){let r=t?["/write","/catch-up"]:["/write","/audit"],s=`\u{1F4DD} ${e.pendingWrites} planned article${Me(e.pendingWrites)} not written yet \u2014 pick up where you left off:`;return{kind:"actions",note:_s(e,r,t),title:s,options:r}}if(e.localAhead>0){let r=t?["/publish","/catch-up"]:["/publish","/audit"],s=`\u{1F4E4} ${e.localAhead} article${Me(e.localAhead)} changed locally \u2014 ready to publish to Document360:`;return{kind:"actions",note:_s(e,r,t),title:s,options:r}}if(!t&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${Me(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`};let n=t?["/catch-up","/audit"]:["/audit","/pull"],o=t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:e.behind>0?`\u{1F4CB} ${e.behind} code change${Me(e.behind)} since your last docs check \u2014 /audit to see what needs updating (or /audit --auto on to run it for you):`:`\u{1F4DA} ${e.tracked} article${Me(e.tracked)} tracked for "${e.profileName}". What next?`;return{kind:"actions",note:_s(e,n,t),title:o,options:n}}var Em=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Zl(e){return e.replace(/\r\n?/g,`
|
|
273
|
+
`)}function ec(e){return e.includes(`
|
|
274
|
+
`)||e.length>200}function tc(e,t){let n=t.split(`
|
|
275
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function nc(e,t){return e.replace(Em,n=>t.get(n)??n)}function oc(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function jo(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
276
|
+
`)){if(s.length===0)o.push({start:r,end:r});else for(let l=0;l<s.length;l+=n)o.push({start:r+l,end:r+Math.min(l+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function Ao(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function rc(e,t,n){let o=Ao(e,t),r=o+n;if(r<0||r>=e.length)return t;let s=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+s,e[r].end)}function sc(e,t,n){let o=e[Ao(e,t)];return n==="start"?o.start:o.end}function ic(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
277
|
+
`),s=0;for(let l=r.length-1;l>=0;l--){let p=r[l];if(s+=Math.max(1,Math.ceil(p.length/o)),s>=t){let g=s-t;return{text:[g>0?p.slice(g*o):p,...r.slice(l+1)].join(`
|
|
278
|
+
`),truncated:l>0||g>0}}}return{text:e,truncated:!1}}function ac(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
279
|
+
`)){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 Ws,jsx as A,jsxs as V}from"react/jsx-runtime";var bh={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},kc=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
280
280
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
281
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function rh(e,t,n,o){let r=Is(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",l=_s(e),p=Z(e),y=(p?.docsDir??hn).replace(/\/+$/,""),g=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${y}/ + config`,b={version:t,claude:s,model:l.model??"Claude Code default model",modelSource:oh[l.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:g};if(p===null)return b;try{let S=pe(e,o);b.profile=S.name,b.apiUrl=S.connection.apiUrl,b.prod=S.production,b.project=S.project.projectName??S.project.projectId??"(chosen at login)";let x=Xe(S.name);if(x){let P={...Ht(x.idToken)??{},...Ht(x.accessToken)??{}},C=P.email??P.preferred_username??"signed in";We(x)?x.refreshToken&&(b.who=C,b.loggedOut=!1,b.sessionHint="session expired \u2014 refreshing\u2026"):(b.who=C,b.loggedOut=!1,b.sessionHint=`session valid until ${new Date(x.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return b}function sh(e,t){try{let n=pe(e,t),o=Xe(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Ht(o.idToken)??{},...Ht(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return We(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var dc=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],qt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],ih="Ask me to write or update an article\u2026";function jo({ch:e,dim:t}){let[n,o]=q(!0);return be(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),E(D,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var ah=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function pc(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var lh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function fc(e){try{return Eo(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function mc(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>fc(mt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&fc(mt(e,o)))}function hc(e,t){try{let n=Z(e);if(!n)return!1;let o=pe(e,t),r=Ao(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=mt(e,(n.docsDir??hn).replace(/\/+$/,""));return!!(Ke(s)&&Eo(s).length>0||Ke(Os(e)))}catch{return!1}}function ch({startTime:e,chars:t}){let[n,o]=q(0);be(()=>{let y=setInterval(()=>o(g=>g+1),120);return()=>clearInterval(y)},[]);let r=qt[n%qt.length],s=dc[Math.floor(n/16)%dc.length],l=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return Y(ne,{children:[E(D,{color:B,children:` ${r} ${s}\u2026 `}),E(D,{color:"gray",children:`(${rn(l)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function uh({text:e}){let[t,n]=q(0);return be(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),E(ne,{paddingX:1,children:E(D,{color:B,children:`${qt[t%qt.length]} ${e}`})})}var dh=12e4;function ph({p:e}){let[t,n]=q(0);be(()=>{let I=setInterval(()=>n(W=>W+1),150);return()=>clearInterval(I)},[]);let o=qt[t%qt.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),l=Math.round(e.chars/4),p=Date.now()-e.lastAt>=dh,y=e.verb??"Converting",g=e.unit??"article",b=e.rows.reduce((I,W)=>I+W.items,0),S=y.toLowerCase(),x=e.rows,P=0;if(x.length>Po){let I=x.findIndex(J=>J.status==="active"||J.status==="pending"),W=Math.max(0,Math.min(I-2,x.length-Po));P=x.slice(0,W).filter(J=>J.status==="done").length,x=x.slice(W,W+Po)}let C=Math.min(40,Math.max(...x.map(I=>Rs(I.label).length),0)),j=I=>I==="failed"?"red":I==="active"?B:void 0;return Y(ne,{flexDirection:"column",children:[Y(ne,{children:[E(D,{color:B,children:` ${o} ${y} ${b} ${g}${b===1?"":"s"} `}),E(D,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${l} tokens \xB7 ${rn(r)} \xB7 esc to stop`})]}),P>0&&E(D,{dimColor:!0,children:` \u2714 +${P} done`}),x.map(I=>Y(D,{color:j(I.status),dimColor:I.status==="done"||I.status==="pending",children:[` ${Wl[I.status]} ${Rs(I.label).padEnd(C)}`,I.status==="active"&&I.itemsDone!==void 0?` (${I.itemsDone}/${I.items} ${g}${I.items===1?"":"s"})`:I.status!=="pending"?` (${I.items} ${g}${I.items===1?"":"s"})`:"",I.status==="active"?` \u2190 ${S}\u2026`:""]},I.label)),p&&E(D,{color:"yellow",children:` \u26A0 no activity for ${rn(s)} \u2014 press esc to stop if it's wedged`})]})}var fh=10800*1e3;function gc({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=gm(),[s,l]=q(n),[p,y]=q(null),[g,b]=q({text:"",pos:0}),S=g.text,x=z(c=>{b(i=>{let a=typeof c=="function"?c(i.text):c;return{text:a,pos:a.length}})},[]),P=z(c=>{b(i=>({text:i.text.slice(0,i.pos)+c+i.text.slice(i.pos),pos:i.pos+c.length}))},[]),C=z(()=>{b(c=>{if(c.pos===0)return c;let i=c.text.slice(0,c.pos),a=zl(i)??i.slice(0,-1);return{text:a+c.text.slice(c.pos),pos:a.length}})},[]),[j,I]=q(!1),[W,J]=q(!1),[fe,oe]=q(0),[De,ue]=q(null),[Qe,G]=q([]),ht=Q(0),[Cc,gn]=q(!1),[Pc,yn]=q(!1),[No,Ws]=q(null),[Rc,gt]=q(0),Je=Q(0),[Bt,yt]=q(0),[wt,wn]=q(null),Fs=Q(new Map),Tc=Q(0),kt=Q([]),xe=Q(null);xe.current===null&&(xe.current=Zl({cwd:e,profileName:s,allowProdWrites:!1}));let Ne=Q({uuid:null,firstPrompt:null,titleFired:!1}),kn=Q(new Map),bt=Q(!1),Io=Q([]),Fe=Q([]),_o=Q(null),[Hs,Ze]=q(null),Oo=Q(null),[et,tt]=q(null),[Ie,xt]=q(null),[He,$t]=q(null),[me,vt]=q(null),[$e,nt]=q(null),[ot,Ct]=q(null),[qs,de]=q(null),[ve,rt]=q(null),[ge,Pt]=q(null),[Bs,Lo]=q([]),st=Q([]),Gt=Q(!1),Ce=Q(null),[bn,ee]=q(null),[Gs,Ys]=q(null),xn=Q(!1),$n=Q(null),Yt=Q(null),[Pe,it]=q(null),[Mo,Vt]=q(null),[Vs,Rt]=q(0),[zs,Tt]=q(0),[Sc,Ks]=q(0),Uo=Ds(()=>{try{return _s(e).model??"auto"}catch{return null}},[e,Sc]),{stdout:je}=wm(),[,Dc]=q(0),Xs=Q(`${je.columns??80}x${je.rows??24}`),qe=z(()=>Math.max(20,(je.columns??80)-1),[je]),u=z(c=>{kt.current.push(c),console.log(yr(c,qe()))},[qe]),[Wo,Fo]=q(null),St=z(c=>{Fo(c),u({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),Ho=Q(!1),qo=z(async()=>{try{if(Ho.current||!Jm(Qm())||Z(e)?.mode==="engineer")return;let c=await Xm({pkg:pt,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;Ho.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${pt} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),yn(!0),(await po().finally(()=>yn(!1))).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),G(a=>a.includes("/exit")?a:[...a,"/exit"]),Ws(c.latest)):u({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${uo}`})}catch{}},[e,o,u]),Bo=z(c=>{let i=Le(e,s);return i.ok?!0:(u({kind:"note",tone:"warn",text:i.reason}),Yt.current=c,G(["/login"]),!1)},[e,s,u]),[Go,Yo]=q(null),zt=Q(!0),vn=Q(0),Kt=Q(0);be(()=>{let c=setInterval(()=>{if(zt.current){vn.current=0,Kt.current=0;return}if(!j)try{if(!Ke(Os(e)))return;if(Oe(e).status==="current"){zt.current=!0,vn.current=0,Kt.current=0,u({kind:"note",tone:"ok",text:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs."}),Fo(null),ue("write the docs for this repo");return}vn.current+=1;let i=vn.current;if((i===4||i%15===0)&&Kt.current<3){Kt.current+=1;let a=Kt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";u({kind:"note",tone:"info",text:_t(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${a}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${a}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,j,u]),be(()=>{let c=Hs??mn(e);if(!j){bo(0),Ft(`${$o} ${c}`);return}bo(3);let i=0;Ft(`${xo[0]} ${c}`);let a=setInterval(()=>{i=(i+1)%xo.length,Ft(`${xo[i]} ${c}`)},400);return()=>clearInterval(a)},[j,e,Hs]),be(()=>()=>bo(0),[]);let Vo=z(c=>{try{let i=Z(e);if(!i)return{kind:"idle"};let a=pe(e,s),h=Xe(a.name),d=!!h&&(!We(h)||!!h.refreshToken),m=hc(e,s)||!mc(e,i.authoritativeSourceFiles),w=Is(t).state==="missing",k=Ao(e,a.name),R=k?Object.keys(k.articles).length:0,T=mt(e,(i.docsDir??hn).replace(/\/+$/,"")),_=!1;try{_=Ke(T)&&Eo(T).length>0}catch{}let M=0;if(k?.lastAnalyzedCommit)try{let F=km("git",["rev-list","--count",`${k.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});F.status===0&&(M=parseInt((F.stdout||"").trim(),10)||0)}catch{}let O=0;try{let F=sc(e);if(F.length>0){let X=(i.docsDir??hn).replace(/\/+$/,"");O=Lr(e,X,F.map(we=>we.path)).length}}catch{}let v=Um(e,s),N={ready:d&&m&&!w,hasDocs:_,tracked:R,pendingText:Wt(Ut(e)),behind:M,pendingWrites:O,localAhead:v,autoAudit:!!i.autoAudit,profileName:a.name,allowAutoAudit:c};return ql(N)}catch{return{kind:"idle"}}},[e,s,t]);be(()=>{let c=performance.now(),i=[],a=(_,M)=>{let O=performance.now();try{return M()}finally{let v=Math.round(performance.now()-O);v>=80&&i.push(`${_}: ${v}ms`)}};u({kind:"banner",info:a("banner",()=>rh(e,o,t,s))});let h=Is(t).state==="missing";if(h&&u({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
|
|
282
|
-
${
|
|
283
|
-
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!Z(e)){
|
|
284
|
-
${
|
|
285
|
-
`)}),
|
|
281
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function xh(e,t,n,o){let r=Fs(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",l=Hs(e),p=Z(e),g=(p?.docsDir??yn).replace(/\/+$/,""),y=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${g}/ + config`,k={version:t,claude:s,model:l.model??"Claude Code default model",modelSource:bh[l.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:y};if(p===null)return k;try{let j=pe(e,o);k.profile=j.name,k.apiUrl=j.connection.apiUrl,k.prod=j.production,k.project=j.project.projectName??j.project.projectId??"(chosen at login)";let x=Qe(j.name);if(x){let P={...Bt(x.idToken)??{},...Bt(x.accessToken)??{}},C=P.email??P.preferred_username??"signed in";Ue(x)?x.refreshToken&&(k.who=C,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=C,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(x.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function $h(e,t){try{let n=pe(e,t),o=Qe(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Bt(o.idToken)??{},...Bt(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return Ue(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 bc=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Gt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],vh="Ask me to write or update an article\u2026";function Io({ch:e,dim:t}){let[n,o]=q(!0);return ke(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),A(D,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Ch=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function xc(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Ph=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function $c(e){try{return Oo(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function vc(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>$c(ht(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&$c(ht(e,o)))}function Cc(e,t){try{let n=Z(e);if(!n)return!1;let o=pe(e,t),r=_o(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=ht(e,(n.docsDir??yn).replace(/\/+$/,""));return!!(Ke(s)&&Oo(s).length>0||Ke(qs(e)))}catch{return!1}}function Rh({startTime:e,chars:t}){let[n,o]=q(0);ke(()=>{let g=setInterval(()=>o(y=>y+1),120);return()=>clearInterval(g)},[]);let r=Gt[n%Gt.length],s=bc[Math.floor(n/16)%bc.length],l=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return V(ee,{children:[A(D,{color:B,children:` ${r} ${s}\u2026 `}),A(D,{color:"gray",children:`(${an(l)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function Th({text:e}){let[t,n]=q(0);return ke(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),A(ee,{paddingX:1,children:A(D,{color:B,children:`${Gt[t%Gt.length]} ${e}`})})}var Sh=12e4;function Dh({p:e}){let[t,n]=q(0);ke(()=>{let I=setInterval(()=>n(W=>W+1),150);return()=>clearInterval(I)},[]);let o=Gt[t%Gt.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),l=Math.round(e.chars/4),p=Date.now()-e.lastAt>=Sh,g=e.verb??"Converting",y=e.unit??"article",k=e.rows.reduce((I,W)=>I+W.items,0),j=g.toLowerCase(),x=e.rows,P=0;if(x.length>Do){let I=x.findIndex(J=>J.status==="active"||J.status==="pending"),W=Math.max(0,Math.min(I-2,x.length-Do));P=x.slice(0,W).filter(J=>J.status==="done").length,x=x.slice(W,W+Do)}let C=Math.min(40,Math.max(...x.map(I=>Ns(I.label).length),0)),E=I=>I==="failed"?"red":I==="active"?B:void 0;return V(ee,{flexDirection:"column",children:[V(ee,{children:[A(D,{color:B,children:` ${o} ${g} ${k} ${y}${k===1?"":"s"} `}),A(D,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${l} tokens \xB7 ${an(r)} \xB7 esc to stop`})]}),P>0&&A(D,{dimColor:!0,children:` \u2714 +${P} done`}),x.map(I=>V(D,{color:E(I.status),dimColor:I.status==="done"||I.status==="pending",children:[` ${Xl[I.status]} ${Ns(I.label).padEnd(C)}`,I.status==="active"&&I.itemsDone!==void 0?` (${I.itemsDone}/${I.items} ${y}${I.items===1?"":"s"})`:I.status!=="pending"?` (${I.items} ${y}${I.items===1?"":"s"})`:"",I.status==="active"?` \u2190 ${j}\u2026`:""]},I.label)),p&&A(D,{color:"yellow",children:` \u26A0 no activity for ${an(s)} \u2014 press esc to stop if it's wedged`})]})}var jh=10800*1e3;function Pc({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Nm(),[s,l]=q(n),[p,g]=q(null),[y,k]=q({text:"",pos:0}),j=y.text,x=z(c=>{k(a=>{let i=typeof c=="function"?c(a.text):c;return{text:i,pos:i.length}})},[]),P=z(c=>{k(a=>({text:a.text.slice(0,a.pos)+c+a.text.slice(a.pos),pos:a.pos+c.length}))},[]),C=z(()=>{k(c=>{if(c.pos===0)return c;let a=c.text.slice(0,c.pos),i=oc(a)??a.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[E,I]=q(!1),[W,J]=q(!1),[fe,oe]=q(0),[Se,ue]=q(null),[Je,G]=q([]),[Lo,Ys]=q(!1),gt=Q(0),[Nc,wn]=q(!1),[Ic,kn]=q(!1),[Mo,zs]=q(null),[_c,yt]=q(0),Ze=Q(0),[Vt,wt]=q(0),[kt,bn]=q(null),Xs=Q(new Map),Oc=Q(0),bt=Q([]),be=Q(null);be.current===null&&(be.current=lc({cwd:e,profileName:s,allowProdWrites:!1}));let Ne=Q({uuid:null,firstPrompt:null,titleFired:!1}),xn=Q(new Map),xt=Q(!1),Uo=Q([]),We=Q([]),Wo=Q(null),[Ks,et]=q(null),Fo=Q(null),[tt,nt]=q(null),[Ie,$t]=q(null),[Fe,vt]=q(null),[me,Ct]=q(null),[xe,ot]=q(null),[rt,Pt]=q(null),[He,Rt]=q(null),[Qs,de]=q(null),[$e,st]=q(null),[ge,Tt]=q(null),[Js,Ho]=q([]),it=Q([]),Yt=Q(!1),ve=Q(null),[$n,te]=q(null),[Zs,ei]=q(null),vn=Q(!1),Cn=Q(null),zt=Q(null),[Ce,at]=q(null),[qo,Xt]=q(null),[ti,St]=q(0),[ni,Dt]=q(0),[Lc,oi]=q(0),Bo=Os(()=>{try{return Hs(e).model??"auto"}catch{return null}},[e,Lc]),{stdout:De}=_m(),[,Mc]=q(0),ri=Q(`${De.columns??80}x${De.rows??24}`),qe=z(()=>Math.max(20,(De.columns??80)-1),[De]),d=z(c=>{bt.current.push(c),console.log($r(c,qe()))},[qe]),[Go,Vo]=q(null),jt=z(c=>{Vo(c),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),Yo=Q(!1),zo=z(async()=>{try{if(Yo.current||!hh(mh())||Z(e)?.mode==="engineer")return;let c=await fh({pkg:ft,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;Yo.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${ft} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),kn(!0),(await go().finally(()=>kn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),G(i=>i.includes("/exit")?i:[...i,"/exit"]),zs(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${ho}`})}catch{}},[e,o,d]),Xo=z(c=>{let a=Oe(e,s);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),zt.current=c,G(["/login"]),!1)},[e,s,d]),[Ko,Qo]=q(null),Kt=Q(!0),Pn=Q(0),Qt=Q(0);ke(()=>{let c=setInterval(()=>{if(Kt.current){Pn.current=0,Qt.current=0;return}if(!E)try{if(!Ke(qs(e)))return;if(_e(e).status==="current"){Kt.current=!0,Pn.current=0,Qt.current=0,d({kind:"note",tone:"ok",text:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs."}),Vo(null),ue("write the docs for this repo");return}Pn.current+=1;let a=Pn.current;if((a===4||a%15===0)&&Qt.current<3){Qt.current+=1;let i=Qt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Lt(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${i}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${i}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,E,d]),ke(()=>{let c=Ks??gn(e);if(!E){Co(0),qt(`${Ro} ${c}`);return}Co(3);let a=0;qt(`${Po[0]} ${c}`);let i=setInterval(()=>{a=(a+1)%Po.length,qt(`${Po[a]} ${c}`)},400);return()=>clearInterval(i)},[E,e,Ks]),ke(()=>()=>Co(0),[]);let Jo=z(c=>{try{let a=Z(e);if(!a)return{kind:"idle"};let i=pe(e,s),h=Qe(i.name),u=!!h&&(!Ue(h)||!!h.refreshToken),m=Cc(e,s)||!vc(e,a.authoritativeSourceFiles),w=Fs(t).state==="missing",b=_o(e,i.name),R=b?Object.keys(b.articles).length:0,T=ht(e,(a.docsDir??yn).replace(/\/+$/,"")),_=!1;try{_=Ke(T)&&Oo(T).length>0}catch{}let M=0;if(b?.lastAnalyzedCommit)try{let F=Om("git",["rev-list","--count",`${b.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});F.status===0&&(M=parseInt((F.stdout||"").trim(),10)||0)}catch{}let O=0;try{let F=mc(e);if(F.length>0){let K=(a.docsDir??yn).replace(/\/+$/,"");O=Br(e,K,F.map(Be=>Be.path)).length}}catch{}let v=nh(e,s),S={ready:u&&m&&!w,hasDocs:_,tracked:R,pendingText:Ht(Ft(e)),behind:M,pendingWrites:O,localAhead:v,autoAudit:!!a.autoAudit,profileName:i.name,allowAutoAudit:c};return Jl(S)}catch{return{kind:"idle"}}},[e,s,t]);ke(()=>{let c=performance.now(),a=[],i=(_,M)=>{let O=performance.now();try{return M()}finally{let v=Math.round(performance.now()-O);v>=80&&a.push(`${_}: ${v}ms`)}};d({kind:"banner",info:i("banner",()=>xh(e,o,t,s))});let h=Fs(t).state==="missing";if(h&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
|
|
282
|
+
${Mm}
|
|
283
|
+
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!Z(e)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
284
|
+
${kc}`}),G(h?["/doctor","/init"]:["/init"]);return}h&&G(["/doctor"]);try{let _=pe(e,s),M=Qe(_.name);M&&Ue(M)&&M.refreshToken?Hm({profile:_.name,connection:_.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),oe(O=>O+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),G(["/login"])}):(!M||Ue(M))&&(d({kind:"note",tone:"warn",text:`Profile "${_.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),G(["/login"]))}catch{}try{let _=Z(e),M=pe(e,s),O=Qe(M.name);_&&O&&!Ue(O)&&vc(e,_.authoritativeSourceFiles)&&!Cc(e,s)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),G(["/scope"]))}catch{}let u=!1;try{let _=i("resolve-genre",()=>eh(e));_.persisted&&_.appType?d({kind:"note",tone:"ok",text:`\u2713 Detected a ${_.appType} app \u2014 enabled the ${_.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):_.source==="unknown"&&Z(e)&&(u=!0,d({kind:"note",tone:"warn",text:"Couldn't tell what kind of product this repo is \u2014 pick one so the docs use the right craft playbook (otherwise output stays generic):"}))}catch{}let m=_e(e);try{if(i("reconcile-devhints",()=>Kn(e)),m.status!=="current")if(Lt(e))d({kind:"note",tone:"warn",text:`\u{1F514} dev\u2194docs protocol updated to v${re}${m.completedVersion?` (you're on v${m.completedVersion})`:""}. Run /devhints to see what changed \u2014 it's also waiting in your inbox. Your docs aren't blocked.`});else{let _=Qn(e);_.length&&(d({kind:"note",tone:"warn",text:_.join(`
|
|
285
|
+
`)}),jt(ct()),Kt.current=!1)}}catch{}try{let _=i("reconcile-feedback",()=>yh(e));_.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${_.archived} resolved item${_.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${_.open>0?`; ${_.open} still open`:""}.`})}catch{}let w=i("ready-decision",()=>Jo(!0)),b=["/genre web","/genre cli","/genre service","/genre library"],R=_=>{let M=_;return u&&(M=[...b.filter(O=>!M.includes(O)),...M]),m.status!=="current"&&Lt(e)&&!M.includes("/devhints")&&(M=[...M,"/devhints"]),M};w.kind==="autoAudit"?(d({kind:"note",tone:"info",text:w.note}),un().then(_=>{_.kind==="forward-to-agent"&&_.prompt&&se(_.prompt,{display:_.display,quietUser:!0})})):w.kind==="noDocs"?(d({kind:"note",tone:"info",text:w.note}),ue(w.ghost),G(R(w.options)),w.title&&de(w.title)):w.kind==="actions"&&(d({kind:"note",tone:"info",text:w.note}),G(R(w.options)),de(w.title));let T=Math.round(performance.now()-c);T>=800&&kh({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${T}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${a.length?a.join(`
|
|
286
286
|
`):"no single phase \u226580ms"}
|
|
287
|
-
cwd: ${e}`}),
|
|
288
|
-
`)});let
|
|
289
|
-
`)}),
|
|
290
|
-
`)}),
|
|
291
|
-
${uc}`}),G(["/init"]),gn(!1),!0},[e,u,St]),oi=z(async c=>{let i=c.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),h=i.slice(1);switch(gn(!0),a){case"help":Vt({tab:0});return;case"exit":case"quit":xe.current?.close(),r();return;case"clear":ye(),kt.current=[],gn(!1),ue(null),ht.current++,u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let d;try{d=pe(e,s)}catch(m){u({kind:"note",tone:"error",text:m.message});return}u({kind:"note",tone:"info",text:`Profile "${d.name}" \u2192 ${d.connection.name} (${d.connection.apiUrl})${d.production?" \u26A0 PRODUCTION":""}`}),J(!0);try{let m=await $m(d.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},k=>u({kind:"note",tone:"info",text:k})),w=vm(d.name,m);if(Cm(w),await nr(w,d.name,k=>u({kind:"note",tone:"info",text:k})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${d.name}" as ${Un(w)}`}),await ei(s),Yt.current){let k=Yt.current;Yt.current=null;let R=Le(e,s);R.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${k}.`}),G([k])):(u({kind:"note",tone:"warn",text:`${R.reason} (then ${k}.)`}),G(["/login"]),Yt.current=k)}else $n.current&&(ue($n.current),$n.current=null,u({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(m){u({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{J(!1),oe(m=>m+1)}return}case"allow-prod":{let d=!1;try{d=pe(e,s).production}catch{}if(!d){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}bt.current=!0,ye(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let d=Qr(h.join(" ")),m=Ne.current.uuid;if(!m){if(!d){u({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Oo.current=d,Ze(d),Ft(`${$o} ${d}`),u({kind:"note",tone:"ok",text:`Session will be named "${d}" once it starts.`});return}if(!d){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Ne.current.firstPrompt??"";ec(w,e).then(k=>{k?(ue(`/rename ${k}`),u({kind:"note",tone:"info",text:`Suggestion: "${k}" \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}_m(m,d),Ze(d),Ft(`${$o} ${d}`),u({kind:"note",tone:"ok",text:`Session renamed to "${d}".`});return}case"profile":{let d=h[0],m=Z(e);if(!d){let w=Object.entries(m?.profiles??{});if(w.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let k=w.map(([_,M])=>({name:_,env:M.connection?.environment??"custom",prod:M.production===!0,who:Qo(_)})),R=s??m?.defaultProfile,T=Math.max(0,k.findIndex(_=>_.name===R));xt({cursor:T,current:T,rows:k});return}if(d==="add"){let w=Jr(e,h[1],h[2]);if(w){u({kind:"note",tone:"error",text:w});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),Jo(h[1],!1);return}if(!m?.profiles?.[d]){u({kind:"note",tone:"error",text:`Unknown profile "${d}". Create it: /profile add ${d} <environment>`});return}Jo(d,!0);return}case"doctor":await un(h,{cwd:e});return;case"mcp":await Jn(h);return;case"init":{if(Z(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let d=Gm().map(m=>({name:m,apiUrl:Ym(m).apiUrl}));$t({cursor:0,rows:d});return}case"resume":{let d=h.join(" ").trim(),m=Im(e).filter(R=>R.uuid!==Ne.current.uuid);if(!d){if(!m.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}it({query:"",cursor:0,sessions:m});return}let w=Nm(e,d);if(!w){u({kind:"note",tone:"error",text:`No session matches "${d}".`});return}ye(w.uuid),Ne.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},Ze(w.name),As(w.uuid),kt.current=[];let k=Ps(e,w.uuid);for(let R of k)u(R);u({kind:"note",tone:"ok",text:k.length?`Resumed "${w.name}" \u2014 restored ${k.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let d=h.join(" ").trim(),m;try{m=await Zt(e,s)}catch(k){u({kind:"note",tone:"error",text:`Could not list workspaces: ${k.message}`});return}if(!d){let k=m.workspaces.map(T=>({id:T.id,name:T.name??T.id,type:T.workspace_type}));if(k.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let R=Math.max(0,k.findIndex(T=>T.id===m.current));vt({cursor:R,current:R,rows:k,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let w=er(m.workspaces,d);if(!w){u({kind:"note",tone:"error",text:`No workspace matches "${d}".`});return}Tn(m.profile,m.projectId,w);return}case"project":{let d=h.join(" ").trim(),m;try{m=await Ge(e,s)}catch(k){u({kind:"note",tone:"error",text:`Could not list projects: ${k.message} (signed in? try /login)`});return}if(!d){let k=m.projects.map(T=>({id:T.id,name:T.name??T.id,sub:T.sub_domain}));if(k.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let R=k.findIndex(T=>T.id===m.current);nt({cursor:Math.max(0,R),current:R,rows:k,profile:m.profile,environment:m.environment});return}let w=tr(m.projects,d);if(!w){u({kind:"note",tone:"error",text:`No project matches "${d}". Available: ${m.projects.map(k=>k.name??k.id).join(", ")}`});return}Dn(m.profile,w);return}case"logout":{let d;try{d=pe(e,s).name}catch(w){u({kind:"note",tone:"error",text:w.message});return}let m=Sm(d);Dm(e,d),ye(),oe(w=>w+1),u({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${d}" and cleared its project/workspace selection.`:`Profile "${d}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),G(["/login"]);return}case"publish":{if(!Bo(c.trim()))return;if(h[0]==="--related"&&h[1]){let m=await to(e,s,h[1].replace(/\\/g,"/"));if(m.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Rn(m);return}if(h[0]&&h[0]!=="--all"){await Xo(h[0]);return}let d=h[0]==="--all";u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await nc({cwd:e,profileName:s}),w=an(m.entries),k=Zn(m.entries);if(k>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${k} article${k===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),w.length===0){u({kind:"note",tone:"ok",text:k>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let R=m.counts["unknown-base"]??0;R>0&&u({kind:"note",tone:"info",text:`(${R} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Ys("Reconciling structure on Document360 (order + related articles)\u2026");try{let T=await ic({cwd:e,profileName:s}),_=cc(await lc({cwd:e,profileName:s})),M=ac(T);M?u({kind:"note",tone:"info",text:M}):T.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${T.skipped}`}),_&&u({kind:"note",tone:"info",text:_}),u({kind:"note",tone:"ok",text:M||_?"\u2713 Structure synced to Document360.":"\u2713 Already in order \u2014 nothing to change."}),de(null),G([{cmd:"/structure",desc:"see the new category + article order"}])}catch(T){u({kind:"note",tone:"warn",text:`Structure sync failed: ${T.message}`})}finally{Ys(null)}return}if(d){await Rn(w.map(R=>R.path));return}Ct({cursor:0,rows:sa(w)})}catch(m){u({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let d=h.join(" ").trim();if(!d){let w=[];try{w=Object.keys(Ao(e,pe(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}rt({query:"",cursor:0,paths:w});return}let m=bm(d)?d:mt(e,d);if(Ke(m)){try{u({kind:"preview",name:mn(m),text:pc(js(m,"utf8"))})}catch(w){u({kind:"note",tone:"error",text:`Could not read ${m}: ${w.message}`})}return}if(lh.test(d)){try{let w=pe(e,s),k={profile:w.name,connection:w.connection},R=w.project.projectId??Rm(k),T=await Tm(k,R,d);u({kind:"preview",name:T.title??d,text:T.content??"*(article has no content)*"})}catch(w){u({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}u({kind:"note",tone:"error",text:`"${d}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let d=h[0]?.trim();if(!d){let R=io(_s(e));tt({cursor:R,current:R});return}let{lines:m,changed:w,effective:k}=cn(e,d);for(let R of m)u({kind:"note",tone:R.startsWith("\u26A0")?"warn":R.startsWith("\u2713")?"ok":"info",text:R});w&&(Ks(R=>R+1),xe.current?.setModel(k));return}case"convert":{if(!Z(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:d,run:m}=Dr(h),w=Km(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 k=jr(w,d);if(k.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${d}". (${w.length} are tracked overall.)`});return}let R=Es(k),T=3,_=`/convert${d?` --scope ${d}`:""} --run`,M=Do(e,"light");if(!m){let v=rc({files:Ar(e,k),op:"convert",model:M.model}),N=d?`Scope: ${d} (${k.length} of ${w.length} tracked)
|
|
287
|
+
cwd: ${e}`}),zo()},[]),ke(()=>{let c=setInterval(()=>{zo()},jh);return()=>clearInterval(c)},[zo]),ke(()=>{if(E||Je.length>0||Lo)return;let c=Jo(!1);(c.kind==="actions"||c.kind==="noDocs")&&(G(c.options),de(c.title??null))},[E,Je,fe,Jo,Lo]),ke(()=>{let c=null,a=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let h=`${De.columns??80}x${De.rows??24}`;h!==ri.current&&(ri.current=h,Mc(u=>u+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+sa(bt.current,qe())+"\x1B[?2026l")},80))},400)};return De.on("resize",i),()=>{c&&clearTimeout(c),a&&clearTimeout(a),De.off("resize",i)}},[De,qe]);let je=Math.max(20,(De.columns??80)-1),si=Os(()=>$h(e,s),[e,s,fe]),Zo=(()=>{if(Ic)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Mo!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Mo?` v${Mo}`:""}\u2026`,isSetup:!0};let c=Z(e);if(!c)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let a=ht(e,(c.docsDir??yn).replace(/\/+$/,"")),i=(()=>{try{return Ke(a)&&Oo(a).length>0}catch{return!1}})();try{let h=pe(e,s),u=Qe(h.name);if(!(!!u&&!(Ue(u)&&!u.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${h.name}")\u2026`,isSetup:!0};if(!h.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!h.project.workspaceId&&!i)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return i?{text:vh,isSetup:!1}:Go?{text:"Press c to copy the prompt above, run it in your coding agent \u2014 then ask me to write the docs",isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Jt=Hl(j),ii=Jt.length>0&&!E,er=p!==null?ic(p,8,je):null,Rn=$e?$e.paths.filter(c=>!$e.query||c.toLowerCase().includes($e.query.toLowerCase())).slice(0,8):[],Tn=Ce?Ce.sessions.filter(c=>{let a=Ce.query.toLowerCase();return!a||c.name.toLowerCase().includes(a)||c.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],ye=z((c,a)=>{be.current?.close(),be.current=lc({cwd:e,resume:c,profileName:a??s,allowProdWrites:xt.current}),c||(Ne.current={uuid:null,firstPrompt:null,titleFired:!1},et(null)),St(0),Dt(0)},[e,s]),ai=z((c,a,i)=>{if(Ch.test(c))try{let h=pe(e,s),u=typeof a.project_id=="string"&&a.project_id||h.project.projectId,m=$o(a,i),w=[],b=vo(i);c.endsWith("publish_article")&&b&&w.push(`Live: ${b}`),m&&u&&w.push(`Preview: ${xo(h.connection.portalUrl,u,m,h.project.languageCode??"en")}`),w.length>0&&d({kind:"link",lines:w})}catch{}},[e,s,d]),se=z(async(c,a)=>{wn(!0),ue(null),G([]),de(null),Vo(null),Qo(null);let i=++gt.current;a?.quietUser||d({kind:"user",text:a?.echoDisplay&&a.display?a.display:c});let h=Ne.current;h.firstPrompt||(h.firstPrompt=a?.display??c),Ze.current=Date.now(),yt(0),I(!0),xn.current.clear();let u="",m=!1,w=!1,b="",R={num:0,closed:!1,cueSeen:!1},T=null,_=()=>{T||(T=setTimeout(()=>{T=null,g(b.length>0?b:null)},60))},M=()=>{T&&clearTimeout(T),T=null,g(null)},O=()=>{if(b.trim()){let v=As(b.trimEnd(),R);d({kind:"assistant",text:v})}b="",M()};try{for await(let v of be.current.send(c))if(v.type==="session"){if(!h.uuid){h.uuid=v.sessionId;let S=new Date().toISOString(),F=Fo.current,K=F??zm(h.firstPrompt??"session");Xm({uuid:v.sessionId,name:K,renamed:!!F,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:S,updatedAt:S}),et(K),Fo.current=null}}else if(v.type==="text"){b+=v.delta,u+=v.delta;let S=ac(b);if(S>0){let F=b.slice(0,S).trimEnd();F&&d({kind:"assistant",text:As(F,R)}),b=b.slice(S)}_(),yt(F=>F+v.delta.length)}else if(v.type==="tool"){m=!0;let S=ko(v.name,v.input);S&&(O(),d({kind:"tool",title:S.title,sep:S.sep,arg:S.arg}),xn.current.set(v.id,{name:v.name,input:v.input}))}else if(v.type==="article_diff"){let S=dt(v.oldContent,v.newContent,qe());S&&(O(),d({kind:"diff",added:S.added,removed:S.removed,lines:S.lines,hidden:S.hidden}))}else if(v.type==="tool_result"){v.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(v.output)&&(vn.current=!0);let S=xn.current.get(v.id);if(S){xn.current.delete(v.id),O();let F=bo(v.output,4,v.isError?void 0:S.name,S.input);d({kind:"tool-result",lines:F.lines,hidden:F.hidden,isError:v.isError}),v.isError||ai(S.name,S.input,v.output)}}else if(v.type==="result"){if(O(),St(S=>S+v.outputTokens),Dt(S=>S+v.costUsd),d({kind:"done",seconds:Math.round((Date.now()-Ze.current)/1e3),tokens:v.outputTokens,costUsd:v.costUsd,ok:v.ok}),!w&&!m&&!u.trim()&&!Yt.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),v.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let S=gh(e);if(Ke(S)){let F=Ls(S,"utf8").trim();F&&(Qo(F),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(v.ok&&R.cueSeen)Ys(!0),G([]);else{let S=v.ok?Vl(u,To.map(F=>F.name)):[];S.length>0?G(S):v.ok&&u.trim()&&Zm(c,u,e).then(F=>{F&>.current===i&&ue(F)}).catch(()=>{})}if(h.uuid&&(Ms(h.uuid),!h.titleFired)){h.titleFired=!0;let S=h.uuid,F=h.firstPrompt;F&&cc(F,e).then(K=>{K&&(Ym(S,K),et(K))}).catch(()=>{})}}else v.type==="error"&&(O(),w=!0,v.kind==="auth"&&(vn.current=!0),d({kind:"note",text:`agent error: ${v.message}`,tone:"error"}))}finally{I(!1),M(),oe(v=>v+1),Ne.current.uuid&&Ml(e,Ne.current.uuid,bt.current),vn.current&&(vn.current=!1,Cn.current=a?.display??c,G(["/login"])),Yt.current&&(Yt.current=!1,it.current.length>0&&(d({kind:"note",tone:"info",text:`(${it.current.length} queued message(s) discarded)`}),it.current=[],Ho([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,ai,qe]),Sn=z(async c=>{let a=Us(c),i=No(e,"standard");Ze.current=Date.now(),yt(0),I(!0);let h=new AbortController;ve.current=h,te({verb:"Publishing",total:a.length,done:0,active:[],rows:hn(a),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Publishing ${c.length} article${c.length===1?"":"s"} across ${a.length} partition${a.length===1?"":"s"} (\u2264${ln} agents at once) on ${i.model}\u2026 (esc to stop)`});try{for await(let u of Eo({cwd:e,partitions:a,promptFor:m=>oo(m.paths),concurrency:ln,profileName:s,allowProdWrites:xt.current,model:i.model,signal:h.signal}))if(u.type==="partition_status")u.status==="running"?te(m=>m&&{...m,active:[...m.active,u.label],rows:Le(m.rows,u.label,"active"),lastAt:Date.now()}):te(m=>m&&{...m,active:m.active.filter(w=>w!==u.label),done:m.done+1,rows:Le(m.rows,u.label,u.status==="done"?"done":"failed"),lastAt:Date.now()});else if(u.type==="partition_event")te(m=>{if(!m)return m;let w={...m,lastAt:Date.now()};return u.event.type==="tool"?w.tools=m.tools+1:u.event.type==="text"&&(w.chars=m.chars+u.event.delta.length),w});else if(u.type==="run_done"){Dt(R=>R+u.totalCostUsd),St(R=>R+u.results.reduce((T,_)=>T+_.outputTokens,0));let m=u.aborted?"Stopped. ":"",w=t.kind==="api"?"api":"subscription";d({kind:"note",tone:u.aborted?"warn":u.ok?"ok":"warn",text:m+Tr(u.results,a,w).join(`
|
|
288
|
+
`)});let b=Rr(e,s);if(b&&d({kind:"note",tone:"info",text:b}),!u.aborted){try{let R=await hc({cwd:e,profileName:s}),T=gc(R);T?d({kind:"note",tone:"info",text:T}):R.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${R.skipped}`})}catch(R){d({kind:"note",tone:"warn",text:`Order sync failed: ${R.message}`})}try{let R=wc(await yc({cwd:e,profileName:s}));R&&d({kind:"note",tone:"info",text:R})}catch(R){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${R.message}`})}}}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{ve.current=null,te(null),I(!1),oe(u=>u+1)}},[e,s,d,t]),tr=z(async c=>{await se(Pr(c),{display:`/publish ${c}`,quietUser:!0});try{let a=await ro(e,s,c.replace(/\\/g,"/"));a.length>0&&(de(`Related articles not yet published (${a.length}):`),G([`/publish --related ${c}`,...a.map(i=>`/publish ${i}`)]))}catch{}},[e,s,se]),nr=z(c=>{let a=Qe(c);if(!a||Ue(a)&&!a.refreshToken)return null;let i={...Bt(a.idToken)??{},...Bt(a.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),or=z((c,a)=>{if(a){let i=Z(e);i&&(i.defaultProfile=c,uc(i,e))}l(c),ye(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),nr(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 do you want to log in now? (press 1)`}),G(["/login"])),oe(i=>i+1)},[e,d,ye,nr]),Dn=z((c,a,i)=>{Mn(e,c,a,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),ye(),_o(e,c)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:Mt(Ot(e)).join(`
|
|
289
|
+
`)}),jt(ct()),Kt.current=_e(e).status==="current"||Lt(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,ye,jt]),jn=z(async c=>{let a;try{a=await tn(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),G(["/workspace"]);return}if(a.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=a.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),h=i.length>0?i:a.workspaces;if(h.length===1){let u=h[0],m=a.workspaces.length-h.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),Dn(a.profile,a.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),G(["/workspace"])},[e,d,Dn]),An=z((c,a)=>{Un(e,c,a.id,a.name),d({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),ye(),jn(c)},[e,d,ye,jn]),li=z(async c=>{let a;try{a=pe(e,c)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:i}=await Ve(e,a.name),h=i.find(u=>u.id===a.project.projectId);h?.name&&wh(e,a.name,{projectName:h.name})}catch{}await jn(a.name);return}try{let{projects:i}=await Ve(e,a.name);if(i.length===1){let h=i[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${h.name??h.id}".`}),An(a.name,{id:h.id,name:h.name});return}if(i.length>1){let h=i.map(u=>({id:u.id,name:u.name??u.id,sub:u.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),ot({cursor:0,current:-1,rows:h,profile:a.name,environment:a.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),G(["/project"])}},[e,d,jn,An]),En=z(()=>{let c=We.current[0];if(!c)return;d({kind:"note",tone:"info",text:`\u25CF ${c.title} (${c.path})`});for(let i of c.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${i}`});c.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let a=dt(c.oldContent,c.newContent,qe());d(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."}),d({kind:"note",tone:"info",text:`Write ${c.path}? (y/n \u2014 anything else cancels)`})},[d,qe]),ci=z(c=>{if(We.current.length===0)return!1;let a=c.trim().toLowerCase();if(a==="y"||a==="yes"){let i=We.current.shift();try{th({cwd:e,profileName:s},i),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${i.path} (sync base advanced).`}),We.current.length===0&&G(h=>h.length>0?h:["/pull"])}catch(h){d({kind:"note",tone:"error",text:`Pull failed: ${h.message}`})}}else if(a==="n"||a==="no"){let i=We.current.shift();d({kind:"note",tone:"info",text:`Skipped ${i.path}.`})}else{let i=We.current.length;return We.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${i} article(s) left untouched).`}),!0}return En(),!0},[e,s,En,d]),ui=z(c=>{let a=Wo.current;if(!a)return!1;if(Wo.current=null,ue(null),gt.current++,c.trim()!==a.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:h}=$s(e,a.targets);d({kind:"note",tone:h.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 u of h)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return a.hadDevhints&&(d({kind:"note",tone:"warn",text:Jn().join(`
|
|
290
|
+
`)}),jt(pr())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
291
|
+
${kc}`}),G(["/init"]),wn(!1),!0},[e,d,jt]),Nn=z(async c=>{let a=c.slice(1).trim().split(/\s+/),i=(a[0]??"").toLowerCase(),h=a.slice(1);if(wn(!0),lo(h)&&["write","check","review","reorder"].includes(i)){let u=Fr(e,s);if(u.length===0){d({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let m=w=>i==="write"?`/write ${Pa(h,w).join(" ")}`.trim():`/${i} ${[w,...h.filter(b=>b!=="--scope")].join(" ")}`.trim();if(u.length===1){Nn(m(u[0].token));return}Rt({cursor:0,rows:u,run:w=>{Nn(m(w))}});return}switch(i){case"help":Xt({tab:0});return;case"exit":case"quit":be.current?.close(),r();return;case"clear":ye(),bt.current=[],wn(!1),ue(null),gt.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=pe(e,s)}catch(m){d({kind:"note",tone:"error",text:m.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),J(!0);try{let m=await Um(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},b=>d({kind:"note",tone:"info",text:b})),w=Wm(u.name,m);if(Fm(w),await ar(w,u.name,b=>d({kind:"note",tone:"info",text:b})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${Hn(w)}`}),await li(s),zt.current){let b=zt.current;zt.current=null;let R=Oe(e,s);R.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${b}.`}),G([b])):(d({kind:"note",tone:"warn",text:`${R.reason} (then ${b}.)`}),G(["/login"]),zt.current=b)}else Cn.current&&(ue(Cn.current),Cn.current=null,d({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(m){d({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{J(!1),oe(m=>m+1)}return}case"allow-prod":{let u=!1;try{u=pe(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}xt.current=!0,ye(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=rs(h.join(" ")),m=Ne.current.uuid;if(!m){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Fo.current=u,et(u),qt(`${Ro} ${u}`),d({kind:"note",tone:"ok",text:`Session will be named "${u}" once it starts.`});return}if(!u){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Ne.current.firstPrompt??"";cc(w,e).then(b=>{b?(ue(`/rename ${b}`),d({kind:"note",tone:"info",text:`Suggestion: "${b}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Jm(m,u),et(u),qt(`${Ro} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=h[0],m=Z(e);if(!u){let w=Object.entries(m?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let b=w.map(([_,M])=>({name:_,env:M.connection?.environment??"custom",prod:M.production===!0,who:nr(_)})),R=s??m?.defaultProfile,T=Math.max(0,b.findIndex(_=>_.name===R));$t({cursor:T,current:T,rows:b});return}if(u==="add"){let w=ss(e,h[1],h[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),or(h[1],!1);return}if(!m?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}or(u,!0);return}case"doctor":await pn(h,{cwd:e});return;case"mcp":await to(h);return;case"init":{if(Z(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let u=lh().map(m=>({name:m,apiUrl:ch(m).apiUrl}));vt({cursor:0,rows:u});return}case"resume":{let u=h.join(" ").trim(),m=Qm(e).filter(R=>R.uuid!==Ne.current.uuid);if(!u){if(!m.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}at({query:"",cursor:0,sessions:m});return}let w=Km(e,u);if(!w){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}ye(w.uuid),Ne.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},et(w.name),Ms(w.uuid),bt.current=[];let b=Es(e,w.uuid);for(let R of b)d(R);d({kind:"note",tone:"ok",text:b.length?`Resumed "${w.name}" \u2014 restored ${b.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=h.join(" ").trim(),m;try{m=await tn(e,s)}catch(b){d({kind:"note",tone:"error",text:`Could not list workspaces: ${b.message}`});return}if(!u){let b=m.workspaces.map(T=>({id:T.id,name:T.name??T.id,type:T.workspace_type}));if(b.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let R=Math.max(0,b.findIndex(T=>T.id===m.current));Ct({cursor:R,current:R,rows:b,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let w=sr(m.workspaces,u);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}Dn(m.profile,m.projectId,w);return}case"project":{let u=h.join(" ").trim(),m;try{m=await Ve(e,s)}catch(b){d({kind:"note",tone:"error",text:`Could not list projects: ${b.message} (signed in? try /login)`});return}if(!u){let b=m.projects.map(T=>({id:T.id,name:T.name??T.id,sub:T.sub_domain}));if(b.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let R=b.findIndex(T=>T.id===m.current);ot({cursor:Math.max(0,R),current:R,rows:b,profile:m.profile,environment:m.environment});return}let w=ir(m.projects,u);if(!w){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${m.projects.map(b=>b.name??b.id).join(", ")}`});return}An(m.profile,w);return}case"logout":{let u;try{u=pe(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let m=Gm(u);Vm(e,u),ye(),oe(w=>w+1),d({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${u}" and cleared its project/workspace selection.`:`Profile "${u}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),G(["/login"]);return}case"publish":{if(!Xo(c.trim()))return;if(h[0]==="--related"&&h[1]){let m=await ro(e,s,h[1].replace(/\\/g,"/"));if(m.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Sn(m);return}if(h[0]&&h[0]!=="--all"){await tr(h[0]);return}let u=h[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await dc({cwd:e,profileName:s}),w=cn(m.entries),b=no(m.entries);if(b>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${b} article${b===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),w.length===0){d({kind:"note",tone:"ok",text:b>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let R=m.counts["unknown-base"]??0;R>0&&d({kind:"note",tone:"info",text:`(${R} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),ei("Reconciling structure on Document360 (order + related articles)\u2026");try{let T=await hc({cwd:e,profileName:s}),_=wc(await yc({cwd:e,profileName:s})),M=gc(T);M?d({kind:"note",tone:"info",text:M}):T.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${T.skipped}`}),_&&d({kind:"note",tone:"info",text:_}),d({kind:"note",tone:"ok",text:M||_?"\u2713 Structure synced to Document360.":"\u2713 Already in order \u2014 nothing to change."}),de(null),G([{cmd:"/structure",desc:"see the new category + article order"}])}catch(T){d({kind:"note",tone:"warn",text:`Structure sync failed: ${T.message}`})}finally{ei(null)}return}if(u){await Sn(w.map(R=>R.path));return}Pt({cursor:0,rows:pa(w)})}catch(m){d({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let u=h.join(" ").trim();if(!u){let w=[];try{w=Object.keys(_o(e,pe(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}st({query:"",cursor:0,paths:w});return}let m=Lm(u)?u:ht(e,u);if(Ke(m)){try{d({kind:"preview",name:gn(m),text:xc(Ls(m,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${m}: ${w.message}`})}return}if(Ph.test(u)){try{let w=pe(e,s),b={profile:w.name,connection:w.connection},R=w.project.projectId??qm(b),T=await Bm(b,R,u);d({kind:"preview",name:T.title??u,text:T.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${u}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let u=h[0]?.trim();if(!u){let R=uo(Hs(e));nt({cursor:R,current:R});return}let{lines:m,changed:w,effective:b}=dn(e,u);for(let R of m)d({kind:"note",tone:R.startsWith("\u26A0")?"warn":R.startsWith("\u2713")?"ok":"info",text:R});w&&(oi(R=>R+1),be.current?.setModel(b));return}case"convert":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:m}=Ir(h),w=ph(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let b=_r(w,u);if(b.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${w.length} are tracked overall.)`});return}let R=Us(b),T=3,_=`/convert${u?` --scope ${u}`:""} --run`,M=No(e,"light");if(!m){let v=fc({files:Or(e,b),op:"convert",model:M.model}),S=u?`Scope: ${u} (${b.length} of ${w.length} tracked)
|
|
292
292
|
`:"",F=`
|
|
293
|
-
Model: ${M.model}${M.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;
|
|
294
|
-
`)+F}),G([_]);return}
|
|
295
|
-
`)})}}catch(v){
|
|
293
|
+
Model: ${M.model}${M.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:S+Mr(R,v,T).join(`
|
|
294
|
+
`)+F}),G([_]);return}Ze.current=Date.now(),yt(0),I(!0);let O=new AbortController;ve.current=O,te({verb:"Converting",total:R.length,done:0,active:[],rows:hn(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${b.length} articles across ${R.length} partitions (\u2264${T} agents at once) on ${M.model}\u2026 (esc to stop)`});try{for await(let v of Eo({cwd:e,partitions:R,promptFor:Lr,concurrency:T,profileName:s,allowProdWrites:xt.current,model:M.model,signal:O.signal}))if(v.type==="partition_status")v.status==="running"?te(S=>S&&{...S,active:[...S.active,v.label],rows:Le(S.rows,v.label,"active"),lastAt:Date.now()}):te(S=>S&&{...S,active:S.active.filter(F=>F!==v.label),done:S.done+1,rows:Le(S.rows,v.label,v.status==="done"?"done":"failed"),lastAt:Date.now()});else if(v.type==="partition_event")te(S=>{if(!S)return S;let F={...S,lastAt:Date.now()};return v.event.type==="tool"?F.tools=S.tools+1:v.event.type==="text"&&(F.chars=S.chars+v.event.delta.length),F});else if(v.type==="run_done"){Dt(K=>K+v.totalCostUsd),St(K=>K+v.results.reduce((Be,Et)=>Be+Et.outputTokens,0));let S=v.aborted?"Stopped. ":"",F=t.kind==="api"?"api":"subscription";d({kind:"note",tone:v.aborted?"warn":v.ok?"ok":"warn",text:S+Ur(v.results,R,F).join(`
|
|
295
|
+
`)})}}catch(v){d({kind:"note",tone:"error",text:`Convert run failed: ${v.message}`})}finally{ve.current=null,te(null),I(!1),oe(v=>v+1)}return}case"write":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=mc(e);if(u.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:w,preview:b,concurrency:R,rewrite:T}=qr(h),{docsDir:_,targets:M,reason:O,rewriting:v}=Kr(e,u,{scope:m,path:w,rewrite:T});if(M.length===0){d({kind:"note",tone:"warn",text:O??"Nothing to write."});return}v&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${M.length} already-written article${M.length===1?"":"s"} (overwrites them; git has your baseline).`});let S=Us(M),F=Hr(R),K=No(e,"standard"),Be=!!w;if(b&&!Be){let Y=fc({files:Gr(e,u,M),op:"write",model:K.model}),ne=m?`Scope: ${m} (${M.length} pending)
|
|
296
296
|
`:"",ce=`
|
|
297
|
-
Model: ${
|
|
298
|
-
`)+ce}),G([`/write${m?` --scope ${m}`:""}`]);return}
|
|
299
|
-
`)});let Ae=
|
|
300
|
-
${
|
|
301
|
-
`)}`}),G(
|
|
302
|
-
`)});return}if(
|
|
297
|
+
Model: ${K.model}${K.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:ne+Yr(S,Y,F).join(`
|
|
298
|
+
`)+ce}),G([`/write${m?` --scope ${m}`:""}`]);return}Ze.current=Date.now(),yt(0),I(!0);let Et=new AbortController;ve.current=Et,te({verb:"Writing",total:S.length,done:0,active:[],rows:hn(S),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${M.length} article${M.length===1?"":"s"} across ${S.length} partition${S.length===1?"":"s"} (\u2264${F} agents at once) on ${K.model}${K.forced?" (forced)":""}\u2026 (esc to stop)`});let mi=new Set;try{for await(let Y of Eo({cwd:e,partitions:S,promptFor:ne=>Vr(ne,_,{rewrite:v||Be}),concurrency:F,profileName:s,allowProdWrites:xt.current,model:K.model,signal:Et.signal}))if(Y.type==="partition_status")Y.status==="running"?te(ne=>ne&&{...ne,active:[...ne.active,Y.label],rows:Le(ne.rows,Y.label,"active"),lastAt:Date.now()}):te(ne=>ne&&{...ne,active:ne.active.filter(ce=>ce!==Y.label),done:ne.done+1,rows:Le(ne.rows,Y.label,Y.status==="done"?"done":"failed"),lastAt:Date.now()});else if(Y.type==="partition_event"){let ne=null;if(Y.event.type==="tool"){let ce=zl(Y.event.name,Y.event.input,S[Y.index]?.paths??[]);ce&&!mi.has(ce)&&(mi.add(ce),ne=Y.label)}te(ce=>{if(!ce)return ce;let Ae={...ce,lastAt:Date.now()};return Y.event.type==="tool"?Ae.tools=ce.tools+1:Y.event.type==="text"&&(Ae.chars=ce.chars+Y.event.delta.length),ne&&(Ae.rows=Yl(Ae.rows,ne)),Ae})}else if(Y.type==="run_done"){Dt(Nt=>Nt+Y.totalCostUsd),St(Nt=>Nt+Y.results.reduce((On,lt)=>On+lt.outputTokens,0));let ne=Y.aborted?"Stopped. ":"",ce=t.kind==="api"?"api":"subscription";d({kind:"note",tone:Y.aborted?"warn":Y.ok?"ok":"warn",text:ne+zr(Y.results,S,ce).join(`
|
|
299
|
+
`)});let Ae=Y.aborted?null:Xr(e,_,M);if(Ae&&d({kind:"note",tone:"warn",text:Ae}),!Y.aborted&&Y.ok){let Nt=m??w??"",On=Nt?` ${Nt}`:"",lt=[];Ae&<.push({cmd:`/check${On} --fix`,desc:"fix the issues the checker just flagged"}),lt.push({cmd:`/review${On} --fix`,desc:"editorial review + apply fixes (style, grammar, structure)"}),lt.push({cmd:"/publish --all",desc:"publish the drafts to Document360"}),lt.push({cmd:"/screenshot --all",desc:"add screenshots first (optional)"}),G(lt),de(Ae?"Written \u2014 but the checker flagged issues. Fix, review, then publish:":"Written. Review for quality, then publish:")}}}catch(Y){d({kind:"note",tone:"error",text:`Write run failed: ${Y.message}`})}finally{ve.current=null,te(null),I(!1),oe(Y=>Y+1)}return}case"draft":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:m}=Qr(e);if(u.length===0&&m===0){d({kind:"note",tone:"info",text:Zr});return}let w=h.join(" ").trim();if(!w&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
300
|
+
${u.map(T=>` \u2022 ${T.name} (${T.docCount} doc${T.docCount===1?"":"s"})`).join(`
|
|
301
|
+
`)}`}),G(u.map(T=>`/draft ${T.name}`));return}let b="",R;if(w){let T=Jr(u,w);T?b=T:R=w}else b=u[0]?.name??"";await se(co(b,R),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!Xo(c.trim()))return;let u=h.find(m=>m.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let b=Date.now(),R=await dc({cwd:e,profileName:s});d({kind:"note",tone:"info",text:io(R,Date.now()-b).join(`
|
|
302
|
+
`)});return}if(u==="--baseline"){let b=h.find(M=>!M.startsWith("--")),R=b?b.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:R?`Setting the sync baseline for ${R}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let T=await sh({cwd:e,profileName:s,relPaths:R?[R]:void 0}),_=R?{rebaselined:[],skipped:[]}:await ih({cwd:e,profileName:s});if(T.baselined.length===0&&T.skipped.length===0&&_.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}T.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${T.baselined.length} article${T.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),_.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${_.rebaselined.length} article${_.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),T.skipped.length>0&&d({kind:"note",tone:"warn",text:`${T.skipped.length} skipped:
|
|
303
303
|
${T.skipped.map(M=>` - ${M.path} (${M.reason})`).join(`
|
|
304
|
-
`)}`}),oe(M=>M+1);return}if(
|
|
305
|
-
`)});return}if(
|
|
306
|
-
`)}),G([{cmd:`/review${m} --fix`,desc:"editorial review + apply fixes (style, grammar, structure)"},{cmd:"/publish --all",desc:"publish the corrected docs to Document360"}]),de(
|
|
307
|
-
`)}),w.length>0&&(G([{cmd:`/check${m} --fix`,desc:"have the agent fix these in place"},{cmd:`/review${m} --fix`,desc:"also run the editorial review (style, grammar, structure)"},{cmd:"/publish --all",desc:"skip fixing \u2014 publish the docs as-is"}]),de(`Found ${w.length} doc issue${w.length===1?"":"s"} above \u2014 fix them, or publish as-is:`));return}case"structure":{let
|
|
308
|
-
`)});return}case"reorder":{let
|
|
309
|
-
`)});return}case"devhints":{if(!Z(e)){
|
|
310
|
-
`)}),
|
|
311
|
-
`)});return}if(
|
|
312
|
-
`)})}return}case"reset":{let
|
|
313
|
-
`)}),ue(mn(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,jn,u,ye,se,Rn,Xo,ei]),An=z(c=>{let i=(c??S).trim();if(x(""),wn(null),yt(0),i.startsWith("/")&&(ue(null),ht.current++,de(null),G(h=>Hl(h,i))),!i||ni(i)||ti(i))return;Io.current.push(i);let a=Vl(i,Fs.current);i.startsWith("/")?(u({kind:"user",text:i}),oi(a)):se(a,{display:i})},[S,ni,ti,oi,se]),ri=z(c=>{if(c.length>1){if(c.includes("\x1B"))return;let i=Bl(c);if(Gl(i)){let a=Yl(++Tc.current,i);Fs.current.set(a,i),P(a)}else P(i);return}P(c)},[P]),Dt=Math.max(10,_e-6),si=Ds(()=>Ro(g.text,Dt),[g.text,Dt]),Zo=z(c=>b(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+c))})),[]),En=z(c=>b(i=>({...i,pos:Kl(Ro(i.text,Dt),i.pos,c)})),[Dt]),Qt=z(c=>b(i=>({...i,pos:Xl(Ro(i.text,Dt),i.pos,c)})),[Dt]),jc=["\x1B[H","\x1B[1~","\x1BOH"],Ac=["\x1B[F","\x1B[4~","\x1BOF"],ii=z((c,i)=>i.leftArrow?(Zo(-1),!0):i.rightArrow?(Zo(1),!0):c&&jc.includes(c)?(Qt("start"),!0):c&&Ac.includes(c)?(Qt("end"),!0):i.ctrl&&c==="a"?(Qt("start"),!0):i.ctrl&&c==="e"?(Qt("end"),!0):!1,[Zo,Qt]);return ym((c,i)=>{if(i.ctrl&&c==="c"){xe.current?.close(),r();return}if(!W){if(j){if(i.escape){if(Ce.current){if(!Ce.current.signal.aborted){let a=(bn?.verb??"work").toLowerCase(),h=bn?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${h}s)\u2026`}),Ce.current.abort()}return}Gt.current||(Gt.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),xe.current?.interrupt());return}if(i.return){let a=S.trim();if(!a)return;st.current.push(a),Lo([...st.current]),x("");return}if(ii(c,i))return;if(i.upArrow){En(-1);return}if(i.downArrow){En(1);return}if(i.backspace||i.delete){C();return}c&&!i.ctrl&&!i.meta&&ri(c);return}if(et){if(i.upArrow){tt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){tt(a=>a&&{...a,cursor:Math.min(Ee.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ee.length){tt(a=>a&&{...a,cursor:Number(c)-1});return}if(i.return){let a=Ee[et.cursor];tt(null);let{lines:h,changed:d,effective:m}=cn(e,a.value??"default");for(let w of h)u({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});d&&(Ks(w=>w+1),xe.current?.setModel(m));return}if(c==="s"){let a=Ee[et.cursor];tt(null),xe.current?.setModel(a.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){tt(null);return}return}if(Ie){if(i.upArrow){xt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){xt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ie.rows.length){xt(a=>a&&{...a,cursor:Number(c)-1});return}if(i.return||c==="s"){let a=Ie.rows[Ie.cursor];xt(null),Jo(a.name,i.return===!0);return}if(i.escape){xt(null);return}return}if(Mo){if(i.escape){Vt(null);return}if(i.leftArrow||i.tab&&i.shift){Vt(a=>a&&{tab:(a.tab-1+Te.length)%Te.length});return}if(i.rightArrow||i.tab){Vt(a=>a&&{tab:(a.tab+1)%Te.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Te.length){Vt({tab:Number(c)-1});return}return}if(He){if(i.upArrow){$t(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){$t(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=He.rows.length){$t(a=>a&&{...a,cursor:Number(c)-1});return}if(i.return){let a=He.rows[He.cursor].name;if($t(null),!lr(e,a).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${a}").`});let d=!1;try{let m=Xe(a);d=!!m&&!(We(m)&&!m.refreshToken)}catch{d=!1}u({kind:"note",tone:"info",text:d?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),G(["/login"]),oe(m=>m+1);return}if(i.escape){$t(null);return}return}if(me){if(i.upArrow){vt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){vt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=me.rows.length){vt(a=>a&&{...a,cursor:Number(c)-1});return}if(i.return){let a=me.rows[me.cursor],{profile:h,projectId:d}=me;vt(null),Tn(h,d,a);return}if(i.escape){vt(null);return}return}if($e){if(i.upArrow){nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){nt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=$e.rows.length){nt(a=>a&&{...a,cursor:Number(c)-1});return}if(i.return){let a=$e.rows[$e.cursor],{profile:h}=$e;nt(null),Dn(h,a);return}if(i.escape){nt(null);return}return}if(ge){if(i.upArrow){Pt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Pt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c===" "){Pt(a=>a&&{...a,rows:a.rows.map((h,d)=>d===a.cursor?{...h,checked:!h.checked}:h)});return}if(i.return){let a=ge.rows.filter(h=>h.checked).map(h=>h.path);if(Pt(null),a.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}vr(e,a),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of a)u({kind:"note",tone:"info",text:` ${h}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){Pt(null);return}return}if(ot){if(i.upArrow){Ct(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ct(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ot.rows.length){Ct(a=>a&&{...a,cursor:Number(c)-1});return}if(i.return){let a=ot.rows[ot.cursor];Ct(null),a.kind==="article"?Xo(a.paths[0]):Rn(a.paths);return}if(i.escape){Ct(null);return}return}if(ve){if(i.escape){rt(null);return}if(i.upArrow){rt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){rt(a=>a&&{...a,cursor:Math.min(Math.max(0,Cn.length-1),a.cursor+1)});return}if(i.return){let a=Cn[ve.cursor];if(a){rt(null);try{u({kind:"preview",name:mn(a),text:pc(js(mt(e,a),"utf8"))})}catch(h){u({kind:"note",tone:"error",text:`Could not read ${a}: ${h.message}`})}}return}if(i.backspace||i.delete){rt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(c&&!i.ctrl&&!i.meta&&c.length===1){rt(a=>a&&{...a,query:a.query+c,cursor:0});return}return}if(Pe){if(i.escape){it(null);return}if(i.upArrow){it(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){it(a=>a&&{...a,cursor:Math.min(Math.max(0,Pn.length-1),a.cursor+1)});return}if(i.return){let a=Pn[Pe.cursor];if(a){it(null),ye(a.uuid),Ne.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Ze(a.name),As(a.uuid),kt.current=[];let h=Ps(e,a.uuid);for(let d of h)u(d);u({kind:"note",tone:"ok",text:h.length?`Resumed "${a.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){it(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(c&&!i.ctrl&&!i.meta&&c.length===1){it(a=>a&&{...a,query:a.query+c,cursor:0});return}return}if(i.tab&&!S&&De){x(De),ue(null),ht.current++;return}if(!S&&Qe.length>0&&c&&/^[1-9]$/.test(c)){let a=Qe[Number(c)-1];if(a){x(ft(a));return}}if(!S&&(Go||Wo)&&c==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=Go!=null;Pl(Go??Wo).then(d=>{u({kind:"note",tone:d?"ok":"warn",text:d?a?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),d&&a&&Yo(null)});return}if(!ii(c,i)){if(Js){if(i.upArrow){yt(a=>Math.max(0,a-1));return}if(i.downArrow){yt(a=>Math.min(Xt.length-1,a+1));return}if(i.tab){x("/"+(Xt[Bt]?.name??"")+" "),yt(0);return}if(i.return){let a=Xt[Bt];if(a){let h=S.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Il(a.usage)&&!h){x("/"+a.name+" "),yt(0);return}An("/"+a.name+(h?" "+h:""));return}}}else{if(i.upArrow){if(S!==""&&wt===null){En(-1);return}let a=Io.current;if(!a.length)return;let h=wt===null?a.length-1:Math.max(0,wt-1);wn(h),x(a[h]??"");return}if(i.downArrow){if(S!==""&&wt===null){En(1);return}let a=Io.current;if(wt===null)return;let h=wt+1;h>=a.length?(wn(null),x("")):(wn(h),x(a[h]??""));return}}if(i.return){An();return}if(i.backspace||i.delete){C();return}if(i.escape){x(""),yt(0),ue(null),G([]),de(null);return}c&&!i.ctrl&&!i.meta&&ri(c)}}}),be(()=>{if(j||W)return;let c=st.current.shift();c!==void 0&&(Lo([...st.current]),An(c))},[j,W,An]),Y(ne,{flexDirection:"column",width:_e,children:[Ko!==null&&Y(ne,{marginTop:1,flexDirection:"column",children:[Ko.truncated&&E(D,{dimColor:!0,children:"\u2026"}),E(D,{children:Ko.text})]}),j&&(bn?E(ph,{p:bn}):E(ch,{startTime:Je.current,chars:Rc})),!j&&Gs?E(uh,{text:Gs}):null,E(ne,{borderStyle:"round",borderColor:Qs.prod?"yellow":B,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:S?si.map((c,i)=>{let a=g.text.slice(c.start,c.end),h=i===To(si,g.pos),d=Math.min(g.pos,c.end)-c.start;return Y(D,{children:[E(D,{color:B,children:i===0?"> ":" "}),h?Y(Ns,{children:[a.slice(0,d),E(jo,{ch:a[d]??" "}),a.slice(d+1)]}):a||" "]},`${i}-${c.start}`)}):Y(D,{children:[E(D,{color:B,children:"> "}),De&&!j?Y(Ns,{children:[E(jo,{ch:De[0],dim:!0}),E(D,{color:"gray",children:De.slice(1)}),E(D,{dimColor:!0,children:" (tab)"})]}):(zo.isSetup||!Cc)&&!j?Y(Ns,{children:[E(jo,{ch:zo.text[0],dim:!0}),E(D,{color:"gray",children:zo.text.slice(1)})]}):E(jo,{ch:" "})]})}),Bs.length>0&&E(ne,{flexDirection:"column",paddingX:1,children:Bs.map((c,i)=>E(D,{color:"gray",children:`\u29D7 queued: ${c}`},`${i}-${c.slice(0,24)}`))}),Mo?E(Ol,{tab:Mo.tab,width:_e}):et?Y(ne,{flexDirection:"column",paddingX:1,children:[E(D,{color:B,bold:!0,children:"Select model"}),E(D,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ee.map((c,i)=>Y(D,{color:i===et.cursor?B:void 0,children:[i===et.cursor?"\u276F ":" ",`${i+1}. ${c.label}${i===et.current?" \u2714":""}`.padEnd(16),E(D,{color:"gray",children:c.desc})]},c.label)),E(D,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Ie?Y(ne,{flexDirection:"column",paddingX:1,children:[E(D,{color:B,bold:!0,children:"Switch connection profile"}),Ie.rows.map((c,i)=>Y(D,{color:i===Ie.cursor?B:void 0,children:[i===Ie.cursor?"\u276F ":" ",`${i+1}. ${c.name}${i===Ie.current?" \u2714":""}`.padEnd(20),E(D,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?E(D,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),E(D,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):He?Y(ne,{flexDirection:"column",paddingX:1,children:[E(D,{color:B,bold:!0,children:"Pick your Document360 environment"}),He.rows.map((c,i)=>Y(D,{color:i===He.cursor?B:void 0,children:[i===He.cursor?"\u276F ":" ",`${i+1}. ${c.name}`.padEnd(16),E(D,{color:"gray",children:c.apiUrl})]},c.name)),E(D,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):me?Y(ne,{flexDirection:"column",paddingX:1,children:[E(D,{color:B,bold:!0,children:"Switch workspace"}),E(D,{dimColor:!0,children:`environment ${me.environment} \xB7 project ${me.projectName??`${me.projectId.slice(0,8)}\u2026`}`}),me.rows.map((c,i)=>Y(D,{color:i===me.cursor?B:void 0,children:[i===me.cursor?"\u276F ":" ",`${i+1}. ${c.name}${i===me.current?" \u2714":""}`.padEnd(30),E(D,{color:"gray",children:c.type??""})]},c.id)),E(D,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):$e?Y(ne,{flexDirection:"column",paddingX:1,children:[E(D,{color:B,bold:!0,children:"Choose project"}),E(D,{dimColor:!0,children:`environment ${$e.environment}`}),$e.rows.map((c,i)=>Y(D,{color:i===$e.cursor?B:void 0,children:[i===$e.cursor?"\u276F ":" ",`${i+1}. ${c.name}${i===$e.current?" \u2714":""}`.padEnd(30),E(D,{color:"gray",children:c.sub??""})]},c.id)),E(D,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ge?(()=>{let i=Math.min(Math.max(0,ge.cursor-Math.floor(7)),Math.max(0,ge.rows.length-14)),a=ge.rows.slice(i,i+14),h=ge.rows.filter(d=>d.checked).length;return Y(ne,{flexDirection:"column",paddingX:1,children:[E(D,{color:B,bold:!0,children:`Which folders back the user docs? (${h} selected of ${ge.rows.length})`}),i>0?E(D,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((d,m)=>{let w=i+m;return Y(D,{color:w===ge.cursor?B:void 0,children:[w===ge.cursor?"\u276F ":" ",d.checked?"\u25C9 ":"\u25CB ",d.path.padEnd(Math.min(48,_e-34)),E(D,{color:"gray",children:no(d)})]},d.path)}),i+14<ge.rows.length?E(D,{dimColor:!0,children:` \u2193 ${ge.rows.length-i-14} more`}):null,E(D,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():ot?Y(ne,{flexDirection:"column",paddingX:1,children:[E(D,{color:B,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),ot.rows.map((c,i)=>{let a=i===ot.cursor,h=c.indent?" ":" ",d=`${i+1}.`.padEnd(3);return Y(D,{color:a?B:void 0,bold:c.kind==="category"&&!a,children:[a?"\u276F ":" ",`${h}${d} ${c.label}`.padEnd(Math.min(56,_e-24)),c.note?E(D,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),E(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ve?Y(ne,{flexDirection:"column",paddingX:1,children:[E(D,{color:B,bold:!0,children:`Preview article${ve.query?` \u2014 filter: ${ve.query}`:" (type to filter)"}`}),Cn.length===0?E(D,{color:"gray",children:"no articles match"}):Cn.map((c,i)=>Y(D,{color:i===ve.cursor?B:void 0,children:[i===ve.cursor?"\u276F ":" ",c]},c)),E(D,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Pe?Y(ne,{flexDirection:"column",paddingX:1,children:[E(D,{color:B,bold:!0,children:`Resume session${Pe.query?` \u2014 filter: ${Pe.query}`:" (type to filter)"}`}),Pn.length===0?E(D,{color:"gray",children:"no sessions match"}):Pn.map((c,i)=>Y(D,{color:i===Pe.cursor?B:void 0,children:[i===Pe.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),E(D,{color:i===Pe.cursor?B:"gray",children:c.firstPrompt.slice(0,Math.max(10,_e-40))})]},c.uuid)),E(D,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Js?Y(ne,{flexDirection:"column",children:[Xt.map((c,i)=>Y(D,{color:i===Bt?B:void 0,children:[i===Bt?"\u276F ":" ",c.usage.padEnd(22)," ",E(D,{color:i===Bt?B:"gray",children:c.name==="model"&&Uo?`${c.desc} (currently ${Uo})`:c.desc})]},c.name)),E(D,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!j&&!S&&Qe.length>0?Y(ne,{flexDirection:"column",paddingX:1,children:[qs?E(D,{color:B,children:qs}):null,Qe.map((c,i)=>{let a=ft(c),h=a.slice(0,Math.max(20,_e-5)),d=_e-h.length-7,m=d>=12?(Fl(c)??El(a)).slice(0,d):"";return Y(D,{children:[E(D,{color:B,children:i+1})," ",h,m?E(D,{dimColor:!0,children:` \u2014 ${m}`}):null]},a)}),E(D,{dimColor:!0,children:`press 1-${Qe.length} to fill the command \xB7 esc dismiss`})]}):E(ne,{paddingX:1,children:Y(D,{color:"gray",children:[Qs.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Uo??"model n/a"}${t.kind==="api"?zs>0?` \xB7 ${he(zs)}`:"":Vs>0?` \xB7 ${Ve(Vs)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}H();import{jsx as gh}from"react/jsx-runtime";async function yc(e=process.cwd(),t="auto",n,o="0.0.0"){let r=hh(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=mh(gh(gc,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
314
|
-
`),process.exit(0)}H();import{writeCrashLog as
|
|
315
|
-
`+$(`\u2717 d360-writer crashed: ${
|
|
304
|
+
`)}`}),oe(M=>M+1);return}if(u==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let b=await oh({cwd:e,profileName:s}),R=b.onlyInLegacy.length===0&&b.onlyInManifest.length===0&&b.mappedMissingFromManifest.length===0,T=[`Legacy listing: ${b.legacyCount} \xB7 Manifest: ${b.manifestCount} \xB7 in both: ${b.inBoth}`];R?T.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(b.mappedMissingFromManifest.length&&T.push(`\u2717 ${b.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${b.mappedMissingFromManifest.slice(0,5).join(", ")}`),b.onlyInLegacy.length&&T.push(`\u26A0 ${b.onlyInLegacy.length} only in the legacy listing: ${b.onlyInLegacy.slice(0,5).join(", ")}`),b.onlyInManifest.length&&T.push(`\u26A0 ${b.onlyInManifest.length} only in the manifest: ${b.onlyInManifest.slice(0,5).join(", ")}`),T.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:R?"ok":"warn",text:T.join(`
|
|
305
|
+
`)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=h[0];if(m){let b=await rh({cwd:e,profileName:s,relPath:m.replace(/\\/g,"/")});We.current=[b],En();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let w=await Ar({cwd:e,profileName:s});for(let b of Er(w))d({kind:"note",tone:b.tone,text:b.text});oe(b=>b+1)}catch(m){d({kind:"note",tone:"error",text:`Pull failed: ${m.message}`})}return}case"scope":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=ah(e);if(u.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Tt({cursor:0,rows:u.map(m=>({...m,checked:m.recommended}))});return}case"audit":{if(h[0]==="--auto"){let m=Z(e);if(!m){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=h[1]!=="off";uc({...m,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let u=await un();u.kind==="forward-to-agent"&&u.prompt&&await se(u.prompt,{display:u.display,quietUser:!0});return}case"check":{let u=h.find(b=>!b.startsWith("--")),m=u?` ${u}`:"",w=pc({cwd:e,scope:u});if(h.includes("--fix")){if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}d({kind:"note",tone:"info",text:`Fixing ${w.length} doc issue${w.length===1?"":"s"}\u2026`}),await se(Cs(w),{display:`/check${m} --fix`,quietUser:!0});let b=pc({cwd:e,scope:u});d({kind:"note",tone:b.length===0?"ok":"warn",text:b.length===0?"\u2713 Doc-checker: all issues resolved.":wo(b).join(`
|
|
306
|
+
`)}),G([{cmd:`/review${m} --fix`,desc:"editorial review + apply fixes (style, grammar, structure)"},{cmd:"/publish --all",desc:"publish the corrected docs to Document360"}]),de(b.length===0?"Deterministic issues fixed. Review for quality, then publish:":"Some issues remain \u2014 review, then publish:");return}d({kind:"note",tone:w.length===0?"ok":"warn",text:wo(w).join(`
|
|
307
|
+
`)}),w.length>0&&(G([{cmd:`/check${m} --fix`,desc:"have the agent fix these in place"},{cmd:`/review${m} --fix`,desc:"also run the editorial review (style, grammar, structure)"},{cmd:"/publish --all",desc:"skip fixing \u2014 publish the docs as-is"}]),de(`Found ${w.length} doc issue${w.length===1?"":"s"} above \u2014 fix them, or publish as-is:`));return}case"structure":{let u=mn(e,s);if(u.length===0){d({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}d({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...u].join(`
|
|
308
|
+
`)});return}case"reorder":{let u=Rs(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await se(u.prompt,{display:u.display,quietUser:!0}),G([{cmd:"/publish --all",desc:"sync the new order to Document360"}]),de("Reordered locally \u2014 publish to sync the new order:");return}case"review":{let u=Ps(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=h.includes("--fix");if(await se(u.prompt,{display:u.display,quietUser:!0}),m)G([{cmd:"/publish --all",desc:"publish the corrected docs to Document360"},{cmd:"/check",desc:"optional: instant re-scan for leaks/bad commands (no tokens)"}]),de("\u2713 Editor applied its fixes \u2014 your docs are corrected. Publish them, or re-scan first:");else{let w=h.filter(b=>b!=="--fix").join(" ");G([{cmd:`/review${w?` ${w}`:""} --fix`,desc:"let the editor apply all the fixes it listed above"},{cmd:"/check --fix",desc:"fix just the deterministic issues (leaks, bad commands)"},{cmd:"/publish --all",desc:"skip fixing \u2014 publish the docs as-is"}]),de("The review listed issues above. Apply the fixes, or publish as-is:")}return}case"capture-setup":{let u=await fn();u.kind==="forward-to-agent"&&u.prompt&&await se(u.prompt,{display:u.display,quietUser:!0});let m=ds(e);m&&d({kind:"note",tone:"info",text:m.join(`
|
|
309
|
+
`)});return}case"devhints":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Mt(Ot(e)).join(`
|
|
310
|
+
`)}),jt(ct()),Kt.current=_e(e).status==="current"||Lt(e);return}case"inbox":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(ps(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await se(fs(),{display:"/inbox",quietUser:!0});return}case"document":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:m}=ts(h);if(!m&&es(e)===0){d({kind:"note",tone:"info",text:os});return}let w=`/document${m?` ${m}`:""}${u?" --publish":""}`;await se(ns(m,u),{display:w,quietUser:!0});return}case"catch-up":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Xo(c.trim()))return;let{publish:u}=hs(h);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let m=await ys({cwd:e,profileName:s});for(let b of ws(m))d({kind:"note",tone:b.startsWith("\u2713")?"ok":b.startsWith("\u2139")?"info":"warn",text:b});let w=Ht(Ft(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await se(gs({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{Yo.current=!0,d({kind:"note",tone:"info",text:`Updating ${ft}\u2026 (don\u2019t close this window)`}),kn(!0),(await go().finally(()=>kn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),G(m=>m.includes("/exit")?m:[...m,"/exit"]),zs("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${ho}`});return}case"screenshot":{let u=ls(h);if(u.mode==="list"){if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:us(cs(e,u.scope),u.scope).join(`
|
|
311
|
+
`)});return}if(u.mode==="single"){let O=await fo(h);O.kind==="forward-to-agent"&&O.prompt&&await se(O.prompt,{display:O.display,quietUser:!0});return}if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=u.mode==="scope"?u.scope:void 0,w=dh(e,{scope:m}).map(O=>O.id);if(w.length===0){d({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let b=6,R=uh(w,3),T=No(e,"standard");Ze.current=Date.now(),yt(0),I(!0);let _=new AbortController;ve.current=_,te({verb:"Authoring",unit:"spec",total:R.length,done:0,active:[],rows:hn(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${w.length} screenshot spec${w.length===1?"":"s"} across ${R.length} partition${R.length===1?"":"s"} (\u2264${b} agents at once) on ${T.model}${T.forced?" (forced)":""}\u2026 (esc to stop)`});let M=!1;try{for await(let O of Eo({cwd:e,partitions:R,promptFor:ol,concurrency:b,profileName:s,allowProdWrites:xt.current,model:T.model,signal:_.signal}))if(O.type==="partition_status")O.status==="running"?te(v=>v&&{...v,active:[...v.active,O.label],rows:Le(v.rows,O.label,"active"),lastAt:Date.now()}):te(v=>v&&{...v,active:v.active.filter(S=>S!==O.label),done:v.done+1,rows:Le(v.rows,O.label,O.status==="done"?"done":"failed"),lastAt:Date.now()});else if(O.type==="partition_event")te(v=>{if(!v)return v;let S={...v,lastAt:Date.now()};return O.event.type==="tool"?S.tools=v.tools+1:O.event.type==="text"&&(S.chars=v.chars+O.event.delta.length),S});else if(O.type==="run_done"){Dt(K=>K+O.totalCostUsd),St(K=>K+O.results.reduce((Be,Et)=>Be+Et.outputTokens,0));let v=O.results.filter(K=>K.ok).length,S=O.aborted?"Stopped. ":"";M=!O.aborted&&u.setup;let F=O.aborted?"":M?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:O.aborted?"warn":O.ok?"ok":"warn",text:`${S}Authored specs \u2014 ${v}/${O.results.length} batches ok.${F}`})}}catch(O){d({kind:"note",tone:"error",text:`Spec authoring failed: ${O.message}`})}finally{ve.current=null,te(null),I(!1),oe(O=>O+1)}if(M){let O=await fn();O.kind==="forward-to-agent"&&O.prompt&&await se(O.prompt,{display:O.display,quietUser:!0});let v=ds(e);v&&d({kind:"note",tone:"info",text:v.join(`
|
|
312
|
+
`)})}return}case"reset":{let u=xs(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Wo.current={repoName:gn(e),targets:u,hadDevhints:Ke(qs(e))},d({kind:"note",tone:"warn",text:vs(e,u).join(`
|
|
313
|
+
`)}),ue(gn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,En,d,ye,se,Sn,tr,li]),In=z(c=>{let a=(c??j).trim();if(x(""),bn(null),wt(0),a.startsWith("/")&&(ue(null),gt.current++,de(null),G(h=>Ql(h,a))),!a||(Ys(!1),ui(a))||ci(a))return;Uo.current.push(a);let i=nc(a,Xs.current);a.startsWith("/")?(d({kind:"user",text:a}),Nn(i)):se(i,{display:a})},[j,ui,ci,Nn,se]),di=z(c=>{if(c.length>1){if(c.includes("\x1B"))return;let a=Zl(c);if(ec(a)){let i=tc(++Oc.current,a);Xs.current.set(i,a),P(i)}else P(a);return}P(c)},[P]),At=Math.max(10,je-6),pi=Os(()=>jo(y.text,At),[y.text,At]),rr=z(c=>k(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+c))})),[]),_n=z(c=>k(a=>({...a,pos:rc(jo(a.text,At),a.pos,c)})),[At]),Zt=z(c=>k(a=>({...a,pos:sc(jo(a.text,At),a.pos,c)})),[At]),Uc=["\x1B[H","\x1B[1~","\x1BOH"],Wc=["\x1B[F","\x1B[4~","\x1BOF"],fi=z((c,a)=>a.leftArrow?(rr(-1),!0):a.rightArrow?(rr(1),!0):c&&Uc.includes(c)?(Zt("start"),!0):c&&Wc.includes(c)?(Zt("end"),!0):a.ctrl&&c==="a"?(Zt("start"),!0):a.ctrl&&c==="e"?(Zt("end"),!0):!1,[rr,Zt]);return Im((c,a)=>{if(a.ctrl&&c==="c"){be.current?.close(),r();return}if(!W){if(E){if(a.escape){if(ve.current){if(!ve.current.signal.aborted){let i=($n?.verb??"work").toLowerCase(),h=$n?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${h}s)\u2026`}),ve.current.abort()}return}Yt.current||(Yt.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),be.current?.interrupt());return}if(a.return){let i=j.trim();if(!i)return;it.current.push(i),Ho([...it.current]),x("");return}if(fi(c,a))return;if(a.upArrow){_n(-1);return}if(a.downArrow){_n(1);return}if(a.backspace||a.delete){C();return}c&&!a.ctrl&&!a.meta&&di(c);return}if(tt){if(a.upArrow){nt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){nt(i=>i&&{...i,cursor:Math.min(Ee.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ee.length){nt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Ee[tt.cursor];nt(null);let{lines:h,changed:u,effective:m}=dn(e,i.value??"default");for(let w of h)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});u&&(oi(w=>w+1),be.current?.setModel(m));return}if(c==="s"){let i=Ee[tt.cursor];nt(null),be.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){nt(null);return}return}if(Ie){if(a.upArrow){$t(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){$t(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ie.rows.length){$t(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return||c==="s"){let i=Ie.rows[Ie.cursor];$t(null),or(i.name,a.return===!0);return}if(a.escape){$t(null);return}return}if(qo){if(a.escape){Xt(null);return}if(a.leftArrow||a.tab&&a.shift){Xt(i=>i&&{tab:(i.tab-1+Re.length)%Re.length});return}if(a.rightArrow||a.tab){Xt(i=>i&&{tab:(i.tab+1)%Re.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Re.length){Xt({tab:Number(c)-1});return}return}if(Fe){if(a.upArrow){vt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){vt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Fe.rows.length){vt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Fe.rows[Fe.cursor].name;if(vt(null),!fr(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let u=!1;try{let m=Qe(i);u=!!m&&!(Ue(m)&&!m.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${i} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${i}) and pick your project. (press 1)`}),G(["/login"]),oe(m=>m+1);return}if(a.escape){vt(null);return}return}if(me){if(a.upArrow){Ct(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ct(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=me.rows.length){Ct(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=me.rows[me.cursor],{profile:h,projectId:u}=me;Ct(null),Dn(h,u,i);return}if(a.escape){Ct(null);return}return}if(xe){if(a.upArrow){ot(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ot(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=xe.rows.length){ot(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=xe.rows[xe.cursor],{profile:h}=xe;ot(null),An(h,i);return}if(a.escape){ot(null);return}return}if(ge){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(c===" "){Tt(i=>i&&{...i,rows:i.rows.map((h,u)=>u===i.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let i=ge.rows.filter(h=>h.checked).map(h=>h.path);if(Tt(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Sr(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of i)d({kind:"note",tone:"info",text:` ${h}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){Tt(null);return}return}if(He){if(a.upArrow){Rt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Rt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=He.rows.length){Rt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=He.rows[He.cursor],h=He.run;Rt(null),h(i.token);return}if(a.escape){Rt(null);return}return}if(rt){if(a.upArrow){Pt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Pt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=rt.rows.length){Pt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=rt.rows[rt.cursor];Pt(null),i.kind==="article"?tr(i.paths[0]):Sn(i.paths);return}if(a.escape){Pt(null);return}return}if($e){if(a.escape){st(null);return}if(a.upArrow){st(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){st(i=>i&&{...i,cursor:Math.min(Math.max(0,Rn.length-1),i.cursor+1)});return}if(a.return){let i=Rn[$e.cursor];if(i){st(null);try{d({kind:"preview",name:gn(i),text:xc(Ls(ht(e,i),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${i}: ${h.message}`})}}return}if(a.backspace||a.delete){st(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){st(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(Ce){if(a.escape){at(null);return}if(a.upArrow){at(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){at(i=>i&&{...i,cursor:Math.min(Math.max(0,Tn.length-1),i.cursor+1)});return}if(a.return){let i=Tn[Ce.cursor];if(i){at(null),ye(i.uuid),Ne.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},et(i.name),Ms(i.uuid),bt.current=[];let h=Es(e,i.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${i.name}" \u2014 restored ${h.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){at(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){at(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(a.tab&&!j&&Se){x(Se),ue(null),gt.current++;return}if(!j&&Je.length>0&&!Lo&&c&&/^[1-9]$/.test(c)){let i=Je[Number(c)-1];if(i){x(mt(i));return}}if(!j&&(Ko||Go)&&c==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let i=Ko!=null;Il(Ko??Go).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?i?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":i?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&i&&Qo(null)});return}if(!fi(c,a)){if(ii){if(a.upArrow){wt(i=>Math.max(0,i-1));return}if(a.downArrow){wt(i=>Math.min(Jt.length-1,i+1));return}if(a.tab){x("/"+(Jt[Vt]?.name??"")+" "),wt(0);return}if(a.return){let i=Jt[Vt];if(i){let h=j.trim().slice(1).split(/\s+/).slice(1).join(" ");if(ql(i.usage)&&!h){x("/"+i.name+" "),wt(0);return}In("/"+i.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(j!==""&&kt===null){_n(-1);return}let i=Uo.current;if(!i.length)return;let h=kt===null?i.length-1:Math.max(0,kt-1);bn(h),x(i[h]??"");return}if(a.downArrow){if(j!==""&&kt===null){_n(1);return}let i=Uo.current;if(kt===null)return;let h=kt+1;h>=i.length?(bn(null),x("")):(bn(h),x(i[h]??""));return}}if(a.return){In();return}if(a.backspace||a.delete){C();return}if(a.escape){x(""),wt(0),ue(null),G([]),de(null);return}c&&!a.ctrl&&!a.meta&&di(c)}}}),ke(()=>{if(E||W)return;let c=it.current.shift();c!==void 0&&(Ho([...it.current]),In(c))},[E,W,In]),V(ee,{flexDirection:"column",width:je,children:[er!==null&&V(ee,{marginTop:1,flexDirection:"column",children:[er.truncated&&A(D,{dimColor:!0,children:"\u2026"}),A(D,{children:er.text})]}),E&&($n?A(Dh,{p:$n}):A(Rh,{startTime:Ze.current,chars:_c})),!E&&Zs?A(Th,{text:Zs}):null,A(ee,{borderStyle:"round",borderColor:si.prod?"yellow":B,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:j?pi.map((c,a)=>{let i=y.text.slice(c.start,c.end),h=a===Ao(pi,y.pos),u=Math.min(y.pos,c.end)-c.start;return V(D,{children:[A(D,{color:B,children:a===0?"> ":" "}),h?V(Ws,{children:[i.slice(0,u),A(Io,{ch:i[u]??" "}),i.slice(u+1)]}):i||" "]},`${a}-${c.start}`)}):V(D,{children:[A(D,{color:B,children:"> "}),Se&&!E?V(Ws,{children:[A(Io,{ch:Se[0],dim:!0}),A(D,{color:"gray",children:Se.slice(1)}),A(D,{dimColor:!0,children:" (tab)"})]}):(Zo.isSetup||!Nc)&&!E?V(Ws,{children:[A(Io,{ch:Zo.text[0],dim:!0}),A(D,{color:"gray",children:Zo.text.slice(1)})]}):A(Io,{ch:" "})]})}),Js.length>0&&A(ee,{flexDirection:"column",paddingX:1,children:Js.map((c,a)=>A(D,{color:"gray",children:`\u29D7 queued: ${c}`},`${a}-${c.slice(0,24)}`))}),qo?A(Gl,{tab:qo.tab,width:je}):tt?V(ee,{flexDirection:"column",paddingX:1,children:[A(D,{color:B,bold:!0,children:"Select model"}),A(D,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ee.map((c,a)=>V(D,{color:a===tt.cursor?B:void 0,children:[a===tt.cursor?"\u276F ":" ",`${a+1}. ${c.label}${a===tt.current?" \u2714":""}`.padEnd(16),A(D,{color:"gray",children:c.desc})]},c.label)),A(D,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Ie?V(ee,{flexDirection:"column",paddingX:1,children:[A(D,{color:B,bold:!0,children:"Switch connection profile"}),Ie.rows.map((c,a)=>V(D,{color:a===Ie.cursor?B:void 0,children:[a===Ie.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===Ie.current?" \u2714":""}`.padEnd(20),A(D,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?A(D,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),A(D,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Fe?V(ee,{flexDirection:"column",paddingX:1,children:[A(D,{color:B,bold:!0,children:"Pick your Document360 environment"}),Fe.rows.map((c,a)=>V(D,{color:a===Fe.cursor?B:void 0,children:[a===Fe.cursor?"\u276F ":" ",`${a+1}. ${c.name}`.padEnd(16),A(D,{color:"gray",children:c.apiUrl})]},c.name)),A(D,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):me?V(ee,{flexDirection:"column",paddingX:1,children:[A(D,{color:B,bold:!0,children:"Switch workspace"}),A(D,{dimColor:!0,children:`environment ${me.environment} \xB7 project ${me.projectName??`${me.projectId.slice(0,8)}\u2026`}`}),me.rows.map((c,a)=>V(D,{color:a===me.cursor?B:void 0,children:[a===me.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===me.current?" \u2714":""}`.padEnd(30),A(D,{color:"gray",children:c.type??""})]},c.id)),A(D,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):xe?V(ee,{flexDirection:"column",paddingX:1,children:[A(D,{color:B,bold:!0,children:"Choose project"}),A(D,{dimColor:!0,children:`environment ${xe.environment}`}),xe.rows.map((c,a)=>V(D,{color:a===xe.cursor?B:void 0,children:[a===xe.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===xe.current?" \u2714":""}`.padEnd(30),A(D,{color:"gray",children:c.sub??""})]},c.id)),A(D,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ge?(()=>{let a=Math.min(Math.max(0,ge.cursor-Math.floor(7)),Math.max(0,ge.rows.length-14)),i=ge.rows.slice(a,a+14),h=ge.rows.filter(u=>u.checked).length;return V(ee,{flexDirection:"column",paddingX:1,children:[A(D,{color:B,bold:!0,children:`Which folders back the user docs? (${h} selected of ${ge.rows.length})`}),a>0?A(D,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((u,m)=>{let w=a+m;return V(D,{color:w===ge.cursor?B:void 0,children:[w===ge.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,je-34)),A(D,{color:"gray",children:so(u)})]},u.path)}),a+14<ge.rows.length?A(D,{dimColor:!0,children:` \u2193 ${ge.rows.length-a-14} more`}):null,A(D,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():He?V(ee,{flexDirection:"column",paddingX:1,children:[A(D,{color:B,bold:!0,children:"Which category? (pick one to scope to)"}),He.rows.map((c,a)=>{let i=a===He.cursor,h=`${a+1}.`.padEnd(3);return V(D,{color:i?B:void 0,children:[i?"\u276F ":" ",`${h} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,je-24))),A(D,{color:"gray",children:` ${c.token}`})]},c.token)}),A(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):rt?V(ee,{flexDirection:"column",paddingX:1,children:[A(D,{color:B,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),rt.rows.map((c,a)=>{let i=a===rt.cursor,h=c.indent?" ":" ",u=`${a+1}.`.padEnd(3);return V(D,{color:i?B:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${h}${u} ${c.label}`.padEnd(Math.min(56,je-24)),c.note?A(D,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),A(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):$e?V(ee,{flexDirection:"column",paddingX:1,children:[A(D,{color:B,bold:!0,children:`Preview article${$e.query?` \u2014 filter: ${$e.query}`:" (type to filter)"}`}),Rn.length===0?A(D,{color:"gray",children:"no articles match"}):Rn.map((c,a)=>V(D,{color:a===$e.cursor?B:void 0,children:[a===$e.cursor?"\u276F ":" ",c]},c)),A(D,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ce?V(ee,{flexDirection:"column",paddingX:1,children:[A(D,{color:B,bold:!0,children:`Resume session${Ce.query?` \u2014 filter: ${Ce.query}`:" (type to filter)"}`}),Tn.length===0?A(D,{color:"gray",children:"no sessions match"}):Tn.map((c,a)=>V(D,{color:a===Ce.cursor?B:void 0,children:[a===Ce.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),A(D,{color:a===Ce.cursor?B:"gray",children:c.firstPrompt.slice(0,Math.max(10,je-40))})]},c.uuid)),A(D,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):ii?V(ee,{flexDirection:"column",children:[Jt.map((c,a)=>V(D,{color:a===Vt?B:void 0,children:[a===Vt?"\u276F ":" ",c.usage.padEnd(22)," ",A(D,{color:a===Vt?B:"gray",children:c.name==="model"&&Bo?`${c.desc} (currently ${Bo})`:c.desc})]},c.name)),A(D,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!E&&!j&&Je.length>0?V(ee,{flexDirection:"column",paddingX:1,children:[Qs?A(D,{color:B,children:Qs}):null,Je.map((c,a)=>{let i=mt(c),h=i.slice(0,Math.max(20,je-5)),u=je-h.length-7,m=u>=12?(Kl(c)??Fl(i)).slice(0,u):"";return V(D,{children:[A(D,{color:B,children:a+1})," ",h,m?A(D,{dimColor:!0,children:` \u2014 ${m}`}):null]},i)}),A(D,{dimColor:!0,children:`press 1-${Je.length} to fill the command \xB7 esc dismiss`})]}):A(ee,{paddingX:1,children:V(D,{color:"gray",children:[si.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Bo??"model n/a"}${t.kind==="api"?ni>0?` \xB7 ${he(ni)}`:"":ti>0?` \xB7 ${ze(ti)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}H();import{jsx as Nh}from"react/jsx-runtime";async function Rc(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Eh(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Ah(Nh(Pc,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
314
|
+
`),process.exit(0)}H();import{writeCrashLog as Tc,isBenignTransportError as Ih}from"document360-engine";var Sc=!1;function Bs(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Dc(e){if(Sc)return;Sc=!0;let t=(n,o)=>{if(Ih(o)){Tc({kind:n,level:"transport",message:Bs(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=Tc({kind:n,level:"fatal",message:Bs(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
315
|
+
`+$(`\u2717 d360-writer crashed: ${Bs(o)}`)+`
|
|
316
316
|
`),r&&process.stderr.write(f(` Crash details: ${r}`)+`
|
|
317
317
|
`+f(" Run: d360-writer logs")+`
|
|
318
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var
|
|
318
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Mh=Oh(import.meta.url),jc=Mh("../package.json");Dc("d360-writer");var Te=new _h;function Gs(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Te.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{Gs(e),await qn({profile:e.profile,manual:e.manual})});Te.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Gs(e),await Ri({profile:e.profile})});Te.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Gs(e),await Pi({profile:e.profile})});var Vs=Te.command("profile").description("Manage connection profiles for the current repo");Vs.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Bn(process.cwd()));Vs.command("use <name>").description("Set the default profile for this repo").action(e=>Gn(process.cwd(),e));Vs.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Vn(process.cwd(),e));var Ac=Te.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Ac.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>It(process.cwd(),e.profile));Ac.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await wi(process.cwd(),e,t.profile)});var Ec=Te.command("project").description("Choose the Document360 project for this repo (active profile's identity)");Ec.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Wn(process.cwd(),e.profile));Ec.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await bi(process.cwd(),e,t.profile)});Te.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(eo(),Qi));await e()});Te.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>ji());Te.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(po(),Xa)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Te.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(jc.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(Lh.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 Ai(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 El(e.cwd,e.auth,e.profile):await Rc(e.cwd,e.auth,e.profile,jc.version)});Te.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|