document360-writer 0.5.96 → 0.5.98
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 +103 -103
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Wd=Object.defineProperty;var no=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Qs=(e,t)=>{for(var n in t)Wd(e,n,{get:t[n],enumerable:!0})};import Ze from"picocolors";var q,Fd,Hd,qd,Js,mn,f,C,L,j,O,ae,we,W=no(()=>{"use strict";q="#7f56d9",[Fd,Hd,qd]=[127,86,217],Js=e=>Ze.isColorSupported?`\x1B[38;2;${Fd};${Hd};${qd}m${e}\x1B[39m`:e,mn=e=>Ze.bold(Js(e)),f=e=>Ze.dim(e),C=e=>Ze.red(e),L=e=>Ze.yellow(e),j=e=>Ze.green(e),O=Js,ae=e=>Ze.gray(e),we=e=>Ze.bold(e)});import{existsSync as Bt,writeFileSync as gt,readFileSync as Su,readdirSync as Du}from"node:fs";import{join as ju}from"node:path";import{devHintsGuidePath as ho,hintsDir as ga,architectureDir as va,messagesDir as Nr,creatorNotesPath as wa,devhintsStatePath as $a,directivesPath as ya,DIRECTIVES_HEADER as Au,roadmapPath as ka,ROADMAP_HEADER as Eu,ensureDir as fo,writeMessage as Nu,listOpenForDev as Iu}from"document360-engine";function xa(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
4
|
<!-- devhints script v${ce} \xB7 maintained by document360-writer (/devhints). -->
|
|
5
5
|
|
|
@@ -206,7 +206,7 @@ do it**:
|
|
|
206
206
|
**Do NOT write or action the documentation yourself** \u2014 same boundary as Part 2. Writing the article is the
|
|
207
207
|
docs agent's job; it actions open directives on its next \`/catch-up\` (as drafts) and flips each to \`[done]\`
|
|
208
208
|
with the article it wrote. You are only the relay so the ask is captured durably and travels via git.
|
|
209
|
-
`}function
|
|
209
|
+
`}function _u(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
|
|
210
210
|
|
|
211
211
|
<!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
|
|
212
212
|
The builder agent reads this FIRST and treats it as authoritative when writing the architecture
|
|
@@ -220,61 +220,61 @@ Anything only a human knows that would help document this product. For example:
|
|
|
220
220
|
- Gotchas or non-obvious behavior.
|
|
221
221
|
|
|
222
222
|
(Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
|
|
223
|
-
`}function
|
|
224
|
-
`)}
|
|
225
|
-
`)}function
|
|
226
|
-
`)}function
|
|
227
|
-
`)}),n.notifiedBuilder=!0))}catch{}return n}function
|
|
228
|
-
`)}function
|
|
229
|
-
`),"utf8")}async function Or(){let e=process.cwd(),t=Sa(e);if(Yt(t)&&!await Iu({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Na(e)??Pa(e),o=await wn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await wn({message:"Capture directory (where document360-capture .spec.ts files live):",default:ja}),i=await wn({message:"Screenshot output directory:",default:Aa}),l=await wn({message:"Default connection profile name:",default:"berlin"}),p=await wn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),m={projectId:o,docsDir:Da,captureDir:r,outputDir:i,profiles:{[l]:{connection:{environment:p},production:!1}},defaultProfile:l,authoritativeSourceFiles:Ia(e)},k=Mu(e);k?.terminologyGlossary&&(m.terminologyGlossary=k.terminologyGlossary),Ta(m,e),Ea(e);let g=Vt(e);console.log(""),console.log(j(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${O(`d360-writer login --profile ${l}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let T of Gt(g))console.log(T);return console.log(""),console.log(`${f("Then ask:")} ${O('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Na(e){let t=wo(e,"package.json");if(!Yt(t))return null;try{return JSON.parse(_u(t,"utf8")).name??null}catch{return null}}function Ia(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Yt(wo(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=wo(e,n);Yt(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 yo=to(()=>{"use strict";W();Qe()});var Ol={};Qs(Ol,{doctorCommand:()=>Cn,renderDoctorChecks:()=>_l,runDoctorChecks:()=>Il});import{existsSync as Af}from"node:fs";import{d360GetAll as Ef,getAccessToken as Nf,isExpired as ji,loadProfileMap as If,loadTokens as _f,packageSkillsDir as El,ENGINE_VERSION as Of,projectConfigPath as Lf,readProjectConfig as Mf,DEFAULT_DOCS_DIR as Uf,fetchManifestSummary as Wf,resolveActiveProfile as Ff,classifyClaudeAuth as Hf,CLAUDE_CODE_SETUP_HINT as Nl,resolveModelSetting as qf,probeModel as Bf,detectAppType as Vf,playbookSkillName as Gf,D360AuthError as Yf}from"document360-engine";async function Il(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Of}`});let o=Number(process.versions.node.split(".")[0]);n.push(o>=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 r=Hf();r.state==="ready"?n.push({level:"ok",label:`Claude auth: ${r.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):r.state==="maybe"?n.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. ${Nl}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Nl});let i=qf(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),r.state==="ready"){let P=await Bf(e,i.model??void 0);P.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(P.latencyMs/1e3).toFixed(1)}s`}):P.timedOut?n.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"`}):n.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 l=Mf(e);if(!l)return n.push({level:"fail",label:`No ${Lf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${l.projectId}`});let p=(l.docsDir??Uf).replace(/\/+$/,"");n.push(l.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 ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let m=l.authoritativeSourceFiles??[];n.push(m.length>0?{level:"ok",label:`Sources: docs grounded in ${m.length} path(s) (${m.slice(0,3).join(", ")}${m.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 k=l.appType??Vf(e);if(k){let P=l.appType?"from config":"auto-detected",N=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${P})${N?` \u2192 ${Gf(k)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.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=Ff(e),n.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(P){return n.push({level:"fail",label:`Profile config: ${P.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let T=_f(g.name);T?ji(T)&&!T.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):ji(T)?n.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(T.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${g.name})`}),n.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let v=If(e,g.name);v?v.projectId&&g.project.projectId&&v.projectId!==g.project.projectId?n.push({level:"fail",label:`Category map projectId (${v.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"}):n.push({level:"ok",label:`Category map: ${Object.keys(v.articles).length} articles, ${Object.keys(v.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),n.push(Af(El())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${El()}`,fix:"Reinstall document360-writer (broken install)"});let _=je(e);if(_.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ce})`}):_.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${_.completedVersion}, current is v${ce}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),T&&(!ji(T)||T.refreshToken)){let P={profile:g.name,connection:g.connection};try{await Nf(P);let D=await Ef(P,"/v3/projects");n.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${D.length} project(s) visible`})}catch(D){n.push({level:"fail",label:`API call failed: ${D.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=v?.projectId??g.project.projectId;if(N&&g.project.workspaceId)try{let D=await Wf(P,N,g.project.workspaceId);if(D){let M=(D.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${g.connection.name} (${D.languages?.length??0} language${(D.languages?.length??0)===1?"":"s"}) \xB7 hash ${M||"(none)"}`})}else n.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(D){D instanceof Yf||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(D.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??N})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${D.message.slice(0,80)})`})}}return n}function _l(e){let t=[""];for(let r of e){let i=r.level==="ok"?j("\u2713"):r.level==="warn"?L("\u26A0"):C("\u2717");t.push(` ${i} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${O(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?j(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):C(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Cn(e,t){console.log(f("Running checks\u2026"));for(let n of _l(await Il(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Eo=to(()=>{"use strict";Qe();W()});import{Command as uw}from"commander";import{createRequire as pw}from"node:module";import{AUTH_MODES as fw}from"document360-engine";import{input as tu}from"@inquirer/prompts";import{loginPkce as nu,refreshTokens as ou,toStoredTokens as ra,clearTokens as ru,decodeJwtClaims as oa,isExpired as iu,loadTokens as su,saveTokens as ia,resolveActiveProfile as io,setProfileProject as au,readProjectConfig as lu}from"document360-engine";W();import{select as Hd}from"@inquirer/prompts";import{resolveActiveProfile as qd,setProfileProject as Bd,resolveProjectId as Vd,listWorkspaces as Gd}from"document360-engine";async function mn(e,t){let n=qd(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Vd(o);return{workspaces:await Gd(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Zs=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;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 no(e,t,n,o,r){Bd(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ea(e,t,n){let o;try{o=await mn(e,n)}catch(i){return console.log(C(`Could not list workspaces: ${i.message}`)),1}let r=Tr(o.workspaces,t);return r?(no(e,o.profile,o.projectId,r.id,r.name),console.log(j(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(C(`No workspace matches "${t}". Available: ${o.workspaces.map(i=>i.name??i.id).join(", ")}`)),1)}async function Ht(e,t){let n;try{n=await mn(e,t)}catch(k){console.log(C(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:i,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 k of o)console.log(` ${k.id===l?O("\u25CF"):" "} ${Zs(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Hd({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${Zs(k)}${k.id===l?" (current)":""}`,value:k.id}))}),m=o.find(k=>k.id===p);no(e,i,r,p,m?.name),console.log(j(`\u2713 Workspace set to "${m?.name??p}" for profile "${i}".`))}W();import{select as Yd}from"@inquirer/prompts";import{resolveActiveProfile as zd,setProfileProject as Kd,listProjects as Xd}from"document360-engine";async function Xe(e,t){let n=zd(e,t),o={profile:n.name,connection:n.connection};return{projects:await Xd(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ta=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;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 oo(e,t,n,o){Kd(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function na(e,t,n){let o;try{o=await Xe(e,n)}catch(i){return console.log(C(`Could not list projects: ${i.message}`)),1}let r=Sr(o.projects,t);return r?(oo(e,o.profile,r.id,r.name),console.log(j(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(C(`No project matches "${t}". Available: ${o.projects.map(i=>i.name??i.id).join(", ")}`)),1)}async function ro(e,t){let n;try{n=await Xe(e,t)}catch(m){console.log(C(`Could not list projects: ${m.message}`));return}let{projects:o,profile:r,current:i}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let m of o)console.log(` ${m.id===i?O("\u25CF"):" "} ${ta(m)} ${f(m.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let l=await Yd({message:"Select the Document360 project for this repo:",choices:o.map(m=>({name:`${ta(m)}${m.id===i?" (current)":""}`,value:m.id}))}),p=o.find(m=>m.id===l);oo(e,r,l,p?.name),console.log(j(`\u2713 Project set to "${p?.name??l}" for profile "${r}". Next: pick a workspace.`))}W();import Qd from"picocolors";function Jd(e=process.env){return e.FORCE_HYPERLINK==="0"||!Qd.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 Zd(e,t=e,n){return Jd(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var eu=/https?:\/\/[^\s\x1b]+/g;function gn(e,t){return e.replace(eu,n=>Zd(n,n,t))}function sa(e){return{...oa(e.idToken)??{},...oa(e.accessToken)??{}}}function so(e){let t=sa(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 ao(e){let t=io(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 nu(n,{manual:e.manual,promptForRedirect:i=>tu({message:i})},i=>console.log(gn(i))),r=ra(t.name,o);if(ia(r),await Dr(r,t.name,i=>console.log(f(i))),console.log(""),console.log(j(`\u2713 Logged in to "${t.name}" as ${so(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{lu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Ht(process.cwd(),t.name))}catch{}}async function Dr(e,t,n){let r=sa(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(io(process.cwd(),t).project.projectId)return;let l;try{let{projects:p}=await Xe(process.cwd(),t);l=p.find(m=>m.id===r)?.name}catch{}au(process.cwd(),t,{projectId:r,projectName:l}),n(` Project "${l??r}" written to profile "${t}".`)}catch{}}async function aa(e){let t=io(process.cwd(),e.profile),n=t.connection,o=su(t.name);if(!o){console.log(C(`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 ${O(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${so(o)}`),iu(o))if(o.refreshToken)try{let r=ra(t.name,await ou(n,o.refreshToken));ia(r),console.log(j(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(L("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function la(e){let t=io(process.cwd(),e.profile);ru(t.name)?console.log(j(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as ca,writeProjectConfig as cu,resolveActiveProfile as du,loadTokens as uu,isExpired as pu}from"document360-engine";function lo(e){let t=ca(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(C("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?O("\u25CF "):" ",i=o.production?L(" \u26A0 PRODUCTION"):"",l=o.connection.environment??"(inline)",p=uu(n),m=p?pu(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${O(n)} \u2192 ${l}${i} [${m}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function co(e,t){let n=ca(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(C(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,cu(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(j(`\u2713 Default profile is now "${t}"${o}`))}function uo(e,t){try{let n=du(e,t);console.log(""),console.log(`Profile ${O(n.name)}${n.production?L(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(C(n.message)),process.exitCode=1}}W();import{existsSync as fu,readdirSync as hu,statSync as da}from"node:fs";import{join as ua}from"node:path";import{apiLogDir as mu}from"document360-engine";function pa(){let e=mu();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!fu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=hu(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 i=(da(ua(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${i} 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 i=(da(ua(e,r)).size/1024).toFixed(1);console.log(` ${C(r)} ${f(`${i} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as gu,resolveAuth as wu,findByName as yu,slugify as ku,touchSession as bu,upsertSession as vu,resolveActiveProfile as $u}from"document360-engine";async function fa(e,t,n,o,r,i){let l=wu(n);l.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("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=$u(e,r)}catch(v){console.error(C(`Document360 profile error: ${v.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),i||(console.error(C("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let m;if(o){let v=yu(e,o);v||(console.error(C(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),m=v.uuid,console.error(f(`Resuming "${v.name}"`))}let k=gu({cwd:e,resume:m,profileName:r,allowProdWrites:i===!0}),g=m??null,T=1;for await(let v of k.send(t))switch(v.type){case"session":if(!g){g=v.sessionId;let _=new Date().toISOString();vu({uuid:g,name:ku(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:_,updatedAt:_})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(ae(` \u2699 ${v.name}`));break;case"result":T=v.ok?0:1,console.error(f(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(C("agent finished with an error result"));break;case"error":console.error(""),console.error(C(`agent error: ${v.message}`)),process.exit(1)}g&&bu(g),process.stdout.write(`
|
|
230
|
-
`),process.exit(T)}import{createInterface as
|
|
223
|
+
`}function Gt(e){fo(ga(e)),fo(va(e)),fo(Nr(e));for(let n of[ga(e),Nr(e)]){let o=ju(n,".gitkeep");Bt(o)||gt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
224
|
+
`)}Bt(wa(e))||gt(wa(e),_u()),Bt(ya(e))||gt(ya(e),Au),Bt(ka(e))||gt(ka(e),Eu),gt(ho(e),xa());let t=Ae(e);return Ra(e,new Date().toISOString()),t}async function Ca(e,t){for(let n of Yt(Gt(t.cwd)))console.log(n);return{kind:"continue"}}function wt(){return[`This is document360-writer's dev hand-off setup (v${ce}).`,'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\u20136). 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); each session,"," check `.d360-writer/messages/` for open questions from the docs agent and answer them promptly and"," in full \u2014 an open docs question BLOCKS the documentation, and `[discovery]` questions define the"," whole product brief, so answer those in depth; AND when the"," human types `@d360-writer <directive>` in your session, append it as an `## [open] <directive>` block"," to `.d360-writer/directives.md` (create if absent) and commit \u2014 do NOT action it yourself (the docs"," agent picks it up on its next /catch-up) \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 IN FULL \u2014 an open docs question blocks the documentation,"," and `[discovery]`-tagged questions (what the product is, who it's for, its core mental model,"," misconceptions, positioning, terminology) define the whole product brief, so answer those in depth."," Fold durable facts into the architecture brief and 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": ${ce},`,' "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(`
|
|
225
|
+
`)}function Ir(e){try{let t=Su($a(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Ra(e,t){let o={...Ir(e)??{},emittedVersion:ce,emittedAt:t};gt($a(e),`${JSON.stringify(o,null,2)}
|
|
226
|
+
`)}function Ye(e){try{return Du(va(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ae(e){let n=Ir(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ce?"stale":"current",completedVersion:n}}function mo(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ce};try{if(!Bt(ho(e)))return n;let o=Ir(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let i=o?.completedVersion??0;ce>r&&(fo(Nr(e)),gt(ho(e),xa()),Ra(e,t),n.guideRefreshed=!0),ce>i&&(Iu(e).some(p=>p.kind==="request"&&p.subject.startsWith(ba))||(Nu(e,{id:`onb${ce}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${ba}${ce})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${ce}${i?` (you last completed v${i})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",wt()].join(`
|
|
227
|
+
`)}),n.notifiedBuilder=!0))}catch{}return n}function go(e){if(!Bt(ho(e)))return[];let t=Ae(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${ce}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Vt,wt(),Vt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function _r(){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, checking"," `.d360-writer/messages/`, and relaying `@d360-writer` directives to `.d360-writer/directives.md`)."," 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(`
|
|
228
|
+
`)}function wo(){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):",Vt,_r(),Vt]}function Yt(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${ce}.`," 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):",Vt,wt(),Vt,"","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 Vt,ce,ba,tt=no(()=>{"use strict";Vt="-".repeat(64),ce=8;ba="Re-run dev\u2194docs onboarding (protocol v"});var _a={};Qs(_a,{initCommand:()=>Lr,scaffoldInit:()=>Or});import{input as yn,confirm as Ou}from"@inquirer/prompts";import{basename as Pa,join as yo}from"node:path";import{existsSync as zt,readFileSync as Lu,readdirSync as Mu,writeFileSync as Uu}from"node:fs";import{writeProjectConfig as Ta,readProjectConfig as Wu,projectConfigPath as Sa,writerDir as Fu,DEFAULT_DOCS_DIR as Da,DEFAULT_CAPTURE_DIR as ja,DEFAULT_OUTPUT_DIR as Aa}from"document360-engine";function Or(e,t="berlin"){let n=Sa(e);if(zt(n))return{created:!1,path:n,profileName:""};let o={projectId:Na(e)??Pa(e),docsDir:Da,captureDir:ja,outputDir:Aa,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Ia(e)};return Ta(o,e),Ea(e),{created:!0,path:n,profileName:t}}function Ea(e){let t=yo(Fu(e),".gitignore");zt(t)||Uu(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
229
|
+
`),"utf8")}async function Lr(){let e=process.cwd(),t=Sa(e);if(zt(t)&&!await Ou({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Na(e)??Pa(e),o=await yn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await yn({message:"Capture directory (where document360-capture .spec.ts files live):",default:ja}),i=await yn({message:"Screenshot output directory:",default:Aa}),l=await yn({message:"Default connection profile name:",default:"berlin"}),p=await yn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),m={projectId:o,docsDir:Da,captureDir:r,outputDir:i,profiles:{[l]:{connection:{environment:p},production:!1}},defaultProfile:l,authoritativeSourceFiles:Ia(e)},k=Wu(e);k?.terminologyGlossary&&(m.terminologyGlossary=k.terminologyGlossary),Ta(m,e),Ea(e);let g=Gt(e);console.log(""),console.log(j(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${O(`d360-writer login --profile ${l}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let T of Yt(g))console.log(T);return console.log(""),console.log(`${f("Then ask:")} ${O('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Na(e){let t=yo(e,"package.json");if(!zt(t))return null;try{return JSON.parse(Lu(t,"utf8")).name??null}catch{return null}}function Ia(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])zt(yo(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=yo(e,n);zt(o)&&!Hu(o)&&t.push(n)}return t}function Hu(e){try{return Mu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var ko=no(()=>{"use strict";W();tt()});var Ml={};Qs(Ml,{doctorCommand:()=>Rn,renderDoctorChecks:()=>Ll,runDoctorChecks:()=>Ol});import{existsSync as Nf}from"node:fs";import{d360GetAll as If,getAccessToken as _f,isExpired as Ai,loadProfileMap as Of,loadTokens as Lf,packageSkillsDir as Il,ENGINE_VERSION as Mf,projectConfigPath as Uf,readProjectConfig as Wf,DEFAULT_DOCS_DIR as Ff,fetchManifestSummary as Hf,resolveActiveProfile as qf,classifyClaudeAuth as Bf,CLAUDE_CODE_SETUP_HINT as _l,resolveModelSetting as Vf,probeModel as Gf,detectAppType as Yf,playbookSkillName as zf,D360AuthError as Kf}from"document360-engine";async function Ol(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Mf}`});let o=Number(process.versions.node.split(".")[0]);n.push(o>=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 r=Bf();r.state==="ready"?n.push({level:"ok",label:`Claude auth: ${r.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):r.state==="maybe"?n.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. ${_l}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:_l});let i=Vf(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),r.state==="ready"){let P=await Gf(e,i.model??void 0);P.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(P.latencyMs/1e3).toFixed(1)}s`}):P.timedOut?n.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"`}):n.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 l=Wf(e);if(!l)return n.push({level:"fail",label:`No ${Uf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${l.projectId}`});let p=(l.docsDir??Ff).replace(/\/+$/,"");n.push(l.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 ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let m=l.authoritativeSourceFiles??[];n.push(m.length>0?{level:"ok",label:`Sources: docs grounded in ${m.length} path(s) (${m.slice(0,3).join(", ")}${m.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 k=l.appType??Yf(e);if(k){let P=l.appType?"from config":"auto-detected",N=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${P})${N?` \u2192 ${zf(k)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.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=qf(e),n.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(P){return n.push({level:"fail",label:`Profile config: ${P.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let T=Lf(g.name);T?Ai(T)&&!T.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Ai(T)?n.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(T.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${g.name})`}),n.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let v=Of(e,g.name);v?v.projectId&&g.project.projectId&&v.projectId!==g.project.projectId?n.push({level:"fail",label:`Category map projectId (${v.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"}):n.push({level:"ok",label:`Category map: ${Object.keys(v.articles).length} articles, ${Object.keys(v.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),n.push(Nf(Il())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Il()}`,fix:"Reinstall document360-writer (broken install)"});let _=Ae(e);if(_.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ce})`}):_.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${_.completedVersion}, current is v${ce}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),T&&(!Ai(T)||T.refreshToken)){let P={profile:g.name,connection:g.connection};try{await _f(P);let S=await If(P,"/v3/projects");n.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${S.length} project(s) visible`})}catch(S){n.push({level:"fail",label:`API call failed: ${S.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=v?.projectId??g.project.projectId;if(N&&g.project.workspaceId)try{let S=await Hf(P,N,g.project.workspaceId);if(S){let M=(S.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${g.connection.name} (${S.languages?.length??0} language${(S.languages?.length??0)===1?"":"s"}) \xB7 hash ${M||"(none)"}`})}else n.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(S){S instanceof Kf||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(S.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??N})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${S.message.slice(0,80)})`})}}return n}function Ll(e){let t=[""];for(let r of e){let i=r.level==="ok"?j("\u2713"):r.level==="warn"?L("\u26A0"):C("\u2717");t.push(` ${i} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${O(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?j(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):C(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Rn(e,t){console.log(f("Running checks\u2026"));for(let n of Ll(await Ol(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var No=no(()=>{"use strict";tt();W()});import{Command as hw}from"commander";import{createRequire as mw}from"node:module";import{AUTH_MODES as gw}from"document360-engine";import{input as ou}from"@inquirer/prompts";import{loginPkce as ru,refreshTokens as iu,toStoredTokens as ra,clearTokens as su,decodeJwtClaims as oa,isExpired as au,loadTokens as lu,saveTokens as ia,resolveActiveProfile as so,setProfileProject as cu,readProjectConfig as du}from"document360-engine";W();import{select as Bd}from"@inquirer/prompts";import{resolveActiveProfile as Vd,setProfileProject as Gd,resolveProjectId as Yd,listWorkspaces as zd}from"document360-engine";async function gn(e,t){let n=Vd(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Yd(o);return{workspaces:await zd(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Zs=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 oo(e,t,n,o,r){Gd(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ea(e,t,n){let o;try{o=await gn(e,n)}catch(i){return console.log(C(`Could not list workspaces: ${i.message}`)),1}let r=Sr(o.workspaces,t);return r?(oo(e,o.profile,o.projectId,r.id,r.name),console.log(j(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(C(`No workspace matches "${t}". Available: ${o.workspaces.map(i=>i.name??i.id).join(", ")}`)),1)}async function qt(e,t){let n;try{n=await gn(e,t)}catch(k){console.log(C(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:i,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 k of o)console.log(` ${k.id===l?O("\u25CF"):" "} ${Zs(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Bd({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${Zs(k)}${k.id===l?" (current)":""}`,value:k.id}))}),m=o.find(k=>k.id===p);oo(e,i,r,p,m?.name),console.log(j(`\u2713 Workspace set to "${m?.name??p}" for profile "${i}".`))}W();import{select as Kd}from"@inquirer/prompts";import{resolveActiveProfile as Xd,setProfileProject as Qd,listProjects as Jd}from"document360-engine";async function et(e,t){let n=Xd(e,t),o={profile:n.name,connection:n.connection};return{projects:await Jd(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ta=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Dr(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 ro(e,t,n,o){Qd(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function na(e,t,n){let o;try{o=await et(e,n)}catch(i){return console.log(C(`Could not list projects: ${i.message}`)),1}let r=Dr(o.projects,t);return r?(ro(e,o.profile,r.id,r.name),console.log(j(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(C(`No project matches "${t}". Available: ${o.projects.map(i=>i.name??i.id).join(", ")}`)),1)}async function io(e,t){let n;try{n=await et(e,t)}catch(m){console.log(C(`Could not list projects: ${m.message}`));return}let{projects:o,profile:r,current:i}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let m of o)console.log(` ${m.id===i?O("\u25CF"):" "} ${ta(m)} ${f(m.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let l=await Kd({message:"Select the Document360 project for this repo:",choices:o.map(m=>({name:`${ta(m)}${m.id===i?" (current)":""}`,value:m.id}))}),p=o.find(m=>m.id===l);ro(e,r,l,p?.name),console.log(j(`\u2713 Project set to "${p?.name??l}" for profile "${r}". Next: pick a workspace.`))}W();import Zd from"picocolors";function eu(e=process.env){return e.FORCE_HYPERLINK==="0"||!Zd.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 tu(e,t=e,n){return eu(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var nu=/https?:\/\/[^\s\x1b]+/g;function wn(e,t){return e.replace(nu,n=>tu(n,n,t))}function sa(e){return{...oa(e.idToken)??{},...oa(e.accessToken)??{}}}function ao(e){let t=sa(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 lo(e){let t=so(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 ru(n,{manual:e.manual,promptForRedirect:i=>ou({message:i})},i=>console.log(wn(i))),r=ra(t.name,o);if(ia(r),await jr(r,t.name,i=>console.log(f(i))),console.log(""),console.log(j(`\u2713 Logged in to "${t.name}" as ${ao(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 qt(process.cwd(),t.name))}catch{}}async function jr(e,t,n){let r=sa(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(so(process.cwd(),t).project.projectId)return;let l;try{let{projects:p}=await et(process.cwd(),t);l=p.find(m=>m.id===r)?.name}catch{}cu(process.cwd(),t,{projectId:r,projectName:l}),n(` Project "${l??r}" written to profile "${t}".`)}catch{}}async function aa(e){let t=so(process.cwd(),e.profile),n=t.connection,o=lu(t.name);if(!o){console.log(C(`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 ${O(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${ao(o)}`),au(o))if(o.refreshToken)try{let r=ra(t.name,await iu(n,o.refreshToken));ia(r),console.log(j(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(L("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function la(e){let t=so(process.cwd(),e.profile);su(t.name)?console.log(j(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as ca,writeProjectConfig as uu,resolveActiveProfile as pu,loadTokens as fu,isExpired as hu}from"document360-engine";function co(e){let t=ca(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(C("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?O("\u25CF "):" ",i=o.production?L(" \u26A0 PRODUCTION"):"",l=o.connection.environment??"(inline)",p=fu(n),m=p?hu(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${O(n)} \u2192 ${l}${i} [${m}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function uo(e,t){let n=ca(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(C(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,uu(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(j(`\u2713 Default profile is now "${t}"${o}`))}function po(e,t){try{let n=pu(e,t);console.log(""),console.log(`Profile ${O(n.name)}${n.production?L(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(C(n.message)),process.exitCode=1}}W();import{existsSync as mu,readdirSync as gu,statSync as da}from"node:fs";import{join as ua}from"node:path";import{apiLogDir as wu}from"document360-engine";function pa(){let e=wu();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!mu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=gu(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 i=(da(ua(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${i} 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 i=(da(ua(e,r)).size/1024).toFixed(1);console.log(` ${C(r)} ${f(`${i} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as yu,resolveAuth as ku,findByName as bu,slugify as vu,touchSession as $u,upsertSession as xu,resolveActiveProfile as Cu}from"document360-engine";async function fa(e,t,n,o,r,i){let l=ku(n);l.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("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=Cu(e,r)}catch(v){console.error(C(`Document360 profile error: ${v.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),i||(console.error(C("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let m;if(o){let v=bu(e,o);v||(console.error(C(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),m=v.uuid,console.error(f(`Resuming "${v.name}"`))}let k=yu({cwd:e,resume:m,profileName:r,allowProdWrites:i===!0}),g=m??null,T=1;for await(let v of k.send(t))switch(v.type){case"session":if(!g){g=v.sessionId;let _=new Date().toISOString();xu({uuid:g,name:vu(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:_,updatedAt:_})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(ae(` \u2699 ${v.name}`));break;case"result":T=v.ok?0:1,console.error(f(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(C("agent finished with an error result"));break;case"error":console.error(""),console.error(C(`agent error: ${v.message}`)),process.exit(1)}g&&$u(g),process.stdout.write(`
|
|
230
|
+
`),process.exit(T)}import{createInterface as $m}from"node:readline/promises";import{createSession as cs,resolveAuth as xm,getSession as Cm,setTitle as Rm,slugify as Pm,touchSession as Pc,upsertSession as Tm,generateTitle as Sm,resolveActiveProfile as Tc,resolveModelSetting as Dm,readProjectConfig as jm,resolveAndPersistAppType as Am,decodeJwtClaims as Rc,isExpired as Em,loadTokens as Nm,isDirectiveMention as Im,stripDirectiveMention as _m,appendDirective as Om,reconcileUpgradeActions as Lm,stampArticles as Mm,listArticleFiles as Um,CONTENT_CAP_VERSION as Wm}from"document360-engine";import{ENGINE_VERSION as Pu}from"document360-engine";var je=[{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:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{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:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{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:"/roadmap",s:"The docs campaign: progress + the next step."},{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:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{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:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{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:"Clear the screen and 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 ha(e){let n=[e?`document360-writer \u2014 help \xB7 v${e.version} \xB7 engine v${e.engineVersion}`:"document360-writer \u2014 help",""];for(let o of je){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(Ru(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function Ar(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:Pu}:void 0;for(let o of ha(n))console.log(o);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}W();import{getSession as Tu}from"document360-engine";async function ma(e,t){let n=t.currentUuid(),o=n?Tu(n):void 0;return console.log(o?f(`
|
|
231
231
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
232
232
|
`):f(`
|
|
233
233
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
234
|
-
`)),{kind:"clear"}}async function
|
|
234
|
+
`)),{kind:"clear"}}async function Er(){return{kind:"exit"}}ko();W();import{readMcpConfig as Mr,writeMcpConfig as Oa}from"document360-engine";async function bo(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(qu(),{kind:"continue"}):t==="add"?(Bu(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Vu(e.slice(1)),{kind:"continue"}):(console.log(C(`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 qu(){let e=Mr(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
|
|
235
235
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
236
|
-
`));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(` ${O(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),i=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${O(n)} ${f(`(${o.type})`)} ${o.url}${i}`)}}console.log("")}function
|
|
237
|
-
`),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(La(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Ma(t[o+1])){let p=Ua(r);o+=2;let m=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)m.push(Ua(t[o++]));n.push({kind:"table",header:p,rows:m});continue}let i=r.match(/^(#{1,6})\s+(.*)$/);if(i){n.push({kind:"heading",level:i[1].length,text:i[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let m=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(m),text:m.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])&&!La(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Ma(t[o+1]));)l.push(t[o++]);n.push({kind:"para",text:l.join(" ")})}return n}function
|
|
238
|
-
`)}),M=Math.max(...
|
|
236
|
+
`));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(` ${O(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),i=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${O(n)} ${f(`(${o.type})`)} ${o.url}${i}`)}}console.log("")}function Bu(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(C("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(C(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Mr(),i;if(n==="stdio")i={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 m=o[++p],k=m?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(C(`-H expects key:value (no spaces). Got: ${m??"(nothing)"}`));return}l[k[1].trim()]=k[2].trim()}else{console.log(C(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}i={type:n,url:o[0],headers:Object.keys(l).length>0?l:void 0}}r.servers[t]=i,Oa(r),console.log(""),console.log(j(`\u2713 Registered "${t}" (${n})`)),console.log(L(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Vu(e){let t=e[0];if(!t){console.log(C("Usage: /mcp remove <name>"));return}let n=Mr();if(!n.servers[t]){console.log(C(`No server named "${t}".`));return}delete n.servers[t],Oa(n),console.log(j(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as sp}from"node:fs";import{join as ap}from"node:path";import{select as lp}from"@inquirer/prompts";import{computeSyncStatus as vo,planPartitions as cp,relatedArticlePaths as dp,resolveModelForOperation as up,runPartitioned as pp,loadProfileMap as fp,resolveActiveProfile as hp,resolveCrossLinks as mp,applyStructureOrder as Ga,orderSyncLine as Ya,applyRelatedArticles as za,relatedSyncLine as Ka}from"document360-engine";import J from"picocolors";import Ha from"wrap-ansi";import Br from"string-width";W();import nt from"picocolors";import Ur from"wrap-ansi";import Wr from"string-width";var La=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Ma=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Ua=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Gu(e){let t=e.replace(/\r/g,"").split(`
|
|
237
|
+
`),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(La(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Ma(t[o+1])){let p=Ua(r);o+=2;let m=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)m.push(Ua(t[o++]));n.push({kind:"table",header:p,rows:m});continue}let i=r.match(/^(#{1,6})\s+(.*)$/);if(i){n.push({kind:"heading",level:i[1].length,text:i[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let m=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(m),text:m.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])&&!La(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Ma(t[o+1]));)l.push(t[o++]);n.push({kind:"para",text:l.join(" ")})}return n}function Fr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?nt.bold(t.slice(2,-2)):t.startsWith("`")?O(t.slice(1,-1)):nt.italic(t.slice(1,-1)))}var Yu=(e,t)=>e+" ".repeat(Math.max(0,t-Wr(e)));function zu(e,t,n){let o=e.length,r=e.map((P,N)=>Math.max(Wr(P),...t.map(S=>Wr(S[N]??"")))),i=Math.max(24,n),l=3*o+1,p=[...r],m=()=>p.reduce((P,N)=>P+N,0)+l,k=0;for(;m()>i&&k++<1e4;){let P=-1,N=6;for(let S=0;S<o;S++)p[S]>N&&(N=p[S],P=S);if(P===-1)break;p[P]-=1}let g=(P,N,S)=>nt.gray(P+p.map(M=>"\u2500".repeat(M+2)).join(N)+S),T=nt.gray("\u2502"),v=(P,N)=>{let S=p.map((V,K)=>{let ne=P[K]??"",Ie=N?nt.bold(ne):Fr(ne);return Ur(Ie,V,{hard:!0}).split(`
|
|
238
|
+
`)}),M=Math.max(...S.map(V=>V.length)),B=[];for(let V=0;V<M;V++)B.push(p.map((K,ne)=>`${T} ${Yu(S[ne][V]??"",K)} `).join("")+T);return B.join(`
|
|
239
239
|
`)},_=[g("\u250C","\u252C","\u2510"),v(e,!0)];return _.push(t.length===0?g("\u2514","\u2534","\u2518"):g("\u251C","\u253C","\u2524")),t.forEach((P,N)=>{_.push(v(P,!1)),_.push(N===t.length-1?g("\u2514","\u2534","\u2518"):g("\u251C","\u253C","\u2524"))}),_.join(`
|
|
240
|
-
`)}function
|
|
240
|
+
`)}function Ku(e,t){switch(e.kind){case"heading":return nt.bold(e.text);case"hr":return nt.gray("\u2500".repeat(t));case"para":return Ur(Fr(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",i=" ".repeat(2+r.length+1),[l="",...p]=Ur(Fr(o.text),Math.max(10,t-i.length)).split(`
|
|
241
241
|
`);return` ${r} ${l}`+p.map(m=>`
|
|
242
242
|
${i}${m}`).join("")}).join(`
|
|
243
|
-
`)}case"code":return e.lines.map(n=>
|
|
244
|
-
`);case"table":return
|
|
243
|
+
`)}case"code":return e.lines.map(n=>nt.gray(" "+n)).join(`
|
|
244
|
+
`);case"table":return zu(e.header,e.rows,t)}}function Hr(e,t){let n=Math.max(20,t);return Gu(e).map(o=>Ku(o,n)).join(`
|
|
245
245
|
|
|
246
|
-
`)}W();import
|
|
247
|
-
`);let r=2,i=3,l=
|
|
246
|
+
`)}W();import Xu from"picocolors";var Qu=[127,86,217],Ju=[22,38,43],Wa={T:Qu,E:Ju},kn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],qr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Zu=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Fa(){if(!Xu.isColorSupported)return[];let e=kn[0].length,t=[];for(let n=0;n<kn.length;n+=2){let o="";for(let r=0;r<e;r++){let i=Wa[kn[n][r]],l=n+1<kn.length?Wa[kn[n+1][r]]:void 0;i&&l?o+=`${qr(i)}${Zu(l)}\u2580\x1B[49m\x1B[39m`:i?o+=`${qr(i)}\u2580\x1B[39m`:l?o+=`${qr(l)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function bn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function ye(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function ot(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Kt=(e,t)=>` ${e.padEnd(13)}${t}`;function ep(e,t){let n=[mn("\u270E document360-writer")+J.gray(` v${e.version} \xB7 engine v${e.engineVersion}`),J.gray(" Reads your code, writes your docs."),"",Kt("Claude:",`${e.claude}${J.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Kt("Document360:",e.configured?e.loggedOut?J.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?J.gray(` (${e.sessionHint})`):""}`:J.yellow("not set up \u2014 run /init")),Kt("Profile:",e.configured?`${e.profile}${J.gray(` (${e.apiUrl})`)}${e.prod?J.bold(J.yellow(" \u26A0 PRODUCTION")):""}`:J.gray("\u2014 (run /init)")),Kt("Project:",e.project),Kt("Mode:",J.gray(e.mode)),Kt("cwd:",J.gray(e.cwd))],o=Fa();if(o.length===0)return n.join(`
|
|
247
|
+
`);let r=2,i=3,l=Br(o[0]);if(!(t>=r+l+i+Math.max(...n.map(g=>Br(g)))))return[...o.map(g=>" "+g),...n].join(`
|
|
248
248
|
`);let m=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let g=0;g<Math.max(o.length+m,n.length);g++){let T=o[g-m]??" ".repeat(l);k.push((" ".repeat(r)+T+" ".repeat(i)+(n[g]??"")).trimEnd())}return k.join(`
|
|
249
|
-
`)}var
|
|
249
|
+
`)}var tp={error:J.red,warn:J.yellow,ok:J.green,info:J.gray};function Vr(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return ep(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",i=Math.max(10,n-4),l=50,p=e.text.split(`
|
|
250
250
|
`).flatMap(k=>Ha(k,i,{hard:!0}).split(`
|
|
251
|
-
`)),m=Math.max(0,p.length-l);return m>0&&(p=[...p.slice(0,l),
|
|
252
|
-
`+p.map((k,g)=>o+(g===0?O(" \u276F "):" ")+k+" ".repeat(Math.max(0,i-
|
|
251
|
+
`)),m=Math.max(0,p.length-l);return m>0&&(p=[...p.slice(0,l),J.dim(`\u2026 +${m} more lines`)]),`
|
|
252
|
+
`+p.map((k,g)=>o+(g===0?O(" \u276F "):" ")+k+" ".repeat(Math.max(0,i-Br(k))+1)+r).join(`
|
|
253
253
|
`)}case"assistant":return`
|
|
254
|
-
`+
|
|
255
|
-
`+Ha(
|
|
256
|
-
`)}case"diff":{let o=l=>l===1?"":"s",i=[
|
|
257
|
-
`)}case"link":return e.lines.map(o=>O(
|
|
254
|
+
`+Hr(e.text,n);case"tool":{let o=e.arg!==null?J.gray(`${e.sep}(${e.arg})`):"";return`
|
|
255
|
+
`+Ha(J.green("\u25CF ")+J.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?J.red:J.gray,r=e.lines.map((i,l)=>o((l===0?" \u23BF ":" ")+i));return e.hidden>0&&r.push(J.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
256
|
+
`)}case"diff":{let o=l=>l===1?"":"s",i=[J.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&i.push(J.dim(` \u2026 +${e.hidden} more diff lines`)),i.join(`
|
|
257
|
+
`)}case"link":return e.lines.map(o=>O(wn(` \u2B95 ${o}`))).join(`
|
|
258
258
|
`);case"preview":return`
|
|
259
|
-
`+
|
|
260
|
-
|
|
261
|
-
`+
|
|
262
|
-
`+
|
|
263
|
-
`+(e.ok?
|
|
264
|
-
`)}import{resolveActiveProfile as
|
|
265
|
-
`)}var Va={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function
|
|
266
|
-
`)}function
|
|
267
|
-
`),display:"/audit"}}W();import{readProjectConfig as
|
|
268
|
-
`)}async function Ja(e,t){let n=t?.cwd??process.cwd();return
|
|
259
|
+
`+mn(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
260
|
+
|
|
261
|
+
`+Hr(e.text,n);case"note":return`
|
|
262
|
+
`+tp[e.tone](wn(e.text));case"done":return`
|
|
263
|
+
`+(e.ok?J.magenta("\u2736 "):J.red("\u2736 "))+J.gray(`Cooked for ${bn(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${ye(e.costUsd)}`:""))}}function qa(e,t){return e.map(n=>Vr(n,t)).join(`
|
|
264
|
+
`)}import{resolveActiveProfile as np,loadTokens as op,isExpired as rp,decodeJwtClaims as Ba}from"document360-engine";function ip(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ee(e,t){try{let n=np(e,t),o=op(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(rp(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={...Ba(o.idToken)??{},...Ba(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 ${ip(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var vn=3;function Gr(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(`
|
|
265
|
+
`)}var Va={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Yr(e){return e.filter(t=>t.path!==null&&t.status in Va&&!t.link).map(t=>({path:t.path,label:Va[t.status]}))}function $o(e){let t=Yr(e),n=new Set(e.filter(o=>o.status==="conflict"&&o.path).map(o=>o.path));return{clean:t.filter(o=>!n.has(o.path)),conflicts:t.filter(o=>n.has(o.path))}}function xo(e){return`\u26A0 ${e} conflict${e===1?"":"s"} skipped \u2014 edited both here and on the portal, so publishing would overwrite the portal edit. Resolve them: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's).`}function Co(e){return e.filter(t=>t.link).length}function zr(e,t){try{let n=fp(e,hp(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=mp(sp(ap(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 gp(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 Xa(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let i=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),l=o.get(i);l?l.push(r):o.set(i,[r])}for(let r of[...o.keys()].sort()){let i=o.get(r).sort((l,p)=>l.path.localeCompare(p.path));n.push({kind:"category",label:`${gp(r)} (${i.length})`,paths:i.map(l=>l.path),indent:!1});for(let l of i){let p=l.path.replace(/\\/g,"/").split("/").pop()??l.path;n.push({kind:"article",label:p,paths:[l.path],indent:!0,note:l.label})}}for(let r of[...t].sort((i,l)=>i.path.localeCompare(l.path))){let i=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:i,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function Ro(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(`
|
|
266
|
+
`)}function Kr(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),i=e.filter(v=>!v.ok),l=e.reduce((v,_)=>v+o(_),0),p=r.reduce((v,_)=>v+o(_),0),m=n==="api"?`${ye(e.reduce((v,_)=>v+_.costUsd,0))} total`:ot(e.reduce((v,_)=>v+_.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,g=v=>`${v} article${v===1?"":"s"}`,T=[];if(i.length===0)T.push(`Published ${g(l)} (${k}) successfully \xB7 ${m}.`),T.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{T.push(`Published ${p}/${g(l)} (${k}) \xB7 ${m}.`),T.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let v of i)T.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return T}async function yt(e,t){let{model:n}=up(e.cwd,"standard"),o=async(r,i)=>{let l=cp(r);console.log(f(i?`Resolving cross-links in ${r.length} article${r.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${r.length} article${r.length===1?"":"s"} across ${l.length} partition${l.length===1?"":"s"} (\u2264${vn} agents at once) on ${n}\u2026`)),i||console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let p=!1;for await(let m of pp({cwd:e.cwd,partitions:l,promptFor:k=>Ro(k.paths),concurrency:vn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(m.type==="partition_status")m.status==="running"?console.log(f(` \u25B8 ${m.label} \u2014 publishing\u2026`)):m.status==="done"?console.log(j(` \u2713 ${m.label}`)):console.log(C(` \u2717 ${m.label}`));else if(m.type==="run_done"){p=m.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let T of Kr(m.results,l,k))console.log(m.ok?j(T):L(T));let g=zr(e.cwd,e.profileName);g&&console.log(f(g));try{let T=Ya(await Ga({cwd:e.cwd,profileName:e.profileName}));T&&console.log(f(T))}catch{}try{let T=Ka(await za({cwd:e.cwd,profileName:e.profileName}));T&&console.log(f(T))}catch{}}return p};try{if(!await o(t,!1)){let i=await Xr(e.cwd,e.profileName,t);i.length>0&&await o(i,!0)}}catch(r){console.log(C(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Po(e,t,n){let o=dp(e,n);if(o.length===0)return[];let r=new Set(Yr((await vo({cwd:e,profileName:t})).entries).map(i=>i.path));return o.filter(i=>r.has(i))}async function Xr(e,t,n){try{let o=new Set(n),r=await vo({cwd:e,profileName:t});return Yr(r.entries).map(i=>i.path).filter(i=>o.has(i))}catch{return[]}}async function Qa(e,t){let n=Ee(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Po(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(j("\u2713 All related articles are already published.")),{kind:"continue"}):await yt(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await vo({cwd:t?.cwd??process.cwd()}),{clean:i,conflicts:l}=$o(r.entries),p=Co(r.entries),m=e.includes("--force")&&l.length>0;p>0&&console.log(L(`\u26A0 ${p} 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.`)),l.length>0&&!m&&console.log(L(xo(l.length)));let k=m?[...i,...l]:i;if(k.length===0){if(l.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(j(p>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let g=Ya(await Ga({cwd:t.cwd,profileName:t.profileName}));g&&console.log(f(g));let T=Ka(await za({cwd:t.cwd,profileName:t.profileName}));T&&console.log(f(T))}catch{}return{kind:"continue"}}return t?await yt(t,k.map(g=>g.path)):{kind:"forward-to-agent",prompt:Ro(k.map(g=>g.path)),display:"/publish --all"}}catch(r){return console.log(C(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let i=await vo({cwd:t?.cwd??process.cwd()}),{clean:l,conflicts:p}=$o(i.entries);r=l;let m=Co(i.entries);if(m>0&&console.log(L(`\u26A0 ${m} 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.`)),p.length>0&&console.log(L(xo(p.length))),r.length===0&&p.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(i){return console.log(C(`Could not compute sync status: ${i.message}`)),console.log(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(j("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(f(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let i of r)console.log(` ${i.path} ${f(`(${i.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>lp({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(i=>({name:i.path,value:i.path,description:i.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await yt(t,r.map(i=>i.path))}return{kind:"forward-to-agent",prompt:Gr(o),display:`/publish ${o}`}}async function $n(){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(`
|
|
267
|
+
`),display:"/audit"}}W();import{readProjectConfig as wp}from"document360-engine";function Qr(){return["Run the discover-product skill against this repo.","","Build (or continue refining) the product brief at `.d360-writer/product-brief.md` by interviewing the","source repo's coding agent (the builder):","1. Gather all grounding \u2014 the code surface (analyze-codebase pass), `.d360-writer/architecture/`"," (+ CREATOR-NOTES), any specs under `.d360-writer/input/`, existing docs, git log, and the current"," product brief if one exists.","2. Self-assess against the 8-point readiness rubric (identity, audience, core mental model,"," misconceptions, positioning, key concepts & terminology, critical journeys, boundaries/non-goals).","3. Write/update the brief \u2014 every claim cited to its grounding \u2014 and keep its frontmatter current"," (status, rounds, open_questions, last_updated).","4. For the dimensions you cannot yet ground confidently, ask the builder a focused batch (\u22646) of pointed",' questions via d360_ask_builder, with the subject prefixed "[discovery] ". Then END the turn \u2014 the'," builder answers async; /catch-up will ingest the answers and continue the loop.","","Set status: confident and hand off to propose-structure ONLY when every rubric dimension passes. If the","builder stays silent across a few rounds, degrade gracefully per the skill (best-effort brief, flagged","open questions) rather than blocking the docs. Do NOT write or publish any articles in this turn."].join(`
|
|
268
|
+
`)}async function Ja(e,t){let n=t?.cwd??process.cwd();return wp(n)?{kind:"forward-to-agent",prompt:Qr(),display:"/discover"}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{checkbox as yp}from"@inquirer/prompts";import{inventoryRepo as kp,readProjectConfig as Za,writeProjectConfig as bp}from"document360-engine";function Jr(e,t){let n=Za(e);n&&(n.authoritativeSourceFiles=t,bp(n,e))}function To(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 el(e,t){let n=t?.cwd??process.cwd();if(!Za(n))return console.log(C("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=kp(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(O("Recommended documentation scope (run /scope in the REPL to choose):"));for(let i of o)console.log(` ${i.recommended?"\u25C9":"\u25CB"} ${i.path} ${f(To(i))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>yp({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(i=>({name:`${i.path} (${To(i)})`,value:i.path,checked:i.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"};Jr(n,r),console.log(j(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let i of r)console.log(` ${i}`);return console.log(""),{kind:"continue"}}W();import{confirm as jp}from"@inquirer/prompts";import{applyPull as ti,computeSyncStatus as cl,compareRemoteSources as Ap,planPull as dl,planImport as Ep,applyImport as Np,establishBaselines as Ip,rebaselineServerMeta as _p,D360AuthError as Op}from"document360-engine";W();var tl=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:C,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:L,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:O,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:C,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:C,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ae,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:ae,mark:"\xB7"}];function vp(e){return e.path?e.path:`${e.title??"(untitled)"} ${ae(`[${e.articleId}]`)}`}function $p(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 So(e,t){let n=[],o=e.entries.filter(g=>g.link);if(o.length>0){n.push(""),n.push(we("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let g of o)n.push(` ${L("~")} ${L(g.path??"")} ${ae(`\u2192 "${g.link.title}"`)}`)}for(let g of tl){let T=e.entries.filter(v=>v.status===g.status&&!(g.status==="untracked-local"&&v.link));if(T.length!==0){n.push(""),n.push(we(g.header));for(let v of T)n.push(` ${g.paint(g.mark)} ${g.paint(vp(v))}${v.detail?ae(` (${v.detail})`):""}`)}}let r=e.counts["in-sync"]??0,i=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,m=i===r?j("\u2713 everything up to date"):[r>0?j(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...tl.map(g=>{let T=(e.counts[g.status]??0)-(g.status==="untracked-local"?p:0);return T>0?`${T} ${l[g.status]}`:null})].filter(Boolean).join(ae(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${$p(t)}`:"";return n.push(m+ae(` \xB7 ${i} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as xp}from"diff";import nl from"picocolors";var ol=80,Cp="\x1B[48;2;74;28;28m",Rp="\x1B[48;2;24;66;24m",rl="\x1B[49m",Zr=e=>String(e).padStart(5);function il(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function sl(e,t,n){if(n===void 0||n<t-4)return e.slice(0,t);let o=Math.max(0,n-12);return`\u2026${e.slice(o).slice(0,Math.max(8,t-1))}`}function ze(e,t,n){let o=v=>{let _=v.replace(/\r\n/g,`
|
|
269
269
|
`);return _.endsWith(`
|
|
270
270
|
`)||_===""?_:_+`
|
|
271
|
-
`},r=o(e),i=o(t);if(r===i)return null;let l=Math.max(20,n-10),p=vp("a","b",r,i,"","",{context:3}),m=0,k=0,g=[];p.hunks.forEach((v,_)=>{_>0&&g.push(nl.gray(" \u2026"));let P=v.oldStart,N=v.newStart;for(let D of v.lines){let M=D[0],B=D.slice(1).slice(0,l);M==="-"?(k++,g.push(`${$p}${Jr(P++)} - ${B}${rl}`)):M==="+"?(m++,g.push(`${xp}${Jr(N++)} + ${B}${rl}`)):(g.push(nl.gray(Jr(N))+" "+B),P++,N++)}});let T=g.slice(0,ol);return{added:m,removed:k,lines:T,hidden:Math.max(0,g.length-ol)}}W();import{select as Cp}from"@inquirer/prompts";import{applyPull as Rp,computeSyncStatus as Pp,planPull as Tp}from"document360-engine";var il=e=>e===1?"":"s";async function Zr(e,t){console.log(""),console.log(`${O("\u25CF")} ${ge(t.title)} ${ae(`(${t.path})`)}`);for(let r of t.notes)console.log(L(` \u26A0 ${r}`));let n=qe(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(ae(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${il(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(f(` \u2026 +${n.hidden} more diff lines`))}else console.log(f(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>Cp({message:`Conflict \u2014 ${t.path}`,choices:[{name:"Keep local (publish \u2014 overwrites the portal edit)",value:"local"},{name:"Take portal (overwrites your local edits)",value:"portal"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip");return o==="portal"?(Rp({cwd:e.cwd,profileName:e.profileName},t),console.log(j(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(f(" Skipped \u2014 still a conflict.")),"skipped")}async function sl(e,t){let n=Ae(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let i=(await Pp({cwd:t.cwd,profileName:t.profileName})).entries.filter(p=>p.status==="conflict"&&p.path).map(p=>p.path);if(o){if(!i.includes(o))return console.log(j(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};i=[o]}if(i.length===0)return console.log(j("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let l=[];for(let p of i){let m=await Tp({cwd:t.cwd,profileName:t.profileName,relPath:p});await Zr(t,m)==="keep-local"&&l.push(p)}if(l.length>0)return console.log(f(`Publishing ${l.length} kept-local article${il(l.length)} over the portal\u2026`)),await wt(t,l)}catch(r){console.log(C(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function cl(e,t){let n=Ae(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await _p(t),{kind:"continue"};if(o==="--baseline")return await Op(t,e.filter(l=>l!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Lp(t),{kind:"continue"};if(o)return console.log(C(`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 Mp(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let i=await ti({cwd:t.cwd,profileName:t.profileName});for(let l of ni(i))console.log(l.tone==="ok"?j(l.text):l.tone==="warn"?L(l.text):f(l.text));console.log("")}catch(r){r instanceof Ip?console.log(C(r.message)):console.log(C(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function ti(e){let t=await al({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 ll({cwd:e.cwd,profileName:e.profileName,relPath:o.path});ei({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 jp({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Ap({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 So=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,yt=e=>e===1?"":"s";function ni(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${yt(e.pulled.length)} into local: ${So(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${yt(e.imported.length)}: ${So(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${yt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${yt(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's). (${So(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${yt(e.failed.length)} failed: ${So(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 _p(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await al({cwd:e.cwd,profileName:e.profileName});for(let o of To(n,Date.now()-t))console.log(o);console.log("")}async function Op(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 Ep({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Np({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(j("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(j(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(j(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(L(`${o.skipped.length} skipped:`));for(let i of o.skipped)console.log(f(` - ${i.path} (${i.reason})`))}}async function Lp(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Dp({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${ge(String(t.legacyCount))} \xB7 Manifest: ${ge(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(j("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(C(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(L(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(L(` ${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 Mp(e,t){let n=t.replace(/\\/g,"/"),o=await ll({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Zr(e,o)==="keep-local"&&(console.log(f(`Publishing ${o.path} over the portal\u2026`)),await wt(e,[o.path]));return}console.log(""),console.log(`${O("\u25CF")} ${ge(o.title)} ${ae(`(${o.path})`)}`);for(let l of o.notes)console.log(L(` \u26A0 ${l}`));let r=qe(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.")),ei({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ae(` \u23BF Added ${r.added} line${yt(r.added)}, removed ${r.removed} line${yt(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(()=>Sp({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}ei({cwd:e.cwd,profileName:e.profileName},o),console.log(j(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as Up}from"node:fs";import{resolve as Wp}from"node:path";import{estimateBulkCost as Fp,planPartitions as Hp,readProjectConfig as qp,resolveModelForOperation as Bp,runPartitioned as Vp,trackedArticlePaths as Gp}from"document360-engine";var oi=3;function ri(e){let t,n=!1;for(let r=0;r<e.length;r++){let i=e[r];i==="--run"||i==="--yes"?n=!0:i==="--scope"?t=e[++r]:i?.startsWith("--scope=")&&(t=i.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function ii(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function si(e,t){return t.map(n=>{let o=0;try{o=Up(Wp(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ai(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:
|
|
271
|
+
`},r=o(e),i=o(t);if(r===i)return null;let l=Math.max(20,n-10),p=xp("a","b",r,i,"","",{context:3}),m=0,k=0,g=[];p.hunks.forEach((v,_)=>{_>0&&g.push(nl.gray(" \u2026"));let P=v.oldStart,N=v.newStart,S=[],M=[],B=()=>{for(let V=0;V<S.length;V++){let K=V<M.length?il(S[V],M[V]):void 0;k++,g.push(`${Cp}${Zr(P++)} - ${sl(S[V],l,K)}${rl}`)}for(let V=0;V<M.length;V++){let K=V<S.length?il(S[V],M[V]):void 0;m++,g.push(`${Rp}${Zr(N++)} + ${sl(M[V],l,K)}${rl}`)}S=[],M=[]};for(let V of v.lines){let K=V[0],ne=V.slice(1);K==="-"?S.push(ne):K==="+"?M.push(ne):(B(),g.push(nl.gray(Zr(N))+" "+ne.slice(0,l)),P++,N++)}B()});let T=g.slice(0,ol);return{added:m,removed:k,lines:T,hidden:Math.max(0,g.length-ol)}}W();import{select as Pp}from"@inquirer/prompts";import{applyPull as Tp,computeSyncStatus as Sp,planPull as Dp}from"document360-engine";var al=e=>e===1?"":"s";async function ei(e,t){console.log(""),console.log(`${O("\u25CF")} ${we(t.title)} ${ae(`(${t.path})`)}`);for(let r of t.notes)console.log(L(` \u26A0 ${r}`));let n=ze(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(ae(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${al(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(f(` \u2026 +${n.hidden} more diff lines`))}else console.log(f(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>Pp({message:`Conflict \u2014 ${t.path}`,choices:[{name:"Keep local (publish \u2014 overwrites the portal edit)",value:"local"},{name:"Take portal (overwrites your local edits)",value:"portal"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip");return o==="portal"?(Tp({cwd:e.cwd,profileName:e.profileName},t),console.log(j(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(f(" Skipped \u2014 still a conflict.")),"skipped")}async function ll(e,t){let n=Ee(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let i=(await Sp({cwd:t.cwd,profileName:t.profileName})).entries.filter(p=>p.status==="conflict"&&p.path).map(p=>p.path);if(o){if(!i.includes(o))return console.log(j(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};i=[o]}if(i.length===0)return console.log(j("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let l=[];for(let p of i){let m=await Dp({cwd:t.cwd,profileName:t.profileName,relPath:p});await ei(t,m)==="keep-local"&&l.push(p)}if(l.length>0)return console.log(f(`Publishing ${l.length} kept-local article${al(l.length)} over the portal\u2026`)),await yt(t,l)}catch(r){console.log(C(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function ul(e,t){let n=Ee(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Lp(t),{kind:"continue"};if(o==="--baseline")return await Mp(t,e.filter(l=>l!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Up(t),{kind:"continue"};if(o)return console.log(C(`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 Wp(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let i=await ni({cwd:t.cwd,profileName:t.profileName});for(let l of oi(i))console.log(l.tone==="ok"?j(l.text):l.tone==="warn"?L(l.text):f(l.text));console.log("")}catch(r){r instanceof Op?console.log(C(r.message)):console.log(C(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function ni(e){let t=await cl({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 dl({cwd:e.cwd,profileName:e.profileName,relPath:o.path});ti({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 Ep({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Np({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 Do=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,kt=e=>e===1?"":"s";function oi(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${kt(e.pulled.length)} into local: ${Do(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${kt(e.imported.length)}: ${Do(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${kt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${kt(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's). (${Do(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${kt(e.failed.length)} failed: ${Do(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 Lp(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await cl({cwd:e.cwd,profileName:e.profileName});for(let o of So(n,Date.now()-t))console.log(o);console.log("")}async function Mp(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 Ip({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await _p({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(j("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(j(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(j(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(L(`${o.skipped.length} skipped:`));for(let i of o.skipped)console.log(f(` - ${i.path} (${i.reason})`))}}async function Up(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Ap({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${we(String(t.legacyCount))} \xB7 Manifest: ${we(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(j("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(C(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(L(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(L(` ${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 Wp(e,t){let n=t.replace(/\\/g,"/"),o=await dl({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await ei(e,o)==="keep-local"&&(console.log(f(`Publishing ${o.path} over the portal\u2026`)),await yt(e,[o.path]));return}console.log(""),console.log(`${O("\u25CF")} ${we(o.title)} ${ae(`(${o.path})`)}`);for(let l of o.notes)console.log(L(` \u26A0 ${l}`));let r=ze(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.")),ti({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ae(` \u23BF Added ${r.added} line${kt(r.added)}, removed ${r.removed} line${kt(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(()=>jp({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}ti({cwd:e.cwd,profileName:e.profileName},o),console.log(j(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as Fp}from"node:fs";import{resolve as Hp}from"node:path";import{estimateBulkCost as qp,planPartitions as Bp,readProjectConfig as Vp,resolveModelForOperation as Gp,runPartitioned as Yp,trackedArticlePaths as zp}from"document360-engine";var ri=3;function ii(e){let t,n=!1;for(let r=0;r<e.length;r++){let i=e[r];i==="--run"||i==="--yes"?n=!0:i==="--scope"?t=e[++r]:i?.startsWith("--scope=")&&(t=i.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function si(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function ai(e,t){return t.map(n=>{let o=0;try{o=Fp(Hp(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function li(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:
|
|
272
272
|
- 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.
|
|
273
273
|
- 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.
|
|
274
274
|
- 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.
|
|
275
275
|
- Work only on these files:
|
|
276
276
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
277
|
-
`)}function
|
|
277
|
+
`)}function ci(e,t,n){let o=e.reduce((p,m)=>p+m.paths.length,0),[r,i]=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: ${ye(r)}\u2013${ye(i)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function di(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),i=e.filter(P=>!P.ok),l=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),m=e.reduce((P,N)=>P+N.costUsd,0),k=e.reduce((P,N)=>P+N.outputTokens,0),g=n==="api"?`${ye(m)} total`:ot(k),T=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=P=>`${P} article${P===1?"":"s"}`,_=[];if(i.length===0)_.push(`Converted ${v(l)} (${T}) successfully \xB7 ${g}.`);else{_.push(`Converted ${p}/${v(l)} (${T}) \xB7 ${g}.`),_.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let P of i)_.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return _}async function pl(e,t){if(!Vp(t.cwd))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=ii(e),r=zp(t.cwd,t.profileName);if(r.length===0)return console.log(C("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let i=si(r,n);if(i.length===0)return console.log(C(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let l=Bp(i),p=`/convert${n?` --scope ${n}`:""} --run`,{model:m,forced:k}=Gp(t.cwd,"light");if(!o){let g=qp({files:ai(t.cwd,i),op:"convert",model:m});n&&console.log(f(`Scope: ${n} (${i.length} of ${r.length} tracked articles).`));for(let T of ci(l,g,ri))console.log(T);return console.log(f(`Model: ${m}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${i.length} articles across ${l.length} partitions (\u2264${ri} agents at once) on ${m}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let g of Yp({cwd:t.cwd,partitions:l,promptFor:li,concurrency:ri,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:m}))if(g.type==="partition_status")g.status==="running"?console.log(f(` \u25B8 ${g.label} \u2014 converting\u2026`)):g.status==="done"?console.log(j(` \u2713 ${g.label}`)):console.log(C(` \u2717 ${g.label}`));else if(g.type==="run_done"){console.log("");let T=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let v of di(g.results,l,T))console.log(g.ok?j(v):L(v))}}catch(g){console.log(C(`Convert run failed: ${g.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as ml}from"node:fs";import{resolve as gl}from"node:path";import{estimateBulkCost as of,lintDocs as rf,planPartitions as sf,readDocsPlan as af,readProjectConfig as wl,DEFAULT_DOCS_DIR as lf,resolveModelForOperation as cf,runPartitioned as df,stampArticles as uf,CONTENT_CAP_VERSION as pf}from"document360-engine";import{readProjectConfig as Kp,loadProfileMap as Xp,resolveActiveProfile as Qp,desiredCategoryOrder as Jp,desiredArticleOrder as Zp,DEFAULT_DOCS_DIR as ef}from"document360-engine";var ui=e=>e.replace(/\\/g,"/"),tf=e=>ui(e).split("/").pop()??e;function nf(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function xn(e,t){try{let n=Kp(e);if(!n)return[];let o=Qp(e,t),r=Xp(e,o.name);if(!r)return[];let i=ui(n.docsDir??ef).replace(/\/+$/,""),l=new Map;for(let m of Zp(r))l.set(m.categoryPath,(l.get(m.categoryPath)??0)+1);let p=[];for(let m of Jp(r)){let k=ui(m.path),g=k.startsWith(`${i}/`)?k.slice(i.length+1):k===i?"":k;g&&p.push({token:g,label:nf(tf(k)),count:l.get(m.path)??0})}return p}catch{return[]}}function fl(e,t){let n=xn(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 rt(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function Xt(e,t,n,o){let r=xn(e,o);if(r.length<=1)return[];let i=n.filter(k=>k.startsWith("--")).join(" "),l=i?` ${i}`:"",p=`/${t}${l} --all`.replace(/\s+/g," "),m=k=>t==="write"?`/write --scope ${k}${l}`:`/${t} ${k}${l}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((k,g)=>k+g.count,0)} articles). Pick a target:`,` ${p} (everything)`,...r.map(k=>` ${m(k.token)} (${k.label} \xB7 ${k.count} article${k.count===1?"":"s"})`)]}function jo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function hl(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 ff=3,hf=8;function pi(e){return e===void 0||!Number.isFinite(e)?ff:Math.max(1,Math.min(Math.floor(e),hf))}function fi(e){let t,n,o=!1,r=!1,i,l=m=>{let k=Number(m);return m!==void 0&&Number.isFinite(k)?k:void 0};for(let m=0;m<e.length;m++){let k=e[m];if(k==="--preview"||k==="--dry-run")o=!0;else if(k==="--rewrite"||k==="--force")r=!0;else{if(k==="--run"||k==="--yes"||k==="--all")continue;k==="--scope"?t=e[++m]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?i=l(e[++m]):k?.startsWith("--concurrency=")?i=l(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=m=>m?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:i,rewrite:r}}function mf(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function gf(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function hi(e,t,n){return n.filter(o=>{try{return ml(gl(e,t,o)).size===0}catch{return!0}})}function mi(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let i=1;for(let l of o.get(r)?.sources??[])try{i+=ml(gl(e,l)).size}catch{}return{path:r,bytes:i}})}function gi(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.
|
|
278
278
|
`:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
279
279
|
- It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose, its \`type\` (concept | task | reference | faq; missing \u21D2 task), and the source files it draws from (AGENT-PLAN.md has the same table).
|
|
280
280
|
- Use the skeleton for that \`type\` (see write-article): a \`concept\`/overview page opens with what the product IS + its mental model and takes NO Prerequisites/Steps; only a \`task\` page gets Steps.
|
|
@@ -284,81 +284,81 @@ ${i}${m}`).join("")}).join(`
|
|
|
284
284
|
- 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.
|
|
285
285
|
Articles:
|
|
286
286
|
`+e.paths.map(r=>`- ${r}`).join(`
|
|
287
|
-
`)}function
|
|
288
|
-
`)}var
|
|
289
|
-
`)}var
|
|
287
|
+
`)}function wi(e,t,n){let o=e.reduce((l,p)=>l+p.paths.length,0),[r,i]=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: ${ye(r)}\u2013${ye(i)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function yi(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),i=e.filter(P=>!P.ok),l=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),m=e.reduce((P,N)=>P+N.costUsd,0),k=e.reduce((P,N)=>P+N.outputTokens,0),g=n==="api"?`${ye(m)} total`:ot(k),T=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=P=>`${P} article${P===1?"":"s"}`,_=[];if(i.length===0)_.push(`Wrote ${v(l)} (${T}) successfully \xB7 ${g}.`),_.push("Next \u2014 push them to Document360:"),_.push("/publish --all"),_.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{_.push(`Wrote ${p}/${v(l)} (${T}) \xB7 ${g}.`),_.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let P of i)_.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return _}function ki(e,t,n){try{let o=rf({cwd:e,paths:n.map(i=>`${t}/${i}`)});if(o.length===0)return null;let r=new Set(o.map(i=>i.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 bi(e,t,n){let o=(wl(e)?.docsDir??lf).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=mf(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 i=gf(r,n.scope);if(n.scope&&i.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:i,planCount:r.length,rewriting:!0};let l=hi(e,o,i);if(l.length===0){let p=n.scope?` under "${n.scope}"`:"",m=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${m} --rewrite to regenerate them all.`}}return{docsDir:o,targets:l,planCount:r.length}}async function yl(e,t){if(!wl(t.cwd))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};if(jo(e)){for(let M of fl(t.cwd,t.profileName))console.log(f(M));return{kind:"continue"}}if(rt("write",e)){let M=Xt(t.cwd,"write",e,t.profileName);if(M.length>0){for(let B of M)console.log(f(B));return{kind:"continue"}}}let n=af(t.cwd);if(n.length===0)return console.log(C("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:i,concurrency:l,rewrite:p}=fi(e),{docsDir:m,targets:k,reason:g,rewriting:T}=bi(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(g?L(g):L("Nothing to write.")),{kind:"continue"};T&&console.log(L(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let v=sf(k),_=pi(l),{model:P,forced:N}=cf(t.cwd,"standard"),S=!!r;if(i&&!S){let M=of({files:mi(t.cwd,n,k),op:"write",model:P});o&&console.log(f(`Scope: ${o} (${k.length} pending).`));for(let B of wi(v,M,_))console.log(B);return console.log(f(`Model: ${P}${N?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${k.length} article${k.length===1?"":"s"} across ${v.length} partition${v.length===1?"":"s"} (\u2264${_} agents at once) on ${P}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let M of df({cwd:t.cwd,partitions:v,promptFor:B=>gi(B,m,{rewrite:T||S}),concurrency:_,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:P}))if(M.type==="partition_status")M.status==="running"?console.log(f(` \u25B8 ${M.label} \u2014 writing\u2026`)):M.status==="done"?console.log(j(` \u2713 ${M.label}`)):console.log(C(` \u2717 ${M.label}`));else if(M.type==="run_done"){console.log("");let B=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let K of yi(M.results,v,B))console.log(M.ok?j(K):L(K));if(M.ok)try{uf(t.cwd,k.map(K=>`${m}/${K}`),{writtenCap:pf})}catch{}let V=ki(t.cwd,m,k);V&&console.log(L(V))}}catch(M){console.log(C(`Write run failed: ${M.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as wf,readdirSync as kl,statSync as bl}from"node:fs";import{join as vl}from"node:path";import{inputDir as yf,readProjectConfig as kf}from"document360-engine";var $l=/\.(md|markdown|pdf|txt)$/i;function vi(e){let t=yf(e);if(!wf(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of kl(t)){let i=vl(t,r),l=!1;try{l=bl(i).isDirectory()}catch{continue}if(l){if(r.startsWith("."))continue;let p=bf(i);p>0&&n.push({name:r,docCount:p})}else $l.test(r)&&o++}return n.sort((r,i)=>r.name.localeCompare(i.name)),{features:n,looseDocs:o}}function bf(e){let t=0;for(let n of kl(e))try{bl(vl(e,n)).isFile()&&$l.test(n)&&t++}catch{}return t}function $i(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 Ao(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(`
|
|
288
|
+
`)}var xi="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function xl(e,t){let n=t?.cwd??process.cwd();if(!kf(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=vi(n);if(o.length===0&&r===0)return console.log(f(xi)),{kind:"continue"};let i=e.join(" ").trim();if(!i){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let m of o)console.log(` ${m.name} ${f(`(${m.docCount} doc${m.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Ao(p),display:p?`/draft ${p}`:"/draft"}}let l=$i(o,i);return{kind:"forward-to-agent",prompt:Ao(l??"",l?void 0:i),display:`/draft ${i}`}}W();import{listOpenForDocs as vf,readProjectConfig as $f}from"document360-engine";function Ci(e){try{return vf(e).filter(t=>t.kind==="request").length}catch{return 0}}function Ri(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Pi(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(`
|
|
289
|
+
`)}var Ti="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 Cl(e,t){let n=t?.cwd??process.cwd();if(!$f(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Ri(e);if(!r&&Ci(n)===0)return console.log(f(Ti)),{kind:"continue"};let i=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Pi(r,o),display:i}}W();import{search as xf}from"@inquirer/prompts";import{findByName as Cf,getSession as Rf,listSessions as Pf,relativeTime as Pl}from"document360-engine";async function Tl(e,t){let n=Pf(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=Cf(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(C(`No session matches "${o}".`)),Rl(n),{kind:"continue"})}if(!process.stdin.isTTY)return Rl(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>xf({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async i=>{let l=(i??"").toLowerCase();return n.filter(p=>!l||p.name.toLowerCase().includes(l)||p.firstPrompt.toLowerCase().includes(l)).map(p=>({name:`${p.name} ${Pl(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Rf(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Rl(e){console.log("");for(let t of e.slice(0,15))console.log(` ${O(t.name)} ${f(Pl(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Tf}from"document360-engine";function Si(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 Sl(e,t){let n=Si(e.join(" "));if(!n)return console.log(C("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Tf(o,n)?console.log(j(`\u2713 Session renamed to "${n}"`)):console.log(C("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(j(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Dl,readProjectConfig as Sf,writeProjectConfig as Df}from"document360-engine";W();function Di(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Sf(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 Dl().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Df(o,e),null):`Unknown environment "${r}". Known: ${Dl().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function jl(e,t){let n=e[0];if(!n)return co(t.cwd),{kind:"continue"};if(n==="add"){let o=Di(t.cwd,e[1],e[2]);return o?(console.log(C(o)),{kind:"continue"}):(console.log(j(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${O(`/profile ${e[1]}`)} then ${O("/login")}`),{kind:"continue"})}return uo(t.cwd,n),po(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as jf}from"@inquirer/prompts";import{readProjectConfig as Af,readUserConfig as Al,resolveModelSetting as ji,writeUserConfig as El}from"document360-engine";var Ue=[{value:null,label:"Auto",desc:"Sonnet (latest) \u2014 right-sized for docs work (recommended); heavier models only when you pin them"},{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 (latest) \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet (latest) \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku (latest) \xB7 fastest for quick answers"}];function Eo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Ue.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Ef(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"auto":return"auto \u2014 the docs-right default (newest Sonnet); /model to pin another"}}function Cn(e,t){let n=()=>ji(e).model;if(t==="default"){let i=Al();return i.defaultModel?(delete i.defaultModel,El(i),{lines:[`\u2713 Personal model override cleared \u2014 now: ${ji(e).model} (auto; applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}El({...Al(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Af(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 Nl(e,t){let n=e[0]?.trim();if(!n){let l=ji(t.cwd);if(!process.stdin.isTTY)return console.log(`${we("Model:")} ${O(l.model)}${l.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${Ef(l)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Eo(l),m;try{m=await t.withPausedInput(()=>jf({message:`Select model (current: ${l.model}${l.source==="auto"?" \xB7 auto":""})`,default:Ue[p].value,choices:Ue.map((v,_)=>({name:`${v.label}${_===p?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:g,effective:T}=Cn(t.cwd,m??"default");for(let v of k)console.log(v.startsWith("\u26A0")?L(v):v.startsWith("\u2713")?j(v):f(v));return g&&await t.setModel(T),{kind:"continue"}}let{lines:o,changed:r,effective:i}=Cn(t.cwd,n);for(let l of o)console.log(l.startsWith("\u26A0")?L(l):l.startsWith("\u2713")?j(l):f(l));return r&&await t.setModel(i),{kind:"continue"}}No();async function Ul(e,t){return await t.withPausedInput(()=>qt(t.cwd)),{kind:"clear"}}async function Wl(e,t){return await t.withPausedInput(()=>io(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as Xf}from"document360-engine";async function Fl(e,t){let n=!1;try{n=Xf(t.cwd).production}catch{}return n?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var Hl=async(e,t)=>{try{await t.withPausedInput(()=>lo({}))}catch(n){console.log(C(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as Qf,clearTokens as Jf,clearProfileProject as Zf}from"document360-engine";async function ql(e,t){let n;try{n=Qf(t.cwd,t.profileName).name}catch(r){return console.log(C(r.message)),{kind:"continue"}}let o=Jf(n);return Zf(t.cwd,n),console.log(o?j(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):f(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(f("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as Bl}from"node:fs";import{isAbsolute as eh,join as th,resolve as nh}from"node:path";import{readProjectConfig as oh,screenshotPlaceholderIds as rh,DEFAULT_CAPTURE_DIR as ih,DEFAULT_OUTPUT_DIR as sh}from"document360-engine";var Vl=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ei(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Vl(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Vl(o),setup:t}:{mode:"single",id:o}}function Ni(e,t){let n=oh(e),o=n?.captureDir??ih,r=n?.outputDir??sh,i=(l,p)=>eh(l)?th(l,p):nh(e,l,p);return rh(e,{scope:t}).map(({id:l,file:p})=>{let m=Bl(i(r,`${l}.png`))?"captured":Bl(i(o,`${l}.spec.ts`))?"spec":"placeholder";return{id:l,file:p,state:m}})}var ah={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},lh={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Ii(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(i=>i.file))].sort(),o=e.filter(i=>i.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 i of n){r.push(i);for(let l of e.filter(p=>p.file===i))r.push(` ${ah[l.state]} ${l.id.padEnd(34)} ${lh[l.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Gl(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(`
|
|
290
290
|
`),"","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(`
|
|
291
|
-
`)}async function
|
|
291
|
+
`)}async function Io(e,t){let n=Ei(e);if(n.mode==="list"){let l=t?.cwd??process.cwd();for(let p of Ii(Ni(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(`
|
|
292
292
|
`),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(`
|
|
293
|
-
`),i=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:i}}import{existsSync as
|
|
294
|
-
`),display:"/capture-setup"}}var
|
|
295
|
-
`)}async function
|
|
296
|
-
`)}var
|
|
297
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
293
|
+
`),i=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:i}}import{existsSync as ch,readFileSync as dh}from"node:fs";import{isAbsolute as uh,join as ph,resolve as fh}from"node:path";import{readProjectConfig as hh,DEFAULT_CAPTURE_DIR as mh}from"document360-engine";async function Pn(){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(`
|
|
294
|
+
`),display:"/capture-setup"}}var Yl="-".repeat(64);function _i(e){let t=mh;try{let g=hh(e);g?.captureDir&&(t=g.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=uh(t)?ph(t,"CAPTURE-TESTID-REQUESTS.json"):fh(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!ch(n))return null;let o;try{let g=JSON.parse(dh(n,"utf8").replace(/^/,""));o=Array.isArray(g?.requests)?g.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(g=>g.file).filter(Boolean)).size,i=o.length,l=`${i} data-testid attribute${i===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,m=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${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.","",Yl,`Read ${m} and ${k}. 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.",Yl]}tt();W();import{listOpenForDocs as gh,readProjectConfig as wh}from"document360-engine";function Oi(e){try{return gh(e).length}catch{return 0}}function Li(){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 to a [discovery]-tagged question (subject starts "[discovery] ") \u2192 this is product-discovery,'," not an article edit: fold the fact into `.d360-writer/product-brief.md` (updating the cited grounding,"," clearing the matching OPEN marker), then RE-RUN the discover-product readiness assessment \u2014 set the"," brief's frontmatter status to `confident` and offer propose-structure if every rubric dimension now"," passes, else ask the next focused batch via d360_ask_builder. Do not touch articles for these."," \u2022 answer (a reply to any other 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(`
|
|
295
|
+
`)}async function zl(e,t){let n=t?.cwd??process.cwd();return wh(n)?Oi(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:Li(),display:"/inbox"}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as yh,listOpenForDocs as kh,listOpenDirectives as bh,readProjectConfig as vh,computeSyncStatus as $h,planPull as xh,applyPull as Ch,planImport as Rh,applyImport as Ph}from"document360-engine";function Tn(e){let t=0,n=0,o=0,r=0;try{t=yh(e).length}catch{}try{let i=kh(e);n=i.filter(l=>l.kind==="request").length,o=i.filter(l=>l.kind==="answer").length}catch{}try{r=bh(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function Sn(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"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),t.length?t.join(", "):null}function Ui(e){return{publish:e.includes("--publish")}}function Wi({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), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page" \u2014 .d360-writer/directives.md).`,"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 \u2014 EXCEPT an answer to a [discovery]-tagged question (subject starts "[discovery] "), which is product discovery: fold it into `.d360-writer/product-brief.md`, then re-run the discover-product readiness assessment (flip the brief to `confident` if every rubric dimension now passes and offer propose-structure, else leave a follow-up [discovery] question) \u2014 address each feedback item (improve the doc it points at \u2014 as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts \u2014 following the active doc-type playbook).',"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 OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done), and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed \u2014 never delete existing steps;"," \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(`
|
|
296
|
+
`)}var Th={status:$h,plan:xh,apply:Ch,planImport:Rh,applyImport:Ph};async function Fi(e,t=Th){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 i=await t.planImport({cwd:e.cwd,profileName:e.profileName,articleId:r.articleId});t.applyImport({cwd:e.cwd,profileName:e.profileName},i),n.imported.push(i.path)}catch(i){n.failed.push({path:r.title??r.articleId,error:i.message})}else if(r.status==="remote-ahead"&&r.path)try{let i=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},i),n.pulled.push(r.path)}catch(i){n.failed.push({path:r.path,error:i.message})}return n}var Mi=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,_o=e=>e===1?"":"s";function Hi(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${_o(e.pulled.length)} into local: ${Mi(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${_o(e.imported.length)} into local drafts: ${Mi(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${_o(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Mi(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${_o(e.failed.length)} failed \u2014 left for /pull.`),t}async function Kl(e,t){let n=t?.cwd??process.cwd();if(!vh(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ee(n,t?.profileName);if(!o.ok)return console.log(C(o.reason)),{kind:"continue"};let{publish:r}=Ui(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let i=await Fi({cwd:n,profileName:t?.profileName});for(let p of Hi(i))console.log(p.startsWith("\u2713")?j(p):p.startsWith("\u2139")?f(p):L(p));let l=Sn(Tn(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:Wi({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as Sh}from"node:child_process";var bt="document360-writer",Oo=`npm i -g ${bt}@latest`;async function Lo(){let e=process.platform==="win32";return new Promise(t=>{try{let n=Sh(`npm i -g ${bt}@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 Xl(){return console.log(f(`Updating ${bt}\u2026`)),(await Lo()).ok?console.log(j("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(C(`Update failed \u2014 run manually: ${Oo}`)),{kind:"continue"}}W();tt();import{existsSync as qi,rmSync as Dh}from"node:fs";import{basename as Ql,resolve as Bi}from"node:path";import{execFileSync as jh}from"node:child_process";import{input as Ah}from"@inquirer/prompts";import{readProjectConfig as Eh,devHintsGuidePath as Nh}from"document360-engine";var Ih=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],_h=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Mo=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Jl=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Zl(e){let t=Mo(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Jl(t)?!0:_h.has(t)}function Vi(e){let t=null;try{t=Eh(e)}catch{t=null}let n=new Set(Ih);for(let o of[Mo(t?.docsDir),Mo(t?.captureDir),Mo(t?.outputDir)])o&&Jl(o)&&n.add(o);return[...n].filter(o=>Zl(o)&&qi(Bi(e,o)))}function Gi(e,t){let n=[],o=[];for(let r of t){if(!Zl(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Dh(Bi(e,r),{recursive:!0,force:!0}),n.push(r)}catch(i){o.push({path:r,error:i.message})}}return{removed:n,failed:o}}function ec(e,t){try{return jh("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
297
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Oh(e){return ec(e,".d360-writer/hints")}function Lh(e){return ec(e,".d360-writer/messages")}function Yi(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Oh(e),o=Lh(e),r=qi(Bi(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(i=>` \u2022 ${i}`),"",...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: ${Ql(e)}`]}async function tc(e,t){let n=Vi(t.cwd);for(let m of Yi(t.cwd,n))console.log(n.length===0?f(m):m);if(n.length===0)return{kind:"continue"};let o=Ql(t.cwd);if((await t.withPausedInput(()=>Ah({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let i=qi(Nh(t.cwd)),{removed:l,failed:p}=Gi(t.cwd,n);console.log(j(`\u2713 Reset complete \u2014 removed ${l.length} item${l.length===1?"":"s"}. The repo is back to its original state.`));for(let m of p)console.log(C(` \u2717 ${m.path}: ${m.error}`));if(i){for(let m of wo())console.log(m);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"}}W();import{lintDocs as Mh}from"document360-engine";function Uo(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 i of r)n.push(` L${i.line}: "${i.term}" \u2014 ${i.message}`)}return n}function zi(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(i=>` - L${i.line} [${i.kind}]: "${i.term}" \u2014 ${i.message}`)].join(`
|
|
298
298
|
`)).join(`
|
|
299
299
|
`)].join(`
|
|
300
|
-
`)}async function
|
|
301
|
-
`);return{prompt:
|
|
302
|
-
`),display:`/reorder${n?` ${n}`:""}`}}async function
|
|
303
|
-
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${
|
|
304
|
-
`)];return r.length&&i.push(r.join(" ")),i.push(
|
|
305
|
-
|
|
306
|
-
`)}function
|
|
307
|
-
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let l=
|
|
308
|
-
`);return{lines:i.slice(0,t).map(l=>
|
|
309
|
-
`))console.log(l(` ${p}`));i.rec.picker&&console.log(O(` Pick one: ${i.rec.picker.options.map(p=>p.cmd).join(" \xB7 ")}`))}}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function
|
|
310
|
-
|
|
311
|
-
`),console.log(`${j("\u25CF")} ${
|
|
312
|
-
`),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&&(
|
|
313
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let i=n[r];if(!t.cueSeen){
|
|
314
|
-
`)}import{existsSync as
|
|
315
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var
|
|
316
|
-
`)){let l=i.trim().replace(
|
|
317
|
-
`)}function
|
|
318
|
-
`)||e.length>200}function
|
|
319
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function
|
|
320
|
-
`)){if(i.length===0)o.push({start:r,end:r});else for(let l=0;l<i.length;l+=n)o.push({start:r+l,end:r+Math.min(l+n,i.length)});r+=i.length+1}return o.length>0?o:[{start:0,end:0}]}function
|
|
300
|
+
`)}async function nc(e,t){let n=e.includes("--fix"),o=e.find(l=>!l.startsWith("--")),r=o?` ${o}`:"",i=Mh({cwd:t.cwd,scope:o});if(n)return i.length===0?(console.log(j("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${i.length} doc issue${i.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:zi(i),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let l of Uo(i))console.log(i.length===0?j(l):L(l));return i.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}W();import{lintDocs as Bh,loadStyleGuide as Vh,buildReviewPrompt as Gh,readProjectConfig as Yh,DEFAULT_DOCS_DIR as zh}from"document360-engine";W();import{readProjectConfig as Uh,loadProfileMap as Wh,resolveActiveProfile as Fh,desiredCategoryOrder as Hh,desiredArticleOrder as qh}from"document360-engine";function oc(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var rc=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Dn(e,t){try{if(!Uh(e))return[];let n=Fh(e,t),o=Wh(e,n.name);if(!o)return[];let r=new Map;for(let l of qh(o)){let p=r.get(l.categoryPath);p?p.push(l):r.set(l.categoryPath,[l])}let i=[];for(let l of Hh(o)){i.push(oc(rc(l.path)));for(let p of(r.get(l.path)??[]).sort((m,k)=>m.order-k.order))i.push(` ${oc(rc(p.path))}`)}return i}catch{return[]}}async function ic(e,t){let n=Dn(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(O("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Ki(e,t){let n=Yh(e);if(!n)return null;let o=(n.docsDir??zh).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),i=t.find(g=>!g.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),l=Bh({cwd:e}),p=i?l.filter(g=>g.path===`${o}/${i}`||g.path.startsWith(`${o}/${i}/`)):l,m=i?"":Dn(e).join(`
|
|
301
|
+
`);return{prompt:Gh({docsRoot:o,scope:i,styleGuide:Vh(e),deterministicFindings:p,fix:r,structure:m||void 0}),display:`/review${i?` ${i}`:""}${r?" --fix":""}`}}async function sc(e,t){if(rt("review",e)){let o=Xt(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=Ki(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as Kh}from"document360-engine";function Xi(e,t){if(!Kh(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(`
|
|
302
|
+
`),display:`/reorder${n?` ${n}`:""}`}}async function ac(e,t){if(rt("reorder",e)){let o=Xt(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=Xi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as Xh,writeProjectConfig as lc,isAppType as Qh,playbookSkillName as Jh,detectAppType as cc}from"document360-engine";var dc=["web","cli","service","library"],Zh=new Set(["web","cli"]);function Qi(e){return Zh.has(e)?`${Jh(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Wo(e,t){let n=t.cwd,o=Xh(n);if(!o)return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let i=o.appType??cc(n);if(i){let l=o.appType?"set in config":"auto-detected";console.log(`${O("Genre:")} ${i} (${l}) \u2014 ${Qi(i)}`)}else console.log(L("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${dc.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:i,...l}=o;lc(l,n);let p=cc(n);return console.log(j(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${Qi(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return Qh(r)?(lc({...o,appType:r},n),console.log(j(`\u2713 Genre set to ${r} \u2014 ${Qi(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(C(`Unknown genre "${r}". Choose one of: ${dc.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}W();import{listRoadmap as uc,roadmapProgress as pc,stampRoadmapDone as em}from"document360-engine";function Ji(e){let t=uc(e);if(t.length===0)return["No docs roadmap yet \u2014 the docs agent seeds .d360-writer/roadmap.md when it pins a structure,","and adds steps as the app changes. You can also write steps by hand (## [open] <step>), or ask:",'"propose the docs roadmap for this repo".'];let n=pc(e),o=[`Docs roadmap \u2014 ${n.done} of ${n.total} step${n.total===1?"":"s"} done:`,""];for(let r of t)o.push(` ${r.status==="done"?"\u2713":"\u25CB"} ${r.title}${r.run?` \xB7 ${r.run}`:""}`);return o.push(""),o.push(n.next?`Next: ${n.next.title}${n.next.run?` \u2014 ${n.next.run}`:""}`:"Campaign complete \u2014 the docs agent adds new steps as the app changes."),o.push("(Edit .d360-writer/roadmap.md freely \xB7 /roadmap done <step> marks one you finished yourself.)"),o}function Zi(e,t){if(!t.trim())return{ok:!1,line:"Usage: /roadmap done <step title>"};if(!em(e,t,{doneAt:new Date().toISOString()})){let r=uc(e).filter(i=>i.status==="open");return{ok:!1,line:r.length?`No open step titled "${t}". Open steps: ${r.map(i=>`"${i.title}"`).join(", ")}`:`No open step titled "${t}" \u2014 the roadmap has no open steps.`}}let o=pc(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${t}${o?` \u2014 next up: ${o.title}${o.run?` (${o.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}async function fc(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Zi(n,e.slice(1).join(" ").trim());return console.log(r.ok?j(r.line):L(r.line)),{kind:"continue"}}let o=Ji(n);console.log(O(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?f(r):r);return{kind:"continue"}}var hc={help:Ar,"?":Ar,clear:ma,exit:Er,quit:Er,init:Lr,mcp:bo,publish:Qa,audit:$n,discover:Ja,scope:el,pull:ul,resolve:ll,convert:pl,write:yl,draft:xl,document:Cl,resume:Tl,rename:Sl,profile:jl,model:Nl,doctor:Rn,workspace:Ul,project:Wl,"allow-prod":Fl,login:Hl,logout:ql,screenshot:Io,"capture-setup":Pn,devhints:Ca,inbox:zl,"catch-up":Kl,update:Xl,reset:tc,check:nc,review:sc,reorder:ac,structure:ic,genre:Wo,roadmap:fc};function mc(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}tt();var tm="Or just tell me what to write or update.",nm='\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 fe(e){return e===1?"":"s"}function Fo(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function ts(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var om={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",options:[{cmd:"/genre web",desc:"web app / SaaS UI"},{cmd:"/genre cli",desc:"command-line tool"},{cmd:"/genre service",desc:"API / backend service"},{cmd:"/genre library",desc:"SDK / library"}]};function rm(e){let t=[];if(e.devhints!=="current"&&e.builderStarted){let n=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",o=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";t.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${n}${o} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${n}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&t.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:om,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.discovery&&e.discovery.status!=="confident"){let n=e.discovery.openQuestions;t.push(e.discovery.status==="pending"?{key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/publish steps)."}:n>0?{key:"discovery",bullet:`product discovery is waiting on ${n} answer${fe(n)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}:{key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${fe(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${fe(n)}.`})}if(e.directives>0||e.pendingText){let n=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",o=[];e.directives>0&&o.push(`${e.directives} owner directive${fe(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
|
|
303
|
+
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${fe(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${fe(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${fe(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${fe(n)} changed both here and on Document360 (conflicts) \u2014 /publish skips these`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each conflict \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${n} conflict${fe(n)} (keep yours / take the portal's / skip).`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${fe(n.total)} done \u2014 next: ${o.title}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${fe(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${fe(n)}.`})}return t}function gc(e){return e.find(t=>t.lead||t.picker)??null}function es(e,t){let n=t.filter(l=>l.bullet).map(l=>` \u2022 ${l.bullet}`),o=gc(t),r=[];o?.lead?r.push(ts(o.lead)):o?.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let l of t.filter(p=>p!==o).slice(0,2))l.follow&&r.push(l.follow);let i=[[e,...n].join(`
|
|
304
|
+
`)];return r.length&&i.push(r.join(" ")),i.push(tm),i.join(`
|
|
305
|
+
|
|
306
|
+
`)}function jn(e){if(!e.ready)return{kind:"idle"};let t=rm(e);if(!e.hasDocs){let i=gc(t);return i&&(i.lead?.kind==="cmd"||i.picker)?{kind:"recommend",rec:{note:es("\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",t),tone:i.tone??"info",lead:i.lead,picker:i.picker}}:{kind:"recommend",rec:{note:nm,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null}}}if(t.length===0){let i=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${fe(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${fe(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${i}`,tone:"info",lead:null,picker:null}}}let n=t.filter(i=>i.lead||i.picker),o=n[0]??null;return o?(o.key==="audit"||o.key==="roadmap"&&n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${fe(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:es("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:es("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as ns,readdirSync as rs}from"node:fs";import{spawnSync as im}from"node:child_process";import{join as Ho}from"node:path";import{readProjectConfig as yc,resolveActiveProfile as kc,loadTokens as sm,isExpired as am,loadProfileMap as bc,localAheadPaths as lm,loadKnownConflicts as cm,readDocsPlan as dm,devHintsGuidePath as um,DEFAULT_DOCS_DIR as os,roadmapProgress as pm,listRoadmap as fm,readProductBriefState as hm}from"document360-engine";tt();function wc(e){try{return rs(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function is(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>wc(Ho(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&wc(Ho(e,o)))}function ss(e,t){try{let n=yc(e);if(!n)return!1;let o=kc(e,t),r=bc(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let i=Ho(e,(n.docsDir??os).replace(/\/+$/,""));return!!(ns(i)&&rs(i).length>0||ns(um(e)))}catch{return!1}}function An(e,t,n){try{let o=yc(e);if(!o)return null;let r=kc(e,t),i=sm(r.name),l=!!i&&(!am(i)||!!i.refreshToken),p=ss(e,t)||!is(e,o.authoritativeSourceFiles),m=bc(e,r.name),k=m?Object.keys(m.articles).length:0,g=Ho(e,(o.docsDir??os).replace(/\/+$/,"")),T=!1;try{T=ns(g)&&rs(g).length>0}catch{}let v=0;if(m?.lastAnalyzedCommit)try{let Te=im("git",["rev-list","--count",`${m.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});Te.status===0&&(v=parseInt((Te.stdout||"").trim(),10)||0)}catch{}let _=0;try{let Te=dm(e);if(Te.length>0){let ke=(o.docsDir??os).replace(/\/+$/,"");_=hi(e,ke,Te.map(Fe=>Fe.path)).length}}catch{}let P=Tn(e),N=Sn({...P,directives:0}),S=lm(e,t),M=new Set(cm(e,r.name)),B=S.filter(Te=>M.has(Te)).length,V=S.length-B,K=Ae(e),ne=pm(e),Ie=hm(e),We=Ie?{status:Ie.status,openQuestions:Ie.openQuestions}:null;return!We&&T&&fm(e).some(ke=>ke.status==="open"&&(ke.run??"").trim()==="/discover")&&(We={status:"pending",openQuestions:0}),{ready:l&&p&&!n.claudeMissing,hasDocs:T,tracked:k,pendingText:N,directives:P.directives,behind:v,pendingWrites:_,localAhead:V,conflicts:B,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:K.status,devhintsCompletedVersion:K.completedVersion,devhintsToVersion:ce,builderStarted:Ye(e),genreUnknown:n.genreUnknown,roadmap:ne,discovery:We}}catch{return null}}function vc(e,t){let n=[],o="";for(let r of e.split(/\s+/).filter(Boolean))for(o.length?o.length+1+r.length<=t?o+=` ${r}`:(n.push(o),o=r):o=r;o.length>t;)n.push(o.slice(0,t)),o=o.slice(t);return o&&n.push(o),n}function qo(e){if(e.length===0)return[];let t=(i,l)=>`${i}${"\u2500".repeat(78)}${l}`,n=(i="")=>`\u2502 ${i.padEnd(76)} \u2502`,o=[`\u2B06 d360-writer upgraded \u2014 ${e.length===1?"one improvement affects":`${e.length} improvements affect`} the docs you've already written:`,"",t("\u250C","\u2510")];e.forEach((i,l)=>{l>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let p of vc(`${l+1}. ${i.feature}`,76))o.push(n(p));o.push(n());for(let p of vc(i.why,73))o.push(n(` ${p}`));o.push(n())}),o.push(t("\u2514","\u2518")),o.push("");let r=e.length>1;return o.push(`\u2713 ${r?"These are":"This is"} now on your docs roadmap \u2014 each launch shows your next step below (/roadmap shows the full campaign).`),o}W();var mm={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"},xc=160,ls=200,Cc=40;function Ce(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function $c(e){let t=Object.entries(e).filter(([,o])=>o!=null&&o!=="");if(t.length===0)return null;let n=t.slice(0,4).map(([o,r])=>`${o}: ${Ce(typeof r=="string"?r:JSON.stringify(r),Cc)}`);return t.length>4&&n.push("\u2026"),Ce(n.join(", "),xc)}var it=e=>typeof e=="string"&&e?e:null,as=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function gm(e){let t=it(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(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ")}function wm(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=it(t.title);if(!o)return null;let r=gm(t.local_path);return n("Create article",`"${Ce(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=it(t.title),r=as(t.article_id);return n("Update article",o?`"${Ce(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",as(t.article_id)?`id ${as(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",it(t.name)?`"${Ce(it(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=it(t.file_path);return n("Upload image",o?Ce(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Bo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...i]=e.split("__"),l=i.join("__");if(r==="document360"){let k=wm(l,t);if(k)return k}let p=l.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:$c(t)}}let n=mm[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:Ce(o,xc)}:{title:e,sep:"",arg:$c(t)}}function ym(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 km(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(ym).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Ce(r,ls))]}if(t!==null&&typeof t=="object"){let n=Object.entries(t).filter(([,o])=>o!==null&&(typeof o=="string"||typeof o=="number"||typeof o=="boolean")).slice(0,6).map(([o,r])=>`${o}: ${Ce(String(r),Cc)}`);return n.length>0?[Ce(n.join(" \xB7 "),ls)]:null}return null}function bm(e){let t=it(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function vm(e,t,n){switch(e){case"d360_create_article":{let o=bm(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=it(t?.name);return[`\u2713 category created${o?` \xB7 "${o}"`:""}`]}case"d360_upload_drive_file":{let o=n.match(/https?:\/\/\S+/);return[`\u2713 uploaded${o?` \xB7 ${Ce(o[0],120)}`:""}`]}default:return null}}function Vo(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
307
|
+
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let l=vm(n.slice(18),o,r);if(l)return{lines:l,hidden:0}}let i=km(r)??r.split(`
|
|
308
|
+
`);return{lines:i.slice(0,t).map(l=>Ce(l,ls)),hidden:Math.max(0,i.length-t)}}function Go(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Yo(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 zo(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 Fm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Hm(e,t,n,o){if(Fm.test(e))try{let r=Tc(o),i=typeof t.project_id=="string"&&t.project_id||r.project.projectId,l=Yo(t,n),p=zo(n);e.endsWith("publish_article")&&p&&console.log(O(` \u2B95 Live: ${p}`)),l&&i&&console.log(O(` \u2B95 Preview: ${Go(r.connection.portalUrl,i,l,r.project.languageCode??"en")}`))}catch{}}async function Sc(e=process.cwd(),t="auto",n,o){let r=xm(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${O("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${O('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),qm(e,n),r.kind==="subscription"&&(r.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 i=!1,l=cs({cwd:e,profileName:n,allowProdWrites:i}),p={uuid:null,firstPrompt:null,titleFired:!1},m=$m({input:process.stdin,output:process.stdout}),k=[],g=null,T=!1;m.on("line",P=>{if(g){let N=g;g=null,N(P)}else k.push(P)}),m.on("close",()=>{if(T=!0,g){let P=g;g=null,P(null)}});function v(){return k.length>0?Promise.resolve(k.shift()):T?Promise.resolve(null):(process.stdout.write(O("> ")),new Promise(P=>{g=P}))}let _={cwd:e,version:o,profileName:n,allowProdWrites:()=>i,restartAgent:()=>{l.close(),l=cs({cwd:e,profileName:n,allowProdWrites:i}),p={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>p.uuid,setPendingName:P=>{p.pendingName=P},setModel:async P=>l.setModel(P),withPausedInput:async P=>{m.pause();try{return await P()}finally{m.resume()}}};try{for(;;){let P=await v();if(P===null)break;let N=P.trim();if(N){if(N.startsWith("/")){let S=mc(N);if(!S)continue;let M=hc[S.name];if(!M){console.log(C(`Unknown command: /${S.name}`)),console.log(f("Type /help for the list."));continue}let B=await M(S.args,_);if(B.kind==="exit")break;if(B.kind==="clear"){_.restartAgent();continue}if(B.kind==="allow-prod"){i=!0,_.restartAgent(),console.log(j("\u2713 Production writes authorized for this session.")),console.log("");continue}if(B.kind==="resume"){l.close(),l=cs({cwd:e,resume:B.uuid,profileName:n,allowProdWrites:i});let V=Cm(B.uuid);p={uuid:B.uuid,firstPrompt:V?.firstPrompt??null,titleFired:!0},Pc(B.uuid),console.log(j(`\u2713 Resumed "${B.name}"`)),console.log("");continue}if(B.kind==="forward-to-agent"){p.firstPrompt||(p.firstPrompt=B.display??B.prompt);let V=(B.display??"").trim().split(/\s+/),K=(V[0]==="/check"||V[0]==="/review")&&V.includes("--fix"),ne=V.slice(1).find(We=>!We.startsWith("--")),Ie=K?Um(e,ne):[];if(await ds(l,B.prompt,r,p,e),K)try{Mm(e,Ie,{reviewedCap:Wm})}catch{}}else Bm(e,n);continue}if(Im(N)){let S=_m(N);if(S){try{Om(e,{title:S,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}p.firstPrompt||(p.firstPrompt=N),await ds(l,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${S}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${S}" and the article path(s) you wrote.`,r,p,e);continue}}p.firstPrompt||(p.firstPrompt=N),await ds(l,N,r,p,e)}}}finally{l.close(),m.close()}}function qm(e,t){console.log(""),console.log(mn("document360-writer")),console.log(f(` cwd: ${e}`));let n=Dm(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Vm(e,t)),!jm(e))console.log(L(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{let o=!1;try{if(mo(e),!Ye(e))for(let r of go(e))console.log(L(` ${r}`))}catch{}try{let r=Am(e);r.persisted&&r.appType?console.log(f(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=Lm(e);for(let i of qo(r.applied))console.log(L(` ${i}`))}catch{}try{let r=An(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),i=r?jn(r):null;if(i?.kind==="recommend"&&i.rec.note){let l=i.rec.tone==="warn"?L:f;for(let p of i.rec.note.split(`
|
|
309
|
+
`))console.log(l(` ${p}`));i.rec.picker&&console.log(O(` Pick one: ${i.rec.picker.options.map(p=>p.cmd).join(" \xB7 ")}`))}}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Bm(e,t){try{let n=An(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?jn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(f(` Next: ${ts(o.rec.lead)}`))}catch{}}function Vm(e,t){try{let n=Tc(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=Nm(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let i={...Rc(r.idToken)??{},...Rc(r.accessToken)??{}},l=i.email??i.preferred_username??"signed in";return Em(r)&&!r.refreshToken?L(` 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 Gm(){console.error(""),console.error(`Sign in with your Claude subscription: run ${O("claude")} once, then retry.`),console.error(` (No Claude Code? ${O("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${O("https://console.anthropic.com/settings/keys")}`)}function Ym(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Tm({uuid:t,name:r??Pm(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function zm(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Sm(o,t).then(r=>{r&&Rm(n,r)}).catch(()=>{})}async function ds(e,t,n,o,r){let i=new Map;for await(let l of e.send(t))Km(l,o,r,n,i)}function Km(e,t,n,o,r){switch(e.type){case"session":t.uuid||Ym(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=Bo(e.name,e.input);i&&(process.stdout.write(`
|
|
310
|
+
|
|
311
|
+
`),console.log(`${j("\u25CF")} ${we(i.title)}${i.arg!==null?ae(`${i.sep}(${i.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=ze(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let l=p=>p===1?"":"s";console.log(ae(` \u23BF Added ${i.added} line${l(i.added)}, removed ${i.removed} line${l(i.removed)}`));for(let p of i.lines)console.log(p);i.hidden>0&&console.log(f(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let l=Vo(e.output,4,e.isError?void 0:i.name,i.input),p=e.isError?C:ae;l.lines.forEach((m,k)=>console.log(p((k===0?" \u23BF ":" ")+m))),l.hidden>0&&console.log(f(` \u2026 +${l.hidden} lines`)),e.isError||Hm(i.name,i.input,e.output,n);break}case"result":process.stdout.write(`
|
|
312
|
+
`),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&&(Pc(t.uuid),t.titleFired||zm(t,n));break;case"error":console.error(""),console.error(C(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Gm();break}}import{render as dw}from"ink";import{resolveAuth as uw}from"document360-engine";import{useCallback as Y,useEffect as Pe,useMemo as gs,useRef as Z,useState as F}from"react";import{Box as oe,Text as A,useApp as dg,useInput as ug,useStdout as pg}from"ink";import{existsSync as Jt,readFileSync as or,readdirSync as fg}from"node:fs";import{basename as Nn,isAbsolute as hg,join as ws}from"node:path";import{createSession as od,classifyClaudeAuth as xs,CLAUDE_CODE_SETUP_HINT as mg,loginPkce as gg,toStoredTokens as wg,saveTokens as yg,getAccessToken as kg,resolveActiveProfile as Re,resolveProjectId as bg,getArticle as vg,decodeJwtClaims as en,isExpired as st,loadTokens as $t,clearTokens as $g,clearProfileProject as xg,setTitle as Cg,slugify as Rg,touchSession as ys,upsertSession as Pg,generateTitle as rd,findByName as Tg,listSessions as Sg,renameSession as Dg,suggestNextAction as jg,readProjectConfig as te,writeProjectConfig as id,resolveAndPersistAppType as Ag,detectAppType as Eg,resolveModelSetting as Cs,loadProfileMap as sd,applyPull as ad,computeSyncStatus as ks,lintDocs as ld,compareRemoteSources as Ng,planPull as cd,establishBaselines as Ig,rebaselineServerMeta as _g,inventoryRepo as Og,knownEnvironments as Lg,resolveEnvironment as Mg,planPartitions as bs,partitionEvenly as Ug,screenshotPlaceholderIds as Wg,trackedArticlePaths as Fg,runPartitioned as rr,estimateBulkCost as dd,resolveModelForOperation as ir,readDocsPlan as Hg,checkForUpdate as qg,detectInstallKind as Bg,isSelfUpdatable as Vg,devHintsGuidePath as ud,toolFeedbackPath as pd,reconcileToolFeedback as Gg,reconcileUpgradeActions as Yg,stampArticles as vs,listArticleFiles as fd,CONTENT_CAP_VERSION as $s,ENGINE_VERSION as vd,DEFAULT_DOCS_DIR as $d,setProfileProject as zg,writeCrashLog as Kg,applyStructureOrder as hd,orderSyncLine as md,applyRelatedArticles as gd,relatedSyncLine as wd}from"document360-engine";tt();import{spawn as Dc}from"node:child_process";function Xm(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Qm(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?Dc([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Dc(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 i=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(i)}catch{o(!1)}})}async function us(e){for(let[t,n]of Xm())if(await Qm(t,n,e))return!0;return!1}var Jm=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function ps(e,t){if(t.closed)return e;let n=e.split(`
|
|
313
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let i=n[r];if(!t.cueSeen){Jm.test(i)&&(t.cueSeen=!0);continue}let l=/^(\s{0,3})[-*•]\s+(.*)$/.exec(i);l?(n[r]=`${l[1]}${++t.num}. ${l[2]}`,o=!0):o&&i.trim()!==""&&/^\S/.test(i)&&(t.closed=!0)}return n.join(`
|
|
314
|
+
`)}import{existsSync as Zm,mkdirSync as eg,readFileSync as tg,writeFileSync as ng}from"node:fs";import{join as jc}from"node:path";import{writerDir as og}from"document360-engine";function Ac(e){return jc(og(e),".sessions")}function Ec(e,t){return jc(Ac(e),`${t}.json`)}function Nc(e,t,n){try{eg(Ac(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");ng(Ec(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function fs(e,t){try{let n=Ec(e,t);if(!Zm(n))return[];let o=JSON.parse(tg(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var rg=e=>`\x1B]0;${e}\x07`,ig=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Ic(e){process.stdout.isTTY&&process.stdout.write(e)}function Qt(e){Ic(rg(e))}function Ko(e){Ic(ig(e))}var Xo=["\xB7 "," \xB7"],Qo="\u{1F7E3}";No();ko();var Jo=[{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:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{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> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; 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:"roadmap",usage:"/roadmap [done <step>]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done <step>` marks one you finished yourself",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:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (publish), take portal (pull), or skip \u2014 for each. Bare: walk them all",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:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",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:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],_c={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/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 Oc(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(_c[n])return _c[n];let o=Jo.find(r=>r.name===t);return o?o.desc:""}function Lc(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Jo.filter(n=>n.name.startsWith(t))}function Mc(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as Uc,Text as de}from"ink";import{jsx as ue,jsxs as Zo}from"react/jsx-runtime";function sg({row:e}){switch(e.t){case"head":return ue(de,{color:q,bold:!0,children:e.s});case"text":return ue(de,{children:e.s});case"dim":return ue(de,{dimColor:!0,children:e.s});case"sub":return ue(de,{bold:!0,dimColor:!0,children:e.s});case"good":return ue(de,{color:"green",children:e.s});case"step":return Zo(de,{children:[ue(de,{color:q,children:`${e.n}. `}),e.s]});case"cmd":return Zo(de,{children:[" ",ue(de,{color:q,children:e.name.padEnd(20)}),ue(de,{dimColor:!0,children:e.s})]});case"gap":return ue(de,{children:" "})}}function Wc({tab:e,width:t,version:n,engineVersion:o}){let r=je[e]??je[0],i=6+je.reduce((p,m)=>p+m.label.length+4,0),l="\u2500".repeat(Math.min(i,Math.max(t-1,20)));return Zo(Uc,{flexDirection:"column",paddingX:1,children:[Zo(de,{children:[ue(de,{color:q,bold:!0,children:"Help "}),je.map((p,m)=>m===e?ue(de,{color:"white",backgroundColor:q,bold:!0,children:` ${p.label} `},p.key):ue(de,{dimColor:!0,children:` ${p.label} `},p.key))]}),ue(de,{color:q,children:l}),ue(Uc,{flexDirection:"column",marginTop:1,children:r.rows.map((p,m)=>ue(sg,{row:p},m))}),ue(de,{dimColor:!0,children:`
|
|
315
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var ag=/^(?:\d+[.)]|[-*•])\s+/;function Fc(e,t,n=4){let o=new Set(t.map(i=>i.toLowerCase())),r=[];for(let i of e.split(`
|
|
316
|
+
`)){let l=i.trim().replace(ag,""),p=l.match(/^`([^`]+)`$/);p&&(l=p[1].trim());let m=l.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!m||!o.has(m[1].toLowerCase()))continue;let k=`/${m[1].toLowerCase()}${m[2]?` ${m[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}W();function En(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Ke(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Hc(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var lg=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function qc(e,t,n){if(!lg.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(i=>{let l=i.replace(/\\/g,"/");return r===l||r.endsWith(`/${l}`)})??null}function hs(e){return e.replace(/^[\w.-]+\//,"")}var er=16,Bc={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function vt(e){return typeof e=="string"?e:e.cmd}function Vc(e){return typeof e=="string"?void 0:e.desc}function ms(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Gc(e,t){let n=ms(t);return e.some(r=>vt(r).trim()===t.trim()||!!n&&ms(vt(r))===n)?e.filter(r=>vt(r).trim()!==t.trim()&&!(n&&ms(vt(r))===n)):[]}import{isDirectiveMention as Xg,stripDirectiveMention as Qg,appendDirective as Jg}from"document360-engine";var cg=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Yc(e){return e.replace(/\r\n?/g,`
|
|
317
|
+
`)}function zc(e){return e.includes(`
|
|
318
|
+
`)||e.length>200}function Kc(e,t){let n=t.split(`
|
|
319
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Xc(e,t){return e.replace(cg,n=>t.get(n)??n)}function Qc(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function tr(e,t){let n=Math.max(1,t),o=[],r=0;for(let i of e.split(`
|
|
320
|
+
`)){if(i.length===0)o.push({start:r,end:r});else for(let l=0;l<i.length;l+=n)o.push({start:r+l,end:r+Math.min(l+n,i.length)});r+=i.length+1}return o.length>0?o:[{start:0,end:0}]}function nr(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Jc(e,t,n){let o=nr(e,t),r=o+n;if(r<0||r>=e.length)return t;let i=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+i,e[r].end)}function Zc(e,t,n){let o=e[nr(e,t)];return n==="start"?o.start:o.end}function ed(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
321
321
|
`),i=0;for(let l=r.length-1;l>=0;l--){let p=r[l];if(i+=Math.max(1,Math.ceil(p.length/o)),i>=t){let m=i-t;return{text:[m>0?p.slice(m*o):p,...r.slice(l+1)].join(`
|
|
322
|
-
`),truncated:l>0||m>0}}}return{text:e,truncated:!1}}function
|
|
323
|
-
`)){let i=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&i<e.length&&(n=i+1),o=i+1}return n}import{Fragment as
|
|
322
|
+
`),truncated:l>0||m>0}}}return{text:e,truncated:!1}}function td(e,t){if(t||e.length===0||/\s$/.test(e))return{head:e,keep:""};let n=e.search(/\s\S*$/);return n<0?{head:"",keep:e}:{head:e.slice(0,n),keep:e.slice(n)}}function nd(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
323
|
+
`)){let i=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&i<e.length&&(n=i+1),o=i+1}return n}import{Fragment as sr,jsx as E,jsxs as z}from"react/jsx-runtime";var Zg={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},yd=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
324
324
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
325
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
326
|
-
${
|
|
327
|
-
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!
|
|
328
|
-
${
|
|
329
|
-
`)}),
|
|
330
|
-
`)})}catch{}let y=s("ready-decision",()=>
|
|
325
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function ew(e,t,n,o){let r=xs(n),i=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=Cs(e),p=te(e),m=(p?.docsDir??$d).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${m}/ + config`,g={version:t,engineVersion:vd,claude:i,model:l.model,modelSource:Zg[l.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:k};if(p===null)return g;try{let T=Re(e,o);g.profile=T.name,g.apiUrl=T.connection.apiUrl,g.prod=T.production,g.project=T.project.projectName??T.project.projectId??"(chosen at login)";let v=$t(T.name);if(v){let _={...en(v.idToken)??{},...en(v.accessToken)??{}},P=_.email??_.preferred_username??"signed in";st(v)?v.refreshToken&&(g.who=P,g.loggedOut=!1,g.sessionHint="session expired \u2014 refreshing\u2026"):(g.who=P,g.loggedOut=!1,g.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return g}function tw(e,t){try{let n=Re(e,t),o=$t(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...en(o.idToken)??{},...en(o.accessToken)??{}},i=r.email??r.preferred_username??"signed in";return st(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${i} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var kd=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],tn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],nw="Ask me to write or update an article\u2026";function Zt({ch:e,dim:t}){let[n,o]=F(!0);return Pe(()=>{let r=setInterval(()=>o(i=>!i),530);return()=>clearInterval(r)},[]),E(A,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var ow=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function bd(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var rw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function iw({startTime:e,chars:t}){let[n,o]=F(0);Pe(()=>{let m=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(m)},[]);let r=tn[n%tn.length],i=kd[Math.floor(n/16)%kd.length],l=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return z(oe,{children:[E(A,{color:q,children:` ${r} ${i}\u2026 `}),E(A,{color:"gray",children:`(${bn(l)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function sw({text:e}){let[t,n]=F(0);return Pe(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),E(oe,{paddingX:1,children:E(A,{color:q,children:`${tn[t%tn.length]} ${e}`})})}var aw=12e4;function lw({p:e}){let[t,n]=F(0);Pe(()=>{let S=setInterval(()=>n(M=>M+1),150);return()=>clearInterval(S)},[]);let o=tn[t%tn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),i=Math.floor((Date.now()-e.lastAt)/1e3),l=Math.round(e.chars/4),p=Date.now()-e.lastAt>=aw,m=e.verb??"Converting",k=e.unit??"article",g=e.rows.reduce((S,M)=>S+M.items,0),T=m.toLowerCase(),v=e.rows,_=0;if(v.length>er){let S=v.findIndex(B=>B.status==="active"||B.status==="pending"),M=Math.max(0,Math.min(S-2,v.length-er));_=v.slice(0,M).filter(B=>B.status==="done").length,v=v.slice(M,M+er)}let P=Math.min(40,Math.max(...v.map(S=>hs(S.label).length),0)),N=S=>S==="failed"?"red":S==="active"?q:void 0;return z(oe,{flexDirection:"column",children:[z(oe,{children:[E(A,{color:q,children:` ${o} ${m} ${g} ${k}${g===1?"":"s"} `}),E(A,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${l} tokens \xB7 ${bn(r)} \xB7 esc to stop`})]}),_>0&&E(A,{dimColor:!0,children:` \u2714 +${_} done`}),v.map(S=>z(A,{color:N(S.status),dimColor:S.status==="done"||S.status==="pending",children:[` ${Bc[S.status]} ${hs(S.label).padEnd(P)}`,S.status==="active"&&S.itemsDone!==void 0?` (${S.itemsDone}/${S.items} ${k}${S.items===1?"":"s"})`:S.status!=="pending"?` (${S.items} ${k}${S.items===1?"":"s"})`:"",S.status==="active"?` \u2190 ${T}\u2026`:""]},S.label)),p&&E(A,{color:"yellow",children:` \u26A0 no activity for ${bn(i)} \u2014 press esc to stop if it's wedged`})]})}var cw=10800*1e3;function xd({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=dg(),[i,l]=F(n),[p,m]=F(null),[k,g]=F({text:"",pos:0}),T=k.text,v=Y(c=>{g(a=>{let s=typeof c=="function"?c(a.text):c;return{text:s,pos:s.length}})},[]),_=Y(c=>{g(a=>({text:a.text.slice(0,a.pos)+c+a.text.slice(a.pos),pos:a.pos+c.length}))},[]),P=Y(()=>{g(c=>{if(c.pos===0)return c;let a=c.text.slice(0,c.pos),s=Qc(a)??a.slice(0,-1);return{text:s+c.text.slice(c.pos),pos:s.length}})},[]),[N,S]=F(!1),[M,B]=F(!1),[V,K]=F(0),[ne,Ie]=F(null),[We,Te]=F(null),[ke,Fe]=F([]),In=Z(!1),lr=Z(!1),[cr,Ss]=F(!1),_n=Z(0),[jd,On]=F(!1),[Ad,Ln]=F(!1),[dr,Ds]=F(null),[Ed,xt]=F(0),at=Z(0),[nn,Ct]=F(0),[Rt,Mn]=F(null),js=Z(new Map),Nd=Z(0),Pt=Z([]),Se=Z(null);Se.current===null&&(Se.current=od({cwd:e,profileName:i,allowProdWrites:!1}));let He=Z({uuid:null,firstPrompt:null,titleFired:!1}),Un=Z(new Map),Tt=Z(!1),ur=Z([]),le=Z([]),St=Z([]),Wn=Z(null),[As,lt]=F(null),pr=Z(null),[ct,dt]=F(null),[qe,Dt]=F(null),[Be,jt]=F(null),[he,At]=F(null),[be,ut]=F(null),[Xe,Et]=F(null),[Ve,pt]=F(null),[Es,on]=F(null),[ve,ft]=F(null),[me,Nt]=F(null),[Ns,fr]=F([]),ht=Z([]),rn=Z(!1),De=Z(null),[Fn,re]=F(null),[Is,_s]=F(null),Hn=Z(!1),qn=Z(null),sn=Z(null),[$e,mt]=F(null),[Bn,an]=F(null),hr=!!(Be||he||be||Xe||Ve||ve||me||$e||Bn),[Os,It]=F(0),[Ls,_t]=F(0),[Id,Ms]=F(0),mr=gs(()=>{try{let c=Cs(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,Id]),{stdout:_e}=pg(),[,_d]=F(0),Us=Z(`${_e.columns??80}x${_e.rows??24}`),Qe=Y(()=>Math.max(20,(_e.columns??80)-1),[_e]),d=Y(c=>{Pt.current.push(c),console.log(Vr(c,Qe()))},[Qe]),ge=Y((c,a)=>{_n.current++,Ie(c),Te(a??null)},[]),Oe=Y(()=>{_n.current++,Ie(null),Te(null)},[]),Q=Y(c=>ge(c,Fo({kind:"cmd",cmd:c,reason:""})),[ge]),Ws=Y((c,a)=>{!a?.silent&&c.note&&d({kind:"note",tone:c.tone,text:c.note}),c.picker&&(Fe(c.picker.options.map(s=>({cmd:s.cmd,desc:s.desc}))),on(c.picker.title)),c.lead&&ge(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,Fo(c.lead))},[d,ge]),Ot=Y((c,a,s="info")=>{c&&d({kind:"note",tone:s,text:c}),a&&ge(a.kind==="cmd"?a.cmd:a.text,Fo(a))},[d,ge]),[ln,gr]=F(null),[Od,Fs]=F(!1),Lt=Y(c=>{gr(c),Fs(!1),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]),wr=Z(!1),yr=Y(async()=>{try{if(wr.current||!Vg(Bg())||te(e)?.mode==="engineer")return;let c=await qg({pkg:bt,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;wr.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${bt} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),Ln(!0),(await Lo().finally(()=>Ln(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),Q("/exit"),Ds(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${Oo}`})}catch{}},[e,o,d,Q]),Vn=Y(c=>{let a=Ee(e,i);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),sn.current=c,Q("/login"),!1)},[e,i,d,Q]),[Gn,kr]=F(null),cn=Z(!0),Yn=Z(0),dn=Z(0);Pe(()=>{let c=setInterval(()=>{if(cn.current){Yn.current=0,dn.current=0;return}if(!N)try{if(!Jt(ud(e)))return;if(Ae(e).status==="current"){cn.current=!0,Yn.current=0,dn.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."}),gr(null),ge("write the docs for this repo");return}Yn.current+=1;let a=Yn.current;if((a===4||a%15===0)&&dn.current<3){dn.current+=1;let s=dn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Ye(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${s}`:`\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.${s}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,N,d]),Pe(()=>{let c=As??Nn(e);if(!N){Ko(0),Qt(`${Qo} ${c}`);return}Ko(3);let a=0;Qt(`${Xo[0]} ${c}`);let s=setInterval(()=>{a=(a+1)%Xo.length,Qt(`${Xo[a]} ${c}`)},400);return()=>clearInterval(s)},[N,e,As]),Pe(()=>()=>Ko(0),[]);let un=Y(c=>{let a=An(e,i,{claudeMissing:xs(t).state==="missing",allowAutoAudit:c,genreUnknown:lr.current});return a?jn(a):{kind:"idle"}},[e,i,t]);Pe(()=>{let c=performance.now(),a=[],s=(w,x)=>{let $=performance.now();try{return x()}finally{let G=Math.round(performance.now()-$);G>=80&&a.push(`${w}: ${G}ms`)}};d({kind:"banner",info:s("banner",()=>ew(e,o,t,i))});let h=xs(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.
|
|
326
|
+
${mg}
|
|
327
|
+
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!te(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:
|
|
328
|
+
${yd}`}),Q(h?"/doctor":"/init");return}h&&Q("/doctor");try{let w=Re(e,i),x=$t(w.name);x&&st(x)&&x.refreshToken?kg({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),K($=>$+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Q("/login")}):(!x||st(x))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 sign in with /login.`}),Q("/login"))}catch{}try{let w=te(e),x=Re(e,i),$=$t(x.name);w&&$&&!st($)&&is(e,w.authoritativeSourceFiles)&&!ss(e,i)&&(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."}),Q("/scope"))}catch{}try{let w=s("resolve-genre",()=>Ag(e));w.persisted&&w.appType?d({kind:"note",tone:"ok",text:`\u2713 Detected a ${w.appType} app \u2014 enabled the ${w.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):w.source==="unknown"&&te(e)&&(lr.current=!0)}catch{}let u=Ae(e);try{if(s("reconcile-devhints",()=>mo(e)),u.status!=="current"&&!Ye(e)){let w=go(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
|
|
329
|
+
`)}),Lt(wt()),cn.current=!1)}}catch{}try{let w=s("reconcile-feedback",()=>Gg(e));w.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}try{let w=s("upgrade-actions",()=>Yg(e));w.applied.length>0&&d({kind:"note",tone:"warn",text:qo(w.applied).join(`
|
|
330
|
+
`)})}catch{}let y=s("ready-decision",()=>un(!0));y.kind==="autoAudit"?(d({kind:"note",tone:"info",text:y.note}),$n().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&ie(w.prompt,{display:w.display,quietUser:!0})})):y.kind==="recommend"&&Ws(y.rec);let b=Math.round(performance.now()-c);b>=800&&Kg({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${b}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${a.length?a.join(`
|
|
331
331
|
`):"no single phase \u226580ms"}
|
|
332
|
-
cwd: ${e}`}),
|
|
333
|
-
`)});let H=
|
|
334
|
-
`)}),
|
|
335
|
-
`)}),
|
|
336
|
-
${
|
|
337
|
-
`)});return}case"mcp":await
|
|
332
|
+
cwd: ${e}`}),yr()},[]),Pe(()=>{let c=setInterval(()=>{yr()},cw);return()=>clearInterval(c)},[yr]),Pe(()=>{if(N||cr||In.current||ne!==null||ke.length>0||T!==""||ln!==null||le.current.length>0||Wn.current||hr)return;let c=un(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&Ws(c.rec,{silent:!0})},[N,ne,ke,T,ln,hr,V,un,cr]),Pe(()=>{let c=null,a=null,s=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let h=`${_e.columns??80}x${_e.rows??24}`;h!==Us.current&&(Us.current=h,_d(u=>u+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+qa(Pt.current,Qe())+"\x1B[?2026l")},80))},400)};return _e.on("resize",s),()=>{c&&clearTimeout(c),a&&clearTimeout(a),_e.off("resize",s)}},[_e,Qe]);let Le=Math.max(20,(_e.columns??80)-1),Hs=gs(()=>tw(e,i),[e,i,V]),br=(()=>{if(Ad)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(dr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${dr?` v${dr}`:""}\u2026`,isSetup:!0};if(Gn)return{text:"\u{1F6E0} press c to copy the d360-writer feedback \u2014 then send it to the team (Teams / Slack / email)\u2026",isSetup:!0};if(ln)return Od?{text:"\u2713 copied \u2014 paste it into your coding agent \xB7 I\u2019ll pick up automatically when it finishes\u2026",isSetup:!0}:{text:"\u2328 press c to copy the prompt above \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(le.current.length>0)return le.current[0].mode==="conflict"?{text:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let c=te(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let a=ws(e,(c.docsDir??$d).replace(/\/+$/,"")),s=(()=>{try{return Jt(a)&&fg(a).length>0}catch{return!1}})();try{let h=Re(e,i),u=$t(h.name);if(!(!!u&&!(st(u)&&!u.refreshToken)))return{text:`Sign in with /login (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&&!s)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return s?{text:nw,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),pn=Lc(T),qs=pn.length>0&&!N,vr=p!==null?ed(p,8,Le):null,zn=ve?ve.paths.filter(c=>!ve.query||c.toLowerCase().includes(ve.query.toLowerCase())).slice(0,8):[],Kn=$e?$e.sessions.filter(c=>{let a=$e.query.toLowerCase();return!a||c.name.toLowerCase().includes(a)||c.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],xe=Y((c,a)=>{Se.current?.close(),Se.current=od({cwd:e,resume:c,profileName:a??i,allowProdWrites:Tt.current}),c||(He.current={uuid:null,firstPrompt:null,titleFired:!1},lt(null)),It(0),_t(0)},[e,i]),Bs=Y((c,a,s)=>{if(ow.test(c))try{let h=Re(e,i),u=typeof a.project_id=="string"&&a.project_id||h.project.projectId,y=Yo(a,s),b=[],w=zo(s);c.endsWith("publish_article")&&w&&b.push(`Live: ${w}`),y&&u&&b.push(`Preview: ${Go(h.connection.portalUrl,u,y,h.project.languageCode??"en")}`),b.length>0&&d({kind:"link",lines:b})}catch{}},[e,i,d]),ie=Y(async(c,a)=>{On(!0),In.current=!1,Oe(),Fe([]),on(null),gr(null);let s=_n.current;a?.quietUser||d({kind:"user",text:a?.echoDisplay&&a.display?a.display:c});let h=He.current;h.firstPrompt||(h.firstPrompt=a?.display??c),at.current=Date.now(),xt(0),S(!0),Un.current.clear();let u="",y=!1,b=!1,w="",x={num:0,closed:!1,cueSeen:!1},$=null,G=()=>{$||($=setTimeout(()=>{$=null,m(w.length>0?w:null)},60))},H=()=>{$&&clearTimeout($),$=null,m(null)},I=(R=!1)=>{let{head:D,keep:U}=td(w,R);D.trim()&&d({kind:"assistant",text:ps(D.trimEnd(),x)}),w=U,H()};try{for await(let R of Se.current.send(c))if(R.type==="session"){if(!h.uuid){h.uuid=R.sessionId;let D=new Date().toISOString(),U=pr.current,ee=U??Rg(h.firstPrompt??"session");Pg({uuid:R.sessionId,name:ee,renamed:!!U,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:D,updatedAt:D}),lt(ee),pr.current=null}}else if(R.type==="text"){w+=R.delta,u+=R.delta;let D=nd(w);if(D>0){let U=w.slice(0,D).trimEnd();U&&d({kind:"assistant",text:ps(U,x)}),w=w.slice(D)}G(),xt(U=>U+R.delta.length)}else if(R.type==="tool"){y=!0;let D=Bo(R.name,R.input);D&&(I(),d({kind:"tool",title:D.title,sep:D.sep,arg:D.arg}),Un.current.set(R.id,{name:R.name,input:R.input}))}else if(R.type==="article_diff"){let D=ze(R.oldContent,R.newContent,Qe());D&&(I(),d({kind:"diff",added:D.added,removed:D.removed,lines:D.lines,hidden:D.hidden}))}else if(R.type==="tool_result"){R.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(R.output)&&(Hn.current=!0);let D=Un.current.get(R.id);if(D){Un.current.delete(R.id),I();let U=Vo(R.output,4,R.isError?void 0:D.name,D.input);d({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:R.isError}),R.isError||Bs(D.name,D.input,R.output)}}else if(R.type==="result"){if(I(!0),It(D=>D+R.outputTokens),_t(D=>D+R.costUsd),d({kind:"done",seconds:Math.round((Date.now()-at.current)/1e3),tokens:R.outputTokens,costUsd:R.costUsd,ok:R.ok}),!b&&!y&&!u.trim()&&!rn.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)."}),R.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let D=pd(e);if(Jt(D)){let U=or(D,"utf8").trim();U&&(kr(U),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(R.ok&&x.cueSeen)Ss(!0),Fe([]);else{let D=R.ok?Fc(u,Jo.map(U=>U.name)):[];if(D.length>0)Q(D[0]);else if(R.ok&&u.trim()){let U=un(!1);U.kind==="recommend"&&(U.rec.lead||U.rec.picker)||jg(c,u,e).then(ee=>{ee&&_n.current===s&&ge(ee)}).catch(()=>{})}}if(h.uuid&&(ys(h.uuid),!h.titleFired)){h.titleFired=!0;let D=h.uuid,U=h.firstPrompt;U&&rd(U,e).then(ee=>{ee&&(Cg(D,ee),lt(ee))}).catch(()=>{})}}else R.type==="error"&&(I(!0),b=!0,R.kind==="auth"&&(Hn.current=!0),d({kind:"note",text:`agent error: ${R.message}`,tone:"error"}))}finally{S(!1),H(),K(R=>R+1),He.current.uuid&&Nc(e,He.current.uuid,Pt.current),Hn.current&&(Hn.current=!1,qn.current=a?.display??c,ge("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")),rn.current&&(rn.current=!1,ht.current.length>0&&(d({kind:"note",tone:"info",text:`(${ht.current.length} queued message(s) discarded)`}),ht.current=[],fr([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Bs,Qe,ge,Q,Oe,un]),Mt=Y(async c=>{let a=ir(e,"standard");at.current=Date.now(),xt(0),S(!0);let s=new AbortController;De.current=s;let h=async(u,y)=>{let b=bs(u);re({verb:"Publishing",total:b.length,done:0,active:[],rows:En(b),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:y?`Resolving cross-links in ${u.length} article${u.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${u.length} article${u.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${vn} agents at once) on ${a.model}\u2026 (esc to stop)`});let w=!1;for await(let x of rr({cwd:e,partitions:b,promptFor:$=>Ro($.paths),concurrency:vn,profileName:i,allowProdWrites:Tt.current,model:a.model,signal:s.signal}))if(x.type==="partition_status")x.status==="running"?re($=>$&&{...$,active:[...$.active,x.label],rows:Ke($.rows,x.label,"active"),lastAt:Date.now()}):re($=>$&&{...$,active:$.active.filter(G=>G!==x.label),done:$.done+1,rows:Ke($.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_event")re($=>{if(!$)return $;let G={...$,lastAt:Date.now()};return x.event.type==="tool"?G.tools=$.tools+1:x.event.type==="text"&&(G.chars=$.chars+x.event.delta.length),G});else if(x.type==="run_done"){w=x.aborted,_t(I=>I+x.totalCostUsd),It(I=>I+x.results.reduce((R,D)=>R+D.outputTokens,0));let $=x.aborted?"Stopped. ":"",G=t.kind==="api"?"api":"subscription";d({kind:"note",tone:x.aborted?"warn":x.ok?"ok":"warn",text:$+Kr(x.results,b,G).join(`
|
|
333
|
+
`)});let H=zr(e,i);if(H&&d({kind:"note",tone:"info",text:H}),!x.aborted){try{let I=await hd({cwd:e,profileName:i}),R=md(I);R?d({kind:"note",tone:"info",text:R}):I.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${I.skipped}`})}catch(I){d({kind:"note",tone:"warn",text:`Order sync failed: ${I.message}`})}try{let I=wd(await gd({cwd:e,profileName:i}));I&&d({kind:"note",tone:"info",text:I})}catch(I){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${I.message}`})}}}return w};try{if(!await h(c,!1)){let y=await Xr(e,i,c);y.length>0&&await h(y,!0)}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{De.current=null,re(null),S(!1),K(u=>u+1)}},[e,i,d,t]),$r=Y(async c=>{await ie(Gr(c),{display:`/publish ${c}`,quietUser:!0});try{let a=await Po(e,i,c.replace(/\\/g,"/"));a.length>0&&(on(`Related articles not yet published (${a.length}):`),Fe([`/publish --related ${c}`,...a.map(s=>`/publish ${s}`)]))}catch{}},[e,i,ie]),xr=Y(c=>{let a=$t(c);if(!a||st(a)&&!a.refreshToken)return null;let s={...en(a.idToken)??{},...en(a.accessToken)??{}};return s.email??s.preferred_username??"signed in"},[]),Cr=Y((c,a)=>{if(a){let s=te(e);s&&(s.defaultProfile=c,id(s,e))}l(c),xe(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),xr(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),Q("/login")),K(s=>s+1)},[e,d,xe,xr,Q]),Xn=Y((c,a,s)=>{oo(e,c,a,s.id,s.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${s.name??s.id}" (agent restarted).`}),xe(),sd(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:Yt(Gt(e)).join(`
|
|
334
|
+
`)}),Lt(wt()),cn.current=Ae(e).status==="current"||Ye(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,xe,Lt]),Qn=Y(async c=>{let a;try{a=await gn(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Q("/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 s=a.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),h=s.length>0?s:a.workspaces;if(h.length===1){let u=h[0],y=a.workspaces.length-h.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${y>0?" (skipped the API-documentation workspace)":""}.`}),Xn(a.profile,a.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),Q("/workspace")},[e,d,Xn,Q]),Jn=Y((c,a)=>{ro(e,c,a.id,a.name),d({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),xe(),Qn(c)},[e,d,xe,Qn]),Vs=Y(async c=>{let a;try{a=Re(e,c)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:s}=await et(e,a.name),h=s.find(u=>u.id===a.project.projectId);h?.name&&zg(e,a.name,{projectName:h.name})}catch{}await Qn(a.name);return}try{let{projects:s}=await et(e,a.name);if(s.length===1){let h=s[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${h.name??h.id}".`}),Jn(a.name,{id:h.id,name:h.name});return}if(s.length>1){let h=s.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?"}),ut({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."}),Q("/project")}},[e,d,Qn,Jn,Q]),Ut=Y(()=>{let c=le.current[0];if(!c)return;Oe();let{plan:a,mode:s}=c;d({kind:"note",tone:"info",text:`\u25CF ${a.title} (${a.path})`});for(let u of a.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${u}`});a.overwritesLocalChanges&&s==="pull"&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let h=ze(a.oldContent,a.newContent,Qe());d(h?{kind:"diff",added:h.added,removed:h.removed,lines:h.lines,hidden:h.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),s==="conflict"?(d({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),d({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):d({kind:"note",tone:"info",text:`Write ${a.path}? (y/n \u2014 anything else cancels)`})},[d,Qe,Oe]),Rr=Y(()=>{if(le.current.length>0){Ut();return}let c=St.current;St.current=[],c.length>0?(d({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),Mt(c)):Q("/pull")},[Ut,d,Mt,Q]),Gs=Y(c=>{if(le.current.length===0)return!1;let a=c.trim().toLowerCase(),s=le.current[0];if(s.mode==="conflict"){if(a==="l"||a==="local")le.current.shift(),St.current.push(s.plan.path),d({kind:"note",tone:"info",text:`Keeping local ${s.plan.path} \u2014 will publish over the portal.`});else if(a==="p"||a==="portal"){le.current.shift();try{ad({cwd:e,profileName:i},s.plan),d({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${s.plan.path} (local overwritten, sync base advanced).`})}catch(h){d({kind:"note",tone:"error",text:`Take-portal failed: ${h.message}`})}}else if(a==="s"||a==="skip"||a==="n")le.current.shift(),d({kind:"note",tone:"info",text:`Skipped ${s.plan.path} \u2014 still a conflict.`});else{let h=le.current.length;return le.current=[],St.current=[],d({kind:"note",tone:"info",text:`Resolve cancelled (${h} conflict${h===1?"":"s"} left untouched).`}),!0}return Rr(),!0}if(a==="y"||a==="yes"){let h=le.current.shift().plan;try{ad({cwd:e,profileName:i},h),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${h.path} (sync base advanced).`})}catch(u){d({kind:"note",tone:"error",text:`Pull failed: ${u.message}`})}}else if(a==="n"||a==="no"){let h=le.current.shift().plan;d({kind:"note",tone:"info",text:`Skipped ${h.path}.`})}else{let h=le.current.length;return le.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${h} article(s) left untouched).`}),!0}return Rr(),!0},[e,i,Rr,d]),Pr=Y(async c=>{d({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let a=await ks({cwd:e,profileName:i}),s=c?.replace(/\\/g,"/"),h=a.entries.filter(y=>y.status==="conflict"&&y.path).map(y=>y.path);if(s){if(!h.includes(s)){d({kind:"note",tone:"ok",text:`${s} isn\u2019t in conflict \u2014 nothing to resolve.`});return}h=[s]}if(h.length===0){d({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let u=[];for(let y of h)try{u.push({plan:await cd({cwd:e,profileName:i,relPath:y}),mode:"conflict"})}catch(b){d({kind:"note",tone:"error",text:`Could not load ${y} from Document360: ${b.message}`})}if(u.length===0)return;d({kind:"note",tone:"info",text:`Resolving ${u.length} conflict${u.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),le.current=u,St.current=[],Ut()}catch(a){d({kind:"note",tone:"error",text:`Could not compute sync status: ${a.message}`})}},[e,i,d,Ut]),Ys=Y(c=>{let a=Wn.current;if(!a)return!1;if(Wn.current=null,Oe(),c.trim()!==a.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:s,failed:h}=Gi(e,a.targets);d({kind:"note",tone:h.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${s.length} item${s.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:wo().join(`
|
|
335
|
+
`)}),Lt(_r())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
336
|
+
${yd}`}),Q("/init"),On(!1),!0},[e,d,Lt,Oe,Q]),fn=Y(async c=>{let a=c.slice(1).trim().split(/\s+/),s=(a[0]??"").toLowerCase(),h=a.slice(1);if(On(!0),jo(h)&&["write","check","review","reorder"].includes(s)){let u=xn(e,i);if(u.length===0){d({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let y=b=>s==="write"?`/write ${hl(h,b).join(" ")}`.trim():`/${s} ${[b,...h.filter(w=>w!=="--scope")].join(" ")}`.trim();if(u.length===1){fn(y(u[0].token));return}pt({cursor:0,rows:u,run:b=>{fn(y(b))}});return}if(rt(s,h)){let u=xn(e,i);if(u.length>1){let y=h.filter($=>$.startsWith("--")).join(" "),b=$=>`/${s}${$?` ${s==="write"?`--scope ${$}`:$}`:""}${y?` ${y}`:""} ${$?"":"--all"}`.replace(/\s+/g," ").trim(),w=u.reduce(($,G)=>$+G.count,0),x={token:"",label:s==="review"?`Everything \u2014 all ${w} articles + structure (IA) review`:s==="reorder"?`Everything \u2014 reorder all ${u.length} categories`:`Everything \u2014 rewrite all ${w} planned articles`,count:w};pt({cursor:0,rows:[x,...u],run:$=>{fn(b($))}});return}}switch(s){case"help":an({tab:0});return;case"exit":case"quit":Se.current?.close(),r();return;case"clear":xe(),Pt.current=[],On(!1),Oe(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=Re(e,i)}catch(y){d({kind:"note",tone:"error",text:y.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),B(!0);try{let y=await gg(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},w=>d({kind:"note",tone:"info",text:w})),b=wg(u.name,y);if(yg(b),await jr(b,u.name,w=>d({kind:"note",tone:"info",text:w})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${ao(b)}`}),await Vs(i),sn.current){let w=sn.current;sn.current=null;let x=Ee(e,i);x.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${w}.`}),Q(w)):(d({kind:"note",tone:"warn",text:`${x.reason} (then ${w}.)`}),Q("/login"),sn.current=w)}else qn.current&&(ge(qn.current,"\u21E5 tab to re-send your last prompt\u2026"),qn.current=null)}catch(y){d({kind:"note",tone:"error",text:`Login failed: ${y.message}`})}finally{B(!1),K(y=>y+1)}return}case"allow-prod":{let u=!1;try{u=Re(e,i).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Tt.current=!0,xe(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Si(h.join(" ")),y=He.current.uuid;if(!y){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}pr.current=u,lt(u),Qt(`${Qo} ${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 b=He.current.firstPrompt??"";rd(b,e).then(w=>{w?(ge(`/rename ${w}`),d({kind:"note",tone:"info",text:`Suggestion: "${w}" \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}Dg(y,u),lt(u),Qt(`${Qo} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=h[0],y=te(e);if(!u){let b=Object.entries(y?.profiles??{});if(b.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let w=b.map(([G,H])=>({name:G,env:H.connection?.environment??"custom",prod:H.production===!0,who:xr(G)})),x=i??y?.defaultProfile,$=Math.max(0,w.findIndex(G=>G.name===x));Dt({cursor:$,current:$,rows:w});return}if(u==="add"){let b=Di(e,h[1],h[2]);if(b){d({kind:"note",tone:"error",text:b});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),Cr(h[1],!1);return}if(!y?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}Cr(u,!0);return}case"doctor":await Rn(h,{cwd:e,version:o});return;case"genre":{await Wo(h,{cwd:e});try{lr.current=!(te(e)?.appType??Eg(e))}catch{}K(u=>u+1);return}case"roadmap":{if(h[0]?.toLowerCase()==="done"){let u=Zi(e,h.slice(1).join(" ").trim());d({kind:"note",tone:u.ok?"ok":"warn",text:u.line}),K(y=>y+1);return}d({kind:"note",tone:"info",text:Ji(e).join(`
|
|
337
|
+
`)});return}case"mcp":await bo(h);return;case"init":{if(te(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=Lg().map(y=>({name:y,apiUrl:Mg(y).apiUrl}));jt({cursor:0,rows:u});return}case"resume":{let u=h.join(" ").trim(),y=Sg(e).filter(x=>x.uuid!==He.current.uuid);if(!u){if(!y.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}mt({query:"",cursor:0,sessions:y});return}let b=Tg(e,u);if(!b){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}xe(b.uuid),He.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},lt(b.name),ys(b.uuid),Pt.current=[];let w=fs(e,b.uuid);for(let x of w)d(x);d({kind:"note",tone:"ok",text:w.length?`Resumed "${b.name}" \u2014 restored ${w.length} message(s); continue where you left off.`:`Resumed "${b.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=h.join(" ").trim(),y;try{y=await gn(e,i)}catch(w){d({kind:"note",tone:"error",text:`Could not list workspaces: ${w.message}`});return}if(!u){let w=y.workspaces.map($=>({id:$.id,name:$.name??$.id,type:$.workspace_type}));if(w.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let x=Math.max(0,w.findIndex($=>$.id===y.current));At({cursor:x,current:x,rows:w,profile:y.profile,projectId:y.projectId,projectName:y.projectName,environment:y.environment});return}let b=Sr(y.workspaces,u);if(!b){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}Xn(y.profile,y.projectId,b);return}case"project":{let u=h.join(" ").trim(),y;try{y=await et(e,i)}catch(w){d({kind:"note",tone:"error",text:`Could not list projects: ${w.message} (signed in? try /login)`});return}if(!u){let w=y.projects.map($=>({id:$.id,name:$.name??$.id,sub:$.sub_domain}));if(w.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let x=w.findIndex($=>$.id===y.current);ut({cursor:Math.max(0,x),current:x,rows:w,profile:y.profile,environment:y.environment});return}let b=Dr(y.projects,u);if(!b){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${y.projects.map(w=>w.name??w.id).join(", ")}`});return}Jn(y.profile,b);return}case"logout":{let u;try{u=Re(e,i).name}catch(b){d({kind:"note",tone:"error",text:b.message});return}let y=$g(u);xg(e,u),xe(),K(b=>b+1),d({kind:"note",tone:y?"ok":"info",text:y?`\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."}),Q("/login");return}case"publish":{if(!Vn(c.trim()))return;if(h[0]==="--related"&&h[1]){let w=await Po(e,i,h[1].replace(/\\/g,"/"));if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Mt(w);return}let u=h.filter(w=>!w.startsWith("--"));if(u[0]){await $r(u[0]);return}let y=h.includes("--all"),b=h.includes("--force");d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let w=await ks({cwd:e,profileName:i}),{clean:x,conflicts:$}=$o(w.entries),G=y&&b&&$.length>0,H=Co(w.entries);if(H>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${H} article${H===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.`}),$.length>0&&!G&&d({kind:"note",tone:"warn",text:xo($.length)}),x.length===0&&!G){if($.length>0){Q("/resolve");return}d({kind:"note",tone:"ok",text:H>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let I=w.counts["unknown-base"]??0;I>0&&d({kind:"note",tone:"info",text:`(${I} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),_s("Reconciling structure on Document360 (order + related articles)\u2026");try{let R=await hd({cwd:e,profileName:i}),D=wd(await gd({cwd:e,profileName:i})),U=md(R);U?d({kind:"note",tone:"info",text:U}):R.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${R.skipped}`}),D&&d({kind:"note",tone:"info",text:D}),d({kind:"note",tone:"ok",text:U||D?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(U||D)&&Q("/structure")}catch(R){d({kind:"note",tone:"warn",text:`Structure sync failed: ${R.message}`})}finally{_s(null)}return}if(y){let I=(G?[...x,...$]:x).map(R=>R.path);await Mt(I),$.length>0&&!G&&Q("/resolve");return}Et({cursor:0,rows:Xa(x,$)})}catch(w){d({kind:"note",tone:"error",text:`Could not compute sync status: ${w.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!Vn(c.trim()))return;await Pr(h.find(u=>!u.startsWith("--")));return}case"preview":{let u=h.join(" ").trim();if(!u){let b=[];try{b=Object.keys(sd(e,Re(e,i).name)?.articles??{})}catch{}if(b.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}ft({query:"",cursor:0,paths:b});return}let y=hg(u)?u:ws(e,u);if(Jt(y)){try{d({kind:"preview",name:Nn(y),text:bd(or(y,"utf8"))})}catch(b){d({kind:"note",tone:"error",text:`Could not read ${y}: ${b.message}`})}return}if(rw.test(u)){try{let b=Re(e,i),w={profile:b.name,connection:b.connection},x=b.project.projectId??bg(w),$=await vg(w,x,u);d({kind:"preview",name:$.title??u,text:$.content??"*(article has no content)*"})}catch(b){d({kind:"note",tone:"error",text:`Could not fetch article: ${b.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 x=Eo(Cs(e));dt({cursor:x,current:x});return}let{lines:y,changed:b,effective:w}=Cn(e,u);for(let x of y)d({kind:"note",tone:x.startsWith("\u26A0")?"warn":x.startsWith("\u2713")?"ok":"info",text:x});b&&(Ms(x=>x+1),Se.current?.setModel(w));return}case"convert":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:y}=ii(h),b=Fg(e,i);if(b.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let w=si(b,u);if(w.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${b.length} are tracked overall.)`});return}let x=bs(w),$=3,G=`/convert${u?` --scope ${u}`:""} --run`,H=ir(e,"light");if(!y){let R=dd({files:ai(e,w),op:"convert",model:H.model}),D=u?`Scope: ${u} (${w.length} of ${b.length} tracked)
|
|
338
338
|
`:"",U=`
|
|
339
|
-
Model: ${H.model}${H.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:
|
|
340
|
-
`)+U}),
|
|
341
|
-
`)})}}catch(R){d({kind:"note",tone:"error",text:`Convert run failed: ${R.message}`})}finally{
|
|
339
|
+
Model: ${H.model}${H.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:D+ci(x,R,$).join(`
|
|
340
|
+
`)+U}),Q(G);return}at.current=Date.now(),xt(0),S(!0);let I=new AbortController;De.current=I,re({verb:"Converting",total:x.length,done:0,active:[],rows:En(x),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${w.length} articles across ${x.length} partitions (\u2264${$} agents at once) on ${H.model}\u2026 (esc to stop)`});try{for await(let R of rr({cwd:e,partitions:x,promptFor:li,concurrency:$,profileName:i,allowProdWrites:Tt.current,model:H.model,signal:I.signal}))if(R.type==="partition_status")R.status==="running"?re(D=>D&&{...D,active:[...D.active,R.label],rows:Ke(D.rows,R.label,"active"),lastAt:Date.now()}):re(D=>D&&{...D,active:D.active.filter(U=>U!==R.label),done:D.done+1,rows:Ke(D.rows,R.label,R.status==="done"?"done":"failed"),lastAt:Date.now()});else if(R.type==="partition_event")re(D=>{if(!D)return D;let U={...D,lastAt:Date.now()};return R.event.type==="tool"?U.tools=D.tools+1:R.event.type==="text"&&(U.chars=D.chars+R.event.delta.length),U});else if(R.type==="run_done"){_t(ee=>ee+R.totalCostUsd),It(ee=>ee+R.results.reduce((Ft,Ht)=>Ft+Ht.outputTokens,0));let D=R.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";d({kind:"note",tone:R.aborted?"warn":R.ok?"ok":"warn",text:D+di(R.results,x,U).join(`
|
|
341
|
+
`)})}}catch(R){d({kind:"note",tone:"error",text:`Convert run failed: ${R.message}`})}finally{De.current=null,re(null),S(!1),K(R=>R+1)}return}case"write":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Hg(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:y,path:b,preview:w,concurrency:x,rewrite:$}=fi(h),{docsDir:G,targets:H,reason:I,rewriting:R}=bi(e,u,{scope:y,path:b,rewrite:$});if(H.length===0){d({kind:"note",tone:"warn",text:I??"Nothing to write."});return}R&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${H.length} already-written article${H.length===1?"":"s"} (overwrites them; git has your baseline).`});let D=bs(H),U=pi(x),ee=ir(e,"standard"),Ft=!!b;if(w&&!Ft){let X=dd({files:mi(e,u,H),op:"write",model:ee.model}),se=y?`Scope: ${y} (${H.length} pending)
|
|
342
342
|
`:"",pe=`
|
|
343
|
-
Model: ${
|
|
344
|
-
`)+pe}),
|
|
345
|
-
`)}),!
|
|
343
|
+
Model: ${ee.model}${ee.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:se+wi(D,X,U).join(`
|
|
344
|
+
`)+pe}),Q(`/write${y?` --scope ${y}`:""}`);return}at.current=Date.now(),xt(0),S(!0);let Ht=new AbortController;De.current=Ht,re({verb:"Writing",total:D.length,done:0,active:[],rows:En(D),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${H.length} article${H.length===1?"":"s"} across ${D.length} partition${D.length===1?"":"s"} (\u2264${U} agents at once) on ${ee.model}${ee.forced?" (forced)":""}\u2026 (esc to stop)`});let to=new Set;try{for await(let X of rr({cwd:e,partitions:D,promptFor:se=>gi(se,G,{rewrite:R||Ft}),concurrency:U,profileName:i,allowProdWrites:Tt.current,model:ee.model,signal:Ht.signal}))if(X.type==="partition_status")X.status==="running"?re(se=>se&&{...se,active:[...se.active,X.label],rows:Ke(se.rows,X.label,"active"),lastAt:Date.now()}):re(se=>se&&{...se,active:se.active.filter(pe=>pe!==X.label),done:se.done+1,rows:Ke(se.rows,X.label,X.status==="done"?"done":"failed"),lastAt:Date.now()});else if(X.type==="partition_event"){let se=null;if(X.event.type==="tool"){let pe=qc(X.event.name,X.event.input,D[X.index]?.paths??[]);pe&&!to.has(pe)&&(to.add(pe),se=X.label)}re(pe=>{if(!pe)return pe;let Me={...pe,lastAt:Date.now()};return X.event.type==="tool"?Me.tools=pe.tools+1:X.event.type==="text"&&(Me.chars=pe.chars+X.event.delta.length),se&&(Me.rows=Hc(Me.rows,se)),Me})}else if(X.type==="run_done"){_t(Je=>Je+X.totalCostUsd),It(Je=>Je+X.results.reduce((Ge,Ud)=>Ge+Ud.outputTokens,0));let se=X.aborted?"Stopped. ":"",pe=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:X.aborted?"warn":X.ok?"ok":"warn",text:se+yi(X.results,D,pe).join(`
|
|
345
|
+
`)}),!X.aborted&&X.ok)try{let Je=(to.size>0?[...to]:H).map(Ge=>`${G}/${Ge}`);vs(e,Je,{writtenCap:$s})}catch{}let Me=X.aborted?null:ki(e,G,H);if(Me&&d({kind:"note",tone:"warn",text:Me}),!X.aborted&&X.ok){let Je=y??b??"",Ge=Je?` ${Je}`:"";Ot(Me?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${Ge} --fix, then /review${Ge} --fix for editorial quality, then /publish --all (add /screenshot --all first if you want images).`:`Written. I\u2019d run /review${Ge} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot --all first if you want images).`,{kind:"cmd",cmd:Me?`/check${Ge} --fix`:`/review${Ge} --fix`,reason:""})}}}catch(X){d({kind:"note",tone:"error",text:`Write run failed: ${X.message}`})}finally{De.current=null,re(null),S(!1),K(X=>X+1)}return}case"draft":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:y}=vi(e);if(u.length===0&&y===0){d({kind:"note",tone:"info",text:xi});return}let b=h.join(" ").trim();if(!b&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
346
346
|
${u.map($=>` \u2022 ${$.name} (${$.docCount} doc${$.docCount===1?"":"s"})`).join(`
|
|
347
|
-
`)}`}),
|
|
348
|
-
`)});return}if(u==="--baseline"){let w=h.find(H=>!H.startsWith("--")),x=w?w.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:x?`Setting the sync baseline for ${x}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let $=await
|
|
347
|
+
`)}`}),Fe(u.map($=>`/draft ${$.name}`));return}let w="",x;if(b){let $=$i(u,b);$?w=$:x=b}else w=u[0]?.name??"";await ie(Ao(w,x),{display:b?`/draft ${b}`:"/draft",quietUser:!0});return}case"pull":{if(!Vn(c.trim()))return;let u=h.find(y=>y.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let w=Date.now(),x=await ks({cwd:e,profileName:i});d({kind:"note",tone:"info",text:So(x,Date.now()-w).join(`
|
|
348
|
+
`)});return}if(u==="--baseline"){let w=h.find(H=>!H.startsWith("--")),x=w?w.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:x?`Setting the sync baseline for ${x}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let $=await Ig({cwd:e,profileName:i,relPaths:x?[x]:void 0}),G=x?{rebaselined:[],skipped:[]}:await _g({cwd:e,profileName:i});if($.baselined.length===0&&$.skipped.length===0&&G.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}$.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${$.baselined.length} article${$.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),G.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${G.rebaselined.length} article${G.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),$.skipped.length>0&&d({kind:"note",tone:"warn",text:`${$.skipped.length} skipped:
|
|
349
349
|
${$.skipped.map(H=>` - ${H.path} (${H.reason})`).join(`
|
|
350
|
-
`)}`}),
|
|
351
|
-
`)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=h[0];if(y){let w=await
|
|
352
|
-
`)}),
|
|
353
|
-
`)}),b.length>0&&
|
|
354
|
-
`)});return}case"reorder":{let u=
|
|
355
|
-
`)});return}case"devhints":{if(!
|
|
356
|
-
`)}),
|
|
357
|
-
`)});return}if(u.mode==="single"){let I=await
|
|
358
|
-
`)})}return}case"reset":{let u=
|
|
359
|
-
`)}),me(En(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${s} \u2014 type /help.`})}},[e,r,i,Mt,Rr,d,$e,ie,Lt,vr,Vs]),Jn=G(c=>{let a=(c??T).trim();if(v(""),Ln(null),xt(0),a.startsWith("/")&&(Nn.current=!1,Ye(),nn(null),it(h=>Bc(h,a))),!a||(Ss(!1),Ys(a))||Gs(a))return;dr.current.push(a);let s=zc(a,js.current);if(a.startsWith("/"))d({kind:"user",text:a}),pn(s);else if(Yg(s)){d({kind:"user",text:a});let h=zg(s);if(!h)ie(s,{display:a,quietUser:!0});else{try{Kg(e,{title:h,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ie(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${h}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${h}" and the article path(s) you wrote.`,{display:a,quietUser:!0})}}else ie(s,{display:a})},[T,Ys,Gs,pn,ie]),zs=G(c=>{if(c.length>1){if(c.includes("\x1B"))return;let a=Vc(c);if(Gc(a)){let s=Yc(++Ad.current,a);js.current.set(s,a),_(s)}else _(a);return}_(c)},[_]),Ut=Math.max(10,Ie-6),Ks=ms(()=>er(k.text,Ut),[k.text,Ut]),Pr=G(c=>g(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+c))})),[]),Zn=G(c=>g(a=>({...a,pos:Xc(er(a.text,Ut),a.pos,c)})),[Ut]),fn=G(c=>g(a=>({...a,pos:Qc(er(a.text,Ut),a.pos,c)})),[Ut]),_d=["\x1B[H","\x1B[1~","\x1BOH"],Od=["\x1B[F","\x1B[4~","\x1BOF"],Xs=G((c,a)=>a.leftArrow?(Pr(-1),!0):a.rightArrow?(Pr(1),!0):c&&_d.includes(c)?(fn("start"),!0):c&&Od.includes(c)?(fn("end"),!0):a.ctrl&&c==="a"?(fn("start"),!0):a.ctrl&&c==="e"?(fn("end"),!0):!1,[Pr,fn]);return lg((c,a)=>{if(a.ctrl&&c==="c"){Te.current?.close(),r();return}if(!M){if(N){if(a.escape){if(Se.current){if(!Se.current.signal.aborted){let s=(Wn?.verb??"work").toLowerCase(),h=Wn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${s} run (finishing in-flight ${h}s)\u2026`}),Se.current.abort()}return}on.current||(on.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Te.current?.interrupt());return}if(a.return){let s=T.trim();if(!s)return;ft.current.push(s),pr([...ft.current]),v("");return}if(Xs(c,a))return;if(a.upArrow){Zn(-1);return}if(a.downArrow){Zn(1);return}if(a.backspace||a.delete){P();return}c&&!a.ctrl&&!a.meta&&zs(c);return}if(lt){if(a.upArrow){ct(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){ct(s=>s&&{...s,cursor:Math.min(Oe.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Oe.length){ct(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=Oe[lt.cursor];ct(null);let{lines:h,changed:u,effective:y}=xn(e,s.value??"default");for(let b of h)d({kind:"note",tone:b.startsWith("\u26A0")?"warn":b.startsWith("\u2713")?"ok":"info",text:b});u&&(Ms(b=>b+1),Te.current?.setModel(y));return}if(c==="s"){let s=Oe[lt.cursor];ct(null),Te.current?.setModel(s.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${s.label} for this session only (your saved default is unchanged).`});return}if(a.escape){ct(null);return}return}if(Me){if(a.upArrow){St(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){St(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Me.rows.length){St(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return||c==="s"){let s=Me.rows[Me.cursor];St(null),xr(s.name,a.return===!0);return}if(a.escape){St(null);return}return}if(qn){if(a.escape){sn(null);return}if(a.leftArrow||a.tab&&a.shift){sn(s=>s&&{tab:(s.tab-1+De.length)%De.length});return}if(a.rightArrow||a.tab){sn(s=>s&&{tab:(s.tab+1)%De.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=De.length){sn({tab:Number(c)-1});return}return}if(Ue){if(a.upArrow){Dt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Dt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ue.rows.length){Dt(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=Ue.rows[Ue.cursor].name;if(Dt(null),!_r(e,s).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 "${s}").`});let u=!1;try{let y=vt(s);u=!!y&&!(nt(y)&&!y.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${s} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${s}) and pick your project.`}),K("/login"),X(y=>y+1);return}if(a.escape){Dt(null);return}return}if(fe){if(a.upArrow){jt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){jt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=fe.rows.length){jt(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=fe.rows[fe.cursor],{profile:h,projectId:u}=fe;jt(null),Kn(h,u,s);return}if(a.escape){jt(null);return}return}if(ke){if(a.upArrow){dt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){dt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ke.rows.length){dt(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=ke.rows[ke.cursor],{profile:h}=ke;dt(null),Qn(h,s);return}if(a.escape){dt(null);return}return}if(he){if(a.upArrow){Et(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Et(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c===" "){Et(s=>s&&{...s,rows:s.rows.map((h,u)=>u===s.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let s=he.rows.filter(h=>h.checked).map(h=>h.path);if(Et(null),s.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Qr(e,s),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${s.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of s)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){Et(null);return}return}if(We){if(a.upArrow){ut(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){ut(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=We.rows.length){ut(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=We.rows[We.cursor],h=We.run;ut(null),h(s.token);return}if(a.escape){ut(null);return}return}if(Ve){if(a.upArrow){At(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){At(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ve.rows.length){At(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=Ve.rows[Ve.cursor];At(null),s.conflict?Rr(s.paths[0]):s.kind==="article"?vr(s.paths[0]):Lt(s.paths);return}if(a.escape){At(null);return}return}if(be){if(a.escape){pt(null);return}if(a.upArrow){pt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){pt(s=>s&&{...s,cursor:Math.min(Math.max(0,Yn.length-1),s.cursor+1)});return}if(a.return){let s=Yn[be.cursor];if(s){pt(null);try{d({kind:"preview",name:En(s),text:yd(nr(gs(e,s),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${s}: ${h.message}`})}}return}if(a.backspace||a.delete){pt(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){pt(s=>s&&{...s,query:s.query+c,cursor:0});return}return}if(ve){if(a.escape){ht(null);return}if(a.upArrow){ht(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){ht(s=>s&&{...s,cursor:Math.min(Math.max(0,zn.length-1),s.cursor+1)});return}if(a.return){let s=zn[ve.cursor];if(s){ht(null),$e(s.uuid),Le.current={uuid:s.uuid,firstPrompt:s.firstPrompt,titleFired:!0},at(s.name),ws(s.uuid),Rt.current=[];let h=ps(e,s.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${s.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${s.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){ht(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){ht(s=>s&&{...s,query:s.query+c,cursor:0});return}return}if(a.tab&&!T&&te){v(te),Ye();return}if(!T&&rt.length>0&&!lr&&c&&/^[1-9]$/.test(c)){let s=rt[Number(c)-1];if(s){v(bt(s));return}}if(!T&&(Vn||an)&&c==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let s=Vn!=null;ds(Vn??an).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?s?"\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.":s?"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&&s&&yr(null),u&&!s&&Fs(!0)});return}if(!Xs(c,a)){if(qs){if(a.upArrow){xt(s=>Math.max(0,s-1));return}if(a.downArrow){xt(s=>Math.min(un.length-1,s+1));return}if(a.tab){v("/"+(un[tn]?.name??"")+" "),xt(0);return}if(a.return){let s=un[tn];if(s){let h=T.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Oc(s.usage)&&!h){v("/"+s.name+" "),xt(0);return}Jn("/"+s.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(T!==""&&Ct===null){Zn(-1);return}let s=dr.current;if(!s.length)return;let h=Ct===null?s.length-1:Math.max(0,Ct-1);Ln(h),v(s[h]??"");return}if(a.downArrow){if(T!==""&&Ct===null){Zn(1);return}let s=dr.current;if(Ct===null)return;let h=Ct+1;h>=s.length?(Ln(null),v("")):(Ln(h),v(s[h]??""));return}}if(a.return){Jn();return}if(a.backspace||a.delete){P();return}if(a.escape){v(""),xt(0),Ye(),it([]),nn(null),Nn.current=!0;return}c&&!a.ctrl&&!a.meta&&zs(c)}}}),Re(()=>{if(N||M)return;let c=ft.current.shift();c!==void 0&&(pr([...ft.current]),Jn(c))},[N,M,Jn]),Y(oe,{flexDirection:"column",width:Ie,children:[br!==null&&Y(oe,{marginTop:1,flexDirection:"column",children:[br.truncated&&E(A,{dimColor:!0,children:"\u2026"}),E(A,{children:br.text})]}),N&&(Wn?E(iw,{p:Wn}):E(nw,{startTime:st.current,chars:jd})),!N&&Is?E(ow,{text:Is}):null,E(oe,{borderStyle:"round",borderColor:Hs.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:T?Ks.map((c,a)=>{let s=k.text.slice(c.start,c.end),h=a===tr(Ks,k.pos),u=Math.min(k.pos,c.end)-c.start;return Y(A,{children:[E(A,{color:q,children:a===0?"> ":" "}),h?Y(ir,{children:[s.slice(0,u),E(Jt,{ch:s[u]??" "}),s.slice(u+1)]}):s||" "]},`${a}-${c.start}`)}):Y(A,{children:[E(A,{color:q,children:"> "}),fr?E(Jt,{ch:" "}):te&&!N&&ot?Y(ir,{children:[E(Jt,{ch:ot[0],dim:!0}),E(A,{color:"gray",children:ot.slice(1)})]}):te&&!N?Y(ir,{children:[E(Jt,{ch:te[0],dim:!0}),E(A,{color:"gray",children:te.slice(1)}),E(A,{dimColor:!0,children:" (tab)"})]}):(kr.isSetup||!Sd)&&!N?Y(ir,{children:[E(Jt,{ch:kr.text[0],dim:!0}),E(A,{color:"gray",children:kr.text.slice(1)})]}):E(Jt,{ch:" "})]})}),Ns.length>0&&E(oe,{flexDirection:"column",paddingX:1,children:Ns.map((c,a)=>E(A,{color:"gray",children:`\u29D7 queued: ${c}`},`${a}-${c.slice(0,24)}`))}),qn?E(Mc,{tab:qn.tab,width:Ie,version:o,engineVersion:kd}):lt?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Select model"}),E(A,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Oe.map((c,a)=>Y(A,{color:a===lt.cursor?q:void 0,children:[a===lt.cursor?"\u276F ":" ",`${a+1}. ${c.label}${a===lt.current?" \u2714":""}`.padEnd(16),E(A,{color:"gray",children:c.desc})]},c.label)),E(A,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Me?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Switch connection profile"}),Me.rows.map((c,a)=>Y(A,{color:a===Me.cursor?q:void 0,children:[a===Me.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===Me.current?" \u2714":""}`.padEnd(20),E(A,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?E(A,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),E(A,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ue?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Pick your Document360 environment"}),Ue.rows.map((c,a)=>Y(A,{color:a===Ue.cursor?q:void 0,children:[a===Ue.cursor?"\u276F ":" ",`${a+1}. ${c.name}`.padEnd(16),E(A,{color:"gray",children:c.apiUrl})]},c.name)),E(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Switch workspace"}),E(A,{dimColor:!0,children:`environment ${fe.environment} \xB7 project ${fe.projectName??`${fe.projectId.slice(0,8)}\u2026`}`}),fe.rows.map((c,a)=>Y(A,{color:a===fe.cursor?q:void 0,children:[a===fe.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===fe.current?" \u2714":""}`.padEnd(30),E(A,{color:"gray",children:c.type??""})]},c.id)),E(A,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ke?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Choose project"}),E(A,{dimColor:!0,children:`environment ${ke.environment}`}),ke.rows.map((c,a)=>Y(A,{color:a===ke.cursor?q:void 0,children:[a===ke.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===ke.current?" \u2714":""}`.padEnd(30),E(A,{color:"gray",children:c.sub??""})]},c.id)),E(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):he?(()=>{let a=Math.min(Math.max(0,he.cursor-Math.floor(7)),Math.max(0,he.rows.length-14)),s=he.rows.slice(a,a+14),h=he.rows.filter(u=>u.checked).length;return Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:`Which folders back the user docs? (${h} selected of ${he.rows.length})`}),a>0?E(A,{dimColor:!0,children:` \u2191 ${a} more`}):null,s.map((u,y)=>{let b=a+y;return Y(A,{color:b===he.cursor?q:void 0,children:[b===he.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Ie-34)),E(A,{color:"gray",children:Po(u)})]},u.path)}),a+14<he.rows.length?E(A,{dimColor:!0,children:` \u2193 ${he.rows.length-a-14} more`}):null,E(A,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():We?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Which category? (pick one to scope to)"}),We.rows.map((c,a)=>{let s=a===We.cursor,h=`${a+1}.`.padEnd(3);return Y(A,{color:s?q:void 0,children:[s?"\u276F ":" ",`${h} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Ie-24))),E(A,{color:"gray",children:` ${c.token}`})]},c.token)}),E(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Ve?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Ve.rows.map((c,a)=>{let s=a===Ve.cursor,h=c.indent?" ":" ",u=`${a+1}.`.padEnd(3);return Y(A,{color:s?q:void 0,bold:c.kind==="category"&&!s,children:[s?"\u276F ":" ",`${h}${u} ${c.label}`.padEnd(Math.min(56,Ie-24)),c.note?E(A,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),E(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):be?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:`Preview article${be.query?` \u2014 filter: ${be.query}`:" (type to filter)"}`}),Yn.length===0?E(A,{color:"gray",children:"no articles match"}):Yn.map((c,a)=>Y(A,{color:a===be.cursor?q:void 0,children:[a===be.cursor?"\u276F ":" ",c]},c)),E(A,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):ve?Y(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:`Resume session${ve.query?` \u2014 filter: ${ve.query}`:" (type to filter)"}`}),zn.length===0?E(A,{color:"gray",children:"no sessions match"}):zn.map((c,a)=>Y(A,{color:a===ve.cursor?q:void 0,children:[a===ve.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),E(A,{color:a===ve.cursor?q:"gray",children:c.firstPrompt.slice(0,Math.max(10,Ie-40))})]},c.uuid)),E(A,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):qs?Y(oe,{flexDirection:"column",children:[un.map((c,a)=>Y(A,{color:a===tn?q:void 0,children:[a===tn?"\u276F ":" ",c.usage.padEnd(22)," ",E(A,{color:a===tn?q:"gray",children:c.name==="model"&&hr?`${c.desc} (currently ${hr})`:c.desc})]},c.name)),E(A,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!T&&rt.length>0?Y(oe,{flexDirection:"column",paddingX:1,children:[Es?E(A,{color:q,children:Es}):null,rt.map((c,a)=>{let s=bt(c),h=s.slice(0,Math.max(20,Ie-5)),u=Ie-h.length-7,y=u>=12?(qc(c)??Ic(s)).slice(0,u):"";return Y(A,{children:[E(A,{color:q,children:a+1})," ",h,y?E(A,{dimColor:!0,children:` \u2014 ${y}`}):null]},s)}),E(A,{dimColor:!0,children:`press 1-${rt.length} to fill \xB7 esc cancel`})]}):E(oe,{paddingX:1,children:Y(A,{color:"gray",children:[Hs.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${hr??"model n/a"}${t.kind==="api"?Ls>0?` \xB7 ${we(Ls)}`:"":Os>0?` \xB7 ${Ze(Os)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as cw}from"react/jsx-runtime";async function $d(e=process.cwd(),t="auto",n,o="0.0.0"){let r=lw(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:i}=aw(cw(vd,{cwd:e,auth:r,profileName:n,version:o}));await i(),process.stdout.write(`
|
|
360
|
-
`),process.exit(0)}W();import{writeCrashLog as
|
|
361
|
-
`+C(`\u2717 d360-writer crashed: ${
|
|
350
|
+
`)}`}),K(H=>H+1);return}if(u==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let w=await Ng({cwd:e,profileName:i}),x=w.onlyInLegacy.length===0&&w.onlyInManifest.length===0&&w.mappedMissingFromManifest.length===0,$=[`Legacy listing: ${w.legacyCount} \xB7 Manifest: ${w.manifestCount} \xB7 in both: ${w.inBoth}`];x?$.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(w.mappedMissingFromManifest.length&&$.push(`\u2717 ${w.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${w.mappedMissingFromManifest.slice(0,5).join(", ")}`),w.onlyInLegacy.length&&$.push(`\u26A0 ${w.onlyInLegacy.length} only in the legacy listing: ${w.onlyInLegacy.slice(0,5).join(", ")}`),w.onlyInManifest.length&&$.push(`\u26A0 ${w.onlyInManifest.length} only in the manifest: ${w.onlyInManifest.slice(0,5).join(", ")}`),$.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:x?"ok":"warn",text:$.join(`
|
|
351
|
+
`)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=h[0];if(y){let w=await cd({cwd:e,profileName:i,relPath:y.replace(/\\/g,"/")});le.current=[{plan:w,mode:w.overwritesLocalChanges?"conflict":"pull"}],St.current=[],Ut();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let b=await ni({cwd:e,profileName:i});for(let w of oi(b))d({kind:"note",tone:w.tone,text:w.text});K(w=>w+1)}catch(y){d({kind:"note",tone:"error",text:`Pull failed: ${y.message}`})}return}case"scope":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Og(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}Nt({cursor:0,rows:u.map(y=>({...y,checked:y.recommended}))});return}case"audit":{if(h[0]==="--auto"){let y=te(e);if(!y){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=h[1]!=="off";id({...y,autoAudit:b},e),d({kind:"note",tone:"ok",text:b?"\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 $n();u.kind==="forward-to-agent"&&u.prompt&&await ie(u.prompt,{display:u.display,quietUser:!0});return}case"check":{let u=h.find(w=>!w.startsWith("--")),y=u?` ${u}`:"",b=ld({cwd:e,scope:u});if(h.includes("--fix")){if(b.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 ${b.length} doc issue${b.length===1?"":"s"}\u2026`});let w=fd(e,u);await ie(zi(b),{display:`/check${y} --fix`,quietUser:!0});try{vs(e,w,{reviewedCap:$s})}catch{}let x=ld({cwd:e,scope:u});d({kind:"note",tone:x.length===0?"ok":"warn",text:x.length===0?"\u2713 Doc-checker: all issues resolved.":Uo(x).join(`
|
|
352
|
+
`)}),Ot(x.length===0?`Deterministic issues fixed. Next: /review${y} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${y} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${y} --fix`,reason:""});return}d({kind:"note",tone:b.length===0?"ok":"warn",text:Uo(b).join(`
|
|
353
|
+
`)}),b.length>0&&Ot(`Found ${b.length} doc issue${b.length===1?"":"s"} above. /check${y} --fix has the agent fix them in place (or /review${y} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${y} --fix`,reason:""});return}case"structure":{let u=Dn(e,i);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(`
|
|
354
|
+
`)});return}case"reorder":{let u=Xi(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ie(u.prompt,{display:u.display,quietUser:!0}),Ot("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let u=Ki(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=h.includes("--fix"),b=h.find(x=>!x.startsWith("--")),w=y?fd(e,b):[];if(await ie(u.prompt,{display:u.display,quietUser:!0}),y)try{vs(e,w,{reviewedCap:$s})}catch{}if(y)Ot("\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let x=h.filter($=>$!=="--fix").join(" ");Ot(`The review listed issues above. /review${x?` ${x}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${x?` ${x}`:""} --fix`,reason:""})}return}case"capture-setup":{let u=await Pn();u.kind==="forward-to-agent"&&u.prompt&&await ie(u.prompt,{display:u.display,quietUser:!0});let y=_i(e);y&&d({kind:"note",tone:"info",text:y.join(`
|
|
355
|
+
`)});return}case"devhints":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Yt(Gt(e)).join(`
|
|
356
|
+
`)}),Lt(wt()),cn.current=Ae(e).status==="current"||Ye(e);return}case"discover":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ie(Qr(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Oi(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 ie(Li(),{display:"/inbox",quietUser:!0});return}case"feedback":{let u=pd(e),y="";try{y=Jt(u)?or(u,"utf8"):""}catch{y=""}if(!/^## /m.test(y)){d({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let b=await us(y.trim());d({kind:"note",tone:b?"ok":"warn",text:b?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${u} and copy it manually.`}),b&&kr(null);return}case"document":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:y}=Ri(h);if(!y&&Ci(e)===0){d({kind:"note",tone:"info",text:Ti});return}let b=`/document${y?` ${y}`:""}${u?" --publish":""}`;await ie(Pi(y,u),{display:b,quietUser:!0});return}case"catch-up":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Vn(c.trim()))return;let{publish:u}=Ui(h);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let y=await Fi({cwd:e,profileName:i});for(let w of Hi(y))d({kind:"note",tone:w.startsWith("\u2713")?"ok":w.startsWith("\u2139")?"info":"warn",text:w});let b=Sn(Tn(e));d({kind:"note",tone:"info",text:b?`Catching up on ${b}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ie(Wi({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{wr.current=!0,d({kind:"note",tone:"info",text:`Updating ${bt}\u2026 (don\u2019t close this window)`}),Ln(!0),(await Lo().finally(()=>Ln(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),Q("/exit"),Ds("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Oo}`});return}case"screenshot":{let u=Ei(h);if(u.mode==="list"){if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Ii(Ni(e,u.scope),u.scope).join(`
|
|
357
|
+
`)});return}if(u.mode==="single"){let I=await Io(h);I.kind==="forward-to-agent"&&I.prompt&&await ie(I.prompt,{display:I.display,quietUser:!0});return}if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=u.mode==="scope"?u.scope:void 0,b=Wg(e,{scope:y}).map(I=>I.id);if(b.length===0){d({kind:"note",tone:"info",text:y?`No screenshot placeholders under ${y}.`:"No screenshot placeholders found in the docs."});return}let w=6,x=Ug(b,3),$=ir(e,"standard");at.current=Date.now(),xt(0),S(!0);let G=new AbortController;De.current=G,re({verb:"Authoring",unit:"spec",total:x.length,done:0,active:[],rows:En(x),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${b.length} screenshot spec${b.length===1?"":"s"} across ${x.length} partition${x.length===1?"":"s"} (\u2264${w} agents at once) on ${$.model}${$.forced?" (forced)":""}\u2026 (esc to stop)`});let H=!1;try{for await(let I of rr({cwd:e,partitions:x,promptFor:Gl,concurrency:w,profileName:i,allowProdWrites:Tt.current,model:$.model,signal:G.signal}))if(I.type==="partition_status")I.status==="running"?re(R=>R&&{...R,active:[...R.active,I.label],rows:Ke(R.rows,I.label,"active"),lastAt:Date.now()}):re(R=>R&&{...R,active:R.active.filter(D=>D!==I.label),done:R.done+1,rows:Ke(R.rows,I.label,I.status==="done"?"done":"failed"),lastAt:Date.now()});else if(I.type==="partition_event")re(R=>{if(!R)return R;let D={...R,lastAt:Date.now()};return I.event.type==="tool"?D.tools=R.tools+1:I.event.type==="text"&&(D.chars=R.chars+I.event.delta.length),D});else if(I.type==="run_done"){_t(ee=>ee+I.totalCostUsd),It(ee=>ee+I.results.reduce((Ft,Ht)=>Ft+Ht.outputTokens,0));let R=I.results.filter(ee=>ee.ok).length,D=I.aborted?"Stopped. ":"";H=!I.aborted&&u.setup;let U=I.aborted?"":H?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:I.aborted?"warn":I.ok?"ok":"warn",text:`${D}Authored specs \u2014 ${R}/${I.results.length} batches ok.${U}`})}}catch(I){d({kind:"note",tone:"error",text:`Spec authoring failed: ${I.message}`})}finally{De.current=null,re(null),S(!1),K(I=>I+1)}if(H){let I=await Pn();I.kind==="forward-to-agent"&&I.prompt&&await ie(I.prompt,{display:I.display,quietUser:!0});let R=_i(e);R&&d({kind:"note",tone:"info",text:R.join(`
|
|
358
|
+
`)})}return}case"reset":{let u=Vi(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Wn.current={repoName:Nn(e),targets:u,hadDevhints:Jt(ud(e))},d({kind:"note",tone:"warn",text:Yi(e,u).join(`
|
|
359
|
+
`)}),ge(Nn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${s} \u2014 type /help.`})}},[e,r,i,Ut,Pr,d,xe,ie,Mt,$r,Vs]),Zn=Y(c=>{let a=(c??T).trim();if(v(""),Mn(null),Ct(0),a.startsWith("/")&&(In.current=!1,Oe(),on(null),Fe(h=>Gc(h,a))),!a||(Ss(!1),Ys(a))||Gs(a))return;ur.current.push(a);let s=Xc(a,js.current);if(a.startsWith("/"))d({kind:"user",text:a}),fn(s);else if(Xg(s)){d({kind:"user",text:a});let h=Qg(s);if(!h)ie(s,{display:a,quietUser:!0});else{try{Jg(e,{title:h,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ie(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${h}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${h}" and the article path(s) you wrote.`,{display:a,quietUser:!0})}}else ie(s,{display:a})},[T,Ys,Gs,fn,ie]),zs=Y(c=>{if(c.length>1){if(c.includes("\x1B"))return;let a=Yc(c);if(zc(a)){let s=Kc(++Nd.current,a);js.current.set(s,a),_(s)}else _(a);return}_(c)},[_]),Wt=Math.max(10,Le-6),Ks=gs(()=>tr(k.text,Wt),[k.text,Wt]),Tr=Y(c=>g(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+c))})),[]),eo=Y(c=>g(a=>({...a,pos:Jc(tr(a.text,Wt),a.pos,c)})),[Wt]),hn=Y(c=>g(a=>({...a,pos:Zc(tr(a.text,Wt),a.pos,c)})),[Wt]),Ld=["\x1B[H","\x1B[1~","\x1BOH"],Md=["\x1B[F","\x1B[4~","\x1BOF"],Xs=Y((c,a)=>a.leftArrow?(Tr(-1),!0):a.rightArrow?(Tr(1),!0):c&&Ld.includes(c)?(hn("start"),!0):c&&Md.includes(c)?(hn("end"),!0):a.ctrl&&c==="a"?(hn("start"),!0):a.ctrl&&c==="e"?(hn("end"),!0):!1,[Tr,hn]);return ug((c,a)=>{if(a.ctrl&&c==="c"){Se.current?.close(),r();return}if(!M){if(N){if(a.escape){if(De.current){if(!De.current.signal.aborted){let s=(Fn?.verb??"work").toLowerCase(),h=Fn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${s} run (finishing in-flight ${h}s)\u2026`}),De.current.abort()}return}rn.current||(rn.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Se.current?.interrupt());return}if(a.return){let s=T.trim();if(!s)return;ht.current.push(s),fr([...ht.current]),v("");return}if(Xs(c,a))return;if(a.upArrow){eo(-1);return}if(a.downArrow){eo(1);return}if(a.backspace||a.delete){P();return}c&&!a.ctrl&&!a.meta&&zs(c);return}if(ct){if(a.upArrow){dt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){dt(s=>s&&{...s,cursor:Math.min(Ue.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ue.length){dt(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=Ue[ct.cursor];dt(null);let{lines:h,changed:u,effective:y}=Cn(e,s.value??"default");for(let b of h)d({kind:"note",tone:b.startsWith("\u26A0")?"warn":b.startsWith("\u2713")?"ok":"info",text:b});u&&(Ms(b=>b+1),Se.current?.setModel(y));return}if(c==="s"){let s=Ue[ct.cursor];dt(null),Se.current?.setModel(s.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${s.label} for this session only (your saved default is unchanged).`});return}if(a.escape){dt(null);return}return}if(qe){if(a.upArrow){Dt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Dt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=qe.rows.length){Dt(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return||c==="s"){let s=qe.rows[qe.cursor];Dt(null),Cr(s.name,a.return===!0);return}if(a.escape){Dt(null);return}return}if(Bn){if(a.escape){an(null);return}if(a.leftArrow||a.tab&&a.shift){an(s=>s&&{tab:(s.tab-1+je.length)%je.length});return}if(a.rightArrow||a.tab){an(s=>s&&{tab:(s.tab+1)%je.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=je.length){an({tab:Number(c)-1});return}return}if(Be){if(a.upArrow){jt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){jt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Be.rows.length){jt(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=Be.rows[Be.cursor].name;if(jt(null),!Or(e,s).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 "${s}").`});let u=!1;try{let y=$t(s);u=!!y&&!(st(y)&&!y.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${s} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${s}) and pick your project.`}),Q("/login"),K(y=>y+1);return}if(a.escape){jt(null);return}return}if(he){if(a.upArrow){At(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){At(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=he.rows.length){At(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=he.rows[he.cursor],{profile:h,projectId:u}=he;At(null),Xn(h,u,s);return}if(a.escape){At(null);return}return}if(be){if(a.upArrow){ut(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){ut(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=be.rows.length){ut(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=be.rows[be.cursor],{profile:h}=be;ut(null),Jn(h,s);return}if(a.escape){ut(null);return}return}if(me){if(a.upArrow){Nt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Nt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c===" "){Nt(s=>s&&{...s,rows:s.rows.map((h,u)=>u===s.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let s=me.rows.filter(h=>h.checked).map(h=>h.path);if(Nt(null),s.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Jr(e,s),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${s.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of s)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){Nt(null);return}return}if(Ve){if(a.upArrow){pt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){pt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ve.rows.length){pt(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=Ve.rows[Ve.cursor],h=Ve.run;pt(null),h(s.token);return}if(a.escape){pt(null);return}return}if(Xe){if(a.upArrow){Et(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Et(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Xe.rows.length){Et(s=>s&&{...s,cursor:Number(c)-1});return}if(a.return){let s=Xe.rows[Xe.cursor];Et(null),s.conflict?Pr(s.paths[0]):s.kind==="article"?$r(s.paths[0]):Mt(s.paths);return}if(a.escape){Et(null);return}return}if(ve){if(a.escape){ft(null);return}if(a.upArrow){ft(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){ft(s=>s&&{...s,cursor:Math.min(Math.max(0,zn.length-1),s.cursor+1)});return}if(a.return){let s=zn[ve.cursor];if(s){ft(null);try{d({kind:"preview",name:Nn(s),text:bd(or(ws(e,s),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${s}: ${h.message}`})}}return}if(a.backspace||a.delete){ft(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){ft(s=>s&&{...s,query:s.query+c,cursor:0});return}return}if($e){if(a.escape){mt(null);return}if(a.upArrow){mt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){mt(s=>s&&{...s,cursor:Math.min(Math.max(0,Kn.length-1),s.cursor+1)});return}if(a.return){let s=Kn[$e.cursor];if(s){mt(null),xe(s.uuid),He.current={uuid:s.uuid,firstPrompt:s.firstPrompt,titleFired:!0},lt(s.name),ys(s.uuid),Pt.current=[];let h=fs(e,s.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${s.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${s.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){mt(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){mt(s=>s&&{...s,query:s.query+c,cursor:0});return}return}if(a.tab&&!T&&ne){v(ne),Oe();return}if(!T&&ke.length>0&&!cr&&c&&/^[1-9]$/.test(c)){let s=ke[Number(c)-1];if(s){v(vt(s));return}}if(!T&&(Gn||ln)&&c==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let s=Gn!=null;us(Gn??ln).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?s?"\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.":s?"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&&s&&kr(null),u&&!s&&Fs(!0)});return}if(!Xs(c,a)){if(qs){if(a.upArrow){Ct(s=>Math.max(0,s-1));return}if(a.downArrow){Ct(s=>Math.min(pn.length-1,s+1));return}if(a.tab){v("/"+(pn[nn]?.name??"")+" "),Ct(0);return}if(a.return){let s=pn[nn];if(s){let h=T.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Mc(s.usage)&&!h){v("/"+s.name+" "),Ct(0);return}Zn("/"+s.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(T!==""&&Rt===null){eo(-1);return}let s=ur.current;if(!s.length)return;let h=Rt===null?s.length-1:Math.max(0,Rt-1);Mn(h),v(s[h]??"");return}if(a.downArrow){if(T!==""&&Rt===null){eo(1);return}let s=ur.current;if(Rt===null)return;let h=Rt+1;h>=s.length?(Mn(null),v("")):(Mn(h),v(s[h]??""));return}}if(a.return){Zn();return}if(a.backspace||a.delete){P();return}if(a.escape){v(""),Ct(0),Oe(),Fe([]),on(null),In.current=!0;return}c&&!a.ctrl&&!a.meta&&zs(c)}}}),Pe(()=>{if(N||M)return;let c=ht.current.shift();c!==void 0&&(fr([...ht.current]),Zn(c))},[N,M,Zn]),z(oe,{flexDirection:"column",width:Le,children:[vr!==null&&z(oe,{marginTop:1,flexDirection:"column",children:[vr.truncated&&E(A,{dimColor:!0,children:"\u2026"}),E(A,{children:vr.text})]}),N&&(Fn?E(lw,{p:Fn}):E(iw,{startTime:at.current,chars:Ed})),!N&&Is?E(sw,{text:Is}):null,E(oe,{borderStyle:"round",borderColor:Hs.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:T?Ks.map((c,a)=>{let s=k.text.slice(c.start,c.end),h=a===nr(Ks,k.pos),u=Math.min(k.pos,c.end)-c.start;return z(A,{children:[E(A,{color:q,children:a===0?"> ":" "}),h?z(sr,{children:[s.slice(0,u),E(Zt,{ch:s[u]??" "}),s.slice(u+1)]}):s||" "]},`${a}-${c.start}`)}):z(A,{children:[E(A,{color:q,children:"> "}),hr?E(Zt,{ch:" "}):ne&&!N&&We?z(sr,{children:[E(Zt,{ch:We[0],dim:!0}),E(A,{color:"gray",children:We.slice(1)})]}):ne&&!N?z(sr,{children:[E(Zt,{ch:ne[0],dim:!0}),E(A,{color:"gray",children:ne.slice(1)}),E(A,{dimColor:!0,children:" (tab)"})]}):(br.isSetup||!jd)&&!N?z(sr,{children:[E(Zt,{ch:br.text[0],dim:!0}),E(A,{color:"gray",children:br.text.slice(1)})]}):E(Zt,{ch:" "})]})}),Ns.length>0&&E(oe,{flexDirection:"column",paddingX:1,children:Ns.map((c,a)=>E(A,{color:"gray",children:`\u29D7 queued: ${c}`},`${a}-${c.slice(0,24)}`))}),Bn?E(Wc,{tab:Bn.tab,width:Le,version:o,engineVersion:vd}):ct?z(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Select model"}),E(A,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ue.map((c,a)=>z(A,{color:a===ct.cursor?q:void 0,children:[a===ct.cursor?"\u276F ":" ",`${a+1}. ${c.label}${a===ct.current?" \u2714":""}`.padEnd(16),E(A,{color:"gray",children:c.desc})]},c.label)),E(A,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):qe?z(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Switch connection profile"}),qe.rows.map((c,a)=>z(A,{color:a===qe.cursor?q:void 0,children:[a===qe.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===qe.current?" \u2714":""}`.padEnd(20),E(A,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?E(A,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),E(A,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Be?z(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Pick your Document360 environment"}),Be.rows.map((c,a)=>z(A,{color:a===Be.cursor?q:void 0,children:[a===Be.cursor?"\u276F ":" ",`${a+1}. ${c.name}`.padEnd(16),E(A,{color:"gray",children:c.apiUrl})]},c.name)),E(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):he?z(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Switch workspace"}),E(A,{dimColor:!0,children:`environment ${he.environment} \xB7 project ${he.projectName??`${he.projectId.slice(0,8)}\u2026`}`}),he.rows.map((c,a)=>z(A,{color:a===he.cursor?q:void 0,children:[a===he.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===he.current?" \u2714":""}`.padEnd(30),E(A,{color:"gray",children:c.type??""})]},c.id)),E(A,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):be?z(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Choose project"}),E(A,{dimColor:!0,children:`environment ${be.environment}`}),be.rows.map((c,a)=>z(A,{color:a===be.cursor?q:void 0,children:[a===be.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===be.current?" \u2714":""}`.padEnd(30),E(A,{color:"gray",children:c.sub??""})]},c.id)),E(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):me?(()=>{let a=Math.min(Math.max(0,me.cursor-Math.floor(7)),Math.max(0,me.rows.length-14)),s=me.rows.slice(a,a+14),h=me.rows.filter(u=>u.checked).length;return z(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:`Which folders back the user docs? (${h} selected of ${me.rows.length})`}),a>0?E(A,{dimColor:!0,children:` \u2191 ${a} more`}):null,s.map((u,y)=>{let b=a+y;return z(A,{color:b===me.cursor?q:void 0,children:[b===me.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Le-34)),E(A,{color:"gray",children:To(u)})]},u.path)}),a+14<me.rows.length?E(A,{dimColor:!0,children:` \u2193 ${me.rows.length-a-14} more`}):null,E(A,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Ve?z(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Which category? (pick one to scope to)"}),Ve.rows.map((c,a)=>{let s=a===Ve.cursor,h=`${a+1}.`.padEnd(3);return z(A,{color:s?q:void 0,children:[s?"\u276F ":" ",`${h} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Le-24))),E(A,{color:"gray",children:` ${c.token}`})]},c.token)}),E(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Xe?z(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Xe.rows.map((c,a)=>{let s=a===Xe.cursor,h=c.indent?" ":" ",u=`${a+1}.`.padEnd(3);return z(A,{color:s?q:void 0,bold:c.kind==="category"&&!s,children:[s?"\u276F ":" ",`${h}${u} ${c.label}`.padEnd(Math.min(56,Le-24)),c.note?E(A,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),E(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ve?z(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:`Preview article${ve.query?` \u2014 filter: ${ve.query}`:" (type to filter)"}`}),zn.length===0?E(A,{color:"gray",children:"no articles match"}):zn.map((c,a)=>z(A,{color:a===ve.cursor?q:void 0,children:[a===ve.cursor?"\u276F ":" ",c]},c)),E(A,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):$e?z(oe,{flexDirection:"column",paddingX:1,children:[E(A,{color:q,bold:!0,children:`Resume session${$e.query?` \u2014 filter: ${$e.query}`:" (type to filter)"}`}),Kn.length===0?E(A,{color:"gray",children:"no sessions match"}):Kn.map((c,a)=>z(A,{color:a===$e.cursor?q:void 0,children:[a===$e.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),E(A,{color:a===$e.cursor?q:"gray",children:c.firstPrompt.slice(0,Math.max(10,Le-40))})]},c.uuid)),E(A,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):qs?z(oe,{flexDirection:"column",children:[pn.map((c,a)=>z(A,{color:a===nn?q:void 0,children:[a===nn?"\u276F ":" ",c.usage.padEnd(22)," ",E(A,{color:a===nn?q:"gray",children:c.name==="model"&&mr?`${c.desc} (currently ${mr})`:c.desc})]},c.name)),E(A,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!T&&ke.length>0?z(oe,{flexDirection:"column",paddingX:1,children:[Es?E(A,{color:q,children:Es}):null,ke.map((c,a)=>{let s=vt(c),h=s.slice(0,Math.max(20,Le-5)),u=Le-h.length-7,y=u>=12?(Vc(c)??Oc(s)).slice(0,u):"";return z(A,{children:[E(A,{color:q,children:a+1})," ",h,y?E(A,{dimColor:!0,children:` \u2014 ${y}`}):null]},s)}),E(A,{dimColor:!0,children:`press 1-${ke.length} to fill \xB7 esc cancel`})]}):E(oe,{paddingX:1,children:z(A,{color:"gray",children:[Hs.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${mr??"model n/a"}${t.kind==="api"?Ls>0?` \xB7 ${ye(Ls)}`:"":Os>0?` \xB7 ${ot(Os)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as pw}from"react/jsx-runtime";async function Cd(e=process.cwd(),t="auto",n,o="0.0.0"){let r=uw(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:i}=dw(pw(xd,{cwd:e,auth:r,profileName:n,version:o}));await i(),process.stdout.write(`
|
|
360
|
+
`),process.exit(0)}W();import{writeCrashLog as Rd,isBenignTransportError as fw}from"document360-engine";var Pd=!1;function Rs(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Td(e){if(Pd)return;Pd=!0;let t=(n,o)=>{if(fw(o)){Rd({kind:n,level:"transport",message:Rs(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=Rd({kind:n,level:"fatal",message:Rs(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
361
|
+
`+C(`\u2717 d360-writer crashed: ${Rs(o)}`)+`
|
|
362
362
|
`),r&&process.stderr.write(f(` Crash details: ${r}`)+`
|
|
363
363
|
`+f(" Run: d360-writer logs")+`
|
|
364
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var
|
|
364
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var ww=mw(import.meta.url),ar=ww("../package.json");Td("d360-writer");var Ne=new hw;function Ps(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Ne.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=>{Ps(e),await lo({profile:e.profile,manual:e.manual})});Ne.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ps(e),await la({profile:e.profile})});Ne.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ps(e),await aa({profile:e.profile})});var Ts=Ne.command("profile").description("Manage connection profiles for the current repo");Ts.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>co(process.cwd()));Ts.command("use <name>").description("Set the default profile for this repo").action(e=>uo(process.cwd(),e));Ts.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>po(process.cwd(),e));var Sd=Ne.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Sd.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>qt(process.cwd(),e.profile));Sd.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await ea(process.cwd(),e,t.profile)});var Dd=Ne.command("project").description("Choose the Document360 project for this repo (active profile's identity)");Dd.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>io(process.cwd(),e.profile));Dd.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await na(process.cwd(),e,t.profile)});Ne.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(ko(),_a));await e()});Ne.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>pa());Ne.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(()=>(No(),Ml)),n=await t(process.cwd(),ar.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Ne.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(ar.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(gw.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 fa(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 Sc(e.cwd,e.auth,e.profile,ar.version):await Cd(e.cwd,e.auth,e.profile,ar.version)});Ne.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|