document360-writer 0.5.89 → 0.5.91
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 +111 -111
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Rd=Object.defineProperty;var Zn=(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)Rd(e,n,{get:t[n],enumerable:!0})};import Ye from"picocolors";var q,Pd,Td,Sd,Bs,un,f,R,L,N,O,le,Pe,U=Zn(()=>{"use strict";q="#7f56d9",[Pd,Td,Sd]=[127,86,217],Bs=e=>Ye.isColorSupported?`\x1B[38;2;${Pd};${Td};${Sd}m${e}\x1B[39m`:e,un=e=>Ye.bold(Bs(e)),f=e=>Ye.dim(e),R=e=>Ye.red(e),L=e=>Ye.yellow(e),N=e=>Ye.green(e),O=Bs,le=e=>Ye.gray(e),Pe=e=>Ye.bold(e)});import{existsSync as Mt,writeFileSync as pt,readFileSync as fu,readdirSync as mu}from"node:fs";import{join as hu}from"node:path";import{devHintsGuidePath as uo,hintsDir as la,architectureDir as fa,messagesDir as Tr,creatorNotesPath as ca,devhintsStatePath as ma,directivesPath as da,DIRECTIVES_HEADER as gu,roadmapPath as ua,ROADMAP_HEADER as wu,ensureDir as co,writeMessage as yu,listOpenForDev as ku}from"document360-engine";function ha(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
4
|
<!-- devhints script v${se} \xB7 maintained by document360-writer (/devhints). -->
|
|
5
5
|
|
|
@@ -193,7 +193,7 @@ do it**:
|
|
|
193
193
|
**Do NOT write or action the documentation yourself** \u2014 same boundary as Part 2. Writing the article is the
|
|
194
194
|
docs agent's job; it actions open directives on its next \`/catch-up\` (as drafts) and flips each to \`[done]\`
|
|
195
195
|
with the article it wrote. You are only the relay so the ask is captured durably and travels via git.
|
|
196
|
-
`}function
|
|
196
|
+
`}function bu(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
|
|
197
197
|
|
|
198
198
|
<!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
|
|
199
199
|
The builder agent reads this FIRST and treats it as authoritative when writing the architecture
|
|
@@ -207,60 +207,60 @@ Anything only a human knows that would help document this product. For example:
|
|
|
207
207
|
- Gotchas or non-obvious behavior.
|
|
208
208
|
|
|
209
209
|
(Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
|
|
210
|
-
`}function Wt(e){
|
|
211
|
-
`)}Mt(
|
|
212
|
-
`)}function
|
|
213
|
-
`)}function We(e){try{return
|
|
214
|
-
`)}),n.notifiedBuilder=!0))}catch{}return n}function
|
|
215
|
-
`)}function
|
|
216
|
-
`),"utf8")}async function Dr(){let e=process.cwd(),t=wa(e);if(Ht(t)&&!await yu({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=va(e)??ga(e),o=await pn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await pn({message:"Capture directory (where document360-capture .spec.ts files live):",default:ba}),i=await pn({message:"Screenshot output directory:",default:$a}),c=await pn({message:"Default connection profile name:",default:"berlin"}),p=await pn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),w={projectId:o,docsDir:ka,captureDir:r,outputDir:i,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Ca(e)},h=$u(e);h?.terminologyGlossary&&(w.terminologyGlossary=h.terminologyGlossary),ya(w,e),xa(e);let k=Wt(e);console.log(""),console.log(N(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of Ft(k))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function va(e){let t=mo(e,"package.json");if(!Ht(t))return null;try{return JSON.parse(wu(t,"utf8")).name??null}catch{return null}}function Ca(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Ht(mo(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=mo(e,n);Ht(o)&&!vu(o)&&t.push(n)}return t}function vu(e){try{return ku(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var ho=Jn(()=>{"use strict";U();Ke()});var vl={};Fs(vl,{doctorCommand:()=>bn,renderDoctorChecks:()=>xl,runDoctorChecks:()=>$l});import{existsSync as cf}from"node:fs";import{d360GetAll as df,getAccessToken as uf,isExpired as $i,loadProfileMap as pf,loadTokens as ff,packageSkillsDir as kl,projectConfigPath as mf,readProjectConfig as hf,DEFAULT_DOCS_DIR as gf,fetchManifestSummary as yf,resolveActiveProfile as wf,classifyClaudeAuth as kf,CLAUDE_CODE_SETUP_HINT as bl,resolveModelSetting as bf,probeModel as $f,detectAppType as xf,playbookSkillName as vf,D360AuthError as Cf}from"document360-engine";async function $l(e){let t=[],n=Number(process.versions.node.split(".")[0]);t.push(n>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let o=kf();o.state==="ready"?t.push({level:"ok",label:`Claude auth: ${o.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):o.state==="maybe"?t.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${bl}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:bl});let r=bf(e);if(t.push({level:"ok",label:`Model: ${r.model} (${r.source==="auto"?"auto \u2014 right-sized for docs; /model to change":r.source})`}),o.state==="ready"){let T=await $f(e,r.model??void 0);T.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(T.latencyMs/1e3).toFixed(1)}s`}):T.timedOut?t.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):t.push({level:"fail",label:`Model call failed \u2014 ${T.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 i=hf(e);if(!i)return t.push({level:"fail",label:`No ${mf(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${i.projectId}`});let c=(i.docsDir??gf).replace(/\/+$/,"");t.push(i.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=i.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let w=i.appType??xf(e);if(w){let T=i.appType?"from config":"auto-detected",P=w==="web"||w==="cli";t.push({level:"ok",label:`Genre: ${w} (${T})${P?` \u2192 ${vf(w)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else t.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let h;try{h=wf(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(T){return t.push({level:"fail",label:`Profile config: ${T.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=ff(h.name);k?$i(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):$i(k)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(k.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${h.name})`}),t.push(h.project.workspaceId?{level:"ok",label:`Workspace: ${h.project.workspaceName??h.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let D=pf(e,h.name);D?D.projectId&&h.project.projectId&&D.projectId!==h.project.projectId?t.push({level:"fail",label:`Category map projectId (${D.projectId}) \u2260 profile projectId (${h.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(D.articles).length} articles, ${Object.keys(D.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${h.name}" (created on first /publish)`}),t.push(cf(kl())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${kl()}`,fix:"Reinstall document360-writer (broken install)"});let $=Se(e);if($.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${se})`}):$.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${$.completedVersion}, current is v${se}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!$i(k)||k.refreshToken)){let T={profile:h.name,connection:h.connection};try{await uf(T);let S=await df(T,"/v3/projects");t.push({level:"ok",label:`API reachable (${h.connection.apiUrl}) \u2014 ${S.length} project(s) visible`})}catch(S){t.push({level:"fail",label:`API call failed: ${S.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let P=D?.projectId??h.project.projectId;if(P&&h.project.workspaceId)try{let S=await yf(T,P,h.project.workspaceId);if(S){let I=(S.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${h.connection.name} (${S.languages?.length??0} language${(S.languages?.length??0)===1?"":"s"}) \xB7 hash ${I||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${h.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 Cf||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(S.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${h.project.projectName??P})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):t.push({level:"warn",label:`Workspace sync manifest: probe failed (${S.message.slice(0,80)})`})}}return t}function xl(e){let t=[""];for(let r of e){let i=r.level==="ok"?N("\u2713"):r.level==="warn"?L("\u26A0"):x("\u2717");t.push(` ${i} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${_(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?N(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):x(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function bn(e,t){console.log(f("Running checks\u2026"));for(let n of xl(await $l(t.cwd)))console.log(n);return{kind:"continue"}}var Po=Jn(()=>{"use strict";Ke();U()});import{Command as Hg}from"commander";import{createRequire as qg}from"node:module";import{AUTH_MODES as Bg}from"document360-engine";import{input as Ud}from"@inquirer/prompts";import{loginPkce as Wd,refreshTokens as Fd,toStoredTokens as zs,clearTokens as Hd,decodeJwtClaims as Ys,isExpired as qd,loadTokens as Bd,saveTokens as Ks,resolveActiveProfile as no,setProfileProject as Vd,readProjectConfig as Gd}from"document360-engine";U();import{select as Pd}from"@inquirer/prompts";import{resolveActiveProfile as Td,setProfileProject as Sd,resolveProjectId as Dd,listWorkspaces as Ad}from"document360-engine";async function dn(e,t){let n=Td(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Dd(o);return{workspaces:await Ad(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var qs=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function br(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 Zn(e,t,n,o,r){Sd(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Bs(e,t,n){let o;try{o=await dn(e,n)}catch(i){return console.log(x(`Could not list workspaces: ${i.message}`)),1}let r=br(o.workspaces,t);return r?(Zn(e,o.profile,o.projectId,r.id,r.name),console.log(N(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(x(`No workspace matches "${t}". Available: ${o.workspaces.map(i=>i.name??i.id).join(", ")}`)),1)}async function Ot(e,t){let n;try{n=await dn(e,t)}catch(h){console.log(x(`Could not list workspaces: ${h.message}`));return}let{workspaces:o,projectId:r,profile:i,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===c?_("\u25CF"):" "} ${qs(h)} ${f(h.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Pd({message:"Select the Document360 workspace for this repo:",choices:o.map(h=>({name:`${qs(h)}${h.id===c?" (current)":""}`,value:h.id}))}),w=o.find(h=>h.id===p);Zn(e,i,r,p,w?.name),console.log(N(`\u2713 Workspace set to "${w?.name??p}" for profile "${i}".`))}U();import{select as jd}from"@inquirer/prompts";import{resolveActiveProfile as Ed,setProfileProject as Nd,listProjects as Id}from"document360-engine";async function ze(e,t){let n=Ed(e,t),o={profile:n.name,connection:n.connection};return{projects:await Id(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Vs=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function $r(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 eo(e,t,n,o){Nd(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Gs(e,t,n){let o;try{o=await ze(e,n)}catch(i){return console.log(x(`Could not list projects: ${i.message}`)),1}let r=$r(o.projects,t);return r?(eo(e,o.profile,r.id,r.name),console.log(N(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(x(`No project matches "${t}". Available: ${o.projects.map(i=>i.name??i.id).join(", ")}`)),1)}async function to(e,t){let n;try{n=await ze(e,t)}catch(w){console.log(x(`Could not list projects: ${w.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 w of o)console.log(` ${w.id===i?_("\u25CF"):" "} ${Vs(w)} ${f(w.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await jd({message:"Select the Document360 project for this repo:",choices:o.map(w=>({name:`${Vs(w)}${w.id===i?" (current)":""}`,value:w.id}))}),p=o.find(w=>w.id===c);eo(e,r,c,p?.name),console.log(N(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}U();import _d from"picocolors";function Ld(e=process.env){return e.FORCE_HYPERLINK==="0"||!_d.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 Od(e,t=e,n){return Ld(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Md=/https?:\/\/[^\s\x1b]+/g;function un(e,t){return e.replace(Md,n=>Od(n,n,t))}function Xs(e){return{...Ys(e.idToken)??{},...Ys(e.accessToken)??{}}}function oo(e){let t=Xs(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 ro(e){let t=no(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 Wd(n,{manual:e.manual,promptForRedirect:i=>Ud({message:i})},i=>console.log(un(i))),r=zs(t.name,o);if(Ks(r),await xr(r,t.name,i=>console.log(f(i))),console.log(""),console.log(N(`\u2713 Logged in to "${t.name}" as ${oo(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{Gd(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Ot(process.cwd(),t.name))}catch{}}async function xr(e,t,n){let r=Xs(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(no(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await ze(process.cwd(),t);c=p.find(w=>w.id===r)?.name}catch{}Vd(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Qs(e){let t=no(process.cwd(),e.profile),n=t.connection,o=Bd(t.name);if(!o){console.log(x(`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 ${_(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${oo(o)}`),qd(o))if(o.refreshToken)try{let r=zs(t.name,await Fd(n,o.refreshToken));Ks(r),console.log(N(`\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 Js(e){let t=no(process.cwd(),e.profile);Hd(t.name)?console.log(N(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}U();import{readProjectConfig as Zs,writeProjectConfig as Yd,resolveActiveProfile as zd,loadTokens as Kd,isExpired as Xd}from"document360-engine";function io(e){let t=Zs(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(x("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?_("\u25CF "):" ",i=o.production?L(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Kd(n),w=p?Xd(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${c}${i} [${w}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function so(e,t){let n=Zs(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(x(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Yd(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(N(`\u2713 Default profile is now "${t}"${o}`))}function ao(e,t){try{let n=zd(e,t);console.log(""),console.log(`Profile ${_(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(x(n.message)),process.exitCode=1}}U();import{existsSync as Qd,readdirSync as Jd,statSync as ea}from"node:fs";import{join as ta}from"node:path";import{apiLogDir as Zd}from"document360-engine";function na(){let e=Zd();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Qd(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Jd(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=(ea(ta(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=(ea(ta(e,r)).size/1024).toFixed(1);console.log(` ${x(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("")}U();import{createSession as eu,resolveAuth as tu,findByName as nu,slugify as ou,touchSession as ru,upsertSession as iu,resolveActiveProfile as su}from"document360-engine";async function oa(e,t,n,o,r,i){let c=tu(n);c.kind==="none"&&(console.error(""),console.error(x("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=su(e,r)}catch($){console.error(x(`Document360 profile error: ${$.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),i||(console.error(x("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let w;if(o){let $=nu(e,o);$||(console.error(x(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),w=$.uuid,console.error(f(`Resuming "${$.name}"`))}let h=eu({cwd:e,resume:w,profileName:r,allowProdWrites:i===!0}),k=w??null,D=1;for await(let $ of h.send(t))switch($.type){case"session":if(!k){k=$.sessionId;let T=new Date().toISOString();iu({uuid:k,name:ou(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:T,updatedAt:T})}break;case"text":process.stdout.write($.delta);break;case"tool":console.error(le(` \u2699 ${$.name}`));break;case"result":D=$.ok?0:1,console.error(f(`(${$.inputTokens}\u2192${$.outputTokens} tokens`+($.costUsd>0?`, $${$.costUsd<.01?$.costUsd.toFixed(4):$.costUsd.toFixed(2)}`:"")+")")),$.ok||console.error(x("agent finished with an error result"));break;case"error":console.error(""),console.error(x(`agent error: ${$.message}`)),process.exit(1)}k&&ru(k),process.stdout.write(`
|
|
217
|
-
`),process.exit(
|
|
210
|
+
`}function Wt(e){co(la(e)),co(fa(e)),co(Tr(e));for(let n of[la(e),Tr(e)]){let o=hu(n,".gitkeep");Mt(o)||pt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
211
|
+
`)}Mt(ca(e))||pt(ca(e),bu()),Mt(da(e))||pt(da(e),gu),Mt(ua(e))||pt(ua(e),wu),pt(uo(e),ha());let t=Se(e);return wa(e,new Date().toISOString()),t}async function ga(e,t){for(let n of Ft(Wt(t.cwd)))console.log(n);return{kind:"continue"}}function ft(){return[`This is document360-writer's dev hand-off setup (v${se}).`,'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; 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 \u2014 fold durable facts into the architecture brief and/or drop"," a reply (`from: dev`, `kind: answer`, `re: <id>`) \u2014 then set the question's frontmatter `status: done`."," If there are none, continue.","5. Then STOP and ask me for tribal knowledge \u2014 present it as a clearly-marked, standalone prompt on its"," own line (NOT buried in prose) and WAIT for my reply before doing anything else. Use this shape:",' "\u23F8 YOUR INPUT NEEDED \u2014 Any tribal knowledge that would help document this product? (folder map,',` terminology, what to prioritize or skip, gotchas.) Type it below, or reply 'none' / 'carry on' to skip."`," If I give you anything, phrase it clearly and append it to `.d360-writer/architecture/CREATOR-NOTES.md`"," (keep the existing header comment and every note already there; only add). If I say 'none'/'carry on', continue.",`6. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${se},`,' "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(`
|
|
212
|
+
`)}function Sr(e){try{let t=fu(ma(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function wa(e,t){let o={...Sr(e)??{},emittedVersion:se,emittedAt:t};pt(ma(e),`${JSON.stringify(o,null,2)}
|
|
213
|
+
`)}function We(e){try{return mu(fa(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Se(e){let n=Sr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<se?"stale":"current",completedVersion:n}}function po(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:se};try{if(!Mt(uo(e)))return n;let o=Sr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let i=o?.completedVersion??0;se>r&&(co(Tr(e)),pt(uo(e),ha()),wa(e,t),n.guideRefreshed=!0),se>i&&(ku(e).some(p=>p.kind==="request"&&p.subject.startsWith(pa))||(yu(e,{id:`onb${se}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${pa}${se})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${se}${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:","",ft()].join(`
|
|
214
|
+
`)}),n.notifiedBuilder=!0))}catch{}return n}function fo(e){if(!Mt(uo(e)))return[];let t=Se(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${se}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Ut,ft(),Ut,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Dr(){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(`
|
|
215
|
+
`)}function mo(){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):",Ut,Dr(),Ut]}function Ft(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${se}.`," 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):",Ut,ft(),Ut,"","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 Ut,se,pa,Ke=Zn(()=>{"use strict";Ut="-".repeat(64),se=7;pa="Re-run dev\u2194docs onboarding (protocol v"});var Ta={};qs(Ta,{initCommand:()=>jr,scaffoldInit:()=>Ar});import{input as mn,confirm as $u}from"@inquirer/prompts";import{basename as ya,join as ho}from"node:path";import{existsSync as Ht,readFileSync as xu,readdirSync as vu,writeFileSync as Cu}from"node:fs";import{writeProjectConfig as ka,readProjectConfig as Ru,projectConfigPath as ba,writerDir as Pu,DEFAULT_DOCS_DIR as $a,DEFAULT_CAPTURE_DIR as xa,DEFAULT_OUTPUT_DIR as va}from"document360-engine";function Ar(e,t="berlin"){let n=ba(e);if(Ht(n))return{created:!1,path:n,profileName:""};let o={projectId:Ra(e)??ya(e),docsDir:$a,captureDir:xa,outputDir:va,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Pa(e)};return ka(o,e),Ca(e),{created:!0,path:n,profileName:t}}function Ca(e){let t=ho(Pu(e),".gitignore");Ht(t)||Cu(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
216
|
+
`),"utf8")}async function jr(){let e=process.cwd(),t=ba(e);if(Ht(t)&&!await $u({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Ra(e)??ya(e),o=await mn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await mn({message:"Capture directory (where document360-capture .spec.ts files live):",default:xa}),i=await mn({message:"Screenshot output directory:",default:va}),c=await mn({message:"Default connection profile name:",default:"berlin"}),p=await mn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),m={projectId:o,docsDir:$a,captureDir:r,outputDir:i,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Pa(e)},k=Ru(e);k?.terminologyGlossary&&(m.terminologyGlossary=k.terminologyGlossary),ka(m,e),Ca(e);let g=Wt(e);console.log(""),console.log(N(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${O(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let T of Ft(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 Ra(e){let t=ho(e,"package.json");if(!Ht(t))return null;try{return JSON.parse(xu(t,"utf8")).name??null}catch{return null}}function Pa(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Ht(ho(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=ho(e,n);Ht(o)&&!Tu(o)&&t.push(n)}return t}function Tu(e){try{return vu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var go=Zn(()=>{"use strict";U();Ke()});var Rl={};qs(Rl,{doctorCommand:()=>$n,renderDoctorChecks:()=>Cl,runDoctorChecks:()=>vl});import{existsSync as ff}from"node:fs";import{d360GetAll as mf,getAccessToken as hf,isExpired as vi,loadProfileMap as gf,loadTokens as wf,packageSkillsDir as $l,ENGINE_VERSION as yf,projectConfigPath as kf,readProjectConfig as bf,DEFAULT_DOCS_DIR as $f,fetchManifestSummary as xf,resolveActiveProfile as vf,classifyClaudeAuth as Cf,CLAUDE_CODE_SETUP_HINT as xl,resolveModelSetting as Rf,probeModel as Pf,detectAppType as Tf,playbookSkillName as Sf,D360AuthError as Df}from"document360-engine";async function vl(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${yf}`});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=Cf();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. ${xl}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:xl});let i=Rf(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 C=await Pf(e,i.model??void 0);C.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(C.latencyMs/1e3).toFixed(1)}s`}):C.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 ${C.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 c=bf(e);if(!c)return n.push({level:"fail",label:`No ${kf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${c.projectId}`});let p=(c.docsDir??$f).replace(/\/+$/,"");n.push(c.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=c.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=c.appType??Tf(e);if(k){let C=c.appType?"from config":"auto-detected",E=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${C})${E?` \u2192 ${Sf(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=vf(e),n.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(C){return n.push({level:"fail",label:`Profile config: ${C.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let T=wf(g.name);T?vi(T)&&!T.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):vi(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 $=gf(e,g.name);$?$.projectId&&g.project.projectId&&$.projectId!==g.project.projectId?n.push({level:"fail",label:`Category map projectId (${$.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($.articles).length} articles, ${Object.keys($.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),n.push(ff($l())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${$l()}`,fix:"Reinstall document360-writer (broken install)"});let I=Se(e);if(I.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${se})`}):I.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${I.completedVersion}, current is v${se}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),T&&(!vi(T)||T.refreshToken)){let C={profile:g.name,connection:g.connection};try{await hf(C);let S=await mf(C,"/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 E=$?.projectId??g.project.projectId;if(E&&g.project.workspaceId)try{let S=await xf(C,E,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 Df||/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??E})`,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 Cl(e){let t=[""];for(let r of e){let i=r.level==="ok"?N("\u2713"):r.level==="warn"?L("\u26A0"):R("\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?N(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):R(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function $n(e,t){console.log(f("Running checks\u2026"));for(let n of Cl(await vl(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var So=Zn(()=>{"use strict";Ke();U()});import{Command as Yg}from"commander";import{createRequire as zg}from"node:module";import{AUTH_MODES as Kg}from"document360-engine";import{input as Hd}from"@inquirer/prompts";import{loginPkce as qd,refreshTokens as Bd,toStoredTokens as Xs,clearTokens as Vd,decodeJwtClaims as Ks,isExpired as Gd,loadTokens as Yd,saveTokens as Qs,resolveActiveProfile as oo,setProfileProject as zd,readProjectConfig as Kd}from"document360-engine";U();import{select as Dd}from"@inquirer/prompts";import{resolveActiveProfile as Ad,setProfileProject as jd,resolveProjectId as Ed,listWorkspaces as Nd}from"document360-engine";async function pn(e,t){let n=Ad(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Ed(o);return{workspaces:await Nd(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Vs=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function xr(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 eo(e,t,n,o,r){jd(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Gs(e,t,n){let o;try{o=await pn(e,n)}catch(i){return console.log(R(`Could not list workspaces: ${i.message}`)),1}let r=xr(o.workspaces,t);return r?(eo(e,o.profile,o.projectId,r.id,r.name),console.log(N(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(R(`No workspace matches "${t}". Available: ${o.workspaces.map(i=>i.name??i.id).join(", ")}`)),1)}async function Lt(e,t){let n;try{n=await pn(e,t)}catch(k){console.log(R(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:i,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===c?O("\u25CF"):" "} ${Vs(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Dd({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${Vs(k)}${k.id===c?" (current)":""}`,value:k.id}))}),m=o.find(k=>k.id===p);eo(e,i,r,p,m?.name),console.log(N(`\u2713 Workspace set to "${m?.name??p}" for profile "${i}".`))}U();import{select as Id}from"@inquirer/prompts";import{resolveActiveProfile as _d,setProfileProject as Od,listProjects as Ld}from"document360-engine";async function ze(e,t){let n=_d(e,t),o={profile:n.name,connection:n.connection};return{projects:await Ld(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Ys=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function vr(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 to(e,t,n,o){Od(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function zs(e,t,n){let o;try{o=await ze(e,n)}catch(i){return console.log(R(`Could not list projects: ${i.message}`)),1}let r=vr(o.projects,t);return r?(to(e,o.profile,r.id,r.name),console.log(N(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(R(`No project matches "${t}". Available: ${o.projects.map(i=>i.name??i.id).join(", ")}`)),1)}async function no(e,t){let n;try{n=await ze(e,t)}catch(m){console.log(R(`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"):" "} ${Ys(m)} ${f(m.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await Id({message:"Select the Document360 project for this repo:",choices:o.map(m=>({name:`${Ys(m)}${m.id===i?" (current)":""}`,value:m.id}))}),p=o.find(m=>m.id===c);to(e,r,c,p?.name),console.log(N(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}U();import Md from"picocolors";function Ud(e=process.env){return e.FORCE_HYPERLINK==="0"||!Md.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 Wd(e,t=e,n){return Ud(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Fd=/https?:\/\/[^\s\x1b]+/g;function fn(e,t){return e.replace(Fd,n=>Wd(n,n,t))}function Js(e){return{...Ks(e.idToken)??{},...Ks(e.accessToken)??{}}}function ro(e){let t=Js(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 io(e){let t=oo(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 qd(n,{manual:e.manual,promptForRedirect:i=>Hd({message:i})},i=>console.log(fn(i))),r=Xs(t.name,o);if(Qs(r),await Cr(r,t.name,i=>console.log(f(i))),console.log(""),console.log(N(`\u2713 Logged in to "${t.name}" as ${ro(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{Kd(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Lt(process.cwd(),t.name))}catch{}}async function Cr(e,t,n){let r=Js(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(oo(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await ze(process.cwd(),t);c=p.find(m=>m.id===r)?.name}catch{}zd(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Zs(e){let t=oo(process.cwd(),e.profile),n=t.connection,o=Yd(t.name);if(!o){console.log(R(`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":""}: ${ro(o)}`),Gd(o))if(o.refreshToken)try{let r=Xs(t.name,await Bd(n,o.refreshToken));Qs(r),console.log(N(`\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 ea(e){let t=oo(process.cwd(),e.profile);Vd(t.name)?console.log(N(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}U();import{readProjectConfig as ta,writeProjectConfig as Xd,resolveActiveProfile as Qd,loadTokens as Jd,isExpired as Zd}from"document360-engine";function so(e){let t=ta(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(R("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"):"",c=o.connection.environment??"(inline)",p=Jd(n),m=p?Zd(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${O(n)} \u2192 ${c}${i} [${m}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function ao(e,t){let n=ta(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(R(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Xd(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(N(`\u2713 Default profile is now "${t}"${o}`))}function lo(e,t){try{let n=Qd(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(R(n.message)),process.exitCode=1}}U();import{existsSync as eu,readdirSync as tu,statSync as na}from"node:fs";import{join as oa}from"node:path";import{apiLogDir as nu}from"document360-engine";function ra(){let e=nu();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!eu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=tu(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=(na(oa(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=(na(oa(e,r)).size/1024).toFixed(1);console.log(` ${R(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("")}U();import{createSession as ou,resolveAuth as ru,findByName as iu,slugify as su,touchSession as au,upsertSession as lu,resolveActiveProfile as cu}from"document360-engine";async function ia(e,t,n,o,r,i){let c=ru(n);c.kind==="none"&&(console.error(""),console.error(R("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)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=cu(e,r)}catch($){console.error(R(`Document360 profile error: ${$.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),i||(console.error(R("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 $=iu(e,o);$||(console.error(R(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),m=$.uuid,console.error(f(`Resuming "${$.name}"`))}let k=ou({cwd:e,resume:m,profileName:r,allowProdWrites:i===!0}),g=m??null,T=1;for await(let $ of k.send(t))switch($.type){case"session":if(!g){g=$.sessionId;let I=new Date().toISOString();lu({uuid:g,name:su(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:I,updatedAt:I})}break;case"text":process.stdout.write($.delta);break;case"tool":console.error(le(` \u2699 ${$.name}`));break;case"result":T=$.ok?0:1,console.error(f(`(${$.inputTokens}\u2192${$.outputTokens} tokens`+($.costUsd>0?`, $${$.costUsd<.01?$.costUsd.toFixed(4):$.costUsd.toFixed(2)}`:"")+")")),$.ok||console.error(R("agent finished with an error result"));break;case"error":console.error(""),console.error(R(`agent error: ${$.message}`)),process.exit(1)}g&&au(g),process.stdout.write(`
|
|
217
|
+
`),process.exit(T)}import{createInterface as Zm}from"node:readline/promises";import{createSession as ts,resolveAuth as eh,getSession as th,setTitle as nh,slugify as oh,touchSession as pc,upsertSession as rh,generateTitle as ih,resolveActiveProfile as fc,resolveModelSetting as sh,readProjectConfig as ah,resolveAndPersistAppType as lh,decodeJwtClaims as uc,isExpired as ch,loadTokens as dh,isDirectiveMention as uh,stripDirectiveMention as ph,appendDirective as fh,reconcileUpgradeActions as mh,stampArticles as hh,listArticleFiles as gh,CONTENT_CAP_VERSION as wh}from"document360-engine";import{ENGINE_VERSION as uu}from"document360-engine";var Te=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --all to author capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then run d360-capture in your app's repo \u2014 it signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot --list",s:"See capture status \u2014 which specs exist and which are done."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"d360-capture is a separate Playwright CLI \u2014 run it in the app's repo (needs its URL + a login)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/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:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"Author capture specs (--all / --list)."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/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 du(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 sa(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 Te){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(du(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function Rr(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:uu}:void 0;for(let o of sa(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"}}U();import{getSession as pu}from"document360-engine";async function aa(e,t){let n=t.currentUuid(),o=n?pu(n):void 0;return console.log(o?f(`
|
|
218
218
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
219
219
|
`):f(`
|
|
220
220
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
221
|
-
`)),{kind:"clear"}}async function
|
|
221
|
+
`)),{kind:"clear"}}async function Pr(){return{kind:"exit"}}go();U();import{readMcpConfig as Er,writeMcpConfig as Sa}from"document360-engine";async function wo(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Su(),{kind:"continue"}):t==="add"?(Du(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Au(e.slice(1)),{kind:"continue"}):(console.log(R(`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 Su(){let e=Er(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
|
|
222
222
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
223
|
-
`));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(` ${
|
|
224
|
-
`),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(
|
|
225
|
-
`)}),
|
|
226
|
-
`)},
|
|
227
|
-
`)}function
|
|
228
|
-
`);return` ${r} ${c}`+p.map(
|
|
229
|
-
${i}${
|
|
223
|
+
`));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 Du(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(R("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(R(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Er(),i;if(n==="stdio")i={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let m=o[++p],k=m?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(R(`-H expects key:value (no spaces). Got: ${m??"(nothing)"}`));return}c[k[1].trim()]=k[2].trim()}else{console.log(R(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}i={type:n,url:o[0],headers:Object.keys(c).length>0?c:void 0}}r.servers[t]=i,Sa(r),console.log(""),console.log(N(`\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 Au(e){let t=e[0];if(!t){console.log(R("Usage: /mcp remove <name>"));return}let n=Er();if(!n.servers[t]){console.log(R(`No server named "${t}".`));return}delete n.servers[t],Sa(n),console.log(N(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}U();import{readFileSync as Vu}from"node:fs";import{join as Gu}from"node:path";import{select as Yu}from"@inquirer/prompts";import{computeSyncStatus as yo,planPartitions as zu,relatedArticlePaths as Ku,resolveModelForOperation as Xu,runPartitioned as Qu,loadProfileMap as Ju,resolveActiveProfile as Zu,resolveCrossLinks as ep,applyStructureOrder as Ma,orderSyncLine as Ua,applyRelatedArticles as Wa,relatedSyncLine as Fa}from"document360-engine";import Q from"picocolors";import Ia from"wrap-ansi";import Mr from"string-width";U();import Xe from"picocolors";import Nr from"wrap-ansi";import Ir from"string-width";var Da=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Aa=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),ja=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function ju(e){let t=e.replace(/\r/g,"").split(`
|
|
224
|
+
`),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(Da(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Aa(t[o+1])){let p=ja(r);o+=2;let m=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)m.push(ja(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 c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Da(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Aa(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function _r(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Xe.bold(t.slice(2,-2)):t.startsWith("`")?O(t.slice(1,-1)):Xe.italic(t.slice(1,-1)))}var Eu=(e,t)=>e+" ".repeat(Math.max(0,t-Ir(e)));function Nu(e,t,n){let o=e.length,r=e.map((C,E)=>Math.max(Ir(C),...t.map(S=>Ir(S[E]??"")))),i=Math.max(24,n),c=3*o+1,p=[...r],m=()=>p.reduce((C,E)=>C+E,0)+c,k=0;for(;m()>i&&k++<1e4;){let C=-1,E=6;for(let S=0;S<o;S++)p[S]>E&&(E=p[S],C=S);if(C===-1)break;p[C]-=1}let g=(C,E,S)=>Xe.gray(C+p.map(M=>"\u2500".repeat(M+2)).join(E)+S),T=Xe.gray("\u2502"),$=(C,E)=>{let S=p.map((J,X)=>{let ae=C[X]??"",kt=E?Xe.bold(ae):_r(ae);return Nr(kt,J,{hard:!0}).split(`
|
|
225
|
+
`)}),M=Math.max(...S.map(J=>J.length)),B=[];for(let J=0;J<M;J++)B.push(p.map((X,ae)=>`${T} ${Eu(S[ae][J]??"",X)} `).join("")+T);return B.join(`
|
|
226
|
+
`)},I=[g("\u250C","\u252C","\u2510"),$(e,!0)];return I.push(t.length===0?g("\u2514","\u2534","\u2518"):g("\u251C","\u253C","\u2524")),t.forEach((C,E)=>{I.push($(C,!1)),I.push(E===t.length-1?g("\u2514","\u2534","\u2518"):g("\u251C","\u253C","\u2524"))}),I.join(`
|
|
227
|
+
`)}function Iu(e,t){switch(e.kind){case"heading":return Xe.bold(e.text);case"hr":return Xe.gray("\u2500".repeat(t));case"para":return Nr(_r(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),[c="",...p]=Nr(_r(o.text),Math.max(10,t-i.length)).split(`
|
|
228
|
+
`);return` ${r} ${c}`+p.map(m=>`
|
|
229
|
+
${i}${m}`).join("")}).join(`
|
|
230
230
|
`)}case"code":return e.lines.map(n=>Xe.gray(" "+n)).join(`
|
|
231
|
-
`);case"table":return
|
|
232
|
-
|
|
233
|
-
`)}U();import
|
|
234
|
-
`);let r=2,i=3,c=
|
|
235
|
-
`);let
|
|
236
|
-
`)}var
|
|
237
|
-
`).flatMap(
|
|
238
|
-
`)),
|
|
239
|
-
`+p.map((
|
|
231
|
+
`);case"table":return Nu(e.header,e.rows,t)}}function Or(e,t){let n=Math.max(20,t);return ju(e).map(o=>Iu(o,n)).join(`
|
|
232
|
+
|
|
233
|
+
`)}U();import _u from"picocolors";var Ou=[127,86,217],Lu=[22,38,43],Ea={T:Ou,E:Lu},hn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Lr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Mu=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Na(){if(!_u.isColorSupported)return[];let e=hn[0].length,t=[];for(let n=0;n<hn.length;n+=2){let o="";for(let r=0;r<e;r++){let i=Ea[hn[n][r]],c=n+1<hn.length?Ea[hn[n+1][r]]:void 0;i&&c?o+=`${Lr(i)}${Mu(c)}\u2580\x1B[49m\x1B[39m`:i?o+=`${Lr(i)}\u2580\x1B[39m`:c?o+=`${Lr(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function gn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function he(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Qe(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var qt=(e,t)=>` ${e.padEnd(13)}${t}`;function Uu(e,t){let n=[un("\u270E document360-writer")+Q.gray(` v${e.version} \xB7 engine v${e.engineVersion}`),Q.gray(" Reads your code, writes your docs."),"",qt("Claude:",`${e.claude}${Q.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),qt("Document360:",e.configured?e.loggedOut?Q.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?Q.gray(` (${e.sessionHint})`):""}`:Q.yellow("not set up \u2014 run /init")),qt("Profile:",e.configured?`${e.profile}${Q.gray(` (${e.apiUrl})`)}${e.prod?Q.bold(Q.yellow(" \u26A0 PRODUCTION")):""}`:Q.gray("\u2014 (run /init)")),qt("Project:",e.project),qt("Mode:",Q.gray(e.mode)),qt("cwd:",Q.gray(e.cwd))],o=Na();if(o.length===0)return n.join(`
|
|
234
|
+
`);let r=2,i=3,c=Mr(o[0]);if(!(t>=r+c+i+Math.max(...n.map(g=>Mr(g)))))return[...o.map(g=>" "+g),...n].join(`
|
|
235
|
+
`);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(c);k.push((" ".repeat(r)+T+" ".repeat(i)+(n[g]??"")).trimEnd())}return k.join(`
|
|
236
|
+
`)}var Wu={error:Q.red,warn:Q.yellow,ok:Q.green,info:Q.gray};function Ur(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Uu(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",i=Math.max(10,n-4),c=50,p=e.text.split(`
|
|
237
|
+
`).flatMap(k=>Ia(k,i,{hard:!0}).split(`
|
|
238
|
+
`)),m=Math.max(0,p.length-c);return m>0&&(p=[...p.slice(0,c),Q.dim(`\u2026 +${m} more lines`)]),`
|
|
239
|
+
`+p.map((k,g)=>o+(g===0?O(" \u276F "):" ")+k+" ".repeat(Math.max(0,i-Mr(k))+1)+r).join(`
|
|
240
240
|
`)}case"assistant":return`
|
|
241
|
-
`+
|
|
242
|
-
`+
|
|
243
|
-
`)}case"diff":{let o=c=>c===1?"":"s",i=[
|
|
244
|
-
`)}case"link":return e.lines.map(o=>
|
|
241
|
+
`+Or(e.text,n);case"tool":{let o=e.arg!==null?Q.gray(`${e.sep}(${e.arg})`):"";return`
|
|
242
|
+
`+Ia(Q.green("\u25CF ")+Q.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?Q.red:Q.gray,r=e.lines.map((i,c)=>o((c===0?" \u23BF ":" ")+i));return e.hidden>0&&r.push(Q.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
243
|
+
`)}case"diff":{let o=c=>c===1?"":"s",i=[Q.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&i.push(Q.dim(` \u2026 +${e.hidden} more diff lines`)),i.join(`
|
|
244
|
+
`)}case"link":return e.lines.map(o=>O(fn(` \u2B95 ${o}`))).join(`
|
|
245
245
|
`);case"preview":return`
|
|
246
|
-
`+
|
|
247
|
-
|
|
248
|
-
`+
|
|
249
|
-
`+
|
|
250
|
-
`+(e.ok?
|
|
251
|
-
`)}import{resolveActiveProfile as
|
|
252
|
-
`)}var
|
|
253
|
-
`)}function
|
|
254
|
-
`),display:"/audit"}}U();import{checkbox as
|
|
255
|
-
`);return
|
|
256
|
-
`)||
|
|
257
|
-
`},r=o(e),i=o(t);if(r===i)return null;let c=Math.max(20,n-10),p=
|
|
246
|
+
`+un(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
247
|
+
|
|
248
|
+
`+Or(e.text,n);case"note":return`
|
|
249
|
+
`+Wu[e.tone](fn(e.text));case"done":return`
|
|
250
|
+
`+(e.ok?Q.magenta("\u2736 "):Q.red("\u2736 "))+Q.gray(`Cooked for ${gn(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${he(e.costUsd)}`:""))}}function _a(e,t){return e.map(n=>Ur(n,t)).join(`
|
|
251
|
+
`)}import{resolveActiveProfile as Fu,loadTokens as Hu,isExpired as qu,decodeJwtClaims as Oa}from"document360-engine";function Bu(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Fe(e,t){try{let n=Fu(e,t),o=Hu(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(qu(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let c={...Oa(o.idToken)??{},...Oa(o.accessToken)??{}}.doc360_project_id;if(typeof c=="string"&&c&&c!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${Bu(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var wn=3;function Fr(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(`
|
|
252
|
+
`)}var La={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Bt(e){return e.filter(t=>t.path!==null&&t.status in La&&!t.link).map(t=>({path:t.path,label:La[t.status]}))}function ko(e){return e.filter(t=>t.link).length}function Hr(e,t){try{let n=Ju(e,Zu(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=ep(Vu(Gu(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 tp(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 Ha(e){let t=[];e.length>1&&t.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(o=>o.path),indent:!1});let n=new Map;for(let o of e){let r=o.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),i=n.get(r);i?i.push(o):n.set(r,[o])}for(let o of[...n.keys()].sort()){let r=n.get(o).sort((i,c)=>i.path.localeCompare(c.path));t.push({kind:"category",label:`${tp(o)} (${r.length})`,paths:r.map(i=>i.path),indent:!1});for(let i of r){let c=i.path.replace(/\\/g,"/").split("/").pop()??i.path;t.push({kind:"article",label:c,paths:[i.path],indent:!0,note:i.label})}}return t}function bo(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(`
|
|
253
|
+
`)}function qr(e,t,n){let o=$=>t[$.index]?.paths.length??0,r=e.filter($=>$.ok),i=e.filter($=>!$.ok),c=e.reduce(($,I)=>$+o(I),0),p=r.reduce(($,I)=>$+o(I),0),m=n==="api"?`${he(e.reduce(($,I)=>$+I.costUsd,0))} total`:Qe(e.reduce(($,I)=>$+I.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,g=$=>`${$} article${$===1?"":"s"}`,T=[];if(i.length===0)T.push(`Published ${g(c)} (${k}) successfully \xB7 ${m}.`),T.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{T.push(`Published ${p}/${g(c)} (${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 $ of i)T.push(` \u2717 ${$.label}${$.error?` \u2014 ${$.error}`:""}`)}return T}async function Wr(e,t){let{model:n}=Xu(e.cwd,"standard"),o=async(r,i)=>{let c=zu(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 ${c.length} partition${c.length===1?"":"s"} (\u2264${wn} 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 Qu({cwd:e.cwd,partitions:c,promptFor:k=>bo(k.paths),concurrency:wn,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(N(` \u2713 ${m.label}`)):console.log(R(` \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 qr(m.results,c,k))console.log(m.ok?N(T):L(T));let g=Hr(e.cwd,e.profileName);g&&console.log(f(g));try{let T=Ua(await Ma({cwd:e.cwd,profileName:e.profileName}));T&&console.log(f(T))}catch{}try{let T=Fa(await Wa({cwd:e.cwd,profileName:e.profileName}));T&&console.log(f(T))}catch{}}return p};try{if(!await o(t,!1)){let i=await Br(e.cwd,e.profileName,t);i.length>0&&await o(i,!0)}}catch(r){console.log(R(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function $o(e,t,n){let o=Ku(e,n);if(o.length===0)return[];let r=new Set(Bt((await yo({cwd:e,profileName:t})).entries).map(i=>i.path));return o.filter(i=>r.has(i))}async function Br(e,t,n){try{let o=new Set(n),r=await yo({cwd:e,profileName:t});return Bt(r.entries).map(i=>i.path).filter(i=>o.has(i))}catch{return[]}}async function qa(e,t){let n=Fe(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await $o(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(N("\u2713 All related articles are already published.")),{kind:"continue"}):await Wr(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await yo({cwd:t?.cwd??process.cwd()}),i=Bt(r.entries),c=ko(r.entries);if(c>0&&console.log(L(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),i.length===0){if(console.log(N(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let p=Ua(await Ma({cwd:t.cwd,profileName:t.profileName}));p&&console.log(f(p));let m=Fa(await Wa({cwd:t.cwd,profileName:t.profileName}));m&&console.log(f(m))}catch{}return{kind:"continue"}}return t?await Wr(t,i.map(p=>p.path)):{kind:"forward-to-agent",prompt:bo(i.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log(R(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let i=await yo({cwd:t?.cwd??process.cwd()});r=Bt(i.entries);let c=ko(i.entries);c>0&&console.log(L(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`))}catch(i){return console.log(R(`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(N("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(f(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let 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(()=>Yu({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 Wr(t,r.map(i=>i.path))}return{kind:"forward-to-agent",prompt:Fr(o),display:`/publish ${o}`}}async function yn(){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(`
|
|
254
|
+
`),display:"/audit"}}U();import{checkbox as np}from"@inquirer/prompts";import{inventoryRepo as op,readProjectConfig as Ba,writeProjectConfig as rp}from"document360-engine";function Vr(e,t){let n=Ba(e);n&&(n.authoritativeSourceFiles=t,rp(n,e))}function xo(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 Va(e,t){let n=t?.cwd??process.cwd();if(!Ba(n))return console.log(R("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=op(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(xo(i))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>np({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(i=>({name:`${i.path} (${xo(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"};Vr(n,r),console.log(N(`\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"}}U();import{confirm as dp}from"@inquirer/prompts";import{applyPull as Yr,computeSyncStatus as Xa,compareRemoteSources as up,planPull as Qa,planImport as pp,applyImport as fp,establishBaselines as mp,rebaselineServerMeta as hp,D360AuthError as gp}from"document360-engine";U();var Ga=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:R,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:R,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:R,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:le,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:le,mark:"\xB7"}];function ip(e){return e.path?e.path:`${e.title??"(untitled)"} ${le(`[${e.articleId}]`)}`}function sp(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 vo(e,t){let n=[],o=e.entries.filter(g=>g.link);if(o.length>0){n.push(""),n.push(Pe("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let g of o)n.push(` ${L("~")} ${L(g.path??"")} ${le(`\u2192 "${g.link.title}"`)}`)}for(let g of Ga){let T=e.entries.filter($=>$.status===g.status&&!(g.status==="untracked-local"&&$.link));if(T.length!==0){n.push(""),n.push(Pe(g.header));for(let $ of T)n.push(` ${g.paint(g.mark)} ${g.paint(ip($))}${$.detail?le(` (${$.detail})`):""}`)}}let r=e.counts["in-sync"]??0,i=e.entries.length;n.push("");let c={"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?N("\u2713 everything up to date"):[r>0?N(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...Ga.map(g=>{let T=(e.counts[g.status]??0)-(g.status==="untracked-local"?p:0);return T>0?`${T} ${c[g.status]}`:null})].filter(Boolean).join(le(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${sp(t)}`:"";return n.push(m+le(` \xB7 ${i} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as ap}from"diff";import Ya from"picocolors";var za=80,lp="\x1B[48;2;74;28;28m",cp="\x1B[48;2;24;66;24m",Ka="\x1B[49m",Gr=e=>String(e).padStart(5);function mt(e,t,n){let o=$=>{let I=$.replace(/\r\n/g,`
|
|
255
|
+
`);return I.endsWith(`
|
|
256
|
+
`)||I===""?I:I+`
|
|
257
|
+
`},r=o(e),i=o(t);if(r===i)return null;let c=Math.max(20,n-10),p=ap("a","b",r,i,"","",{context:3}),m=0,k=0,g=[];p.hunks.forEach(($,I)=>{I>0&&g.push(Ya.gray(" \u2026"));let C=$.oldStart,E=$.newStart;for(let S of $.lines){let M=S[0],B=S.slice(1).slice(0,c);M==="-"?(k++,g.push(`${lp}${Gr(C++)} - ${B}${Ka}`)):M==="+"?(m++,g.push(`${cp}${Gr(E++)} + ${B}${Ka}`)):(g.push(Ya.gray(Gr(E))+" "+B),C++,E++)}});let T=g.slice(0,za);return{added:m,removed:k,lines:T,hidden:Math.max(0,g.length-za)}}async function Ja(e,t){let n=Fe(t.cwd,t.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await wp(t),{kind:"continue"};if(o==="--baseline")return await yp(t,e.filter(c=>c!=="--baseline")),{kind:"continue"};if(o==="--compare")return await kp(t),{kind:"continue"};if(o)return console.log(R(`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 bp(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let i=await zr({cwd:t.cwd,profileName:t.profileName});for(let c of Kr(i))console.log(c.tone==="ok"?N(c.text):c.tone==="warn"?L(c.text):f(c.text));console.log("")}catch(r){r instanceof gp?console.log(R(r.message)):console.log(R(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function zr(e){let t=await Xa({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 Qa({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Yr({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 pp({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});fp({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 Co=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,ht=e=>e===1?"":"s";function Kr(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${ht(e.pulled.length)} into local: ${Co(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${ht(e.imported.length)}: ${Co(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${ht(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${ht(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Take the portal copy: /pull <path> \xB7 keep yours: /publish <path>. (${Co(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${ht(e.failed.length)} failed: ${Co(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 wp(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Xa({cwd:e.cwd,profileName:e.profileName});for(let o of vo(n,Date.now()-t))console.log(o);console.log("")}async function yp(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 mp({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await hp({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(N("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(N(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(N(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(L(`${o.skipped.length} skipped:`));for(let i of o.skipped)console.log(f(` - ${i.path} (${i.reason})`))}}async function kp(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await up({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Pe(String(t.legacyCount))} \xB7 Manifest: ${Pe(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(N("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(R(`\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 bp(e,t){let n=t.replace(/\\/g,"/"),o=await Qa({cwd:e.cwd,profileName:e.profileName,relPath:n});console.log(""),console.log(`${O("\u25CF")} ${Pe(o.title)} ${le(`(${o.path})`)}`);for(let c of o.notes)console.log(L(` \u26A0 ${c}`));o.overwritesLocalChanges&&console.log(L(" \u26A0 This OVERWRITES local edits made since the last sync."));let r=mt(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.")),Yr({cwd:e.cwd,profileName:e.profileName},o);return}console.log(le(` \u23BF Added ${r.added} line${ht(r.added)}, removed ${r.removed} line${ht(r.removed)}`));for(let c of r.lines)console.log(c);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>dp({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}Yr({cwd:e.cwd,profileName:e.profileName},o),console.log(N(` \u2713 Pulled ${o.path} (sync base advanced).`))}U();import{statSync as $p}from"node:fs";import{resolve as xp}from"node:path";import{estimateBulkCost as vp,planPartitions as Cp,readProjectConfig as Rp,resolveModelForOperation as Pp,runPartitioned as Tp,trackedArticlePaths as Sp}from"document360-engine";var Xr=3;function Qr(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 Jr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Zr(e,t){return t.map(n=>{let o=0;try{o=$p(xp(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ei(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:
|
|
258
258
|
- 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.
|
|
259
259
|
- 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.
|
|
260
260
|
- 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.
|
|
261
261
|
- Work only on these files:
|
|
262
262
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
263
|
-
`)}function
|
|
263
|
+
`)}function ti(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: ${he(r)}\u2013${he(i)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function ni(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),i=e.filter(C=>!C.ok),c=e.reduce((C,E)=>C+o(E),0),p=r.reduce((C,E)=>C+o(E),0),m=e.reduce((C,E)=>C+E.costUsd,0),k=e.reduce((C,E)=>C+E.outputTokens,0),g=n==="api"?`${he(m)} total`:Qe(k),T=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,$=C=>`${C} article${C===1?"":"s"}`,I=[];if(i.length===0)I.push(`Converted ${$(c)} (${T}) successfully \xB7 ${g}.`);else{I.push(`Converted ${p}/${$(c)} (${T}) \xB7 ${g}.`),I.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of i)I.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return I}async function Za(e,t){if(!Rp(t.cwd))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Qr(e),r=Sp(t.cwd,t.profileName);if(r.length===0)return console.log(R("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let i=Jr(r,n);if(i.length===0)return console.log(R(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=Cp(i),p=`/convert${n?` --scope ${n}`:""} --run`,{model:m,forced:k}=Pp(t.cwd,"light");if(!o){let g=vp({files:Zr(t.cwd,i),op:"convert",model:m});n&&console.log(f(`Scope: ${n} (${i.length} of ${r.length} tracked articles).`));for(let T of ti(c,g,Xr))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 ${c.length} partitions (\u2264${Xr} 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 Tp({cwd:t.cwd,partitions:c,promptFor:ei,concurrency:Xr,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(N(` \u2713 ${g.label}`)):console.log(R(` \u2717 ${g.label}`));else if(g.type==="run_done"){console.log("");let T=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let $ of ni(g.results,c,T))console.log(g.ok?N($):L($))}}catch(g){console.log(R(`Convert run failed: ${g.message}`))}return console.log(""),{kind:"continue"}}U();import{statSync as nl}from"node:fs";import{resolve as ol}from"node:path";import{estimateBulkCost as Lp,lintDocs as Mp,planPartitions as Up,readDocsPlan as Wp,readProjectConfig as rl,DEFAULT_DOCS_DIR as Fp,resolveModelForOperation as Hp,runPartitioned as qp,stampArticles as Bp,CONTENT_CAP_VERSION as Vp}from"document360-engine";import{readProjectConfig as Dp,loadProfileMap as Ap,resolveActiveProfile as jp,desiredCategoryOrder as Ep,desiredArticleOrder as Np,DEFAULT_DOCS_DIR as Ip}from"document360-engine";var oi=e=>e.replace(/\\/g,"/"),_p=e=>oi(e).split("/").pop()??e;function Op(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function kn(e,t){try{let n=Dp(e);if(!n)return[];let o=jp(e,t),r=Ap(e,o.name);if(!r)return[];let i=oi(n.docsDir??Ip).replace(/\/+$/,""),c=new Map;for(let m of Np(r))c.set(m.categoryPath,(c.get(m.categoryPath)??0)+1);let p=[];for(let m of Ep(r)){let k=oi(m.path),g=k.startsWith(`${i}/`)?k.slice(i.length+1):k===i?"":k;g&&p.push({token:g,label:Op(_p(k)),count:c.get(m.path)??0})}return p}catch{return[]}}function el(e,t){let n=kn(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 Je(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function Vt(e,t,n,o){let r=kn(e,o);if(r.length<=1)return[];let i=n.filter(k=>k.startsWith("--")).join(" "),c=i?` ${i}`:"",p=`/${t}${c} --all`.replace(/\s+/g," "),m=k=>t==="write"?`/write --scope ${k}${c}`:`/${t} ${k}${c}`;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 Ro(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function tl(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 Gp=3,Yp=8;function ri(e){return e===void 0||!Number.isFinite(e)?Gp:Math.max(1,Math.min(Math.floor(e),Yp))}function ii(e){let t,n,o=!1,r=!1,i,c=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=c(e[++m]):k?.startsWith("--concurrency=")?i=c(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 zp(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Kp(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function si(e,t,n){return n.filter(o=>{try{return nl(ol(e,t,o)).size===0}catch{return!0}})}function ai(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let i=1;for(let c of o.get(r)?.sources??[])try{i+=nl(ol(e,c)).size}catch{}return{path:r,bytes:i}})}function li(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.
|
|
264
264
|
`:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
265
265
|
- It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose and the source files it draws from (AGENT-PLAN.md has the same table).
|
|
266
266
|
- Read ONLY those source files plus any shared context you genuinely need, and ground every statement in them. Never invent UI labels, routes, or behaviour \u2014 if the source does not say it, omit it.
|
|
@@ -269,79 +269,79 @@ ${i}${w}`).join("")}).join(`
|
|
|
269
269
|
- 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.
|
|
270
270
|
Articles:
|
|
271
271
|
`+e.paths.map(r=>`- ${r}`).join(`
|
|
272
|
-
`)}function
|
|
273
|
-
`)}var
|
|
274
|
-
`)}var
|
|
272
|
+
`)}function ci(e,t,n){let o=e.reduce((c,p)=>c+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(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${he(r)}\u2013${he(i)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function di(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),i=e.filter(C=>!C.ok),c=e.reduce((C,E)=>C+o(E),0),p=r.reduce((C,E)=>C+o(E),0),m=e.reduce((C,E)=>C+E.costUsd,0),k=e.reduce((C,E)=>C+E.outputTokens,0),g=n==="api"?`${he(m)} total`:Qe(k),T=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,$=C=>`${C} article${C===1?"":"s"}`,I=[];if(i.length===0)I.push(`Wrote ${$(c)} (${T}) successfully \xB7 ${g}.`),I.push("Next \u2014 push them to Document360:"),I.push("/publish --all"),I.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{I.push(`Wrote ${p}/${$(c)} (${T}) \xB7 ${g}.`),I.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of i)I.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return I}function ui(e,t,n){try{let o=Mp({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 pi(e,t,n){let o=(rl(e)?.docsDir??Fp).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=zp(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=Kp(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 c=si(e,o,i);if(c.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:c,planCount:r.length}}async function il(e,t){if(!rl(t.cwd))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Ro(e)){for(let M of el(t.cwd,t.profileName))console.log(f(M));return{kind:"continue"}}if(Je("write",e)){let M=Vt(t.cwd,"write",e,t.profileName);if(M.length>0){for(let B of M)console.log(f(B));return{kind:"continue"}}}let n=Wp(t.cwd);if(n.length===0)return console.log(R("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:c,rewrite:p}=ii(e),{docsDir:m,targets:k,reason:g,rewriting:T}=pi(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 $=Up(k),I=ri(c),{model:C,forced:E}=Hp(t.cwd,"standard"),S=!!r;if(i&&!S){let M=Lp({files:ai(t.cwd,n,k),op:"write",model:C});o&&console.log(f(`Scope: ${o} (${k.length} pending).`));for(let B of ci($,M,I))console.log(B);return console.log(f(`Model: ${C}${E?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${k.length} article${k.length===1?"":"s"} across ${$.length} partition${$.length===1?"":"s"} (\u2264${I} agents at once) on ${C}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let M of qp({cwd:t.cwd,partitions:$,promptFor:B=>li(B,m,{rewrite:T||S}),concurrency:I,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(M.type==="partition_status")M.status==="running"?console.log(f(` \u25B8 ${M.label} \u2014 writing\u2026`)):M.status==="done"?console.log(N(` \u2713 ${M.label}`)):console.log(R(` \u2717 ${M.label}`));else if(M.type==="run_done"){console.log("");let B=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let X of di(M.results,$,B))console.log(M.ok?N(X):L(X));if(M.ok)try{Bp(t.cwd,k.map(X=>`${m}/${X}`),{writtenCap:Vp})}catch{}let J=ui(t.cwd,m,k);J&&console.log(L(J))}}catch(M){console.log(R(`Write run failed: ${M.message}`))}return console.log(""),{kind:"continue"}}U();import{existsSync as Xp,readdirSync as sl,statSync as al}from"node:fs";import{join as ll}from"node:path";import{inputDir as Qp,readProjectConfig as Jp}from"document360-engine";var cl=/\.(md|markdown|pdf|txt)$/i;function fi(e){let t=Qp(e);if(!Xp(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of sl(t)){let i=ll(t,r),c=!1;try{c=al(i).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=Zp(i);p>0&&n.push({name:r,docCount:p})}else cl.test(r)&&o++}return n.sort((r,i)=>r.name.localeCompare(i.name)),{features:n,looseDocs:o}}function Zp(e){let t=0;for(let n of sl(e))try{al(ll(e,n)).isFile()&&cl.test(n)&&t++}catch{}return t}function mi(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 Po(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(`
|
|
273
|
+
`)}var hi="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function dl(e,t){let n=t?.cwd??process.cwd();if(!Jp(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=fi(n);if(o.length===0&&r===0)return console.log(f(hi)),{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:Po(p),display:p?`/draft ${p}`:"/draft"}}let c=mi(o,i);return{kind:"forward-to-agent",prompt:Po(c??"",c?void 0:i),display:`/draft ${i}`}}U();import{listOpenForDocs as ef,readProjectConfig as tf}from"document360-engine";function gi(e){try{return ef(e).filter(t=>t.kind==="request").length}catch{return 0}}function wi(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function yi(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(`
|
|
274
|
+
`)}var ki="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 ul(e,t){let n=t?.cwd??process.cwd();if(!tf(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=wi(e);if(!r&&gi(n)===0)return console.log(f(ki)),{kind:"continue"};let i=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:yi(r,o),display:i}}U();import{search as nf}from"@inquirer/prompts";import{findByName as of,getSession as rf,listSessions as sf,relativeTime as fl}from"document360-engine";async function ml(e,t){let n=sf(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=of(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(R(`No session matches "${o}".`)),pl(n),{kind:"continue"})}if(!process.stdin.isTTY)return pl(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>nf({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async i=>{let c=(i??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${fl(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 pl(e){console.log("");for(let t of e.slice(0,15))console.log(` ${O(t.name)} ${f(fl(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}U();import{renameSession as af}from"document360-engine";function bi(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 hl(e,t){let n=bi(e.join(" "));if(!n)return console.log(R("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(af(o,n)?console.log(N(`\u2713 Session renamed to "${n}"`)):console.log(R("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(N(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as gl,readProjectConfig as lf,writeProjectConfig as cf}from"document360-engine";U();function $i(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=lf(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 gl().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},cf(o,e),null):`Unknown environment "${r}". Known: ${gl().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function wl(e,t){let n=e[0];if(!n)return so(t.cwd),{kind:"continue"};if(n==="add"){let o=$i(t.cwd,e[1],e[2]);return o?(console.log(R(o)),{kind:"continue"}):(console.log(N(`\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 ao(t.cwd,n),lo(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}U();import{select as df}from"@inquirer/prompts";import{readProjectConfig as uf,readUserConfig as yl,resolveModelSetting as xi,writeUserConfig as kl}from"document360-engine";var Ie=[{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 To(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Ie.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function pf(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 bn(e,t){let n=()=>xi(e).model;if(t==="default"){let i=yl();return i.defaultModel?(delete i.defaultModel,kl(i),{lines:[`\u2713 Personal model override cleared \u2014 now: ${xi(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}}kl({...yl(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=uf(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 bl(e,t){let n=e[0]?.trim();if(!n){let c=xi(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${O(c.model)}${c.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${pf(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=To(c),m;try{m=await t.withPausedInput(()=>df({message:`Select model (current: ${c.model}${c.source==="auto"?" \xB7 auto":""})`,default:Ie[p].value,choices:Ie.map(($,I)=>({name:`${$.label}${I===p?" \u2714":""}`,value:$.value,description:$.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:g,effective:T}=bn(t.cwd,m??"default");for(let $ of k)console.log($.startsWith("\u26A0")?L($):$.startsWith("\u2713")?N($):f($));return g&&await t.setModel(T),{kind:"continue"}}let{lines:o,changed:r,effective:i}=bn(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?L(c):c.startsWith("\u2713")?N(c):f(c));return r&&await t.setModel(i),{kind:"continue"}}So();async function Pl(e,t){return await t.withPausedInput(()=>Lt(t.cwd)),{kind:"clear"}}async function Tl(e,t){return await t.withPausedInput(()=>no(t.cwd,t.profileName)),{kind:"clear"}}U();import{resolveActiveProfile as Af}from"document360-engine";async function Sl(e,t){let n=!1;try{n=Af(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"})}U();var Dl=async(e,t)=>{try{await t.withPausedInput(()=>io({}))}catch(n){console.log(R(`Login failed: ${n.message}`))}return{kind:"continue"}};U();import{resolveActiveProfile as jf,clearTokens as Ef,clearProfileProject as Nf}from"document360-engine";async function Al(e,t){let n;try{n=jf(t.cwd,t.profileName).name}catch(r){return console.log(R(r.message)),{kind:"continue"}}let o=Ef(n);return Nf(t.cwd,n),console.log(o?N(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):f(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(f("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as jl}from"node:fs";import{isAbsolute as If,join as _f,resolve as Of}from"node:path";import{readProjectConfig as Lf,screenshotPlaceholderIds as Mf,DEFAULT_CAPTURE_DIR as Uf,DEFAULT_OUTPUT_DIR as Wf}from"document360-engine";var El=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ci(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?El(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:El(o),setup:t}:{mode:"single",id:o}}function Ri(e,t){let n=Lf(e),o=n?.captureDir??Uf,r=n?.outputDir??Wf,i=(c,p)=>If(c)?_f(c,p):Of(e,c,p);return Mf(e,{scope:t}).map(({id:c,file:p})=>{let m=jl(i(r,`${c}.png`))?"captured":jl(i(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:m}})}var Ff={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Hf={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Pi(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 c of e.filter(p=>p.file===i))r.push(` ${Ff[c.state]} ${c.id.padEnd(34)} ${Hf[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Nl(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(`
|
|
275
275
|
`),"","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(`
|
|
276
|
-
`)}async function
|
|
276
|
+
`)}async function Do(e,t){let n=Ci(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of Pi(Ri(c,n.scope),n.scope))console.log(p);return{kind:"continue"}}if(n.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${n.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${n.id}.spec.ts. Report the spec path and any TODO data-testids or data to stage.`].join(`
|
|
277
277
|
`),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(`
|
|
278
|
-
`),i=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:i}}import{existsSync as
|
|
279
|
-
`),display:"/capture-setup"}}var
|
|
280
|
-
`)}async function
|
|
281
|
-
`)}var
|
|
282
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
278
|
+
`),i=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:i}}import{existsSync as qf,readFileSync as Bf}from"node:fs";import{isAbsolute as Vf,join as Gf,resolve as Yf}from"node:path";import{readProjectConfig as zf,DEFAULT_CAPTURE_DIR as Kf}from"document360-engine";async function xn(){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(`
|
|
279
|
+
`),display:"/capture-setup"}}var Il="-".repeat(64);function Ti(e){let t=Kf;try{let g=zf(e);g?.captureDir&&(t=g.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Vf(t)?Gf(t,"CAPTURE-TESTID-REQUESTS.json"):Yf(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!qf(n))return null;let o;try{let g=JSON.parse(Bf(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,c=`${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 ${c} requested across ${p}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",Il,`Read ${m} and ${k}. They list ${c} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",Il]}Ke();U();import{listOpenForDocs as Xf,readProjectConfig as Qf}from"document360-engine";function Si(e){try{return Xf(e).length}catch{return 0}}function Di(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape."," \u2022 answer (a reply to a question you asked; `re` = your question id) \u2192 fold the fact into the affected"," article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only \u2014 do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
|
|
280
|
+
`)}async function _l(e,t){let n=t?.cwd??process.cwd();return Qf(n)?Si(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:Di(),display:"/inbox"}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{listOpenHints as Jf,listOpenForDocs as Zf,listOpenDirectives as em,readProjectConfig as tm,computeSyncStatus as nm,planPull as om,applyPull as rm,planImport as im,applyImport as sm}from"document360-engine";function vn(e){let t=0,n=0,o=0,r=0;try{t=Jf(e).length}catch{}try{let i=Zf(e);n=i.filter(c=>c.kind==="request").length,o=i.filter(c=>c.kind==="answer").length}catch{}try{r=em(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function Cn(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 ji(e){return{publish:e.includes("--publish")}}function Ei({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, 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(`
|
|
281
|
+
`)}var am={status:nm,plan:om,apply:rm,planImport:im,applyImport:sm};async function Ni(e,t=am){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 Ai=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Ao=e=>e===1?"":"s";function Ii(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${Ao(e.pulled.length)} into local: ${Ai(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Ao(e.imported.length)} into local drafts: ${Ai(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Ao(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Ai(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${Ao(e.failed.length)} failed \u2014 left for /pull.`),t}async function Ol(e,t){let n=t?.cwd??process.cwd();if(!tm(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Fe(n,t?.profileName);if(!o.ok)return console.log(R(o.reason)),{kind:"continue"};let{publish:r}=ji(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let i=await Ni({cwd:n,profileName:t?.profileName});for(let p of Ii(i))console.log(p.startsWith("\u2713")?N(p):p.startsWith("\u2139")?f(p):L(p));let c=Cn(vn(n));return console.log(f(c?`Catching up on ${c}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Ei({publish:r}),display:`/catch-up${r?" --publish":""}`}}U();import{spawn as lm}from"node:child_process";var gt="document360-writer",jo=`npm i -g ${gt}@latest`;async function Eo(){let e=process.platform==="win32";return new Promise(t=>{try{let n=lm(`npm i -g ${gt}@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 Ll(){return console.log(f(`Updating ${gt}\u2026`)),(await Eo()).ok?console.log(N("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(R(`Update failed \u2014 run manually: ${jo}`)),{kind:"continue"}}U();Ke();import{existsSync as _i,rmSync as cm}from"node:fs";import{basename as Ml,resolve as Oi}from"node:path";import{execFileSync as dm}from"node:child_process";import{input as um}from"@inquirer/prompts";import{readProjectConfig as pm,devHintsGuidePath as fm}from"document360-engine";var mm=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],hm=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),No=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Ul=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Wl(e){let t=No(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Ul(t)?!0:hm.has(t)}function Li(e){let t=null;try{t=pm(e)}catch{t=null}let n=new Set(mm);for(let o of[No(t?.docsDir),No(t?.captureDir),No(t?.outputDir)])o&&Ul(o)&&n.add(o);return[...n].filter(o=>Wl(o)&&_i(Oi(e,o)))}function Mi(e,t){let n=[],o=[];for(let r of t){if(!Wl(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{cm(Oi(e,r),{recursive:!0,force:!0}),n.push(r)}catch(i){o.push({path:r,error:i.message})}}return{removed:n,failed:o}}function Fl(e,t){try{return dm("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
282
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function gm(e){return Fl(e,".d360-writer/hints")}function wm(e){return Fl(e,".d360-writer/messages")}function Ui(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=gm(e),o=wm(e),r=_i(Oi(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: ${Ml(e)}`]}async function Hl(e,t){let n=Li(t.cwd);for(let m of Ui(t.cwd,n))console.log(n.length===0?f(m):m);if(n.length===0)return{kind:"continue"};let o=Ml(t.cwd);if((await t.withPausedInput(()=>um({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let i=_i(fm(t.cwd)),{removed:c,failed:p}=Mi(t.cwd,n);console.log(N(`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`));for(let m of p)console.log(R(` \u2717 ${m.path}: ${m.error}`));if(i){for(let m of mo())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"}}U();import{lintDocs as ym}from"document360-engine";function Io(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 Wi(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(`
|
|
283
283
|
`)).join(`
|
|
284
284
|
`)].join(`
|
|
285
|
-
`)}async function
|
|
286
|
-
`);return{prompt
|
|
287
|
-
`),display:`/reorder${n?` ${n}`:""}`}}async function
|
|
288
|
-
\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${be(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${be(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${be(n)} up.`})}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${be(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${be(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${be(n)}.`})}return t}function
|
|
289
|
-
`)}function
|
|
290
|
-
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=
|
|
291
|
-
`);return{lines:i.slice(0,t).map(c=>$e(c,
|
|
292
|
-
`))console.log(c(` ${p}`));i.rec.picker&&console.log(
|
|
293
|
-
|
|
294
|
-
`),console.log(`${N("\u25CF")} ${Pe(i.title)}${i.arg!==null?le(`${i.sep}(${i.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=mt(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let c=p=>p===1?"":"s";console.log(le(` \u23BF Added ${i.added} line${c(i.added)}, removed ${i.removed} line${c(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 c=
|
|
295
|
-
`),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&&(
|
|
296
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let i=n[r];if(!t.cueSeen){
|
|
297
|
-
`)}import{existsSync as
|
|
298
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var
|
|
299
|
-
`)){let c=i.trim().replace(
|
|
300
|
-
`)}function
|
|
301
|
-
`)||e.length>200}function
|
|
302
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function
|
|
303
|
-
`)){if(i.length===0)o.push({start:r,end:r});else for(let c=0;c<i.length;c+=n)o.push({start:r+c,end:r+Math.min(c+n,i.length)});r+=i.length+1}return o.length>0?o:[{start:0,end:0}]}function
|
|
304
|
-
`),i=0;for(let c=r.length-1;c>=0;c--){let p=r[c];if(i+=Math.max(1,Math.ceil(p.length/o)),i>=t){let
|
|
305
|
-
`),truncated:c>0||
|
|
306
|
-
`)){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
|
|
285
|
+
`)}async function ql(e,t){let n=e.includes("--fix"),o=e.find(c=>!c.startsWith("--")),r=o?` ${o}`:"",i=ym({cwd:t.cwd,scope:o});if(n)return i.length===0?(console.log(N("\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:Wi(i),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let c of Io(i))console.log(i.length===0?N(c):L(c));return i.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}U();import{lintDocs as Cm,loadStyleGuide as Rm,buildReviewPrompt as Pm,readProjectConfig as Tm,DEFAULT_DOCS_DIR as Sm}from"document360-engine";U();import{readProjectConfig as km,loadProfileMap as bm,resolveActiveProfile as $m,desiredCategoryOrder as xm,desiredArticleOrder as vm}from"document360-engine";function Bl(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Vl=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Rn(e,t){try{if(!km(e))return[];let n=$m(e,t),o=bm(e,n.name);if(!o)return[];let r=new Map;for(let c of vm(o)){let p=r.get(c.categoryPath);p?p.push(c):r.set(c.categoryPath,[c])}let i=[];for(let c of xm(o)){i.push(Bl(Vl(c.path)));for(let p of(r.get(c.path)??[]).sort((m,k)=>m.order-k.order))i.push(` ${Bl(Vl(p.path))}`)}return i}catch{return[]}}async function Gl(e,t){let n=Rn(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 Fi(e,t){let n=Tm(e);if(!n)return null;let o=(n.docsDir??Sm).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),i=t.find(g=>!g.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),c=Cm({cwd:e}),p=i?c.filter(g=>g.path===`${o}/${i}`||g.path.startsWith(`${o}/${i}/`)):c,m=i?"":Rn(e).join(`
|
|
286
|
+
`);return{prompt:Pm({docsRoot:o,scope:i,styleGuide:Rm(e),deterministicFindings:p,fix:r,structure:m||void 0}),display:`/review${i?` ${i}`:""}${r?" --fix":""}`}}async function Yl(e,t){if(Je("review",e)){let o=Vt(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=Fi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{readProjectConfig as Dm}from"document360-engine";function Hi(e,t){if(!Dm(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(`
|
|
287
|
+
`),display:`/reorder${n?` ${n}`:""}`}}async function zl(e,t){if(Je("reorder",e)){let o=Vt(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=Hi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{readProjectConfig as Am,writeProjectConfig as Kl,isAppType as jm,playbookSkillName as Em,detectAppType as Xl}from"document360-engine";var Ql=["web","cli","service","library"],Nm=new Set(["web","cli"]);function qi(e){return Nm.has(e)?`${Em(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function _o(e,t){let n=t.cwd,o=Am(n);if(!o)return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let i=o.appType??Xl(n);if(i){let c=o.appType?"set in config":"auto-detected";console.log(`${O("Genre:")} ${i} (${c}) \u2014 ${qi(i)}`)}else console.log(L("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${Ql.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,...c}=o;Kl(c,n);let p=Xl(n);return console.log(N(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${qi(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return jm(r)?(Kl({...o,appType:r},n),console.log(N(`\u2713 Genre set to ${r} \u2014 ${qi(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(R(`Unknown genre "${r}". Choose one of: ${Ql.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}U();import{listRoadmap as Jl,roadmapProgress as Zl,stampRoadmapDone as Im}from"document360-engine";function Bi(e){let t=Jl(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=Zl(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 Vi(e,t){if(!t.trim())return{ok:!1,line:"Usage: /roadmap done <step title>"};if(!Im(e,t,{doneAt:new Date().toISOString()})){let r=Jl(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=Zl(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 ec(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Vi(n,e.slice(1).join(" ").trim());return console.log(r.ok?N(r.line):L(r.line)),{kind:"continue"}}let o=Bi(n);console.log(O(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?f(r):r);return{kind:"continue"}}var tc={help:Rr,"?":Rr,clear:aa,exit:Pr,quit:Pr,init:jr,mcp:wo,publish:qa,audit:yn,scope:Va,pull:Ja,convert:Za,write:il,draft:dl,document:ul,resume:ml,rename:hl,profile:wl,model:bl,doctor:$n,workspace:Pl,project:Tl,"allow-prod":Sl,login:Dl,logout:Al,screenshot:Do,"capture-setup":xn,devhints:ga,inbox:_l,"catch-up":Ol,update:Ll,reset:Hl,check:ql,review:Yl,reorder:zl,structure:Gl,genre:_o,roadmap:ec};function nc(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),o=(n[0]??"").toLowerCase();return o?{name:o,args:n.slice(1)}:null}Ke();var _m="Or just tell me what to write or update.",Om='\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 be(e){return e===1?"":"s"}function Oo(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Gi(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var Lm={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 Mm(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:Lm,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${be(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${be(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${be(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
|
|
288
|
+
\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${be(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${be(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${be(n)} up.`})}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${be(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${be(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${be(n)}.`})}return t}function oc(e,t){let n=t.filter(i=>i.bullet).map(i=>` \u2022 ${i.bullet}`),o=t[0],r=[];o.lead?r.push(Gi(o.lead)):o.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let i of t.slice(1,3))i.follow&&r.push(i.follow);return[e,...n,r.join(" "),_m].join(`
|
|
289
|
+
`)}function Pn(e){if(!e.ready)return{kind:"idle"};let t=Mm(e);if(!e.hasDocs){let r=t[0];return r&&(r.lead?.kind==="cmd"||r.picker)?{kind:"recommend",rec:{note:oc("\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",t),tone:r.tone??"info",lead:r.lead,picker:r.picker}}:{kind:"recommend",rec:{note:Om,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 r=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${be(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${be(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${r}`,tone:"info",lead:null,picker:null}}}let n=t[0];return(n.key==="audit"||n.key==="roadmap"&&t[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${be(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:oc("Welcome back \u2014 where your docs stand:",t),tone:n.tone??"info",lead:n.lead,picker:n.picker}}}import{existsSync as Yi,readdirSync as Ki}from"node:fs";import{spawnSync as Um}from"node:child_process";import{join as Lo}from"node:path";import{readProjectConfig as ic,resolveActiveProfile as sc,loadTokens as Wm,isExpired as Fm,loadProfileMap as ac,countLocalAhead as Hm,readDocsPlan as qm,devHintsGuidePath as Bm,DEFAULT_DOCS_DIR as zi,roadmapProgress as Vm}from"document360-engine";Ke();function rc(e){try{return Ki(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Xi(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>rc(Lo(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&rc(Lo(e,o)))}function Qi(e,t){try{let n=ic(e);if(!n)return!1;let o=sc(e,t),r=ac(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let i=Lo(e,(n.docsDir??zi).replace(/\/+$/,""));return!!(Yi(i)&&Ki(i).length>0||Yi(Bm(e)))}catch{return!1}}function Tn(e,t,n){try{let o=ic(e);if(!o)return null;let r=sc(e,t),i=Wm(r.name),c=!!i&&(!Fm(i)||!!i.refreshToken),p=Qi(e,t)||!Xi(e,o.authoritativeSourceFiles),m=ac(e,r.name),k=m?Object.keys(m.articles).length:0,g=Lo(e,(o.docsDir??zi).replace(/\/+$/,"")),T=!1;try{T=Yi(g)&&Ki(g).length>0}catch{}let $=0;if(m?.lastAnalyzedCommit)try{let J=Um("git",["rev-list","--count",`${m.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});J.status===0&&($=parseInt((J.stdout||"").trim(),10)||0)}catch{}let I=0;try{let J=qm(e);if(J.length>0){let X=(o.docsDir??zi).replace(/\/+$/,"");I=si(e,X,J.map(ae=>ae.path)).length}}catch{}let C=vn(e),E=Cn({...C,directives:0}),S=Hm(e,t),M=Se(e),B=Vm(e);return{ready:c&&p&&!n.claudeMissing,hasDocs:T,tracked:k,pendingText:E,directives:C.directives,behind:$,pendingWrites:I,localAhead:S,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:M.status,devhintsCompletedVersion:M.completedVersion,devhintsToVersion:se,builderStarted:We(e),genreUnknown:n.genreUnknown,roadmap:B}}catch{return null}}function Ji(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 Mo(e){if(e.length===0)return[];let t=(r,i)=>`${r}${"\u2500".repeat(78)}${i}`,n=(r="")=>`\u2502 ${r.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")];return e.forEach((r,i)=>{i>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let c of Ji(`${i+1}. ${r.feature}`,76))o.push(n(c));o.push(n());for(let c of Ji(r.why,73))o.push(n(` ${c}`));o.push(n());for(let c of Ji(`\u2192 What to do: ${r.how}`,73))o.push(n(` ${c}`));o.push(n())}),o.push(t("\u2514","\u2518")),o.push(""),o.push("\u2713 These are on your docs roadmap \u2014 each launch walks you to the next step (/roadmap shows them all)."),o}U();var Gm={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"},cc=160,es=200,dc=40;function $e(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function lc(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}: ${$e(typeof r=="string"?r:JSON.stringify(r),dc)}`);return t.length>4&&n.push("\u2026"),$e(n.join(", "),cc)}var Ze=e=>typeof e=="string"&&e?e:null,Zi=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Ym(e){let t=Ze(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 zm(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Ze(t.title);if(!o)return null;let r=Ym(t.local_path);return n("Create article",`"${$e(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Ze(t.title),r=Zi(t.article_id);return n("Update article",o?`"${$e(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Zi(t.article_id)?`id ${Zi(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",Ze(t.name)?`"${$e(Ze(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Ze(t.file_path);return n("Upload image",o?$e(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Uo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...i]=e.split("__"),c=i.join("__");if(r==="document360"){let k=zm(c,t);if(k)return k}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:lc(t)}}let n=Gm[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:$e(o,cc)}:{title:e,sep:"",arg:lc(t)}}function Km(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 Xm(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Km).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>$e(r,es))]}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}: ${$e(String(r),dc)}`);return n.length>0?[$e(n.join(" \xB7 "),es)]:null}return null}function Qm(e){let t=Ze(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Jm(e,t,n){switch(e){case"d360_create_article":{let o=Qm(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=Ze(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 ${$e(o[0],120)}`:""}`]}default:return null}}function Wo(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
290
|
+
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=Jm(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let i=Xm(r)??r.split(`
|
|
291
|
+
`);return{lines:i.slice(0,t).map(c=>$e(c,es)),hidden:Math.max(0,i.length-t)}}function Fo(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Ho(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 qo(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 yh=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function kh(e,t,n,o){if(yh.test(e))try{let r=fc(o),i=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=Ho(t,n),p=qo(n);e.endsWith("publish_article")&&p&&console.log(O(` \u2B95 Live: ${p}`)),c&&i&&console.log(O(` \u2B95 Preview: ${Fo(r.connection.portalUrl,i,c,r.project.languageCode??"en")}`))}catch{}}async function mc(e=process.cwd(),t="auto",n,o){let r=eh(t);r.kind==="none"&&(console.error(""),console.error(R("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)),bh(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,c=ts({cwd:e,profileName:n,allowProdWrites:i}),p={uuid:null,firstPrompt:null,titleFired:!1},m=Zm({input:process.stdin,output:process.stdout}),k=[],g=null,T=!1;m.on("line",C=>{if(g){let E=g;g=null,E(C)}else k.push(C)}),m.on("close",()=>{if(T=!0,g){let C=g;g=null,C(null)}});function $(){return k.length>0?Promise.resolve(k.shift()):T?Promise.resolve(null):(process.stdout.write(O("> ")),new Promise(C=>{g=C}))}let I={cwd:e,version:o,profileName:n,allowProdWrites:()=>i,restartAgent:()=>{c.close(),c=ts({cwd:e,profileName:n,allowProdWrites:i}),p={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>p.uuid,setPendingName:C=>{p.pendingName=C},setModel:async C=>c.setModel(C),withPausedInput:async C=>{m.pause();try{return await C()}finally{m.resume()}}};try{for(;;){let C=await $();if(C===null)break;let E=C.trim();if(E){if(E.startsWith("/")){let S=nc(E);if(!S)continue;let M=tc[S.name];if(!M){console.log(R(`Unknown command: /${S.name}`)),console.log(f("Type /help for the list."));continue}let B=await M(S.args,I);if(B.kind==="exit")break;if(B.kind==="clear"){I.restartAgent();continue}if(B.kind==="allow-prod"){i=!0,I.restartAgent(),console.log(N("\u2713 Production writes authorized for this session.")),console.log("");continue}if(B.kind==="resume"){c.close(),c=ts({cwd:e,resume:B.uuid,profileName:n,allowProdWrites:i});let J=th(B.uuid);p={uuid:B.uuid,firstPrompt:J?.firstPrompt??null,titleFired:!0},pc(B.uuid),console.log(N(`\u2713 Resumed "${B.name}"`)),console.log("");continue}if(B.kind==="forward-to-agent"){p.firstPrompt||(p.firstPrompt=B.display??B.prompt);let J=(B.display??"").trim().split(/\s+/),X=(J[0]==="/check"||J[0]==="/review")&&J.includes("--fix"),ae=J.slice(1).find(Qt=>!Qt.startsWith("--")),kt=X?gh(e,ae):[];if(await ns(c,B.prompt,r,p,e),X)try{hh(e,kt,{reviewedCap:wh})}catch{}}else $h(e,n);continue}if(uh(E)){let S=ph(E);if(S){try{fh(e,{title:S,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}p.firstPrompt||(p.firstPrompt=E),await ns(c,`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=E),await ns(c,E,r,p,e)}}}finally{c.close(),m.close()}}function bh(e,t){console.log(""),console.log(un("document360-writer")),console.log(f(` cwd: ${e}`));let n=sh(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(xh(e,t)),!ah(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(po(e),!We(e))for(let r of fo(e))console.log(L(` ${r}`))}catch{}try{let r=lh(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=mh(e);for(let i of Mo(r.applied))console.log(L(` ${i}`))}catch{}try{let r=Tn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),i=r?Pn(r):null;if(i?.kind==="recommend"&&i.rec.note){let c=i.rec.tone==="warn"?L:f;for(let p of i.rec.note.split(`
|
|
292
|
+
`))console.log(c(` ${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 $h(e,t){try{let n=Tn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Pn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(f(` Next: ${Gi(o.rec.lead)}`))}catch{}}function xh(e,t){try{let n=fc(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=dh(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let i={...uc(r.idToken)??{},...uc(r.accessToken)??{}},c=i.email??i.preferred_username??"signed in";return ch(r)&&!r.refreshToken?L(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function vh(){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 Ch(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;rh({uuid:t,name:r??oh(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Rh(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||ih(o,t).then(r=>{r&&nh(n,r)}).catch(()=>{})}async function ns(e,t,n,o,r){let i=new Map;for await(let c of e.send(t))Ph(c,o,r,n,i)}function Ph(e,t,n,o,r){switch(e.type){case"session":t.uuid||Ch(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=Uo(e.name,e.input);i&&(process.stdout.write(`
|
|
293
|
+
|
|
294
|
+
`),console.log(`${N("\u25CF")} ${Pe(i.title)}${i.arg!==null?le(`${i.sep}(${i.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=mt(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let c=p=>p===1?"":"s";console.log(le(` \u23BF Added ${i.added} line${c(i.added)}, removed ${i.removed} line${c(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 c=Wo(e.output,4,e.isError?void 0:i.name,i.input),p=e.isError?R:le;c.lines.forEach((m,k)=>console.log(p((k===0?" \u23BF ":" ")+m))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||kh(i.name,i.input,e.output,n);break}case"result":process.stdout.write(`
|
|
295
|
+
`),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||Rh(t,n));break;case"error":console.error(""),console.error(R(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&vh();break}}import{render as qg}from"ink";import{resolveAuth as Bg}from"document360-engine";import{useCallback as Y,useEffect as ve,useMemo as ls,useRef as ee,useState as W}from"react";import{Box as ne,Text as A,useApp as Fh,useInput as Hh,useStdout as qh}from"ink";import{existsSync as Yt,readFileSync as Jo,readdirSync as Bh}from"node:fs";import{basename as Dn,isAbsolute as Vh,join as cs}from"node:path";import{createSession as qc,classifyClaudeAuth as ms,CLAUDE_CODE_SETUP_HINT as Gh,loginPkce as Yh,toStoredTokens as zh,saveTokens as Kh,getAccessToken as Xh,resolveActiveProfile as xe,resolveProjectId as Qh,getArticle as Jh,decodeJwtClaims as Kt,isExpired as et,loadTokens as yt,clearTokens as Zh,clearProfileProject as eg,setTitle as tg,slugify as ng,touchSession as ds,upsertSession as og,generateTitle as Bc,findByName as rg,listSessions as ig,renameSession as sg,suggestNextAction as ag,readProjectConfig as te,writeProjectConfig as Vc,resolveAndPersistAppType as lg,detectAppType as cg,resolveModelSetting as hs,loadProfileMap as Gc,applyPull as dg,computeSyncStatus as Yc,lintDocs as zc,compareRemoteSources as ug,planPull as pg,establishBaselines as fg,rebaselineServerMeta as mg,inventoryRepo as hg,knownEnvironments as gg,resolveEnvironment as wg,planPartitions as us,partitionEvenly as yg,screenshotPlaceholderIds as kg,trackedArticlePaths as bg,runPartitioned as Zo,estimateBulkCost as Kc,resolveModelForOperation as er,readDocsPlan as $g,checkForUpdate as xg,detectInstallKind as vg,isSelfUpdatable as Cg,devHintsGuidePath as Xc,toolFeedbackPath as Qc,reconcileToolFeedback as Rg,reconcileUpgradeActions as Pg,stampArticles as ps,listArticleFiles as Jc,CONTENT_CAP_VERSION as fs,ENGINE_VERSION as sd,DEFAULT_DOCS_DIR as ad,setProfileProject as Tg,writeCrashLog as Sg,applyStructureOrder as Zc,orderSyncLine as ed,applyRelatedArticles as td,relatedSyncLine as nd}from"document360-engine";Ke();import{spawn as hc}from"node:child_process";function Th(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Sh(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?hc([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):hc(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",c=>o(c===0)),r.stdin?.on("error",()=>o(!1));let i=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(i)}catch{o(!1)}})}async function os(e){for(let[t,n]of Th())if(await Sh(t,n,e))return!0;return!1}var Dh=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function rs(e,t){if(t.closed)return e;let n=e.split(`
|
|
296
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let i=n[r];if(!t.cueSeen){Dh.test(i)&&(t.cueSeen=!0);continue}let c=/^(\s{0,3})[-*•]\s+(.*)$/.exec(i);c?(n[r]=`${c[1]}${++t.num}. ${c[2]}`,o=!0):o&&i.trim()!==""&&/^\S/.test(i)&&(t.closed=!0)}return n.join(`
|
|
297
|
+
`)}import{existsSync as Ah,mkdirSync as jh,readFileSync as Eh,writeFileSync as Nh}from"node:fs";import{join as gc}from"node:path";import{writerDir as Ih}from"document360-engine";function wc(e){return gc(Ih(e),".sessions")}function yc(e,t){return gc(wc(e),`${t}.json`)}function kc(e,t,n){try{jh(wc(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Nh(yc(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function is(e,t){try{let n=yc(e,t);if(!Ah(n))return[];let o=JSON.parse(Eh(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var _h=e=>`\x1B]0;${e}\x07`,Oh=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function bc(e){process.stdout.isTTY&&process.stdout.write(e)}function Gt(e){bc(_h(e))}function Bo(e){bc(Oh(e))}var Vo=["\xB7 "," \xB7"],Go="\u{1F7E3}";So();go();var Yo=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path> | --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:"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","/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 xc(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if($c[n])return $c[n];let o=Yo.find(r=>r.name===t);return o?o.desc:""}function vc(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Yo.filter(n=>n.name.startsWith(t))}function Cc(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}U();import{Box as Rc,Text as ce}from"ink";import{jsx as de,jsxs as zo}from"react/jsx-runtime";function Lh({row:e}){switch(e.t){case"head":return de(ce,{color:q,bold:!0,children:e.s});case"text":return de(ce,{children:e.s});case"dim":return de(ce,{dimColor:!0,children:e.s});case"sub":return de(ce,{bold:!0,dimColor:!0,children:e.s});case"good":return de(ce,{color:"green",children:e.s});case"step":return zo(ce,{children:[de(ce,{color:q,children:`${e.n}. `}),e.s]});case"cmd":return zo(ce,{children:[" ",de(ce,{color:q,children:e.name.padEnd(20)}),de(ce,{dimColor:!0,children:e.s})]});case"gap":return de(ce,{children:" "})}}function Pc({tab:e,width:t,version:n,engineVersion:o}){let r=Te[e]??Te[0],i=6+Te.reduce((p,m)=>p+m.label.length+4,0),c="\u2500".repeat(Math.min(i,Math.max(t-1,20)));return zo(Rc,{flexDirection:"column",paddingX:1,children:[zo(ce,{children:[de(ce,{color:q,bold:!0,children:"Help "}),Te.map((p,m)=>m===e?de(ce,{color:"white",backgroundColor:q,bold:!0,children:` ${p.label} `},p.key):de(ce,{dimColor:!0,children:` ${p.label} `},p.key))]}),de(ce,{color:q,children:c}),de(Rc,{flexDirection:"column",marginTop:1,children:r.rows.map((p,m)=>de(Lh,{row:p},m))}),de(ce,{dimColor:!0,children:`
|
|
298
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var Mh=/^(?:\d+[.)]|[-*•])\s+/;function Tc(e,t,n=4){let o=new Set(t.map(i=>i.toLowerCase())),r=[];for(let i of e.split(`
|
|
299
|
+
`)){let c=i.trim().replace(Mh,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let m=c.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}U();function Sn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function He(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Sc(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Uh=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Dc(e,t,n){if(!Uh.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 c=i.replace(/\\/g,"/");return r===c||r.endsWith(`/${c}`)})??null}function ss(e){return e.replace(/^[\w.-]+\//,"")}var Ko=16,Ac={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function wt(e){return typeof e=="string"?e:e.cmd}function jc(e){return typeof e=="string"?void 0:e.desc}function as(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Ec(e,t){let n=as(t);return e.some(r=>wt(r).trim()===t.trim()||!!n&&as(wt(r))===n)?e.filter(r=>wt(r).trim()!==t.trim()&&!(n&&as(wt(r))===n)):[]}import{isDirectiveMention as Dg,stripDirectiveMention as Ag,appendDirective as jg}from"document360-engine";var Wh=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Nc(e){return e.replace(/\r\n?/g,`
|
|
300
|
+
`)}function Ic(e){return e.includes(`
|
|
301
|
+
`)||e.length>200}function _c(e,t){let n=t.split(`
|
|
302
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Oc(e,t){return e.replace(Wh,n=>t.get(n)??n)}function Lc(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Xo(e,t){let n=Math.max(1,t),o=[],r=0;for(let i of e.split(`
|
|
303
|
+
`)){if(i.length===0)o.push({start:r,end:r});else for(let c=0;c<i.length;c+=n)o.push({start:r+c,end:r+Math.min(c+n,i.length)});r+=i.length+1}return o.length>0?o:[{start:0,end:0}]}function Qo(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Mc(e,t,n){let o=Qo(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 Uc(e,t,n){let o=e[Qo(e,t)];return n==="start"?o.start:o.end}function Wc(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
304
|
+
`),i=0;for(let c=r.length-1;c>=0;c--){let p=r[c];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(c+1)].join(`
|
|
305
|
+
`),truncated:c>0||m>0}}}return{text:e,truncated:!1}}function Fc(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 Hc(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
306
|
+
`)){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 tr,jsx as j,jsxs as G}from"react/jsx-runtime";var Eg={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},od=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
307
307
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
308
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
309
|
-
${
|
|
310
|
-
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)){
|
|
311
|
-
${
|
|
312
|
-
`)}),Nt(ft()),
|
|
313
|
-
`)})}catch{}let
|
|
308
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Ng(e,t,n,o){let r=ms(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)",c=hs(e),p=te(e),m=(p?.docsDir??ad).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${m}/ + config`,g={version:t,engineVersion:sd,claude:i,model:c.model,modelSource:Eg[c.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=xe(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 $=yt(T.name);if($){let I={...Kt($.idToken)??{},...Kt($.accessToken)??{}},C=I.email??I.preferred_username??"signed in";et($)?$.refreshToken&&(g.who=C,g.loggedOut=!1,g.sessionHint="session expired \u2014 refreshing\u2026"):(g.who=C,g.loggedOut=!1,g.sessionHint=`session valid until ${new Date($.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return g}function Ig(e,t){try{let n=xe(e,t),o=yt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Kt(o.idToken)??{},...Kt(o.accessToken)??{}},i=r.email??r.preferred_username??"signed in";return et(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 rd=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Xt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],_g="Ask me to write or update an article\u2026";function zt({ch:e,dim:t}){let[n,o]=W(!0);return ve(()=>{let r=setInterval(()=>o(i=>!i),530);return()=>clearInterval(r)},[]),j(A,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Og=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function id(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Lg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Mg({startTime:e,chars:t}){let[n,o]=W(0);ve(()=>{let m=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(m)},[]);let r=Xt[n%Xt.length],i=rd[Math.floor(n/16)%rd.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return G(ne,{children:[j(A,{color:q,children:` ${r} ${i}\u2026 `}),j(A,{color:"gray",children:`(${gn(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function Ug({text:e}){let[t,n]=W(0);return ve(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),j(ne,{paddingX:1,children:j(A,{color:q,children:`${Xt[t%Xt.length]} ${e}`})})}var Wg=12e4;function Fg({p:e}){let[t,n]=W(0);ve(()=>{let S=setInterval(()=>n(M=>M+1),150);return()=>clearInterval(S)},[]);let o=Xt[t%Xt.length],r=Math.floor((Date.now()-e.startedAt)/1e3),i=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),p=Date.now()-e.lastAt>=Wg,m=e.verb??"Converting",k=e.unit??"article",g=e.rows.reduce((S,M)=>S+M.items,0),T=m.toLowerCase(),$=e.rows,I=0;if($.length>Ko){let S=$.findIndex(B=>B.status==="active"||B.status==="pending"),M=Math.max(0,Math.min(S-2,$.length-Ko));I=$.slice(0,M).filter(B=>B.status==="done").length,$=$.slice(M,M+Ko)}let C=Math.min(40,Math.max(...$.map(S=>ss(S.label).length),0)),E=S=>S==="failed"?"red":S==="active"?q:void 0;return G(ne,{flexDirection:"column",children:[G(ne,{children:[j(A,{color:q,children:` ${o} ${m} ${g} ${k}${g===1?"":"s"} `}),j(A,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${gn(r)} \xB7 esc to stop`})]}),I>0&&j(A,{dimColor:!0,children:` \u2714 +${I} done`}),$.map(S=>G(A,{color:E(S.status),dimColor:S.status==="done"||S.status==="pending",children:[` ${Ac[S.status]} ${ss(S.label).padEnd(C)}`,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&&j(A,{color:"yellow",children:` \u26A0 no activity for ${gn(i)} \u2014 press esc to stop if it's wedged`})]})}var Hg=10800*1e3;function ld({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Fh(),[i,c]=W(n),[p,m]=W(null),[k,g]=W({text:"",pos:0}),T=k.text,$=Y(l=>{g(a=>{let s=typeof l=="function"?l(a.text):l;return{text:s,pos:s.length}})},[]),I=Y(l=>{g(a=>({text:a.text.slice(0,a.pos)+l+a.text.slice(a.pos),pos:a.pos+l.length}))},[]),C=Y(()=>{g(l=>{if(l.pos===0)return l;let a=l.text.slice(0,l.pos),s=Lc(a)??a.slice(0,-1);return{text:s+l.text.slice(l.pos),pos:s.length}})},[]),[E,S]=W(!1),[M,B]=W(!1),[J,X]=W(0),[ae,kt]=W(null),[Qt,ks]=W(null),[tt,nt]=W([]),An=ee(!1),or=ee(!1),[rr,bs]=W(!1),jn=ee(0),[hd,En]=W(!1),[gd,Nn]=W(!1),[ir,$s]=W(null),[wd,bt]=W(0),ot=ee(0),[Jt,$t]=W(0),[xt,In]=W(null),xs=ee(new Map),yd=ee(0),vt=ee([]),Ce=ee(null);Ce.current===null&&(Ce.current=qc({cwd:e,profileName:i,allowProdWrites:!1}));let _e=ee({uuid:null,firstPrompt:null,titleFired:!1}),_n=ee(new Map),Ct=ee(!1),sr=ee([]),Ae=ee([]),On=ee(null),[vs,rt]=W(null),ar=ee(null),[it,st]=W(null),[Oe,Rt]=W(null),[Le,Pt]=W(null),[pe,Tt]=W(null),[ge,at]=W(null),[qe,St]=W(null),[Me,lt]=W(null),[Cs,Zt]=W(null),[we,ct]=W(null),[fe,Dt]=W(null),[Rs,lr]=W([]),dt=ee([]),en=ee(!1),Re=ee(null),[Ln,oe]=W(null),[Ps,Ts]=W(null),Mn=ee(!1),Un=ee(null),tn=ee(null),[ye,ut]=W(null),[Wn,nn]=W(null),cr=!!(Le||pe||ge||qe||Me||we||fe||ye||Wn),[Ss,At]=W(0),[Ds,jt]=W(0),[kd,As]=W(0),dr=ls(()=>{try{let l=hs(e);return l.source==="auto"?`${l.model} (auto)`:l.model}catch{return null}},[e,kd]),{stdout:je}=qh(),[,bd]=W(0),js=ee(`${je.columns??80}x${je.rows??24}`),Be=Y(()=>Math.max(20,(je.columns??80)-1),[je]),d=Y(l=>{vt.current.push(l),console.log(Ur(l,Be()))},[Be]),me=Y((l,a)=>{jn.current++,kt(l),ks(a??null)},[]),Ve=Y(()=>{jn.current++,kt(null),ks(null)},[]),K=Y(l=>me(l,Oo({kind:"cmd",cmd:l,reason:""})),[me]),Es=Y((l,a)=>{!a?.silent&&l.note&&d({kind:"note",tone:l.tone,text:l.note}),l.picker&&(nt(l.picker.options.map(s=>({cmd:s.cmd,desc:s.desc}))),Zt(l.picker.title)),l.lead&&me(l.lead.kind==="cmd"?l.lead.cmd:l.lead.text,Oo(l.lead))},[d,me]),Et=Y((l,a,s="info")=>{l&&d({kind:"note",tone:s,text:l}),a&&me(a.kind==="cmd"?a.cmd:a.text,Oo(a))},[d,me]),[on,ur]=W(null),[$d,Ns]=W(!1),Nt=Y(l=>{ur(l),Ns(!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]),pr=ee(!1),fr=Y(async()=>{try{if(pr.current||!Cg(vg())||te(e)?.mode==="engineer")return;let l=await xg({pkg:gt,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;pr.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${gt} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),Nn(!0),(await Eo().finally(()=>Nn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),K("/exit"),$s(l.latest)):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${jo}`})}catch{}},[e,o,d,K]),mr=Y(l=>{let a=Fe(e,i);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),tn.current=l,K("/login"),!1)},[e,i,d,K]),[Fn,hr]=W(null),rn=ee(!0),Hn=ee(0),sn=ee(0);ve(()=>{let l=setInterval(()=>{if(rn.current){Hn.current=0,sn.current=0;return}if(!E)try{if(!Yt(Xc(e)))return;if(Se(e).status==="current"){rn.current=!0,Hn.current=0,sn.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."}),ur(null),me("write the docs for this repo");return}Hn.current+=1;let a=Hn.current;if((a===4||a%15===0)&&sn.current<3){sn.current+=1;let s=sn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:We(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(l)},[e,E,d]),ve(()=>{let l=vs??Dn(e);if(!E){Bo(0),Gt(`${Go} ${l}`);return}Bo(3);let a=0;Gt(`${Vo[0]} ${l}`);let s=setInterval(()=>{a=(a+1)%Vo.length,Gt(`${Vo[a]} ${l}`)},400);return()=>clearInterval(s)},[E,e,vs]),ve(()=>()=>Bo(0),[]);let an=Y(l=>{let a=Tn(e,i,{claudeMissing:ms(t).state==="missing",allowAutoAudit:l,genreUnknown:or.current});return a?Pn(a):{kind:"idle"}},[e,i,t]);ve(()=>{let l=performance.now(),a=[],s=(y,x)=>{let v=performance.now();try{return x()}finally{let V=Math.round(performance.now()-v);V>=80&&a.push(`${y}: ${V}ms`)}};d({kind:"banner",info:s("banner",()=>Ng(e,o,t,i))});let h=ms(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.
|
|
309
|
+
${Gh}
|
|
310
|
+
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:
|
|
311
|
+
${od}`}),K(h?"/doctor":"/init");return}h&&K("/doctor");try{let y=xe(e,i),x=yt(y.name);x&&et(x)&&x.refreshToken?Xh({profile:y.name,connection:y.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),X(v=>v+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),K("/login")}):(!x||et(x))&&(d({kind:"note",tone:"warn",text:`Profile "${y.name}" is not signed in \u2014 sign in with /login.`}),K("/login"))}catch{}try{let y=te(e),x=xe(e,i),v=yt(x.name);y&&v&&!et(v)&&Xi(e,y.authoritativeSourceFiles)&&!Qi(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."}),K("/scope"))}catch{}try{let y=s("resolve-genre",()=>lg(e));y.persisted&&y.appType?d({kind:"note",tone:"ok",text:`\u2713 Detected a ${y.appType} app \u2014 enabled the ${y.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):y.source==="unknown"&&te(e)&&(or.current=!0)}catch{}let u=Se(e);try{if(s("reconcile-devhints",()=>po(e)),u.status!=="current"&&!We(e)){let y=fo(e);y.length&&(d({kind:"note",tone:"warn",text:y.join(`
|
|
312
|
+
`)}),Nt(ft()),rn.current=!1)}}catch{}try{let y=s("reconcile-feedback",()=>Rg(e));y.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${y.archived} resolved item${y.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${y.open>0?`; ${y.open} still open`:""}.`})}catch{}try{let y=s("upgrade-actions",()=>Pg(e));y.applied.length>0&&d({kind:"note",tone:"warn",text:Mo(y.applied).join(`
|
|
313
|
+
`)})}catch{}let w=s("ready-decision",()=>an(!0));w.kind==="autoAudit"?(d({kind:"note",tone:"info",text:w.note}),yn().then(y=>{y.kind==="forward-to-agent"&&y.prompt&&ie(y.prompt,{display:y.display,quietUser:!0})})):w.kind==="recommend"&&Es(w.rec);let b=Math.round(performance.now()-l);b>=800&&Sg({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(`
|
|
314
314
|
`):"no single phase \u226580ms"}
|
|
315
|
-
cwd: ${e}`}),
|
|
316
|
-
`)});let
|
|
317
|
-
`)}),Nt(ft()),
|
|
318
|
-
`)}),Nt(
|
|
319
|
-
${
|
|
320
|
-
`)});return}case"mcp":await
|
|
321
|
-
`:"",
|
|
322
|
-
Model: ${
|
|
323
|
-
`)+
|
|
324
|
-
`)})}}catch(
|
|
315
|
+
cwd: ${e}`}),fr()},[]),ve(()=>{let l=setInterval(()=>{fr()},Hg);return()=>clearInterval(l)},[fr]),ve(()=>{if(E||rr||An.current||ae!==null||tt.length>0||T!==""||on!==null||Ae.current.length>0||On.current||cr)return;let l=an(!1);l.kind==="recommend"&&(l.rec.lead||l.rec.picker)&&Es(l.rec,{silent:!0})},[E,ae,tt,T,on,cr,J,an,rr]),ve(()=>{let l=null,a=null,s=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let h=`${je.columns??80}x${je.rows??24}`;h!==js.current&&(js.current=h,bd(u=>u+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+_a(vt.current,Be())+"\x1B[?2026l")},80))},400)};return je.on("resize",s),()=>{l&&clearTimeout(l),a&&clearTimeout(a),je.off("resize",s)}},[je,Be]);let Ee=Math.max(20,(je.columns??80)-1),Is=ls(()=>Ig(e,i),[e,i,J]),gr=(()=>{if(gd)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(ir!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${ir?` v${ir}`:""}\u2026`,isSetup:!0};if(Fn)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(on)return $d?{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(Ae.current.length>0)return{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let l=te(e);if(!l)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let a=cs(e,(l.docsDir??ad).replace(/\/+$/,"")),s=(()=>{try{return Yt(a)&&Bh(a).length>0}catch{return!1}})();try{let h=xe(e,i),u=yt(h.name);if(!(!!u&&!(et(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:_g,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),ln=vc(T),_s=ln.length>0&&!E,wr=p!==null?Wc(p,8,Ee):null,qn=we?we.paths.filter(l=>!we.query||l.toLowerCase().includes(we.query.toLowerCase())).slice(0,8):[],Bn=ye?ye.sessions.filter(l=>{let a=ye.query.toLowerCase();return!a||l.name.toLowerCase().includes(a)||l.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],ke=Y((l,a)=>{Ce.current?.close(),Ce.current=qc({cwd:e,resume:l,profileName:a??i,allowProdWrites:Ct.current}),l||(_e.current={uuid:null,firstPrompt:null,titleFired:!1},rt(null)),At(0),jt(0)},[e,i]),Os=Y((l,a,s)=>{if(Og.test(l))try{let h=xe(e,i),u=typeof a.project_id=="string"&&a.project_id||h.project.projectId,w=Ho(a,s),b=[],y=qo(s);l.endsWith("publish_article")&&y&&b.push(`Live: ${y}`),w&&u&&b.push(`Preview: ${Fo(h.connection.portalUrl,u,w,h.project.languageCode??"en")}`),b.length>0&&d({kind:"link",lines:b})}catch{}},[e,i,d]),ie=Y(async(l,a)=>{En(!0),An.current=!1,Ve(),nt([]),Zt(null),ur(null);let s=jn.current;a?.quietUser||d({kind:"user",text:a?.echoDisplay&&a.display?a.display:l});let h=_e.current;h.firstPrompt||(h.firstPrompt=a?.display??l),ot.current=Date.now(),bt(0),S(!0),_n.current.clear();let u="",w=!1,b=!1,y="",x={num:0,closed:!1,cueSeen:!1},v=null,V=()=>{v||(v=setTimeout(()=>{v=null,m(y.length>0?y:null)},60))},F=()=>{v&&clearTimeout(v),v=null,m(null)},_=(P=!1)=>{let{head:D,keep:H}=Fc(y,P);D.trim()&&d({kind:"assistant",text:rs(D.trimEnd(),x)}),y=H,F()};try{for await(let P of Ce.current.send(l))if(P.type==="session"){if(!h.uuid){h.uuid=P.sessionId;let D=new Date().toISOString(),H=ar.current,Z=H??ng(h.firstPrompt??"session");og({uuid:P.sessionId,name:Z,renamed:!!H,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:D,updatedAt:D}),rt(Z),ar.current=null}}else if(P.type==="text"){y+=P.delta,u+=P.delta;let D=Hc(y);if(D>0){let H=y.slice(0,D).trimEnd();H&&d({kind:"assistant",text:rs(H,x)}),y=y.slice(D)}V(),bt(H=>H+P.delta.length)}else if(P.type==="tool"){w=!0;let D=Uo(P.name,P.input);D&&(_(),d({kind:"tool",title:D.title,sep:D.sep,arg:D.arg}),_n.current.set(P.id,{name:P.name,input:P.input}))}else if(P.type==="article_diff"){let D=mt(P.oldContent,P.newContent,Be());D&&(_(),d({kind:"diff",added:D.added,removed:D.removed,lines:D.lines,hidden:D.hidden}))}else if(P.type==="tool_result"){P.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(P.output)&&(Mn.current=!0);let D=_n.current.get(P.id);if(D){_n.current.delete(P.id),_();let H=Wo(P.output,4,P.isError?void 0:D.name,D.input);d({kind:"tool-result",lines:H.lines,hidden:H.hidden,isError:P.isError}),P.isError||Os(D.name,D.input,P.output)}}else if(P.type==="result"){if(_(!0),At(D=>D+P.outputTokens),jt(D=>D+P.costUsd),d({kind:"done",seconds:Math.round((Date.now()-ot.current)/1e3),tokens:P.outputTokens,costUsd:P.costUsd,ok:P.ok}),!b&&!w&&!u.trim()&&!en.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)."}),P.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let D=Qc(e);if(Yt(D)){let H=Jo(D,"utf8").trim();H&&(hr(H),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(P.ok&&x.cueSeen)bs(!0),nt([]);else{let D=P.ok?Tc(u,Yo.map(H=>H.name)):[];if(D.length>0)K(D[0]);else if(P.ok&&u.trim()){let H=an(!1);H.kind==="recommend"&&(H.rec.lead||H.rec.picker)||ag(l,u,e).then(Z=>{Z&&jn.current===s&&me(Z)}).catch(()=>{})}}if(h.uuid&&(ds(h.uuid),!h.titleFired)){h.titleFired=!0;let D=h.uuid,H=h.firstPrompt;H&&Bc(H,e).then(Z=>{Z&&(tg(D,Z),rt(Z))}).catch(()=>{})}}else P.type==="error"&&(_(!0),b=!0,P.kind==="auth"&&(Mn.current=!0),d({kind:"note",text:`agent error: ${P.message}`,tone:"error"}))}finally{S(!1),F(),X(P=>P+1),_e.current.uuid&&kc(e,_e.current.uuid,vt.current),Mn.current&&(Mn.current=!1,Un.current=a?.display??l,me("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")),en.current&&(en.current=!1,dt.current.length>0&&(d({kind:"note",tone:"info",text:`(${dt.current.length} queued message(s) discarded)`}),dt.current=[],lr([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Os,Be,me,K,Ve,an]),Vn=Y(async l=>{let a=er(e,"standard");ot.current=Date.now(),bt(0),S(!0);let s=new AbortController;Re.current=s;let h=async(u,w)=>{let b=us(u);oe({verb:"Publishing",total:b.length,done:0,active:[],rows:Sn(b),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:w?`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${wn} agents at once) on ${a.model}\u2026 (esc to stop)`});let y=!1;for await(let x of Zo({cwd:e,partitions:b,promptFor:v=>bo(v.paths),concurrency:wn,profileName:i,allowProdWrites:Ct.current,model:a.model,signal:s.signal}))if(x.type==="partition_status")x.status==="running"?oe(v=>v&&{...v,active:[...v.active,x.label],rows:He(v.rows,x.label,"active"),lastAt:Date.now()}):oe(v=>v&&{...v,active:v.active.filter(V=>V!==x.label),done:v.done+1,rows:He(v.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_event")oe(v=>{if(!v)return v;let V={...v,lastAt:Date.now()};return x.event.type==="tool"?V.tools=v.tools+1:x.event.type==="text"&&(V.chars=v.chars+x.event.delta.length),V});else if(x.type==="run_done"){y=x.aborted,jt(_=>_+x.totalCostUsd),At(_=>_+x.results.reduce((P,D)=>P+D.outputTokens,0));let v=x.aborted?"Stopped. ":"",V=t.kind==="api"?"api":"subscription";d({kind:"note",tone:x.aborted?"warn":x.ok?"ok":"warn",text:v+qr(x.results,b,V).join(`
|
|
316
|
+
`)});let F=Hr(e,i);if(F&&d({kind:"note",tone:"info",text:F}),!x.aborted){try{let _=await Zc({cwd:e,profileName:i}),P=ed(_);P?d({kind:"note",tone:"info",text:P}):_.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${_.skipped}`})}catch(_){d({kind:"note",tone:"warn",text:`Order sync failed: ${_.message}`})}try{let _=nd(await td({cwd:e,profileName:i}));_&&d({kind:"note",tone:"info",text:_})}catch(_){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${_.message}`})}}}return y};try{if(!await h(l,!1)){let w=await Br(e,i,l);w.length>0&&await h(w,!0)}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{Re.current=null,oe(null),S(!1),X(u=>u+1)}},[e,i,d,t]),yr=Y(async l=>{await ie(Fr(l),{display:`/publish ${l}`,quietUser:!0});try{let a=await $o(e,i,l.replace(/\\/g,"/"));a.length>0&&(Zt(`Related articles not yet published (${a.length}):`),nt([`/publish --related ${l}`,...a.map(s=>`/publish ${s}`)]))}catch{}},[e,i,ie]),kr=Y(l=>{let a=yt(l);if(!a||et(a)&&!a.refreshToken)return null;let s={...Kt(a.idToken)??{},...Kt(a.accessToken)??{}};return s.email??s.preferred_username??"signed in"},[]),br=Y((l,a)=>{if(a){let s=te(e);s&&(s.defaultProfile=l,Vc(s,e))}c(l),ke(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),kr(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 sign in with /login.`}),K("/login")),X(s=>s+1)},[e,d,ke,kr,K]),Gn=Y((l,a,s)=>{eo(e,l,a,s.id,s.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${s.name??s.id}" (agent restarted).`}),ke(),Gc(e,l)||(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:Ft(Wt(e)).join(`
|
|
317
|
+
`)}),Nt(ft()),rn.current=Se(e).status==="current"||We(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,ke,Nt]),Yn=Y(async l=>{let a;try{a=await pn(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),K("/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],w=a.workspaces.length-h.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${w>0?" (skipped the API-documentation workspace)":""}.`}),Gn(a.profile,a.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),K("/workspace")},[e,d,Gn,K]),zn=Y((l,a)=>{to(e,l,a.id,a.name),d({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),ke(),Yn(l)},[e,d,ke,Yn]),Ls=Y(async l=>{let a;try{a=xe(e,l)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:s}=await ze(e,a.name),h=s.find(u=>u.id===a.project.projectId);h?.name&&Tg(e,a.name,{projectName:h.name})}catch{}await Yn(a.name);return}try{let{projects:s}=await ze(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}".`}),zn(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?"}),at({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."}),K("/project")}},[e,d,Yn,zn,K]),Kn=Y(()=>{let l=Ae.current[0];if(!l)return;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let s of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${s}`});l.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let a=mt(l.oldContent,l.newContent,Be());d(a?{kind:"diff",added:a.added,removed:a.removed,lines:a.lines,hidden:a.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,Be]),Ms=Y(l=>{if(Ae.current.length===0)return!1;let a=l.trim().toLowerCase();if(a==="y"||a==="yes"){let s=Ae.current.shift();try{dg({cwd:e,profileName:i},s),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${s.path} (sync base advanced).`}),Ae.current.length===0&&K("/pull")}catch(h){d({kind:"note",tone:"error",text:`Pull failed: ${h.message}`})}}else if(a==="n"||a==="no"){let s=Ae.current.shift();d({kind:"note",tone:"info",text:`Skipped ${s.path}.`})}else{let s=Ae.current.length;return Ae.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${s} article(s) left untouched).`}),!0}return Kn(),!0},[e,i,Kn,d]),Us=Y(l=>{let a=On.current;if(!a)return!1;if(On.current=null,Ve(),l.trim()!==a.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:s,failed:h}=Mi(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:mo().join(`
|
|
318
|
+
`)}),Nt(Dr())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
319
|
+
${od}`}),K("/init"),En(!1),!0},[e,d,Nt,Ve,K]),cn=Y(async l=>{let a=l.slice(1).trim().split(/\s+/),s=(a[0]??"").toLowerCase(),h=a.slice(1);if(En(!0),Ro(h)&&["write","check","review","reorder"].includes(s)){let u=kn(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 w=b=>s==="write"?`/write ${tl(h,b).join(" ")}`.trim():`/${s} ${[b,...h.filter(y=>y!=="--scope")].join(" ")}`.trim();if(u.length===1){cn(w(u[0].token));return}lt({cursor:0,rows:u,run:b=>{cn(w(b))}});return}if(Je(s,h)){let u=kn(e,i);if(u.length>1){let w=h.filter(v=>v.startsWith("--")).join(" "),b=v=>`/${s}${v?` ${s==="write"?`--scope ${v}`:v}`:""}${w?` ${w}`:""} ${v?"":"--all"}`.replace(/\s+/g," ").trim(),y=u.reduce((v,V)=>v+V.count,0),x={token:"",label:s==="review"?`Everything \u2014 all ${y} articles + structure (IA) review`:s==="reorder"?`Everything \u2014 reorder all ${u.length} categories`:`Everything \u2014 rewrite all ${y} planned articles`,count:y};lt({cursor:0,rows:[x,...u],run:v=>{cn(b(v))}});return}}switch(s){case"help":nn({tab:0});return;case"exit":case"quit":Ce.current?.close(),r();return;case"clear":ke(),vt.current=[],En(!1),Ve(),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=xe(e,i)}catch(w){d({kind:"note",tone:"error",text:w.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 w=await Yh(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},y=>d({kind:"note",tone:"info",text:y})),b=zh(u.name,w);if(Kh(b),await Cr(b,u.name,y=>d({kind:"note",tone:"info",text:y})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${ro(b)}`}),await Ls(i),tn.current){let y=tn.current;tn.current=null;let x=Fe(e,i);x.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${y}.`}),K(y)):(d({kind:"note",tone:"warn",text:`${x.reason} (then ${y}.)`}),K("/login"),tn.current=y)}else Un.current&&(me(Un.current,"\u21E5 tab to re-send your last prompt\u2026"),Un.current=null)}catch(w){d({kind:"note",tone:"error",text:`Login failed: ${w.message}`})}finally{B(!1),X(w=>w+1)}return}case"allow-prod":{let u=!1;try{u=xe(e,i).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Ct.current=!0,ke(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=bi(h.join(" ")),w=_e.current.uuid;if(!w){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}ar.current=u,rt(u),Gt(`${Go} ${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=_e.current.firstPrompt??"";Bc(b,e).then(y=>{y?(me(`/rename ${y}`),d({kind:"note",tone:"info",text:`Suggestion: "${y}" \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}sg(w,u),rt(u),Gt(`${Go} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=h[0],w=te(e);if(!u){let b=Object.entries(w?.profiles??{});if(b.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let y=b.map(([V,F])=>({name:V,env:F.connection?.environment??"custom",prod:F.production===!0,who:kr(V)})),x=i??w?.defaultProfile,v=Math.max(0,y.findIndex(V=>V.name===x));Rt({cursor:v,current:v,rows:y});return}if(u==="add"){let b=$i(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]}).`}),br(h[1],!1);return}if(!w?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}br(u,!0);return}case"doctor":await $n(h,{cwd:e,version:o});return;case"genre":{await _o(h,{cwd:e});try{or.current=!(te(e)?.appType??cg(e))}catch{}X(u=>u+1);return}case"roadmap":{if(h[0]?.toLowerCase()==="done"){let u=Vi(e,h.slice(1).join(" ").trim());d({kind:"note",tone:u.ok?"ok":"warn",text:u.line}),X(w=>w+1);return}d({kind:"note",tone:"info",text:Bi(e).join(`
|
|
320
|
+
`)});return}case"mcp":await wo(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=gg().map(w=>({name:w,apiUrl:wg(w).apiUrl}));Pt({cursor:0,rows:u});return}case"resume":{let u=h.join(" ").trim(),w=ig(e).filter(x=>x.uuid!==_e.current.uuid);if(!u){if(!w.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}ut({query:"",cursor:0,sessions:w});return}let b=rg(e,u);if(!b){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}ke(b.uuid),_e.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},rt(b.name),ds(b.uuid),vt.current=[];let y=is(e,b.uuid);for(let x of y)d(x);d({kind:"note",tone:"ok",text:y.length?`Resumed "${b.name}" \u2014 restored ${y.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(),w;try{w=await pn(e,i)}catch(y){d({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!u){let y=w.workspaces.map(v=>({id:v.id,name:v.name??v.id,type:v.workspace_type}));if(y.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let x=Math.max(0,y.findIndex(v=>v.id===w.current));Tt({cursor:x,current:x,rows:y,profile:w.profile,projectId:w.projectId,projectName:w.projectName,environment:w.environment});return}let b=xr(w.workspaces,u);if(!b){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}Gn(w.profile,w.projectId,b);return}case"project":{let u=h.join(" ").trim(),w;try{w=await ze(e,i)}catch(y){d({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!u){let y=w.projects.map(v=>({id:v.id,name:v.name??v.id,sub:v.sub_domain}));if(y.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let x=y.findIndex(v=>v.id===w.current);at({cursor:Math.max(0,x),current:x,rows:y,profile:w.profile,environment:w.environment});return}let b=vr(w.projects,u);if(!b){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${w.projects.map(y=>y.name??y.id).join(", ")}`});return}zn(w.profile,b);return}case"logout":{let u;try{u=xe(e,i).name}catch(b){d({kind:"note",tone:"error",text:b.message});return}let w=Zh(u);eg(e,u),ke(),X(b=>b+1),d({kind:"note",tone:w?"ok":"info",text:w?`\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."}),K("/login");return}case"publish":{if(!mr(l.trim()))return;if(h[0]==="--related"&&h[1]){let w=await $o(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 Vn(w);return}if(h[0]&&h[0]!=="--all"){await yr(h[0]);return}let u=h[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let w=await Yc({cwd:e,profileName:i}),b=Bt(w.entries),y=ko(w.entries);if(y>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${y} article${y===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.`}),b.length===0){d({kind:"note",tone:"ok",text:y>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let x=w.counts["unknown-base"]??0;x>0&&d({kind:"note",tone:"info",text:`(${x} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Ts("Reconciling structure on Document360 (order + related articles)\u2026");try{let v=await Zc({cwd:e,profileName:i}),V=nd(await td({cwd:e,profileName:i})),F=ed(v);F?d({kind:"note",tone:"info",text:F}):v.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${v.skipped}`}),V&&d({kind:"note",tone:"info",text:V}),d({kind:"note",tone:"ok",text:F||V?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(F||V)&&K("/structure")}catch(v){d({kind:"note",tone:"warn",text:`Structure sync failed: ${v.message}`})}finally{Ts(null)}return}if(u){await Vn(b.map(x=>x.path));return}St({cursor:0,rows:Ha(b)})}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"preview":{let u=h.join(" ").trim();if(!u){let b=[];try{b=Object.keys(Gc(e,xe(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}ct({query:"",cursor:0,paths:b});return}let w=Vh(u)?u:cs(e,u);if(Yt(w)){try{d({kind:"preview",name:Dn(w),text:id(Jo(w,"utf8"))})}catch(b){d({kind:"note",tone:"error",text:`Could not read ${w}: ${b.message}`})}return}if(Lg.test(u)){try{let b=xe(e,i),y={profile:b.name,connection:b.connection},x=b.project.projectId??Qh(y),v=await Jh(y,x,u);d({kind:"preview",name:v.title??u,text:v.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=To(hs(e));st({cursor:x,current:x});return}let{lines:w,changed:b,effective:y}=bn(e,u);for(let x of w)d({kind:"note",tone:x.startsWith("\u26A0")?"warn":x.startsWith("\u2713")?"ok":"info",text:x});b&&(As(x=>x+1),Ce.current?.setModel(y));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:w}=Qr(h),b=bg(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 y=Jr(b,u);if(y.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${b.length} are tracked overall.)`});return}let x=us(y),v=3,V=`/convert${u?` --scope ${u}`:""} --run`,F=er(e,"light");if(!w){let P=Kc({files:Zr(e,y),op:"convert",model:F.model}),D=u?`Scope: ${u} (${y.length} of ${b.length} tracked)
|
|
321
|
+
`:"",H=`
|
|
322
|
+
Model: ${F.model}${F.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:D+ti(x,P,v).join(`
|
|
323
|
+
`)+H}),K(V);return}ot.current=Date.now(),bt(0),S(!0);let _=new AbortController;Re.current=_,oe({verb:"Converting",total:x.length,done:0,active:[],rows:Sn(x),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${y.length} articles across ${x.length} partitions (\u2264${v} agents at once) on ${F.model}\u2026 (esc to stop)`});try{for await(let P of Zo({cwd:e,partitions:x,promptFor:ei,concurrency:v,profileName:i,allowProdWrites:Ct.current,model:F.model,signal:_.signal}))if(P.type==="partition_status")P.status==="running"?oe(D=>D&&{...D,active:[...D.active,P.label],rows:He(D.rows,P.label,"active"),lastAt:Date.now()}):oe(D=>D&&{...D,active:D.active.filter(H=>H!==P.label),done:D.done+1,rows:He(D.rows,P.label,P.status==="done"?"done":"failed"),lastAt:Date.now()});else if(P.type==="partition_event")oe(D=>{if(!D)return D;let H={...D,lastAt:Date.now()};return P.event.type==="tool"?H.tools=D.tools+1:P.event.type==="text"&&(H.chars=D.chars+P.event.delta.length),H});else if(P.type==="run_done"){jt(Z=>Z+P.totalCostUsd),At(Z=>Z+P.results.reduce((_t,Ot)=>_t+Ot.outputTokens,0));let D=P.aborted?"Stopped. ":"",H=t.kind==="api"?"api":"subscription";d({kind:"note",tone:P.aborted?"warn":P.ok?"ok":"warn",text:D+ni(P.results,x,H).join(`
|
|
324
|
+
`)})}}catch(P){d({kind:"note",tone:"error",text:`Convert run failed: ${P.message}`})}finally{Re.current=null,oe(null),S(!1),X(P=>P+1)}return}case"write":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=$g(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:w,path:b,preview:y,concurrency:x,rewrite:v}=ii(h),{docsDir:V,targets:F,reason:_,rewriting:P}=pi(e,u,{scope:w,path:b,rewrite:v});if(F.length===0){d({kind:"note",tone:"warn",text:_??"Nothing to write."});return}P&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${F.length} already-written article${F.length===1?"":"s"} (overwrites them; git has your baseline).`});let D=us(F),H=ri(x),Z=er(e,"standard"),_t=!!b;if(y&&!_t){let z=Kc({files:ai(e,u,F),op:"write",model:Z.model}),re=w?`Scope: ${w} (${F.length} pending)
|
|
325
325
|
`:"",ue=`
|
|
326
|
-
Model: ${
|
|
327
|
-
`)+ue}),K(`/write${
|
|
328
|
-
`)}),!
|
|
329
|
-
${
|
|
330
|
-
`)}`}),nt(
|
|
331
|
-
`)});return}if(
|
|
332
|
-
${
|
|
333
|
-
`)}`}),
|
|
334
|
-
`)});return}if(
|
|
335
|
-
`)}),Et(
|
|
336
|
-
`)}),b.length>0&&Et(`Found ${b.length} doc issue${b.length===1?"":"s"} above. /check${
|
|
337
|
-
`)});return}case"reorder":{let
|
|
338
|
-
`)});return}case"devhints":{if(!te(e)){
|
|
339
|
-
`)}),Nt(ft()),
|
|
340
|
-
`)});return}if(
|
|
341
|
-
`)})}return}case"reset":{let
|
|
342
|
-
`)}),me(Sn(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${s} \u2014 type /help.`})}},[e,r,i,zn,u,ke,ie,Bn,gr,_s]),Kn=V(l=>{let a=(l??D).trim();if($(""),Nn(null),$t(0),a.startsWith("/")&&(Dn.current=!1,Ve(),Qt(null),nt(g=>Ac(g,a))),!a||(ws(!1),Os(a))||Ls(a))return;rr.current.push(a);let s=Ic(a,bs.current);if(a.startsWith("/"))u({kind:"user",text:a}),an(s);else if(Cg(s)){u({kind:"user",text:a});let g=Rg(s);if(!g)ie(s,{display:a,quietUser:!0});else{try{Pg(e,{title:g,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ie(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${g}". 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 "${g}" and the article path(s) you wrote.`,{display:a,quietUser:!0})}}else ie(s,{display:a})},[D,Os,Ls,an,ie]),Ms=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let a=jc(l);if(Ec(a)){let s=Nc(++hd.current,a);bs.current.set(s,a),T(s)}else T(a);return}T(l)},[T]),It=Math.max(10,Ee-6),Us=ss(()=>zo(h.text,It),[h.text,It]),kr=V(l=>k(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+l))})),[]),Xn=V(l=>k(a=>({...a,pos:Lc(zo(a.text,It),a.pos,l)})),[It]),ln=V(l=>k(a=>({...a,pos:Oc(zo(a.text,It),a.pos,l)})),[It]),kd=["\x1B[H","\x1B[1~","\x1BOH"],bd=["\x1B[F","\x1B[4~","\x1BOF"],Ws=V((l,a)=>a.leftArrow?(kr(-1),!0):a.rightArrow?(kr(1),!0):l&&kd.includes(l)?(ln("start"),!0):l&&bd.includes(l)?(ln("end"),!0):a.ctrl&&l==="a"?(ln("start"),!0):a.ctrl&&l==="e"?(ln("end"),!0):!1,[kr,ln]);return Oh((l,a)=>{if(a.ctrl&&l==="c"){Ce.current?.close(),r();return}if(!O){if(S){if(a.escape){if(Re.current){if(!Re.current.signal.aborted){let s=(Ln?.verb??"work").toLowerCase(),g=Ln?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${s} run (finishing in-flight ${g}s)\u2026`}),Re.current.abort()}return}Jt.current||(Jt.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Ce.current?.interrupt());return}if(a.return){let s=D.trim();if(!s)return;dt.current.push(s),sr([...dt.current]),$("");return}if(Ws(l,a))return;if(a.upArrow){Xn(-1);return}if(a.downArrow){Xn(1);return}if(a.backspace||a.delete){P();return}l&&!a.ctrl&&!a.meta&&Ms(l);return}if(it){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(Ie.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ie.length){st(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Ie[it.cursor];st(null);let{lines:g,changed:d,effective:m}=kn(e,s.value??"default");for(let b of g)u({kind:"note",tone:b.startsWith("\u26A0")?"warn":b.startsWith("\u2713")?"ok":"info",text:b});d&&(Ss(b=>b+1),Ce.current?.setModel(m));return}if(l==="s"){let s=Ie[it.cursor];st(null),Ce.current?.setModel(s.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${s.label} for this session only (your saved default is unchanged).`});return}if(a.escape){st(null);return}return}if(Le){if(a.upArrow){Rt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Rt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Le.rows.length){Rt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return||l==="s"){let s=Le.rows[Le.cursor];Rt(null),wr(s.name,a.return===!0);return}if(a.escape){Rt(null);return}return}if(Un){if(a.escape){en(null);return}if(a.leftArrow||a.tab&&a.shift){en(s=>s&&{tab:(s.tab-1+Te.length)%Te.length});return}if(a.rightArrow||a.tab){en(s=>s&&{tab:(s.tab+1)%Te.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Te.length){en({tab:Number(l)-1});return}return}if(Oe){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(l&&/^[1-9]$/.test(l)&&Number(l)<=Oe.rows.length){Pt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Oe.rows[Oe.cursor].name;if(Pt(null),!Sr(e,s).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${s}").`});let d=!1;try{let m=wt(s);d=!!m&&!(et(m)&&!m.refreshToken)}catch{d=!1}u({kind:"note",tone:"info",text:d?`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"),Q(m=>m+1);return}if(a.escape){Pt(null);return}return}if(pe){if(a.upArrow){Tt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Tt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=pe.rows.length){Tt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=pe.rows[pe.cursor],{profile:g,projectId:d}=pe;Tt(null),Vn(g,d,s);return}if(a.escape){Tt(null);return}return}if(ge){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(l&&/^[1-9]$/.test(l)&&Number(l)<=ge.rows.length){at(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=ge.rows[ge.cursor],{profile:g}=ge;at(null),Yn(g,s);return}if(a.escape){at(null);return}return}if(fe){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(l===" "){Dt(s=>s&&{...s,rows:s.rows.map((g,d)=>d===s.cursor?{...g,checked:!g.checked}:g)});return}if(a.return){let s=fe.rows.filter(g=>g.checked).map(g=>g.path);if(Dt(null),s.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}qr(e,s),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${s.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let g of s)u({kind:"note",tone:"info",text:` ${g}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){Dt(null);return}return}if(Me){if(a.upArrow){lt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){lt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Me.rows.length){lt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Me.rows[Me.cursor],g=Me.run;lt(null),g(s.token);return}if(a.escape){lt(null);return}return}if(qe){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(l&&/^[1-9]$/.test(l)&&Number(l)<=qe.rows.length){St(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=qe.rows[qe.cursor];St(null),s.kind==="article"?gr(s.paths[0]):Bn(s.paths);return}if(a.escape){St(null);return}return}if(ye){if(a.escape){ct(null);return}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(Math.max(0,Hn.length-1),s.cursor+1)});return}if(a.return){let s=Hn[ye.cursor];if(s){ct(null);try{u({kind:"preview",name:Sn(s),text:nd(Xo(as(e,s),"utf8"))})}catch(g){u({kind:"note",tone:"error",text:`Could not read ${s}: ${g.message}`})}}return}if(a.backspace||a.delete){ct(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){ct(s=>s&&{...s,query:s.query+l,cursor:0});return}return}if(we){if(a.escape){ut(null);return}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(Math.max(0,qn.length-1),s.cursor+1)});return}if(a.return){let s=qn[we.cursor];if(s){ut(null),ke(s.uuid),_e.current={uuid:s.uuid,firstPrompt:s.firstPrompt,titleFired:!0},rt(s.name),ls(s.uuid),vt.current=[];let g=os(e,s.uuid);for(let d of g)u(d);u({kind:"note",tone:"ok",text:g.length?`Resumed "${s.name}" \u2014 restored ${g.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){ut(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){ut(s=>s&&{...s,query:s.query+l,cursor:0});return}return}if(a.tab&&!D&&ae){$(ae),Ve();return}if(!D&&tt.length>0&&!nr&&l&&/^[1-9]$/.test(l)){let s=tt[Number(l)-1];if(s){$(yt(s));return}}if(!D&&(Wn||tn)&&l==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let s=Wn!=null;ts(Wn??tn).then(d=>{u({kind:"note",tone:d?"ok":"warn",text:d?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."}),d&&s&&fr(null),d&&!s&&js(!0)});return}if(!Ws(l,a)){if(Ns){if(a.upArrow){$t(s=>Math.max(0,s-1));return}if(a.downArrow){$t(s=>Math.min(sn.length-1,s+1));return}if(a.tab){$("/"+(sn[Xt]?.name??"")+" "),$t(0);return}if(a.return){let s=sn[Xt];if(s){let g=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(xc(s.usage)&&!g){$("/"+s.name+" "),$t(0);return}Kn("/"+s.name+(g?" "+g:""));return}}}else{if(a.upArrow){if(D!==""&&xt===null){Xn(-1);return}let s=rr.current;if(!s.length)return;let g=xt===null?s.length-1:Math.max(0,xt-1);Nn(g),$(s[g]??"");return}if(a.downArrow){if(D!==""&&xt===null){Xn(1);return}let s=rr.current;if(xt===null)return;let g=xt+1;g>=s.length?(Nn(null),$("")):(Nn(g),$(s[g]??""));return}}if(a.return){Kn();return}if(a.backspace||a.delete){P();return}if(a.escape){$(""),$t(0),Ve(),nt([]),Qt(null),Dn.current=!0;return}l&&!a.ctrl&&!a.meta&&Ms(l)}}}),ve(()=>{if(S||O)return;let l=dt.current.shift();l!==void 0&&(sr([...dt.current]),Kn(l))},[S,O,Kn]),B(ne,{flexDirection:"column",width:Ee,children:[hr!==null&&B(ne,{marginTop:1,flexDirection:"column",children:[hr.truncated&&j(A,{dimColor:!0,children:"\u2026"}),j(A,{children:hr.text})]}),S&&(Ln?j(Lg,{p:Ln}):j(Ng,{startTime:ot.current,chars:md})),!S&&Cs?j(Ig,{text:Cs}):null,j(ne,{borderStyle:"round",borderColor:Es.prod?"yellow":F,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?Us.map((l,a)=>{let s=h.text.slice(l.start,l.end),g=a===Ko(Us,h.pos),d=Math.min(h.pos,l.end)-l.start;return B(A,{children:[j(A,{color:F,children:a===0?"> ":" "}),g?B(Zo,{children:[s.slice(0,d),j(Yt,{ch:s[d]??" "}),s.slice(d+1)]}):s||" "]},`${a}-${l.start}`)}):B(A,{children:[j(A,{color:F,children:"> "}),ar?j(Yt,{ch:" "}):ae&&!S&&er?B(Zo,{children:[j(Yt,{ch:er[0],dim:!0}),j(A,{color:"gray",children:er.slice(1)})]}):ae&&!S?B(Zo,{children:[j(Yt,{ch:ae[0],dim:!0}),j(A,{color:"gray",children:ae.slice(1)}),j(A,{dimColor:!0,children:" (tab)"})]}):(mr.isSetup||!pd)&&!S?B(Zo,{children:[j(Yt,{ch:mr.text[0],dim:!0}),j(A,{color:"gray",children:mr.text.slice(1)})]}):j(Yt,{ch:" "})]})}),vs.length>0&&j(ne,{flexDirection:"column",paddingX:1,children:vs.map((l,a)=>j(A,{color:"gray",children:`\u29D7 queued: ${l}`},`${a}-${l.slice(0,24)}`))}),Un?j(Cc,{tab:Un.tab,width:Ee}):it?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Select model"}),j(A,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ie.map((l,a)=>B(A,{color:a===it.cursor?F:void 0,children:[a===it.cursor?"\u276F ":" ",`${a+1}. ${l.label}${a===it.current?" \u2714":""}`.padEnd(16),j(A,{color:"gray",children:l.desc})]},l.label)),j(A,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Le?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Switch connection profile"}),Le.rows.map((l,a)=>B(A,{color:a===Le.cursor?F:void 0,children:[a===Le.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===Le.current?" \u2714":""}`.padEnd(20),j(A,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?j(A,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),j(A,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Oe?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Pick your Document360 environment"}),Oe.rows.map((l,a)=>B(A,{color:a===Oe.cursor?F:void 0,children:[a===Oe.cursor?"\u276F ":" ",`${a+1}. ${l.name}`.padEnd(16),j(A,{color:"gray",children:l.apiUrl})]},l.name)),j(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):pe?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Switch workspace"}),j(A,{dimColor:!0,children:`environment ${pe.environment} \xB7 project ${pe.projectName??`${pe.projectId.slice(0,8)}\u2026`}`}),pe.rows.map((l,a)=>B(A,{color:a===pe.cursor?F:void 0,children:[a===pe.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===pe.current?" \u2714":""}`.padEnd(30),j(A,{color:"gray",children:l.type??""})]},l.id)),j(A,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ge?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Choose project"}),j(A,{dimColor:!0,children:`environment ${ge.environment}`}),ge.rows.map((l,a)=>B(A,{color:a===ge.cursor?F:void 0,children:[a===ge.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===ge.current?" \u2714":""}`.padEnd(30),j(A,{color:"gray",children:l.sub??""})]},l.id)),j(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?(()=>{let a=Math.min(Math.max(0,fe.cursor-Math.floor(7)),Math.max(0,fe.rows.length-14)),s=fe.rows.slice(a,a+14),g=fe.rows.filter(d=>d.checked).length;return B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:`Which folders back the user docs? (${g} selected of ${fe.rows.length})`}),a>0?j(A,{dimColor:!0,children:` \u2191 ${a} more`}):null,s.map((d,m)=>{let b=a+m;return B(A,{color:b===fe.cursor?F:void 0,children:[b===fe.cursor?"\u276F ":" ",d.checked?"\u25C9 ":"\u25CB ",d.path.padEnd(Math.min(48,Ee-34)),j(A,{color:"gray",children:bo(d)})]},d.path)}),a+14<fe.rows.length?j(A,{dimColor:!0,children:` \u2193 ${fe.rows.length-a-14} more`}):null,j(A,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Me?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Which category? (pick one to scope to)"}),Me.rows.map((l,a)=>{let s=a===Me.cursor,g=`${a+1}.`.padEnd(3);return B(A,{color:s?F:void 0,children:[s?"\u276F ":" ",`${g} ${l.label} (${l.count})`.padEnd(Math.min(44,Math.max(20,Ee-24))),j(A,{color:"gray",children:` ${l.token}`})]},l.token)}),j(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):qe?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),qe.rows.map((l,a)=>{let s=a===qe.cursor,g=l.indent?" ":" ",d=`${a+1}.`.padEnd(3);return B(A,{color:s?F:void 0,bold:l.kind==="category"&&!s,children:[s?"\u276F ":" ",`${g}${d} ${l.label}`.padEnd(Math.min(56,Ee-24)),l.note?j(A,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),j(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ye?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:`Preview article${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),Hn.length===0?j(A,{color:"gray",children:"no articles match"}):Hn.map((l,a)=>B(A,{color:a===ye.cursor?F:void 0,children:[a===ye.cursor?"\u276F ":" ",l]},l)),j(A,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):we?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:`Resume session${we.query?` \u2014 filter: ${we.query}`:" (type to filter)"}`}),qn.length===0?j(A,{color:"gray",children:"no sessions match"}):qn.map((l,a)=>B(A,{color:a===we.cursor?F:void 0,children:[a===we.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),j(A,{color:a===we.cursor?F:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ee-40))})]},l.uuid)),j(A,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Ns?B(ne,{flexDirection:"column",children:[sn.map((l,a)=>B(A,{color:a===Xt?F:void 0,children:[a===Xt?"\u276F ":" ",l.usage.padEnd(22)," ",j(A,{color:a===Xt?F:"gray",children:l.name==="model"&&lr?`${l.desc} (currently ${lr})`:l.desc})]},l.name)),j(A,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!S&&!D&&tt.length>0?B(ne,{flexDirection:"column",paddingX:1,children:[xs?j(A,{color:F,children:xs}):null,tt.map((l,a)=>{let s=yt(l),g=s.slice(0,Math.max(20,Ee-5)),d=Ee-g.length-7,m=d>=12?(Dc(l)??bc(s)).slice(0,d):"";return B(A,{children:[j(A,{color:F,children:a+1})," ",g,m?j(A,{dimColor:!0,children:` \u2014 ${m}`}):null]},s)}),j(A,{dimColor:!0,children:`press 1-${tt.length} to fill \xB7 esc cancel`})]}):j(ne,{paddingX:1,children:B(A,{color:"gray",children:[Es.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${lr??"model n/a"}${t.kind==="api"?Ts>0?` \xB7 ${he(Ts)}`:"":Ps>0?` \xB7 ${Qe(Ps)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}U();import{jsx as Wg}from"react/jsx-runtime";async function id(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Ug(t);r.kind==="none"&&(console.error(""),console.error(x("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:i}=Mg(Wg(rd,{cwd:e,auth:r,profileName:n,version:o}));await i(),process.stdout.write(`
|
|
343
|
-
`),process.exit(0)}U();import{writeCrashLog as
|
|
344
|
-
`+
|
|
326
|
+
Model: ${Z.model}${Z.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:re+ci(D,z,H).join(`
|
|
327
|
+
`)+ue}),K(`/write${w?` --scope ${w}`:""}`);return}ot.current=Date.now(),bt(0),S(!0);let Ot=new AbortController;Re.current=Ot,oe({verb:"Writing",total:D.length,done:0,active:[],rows:Sn(D),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${F.length} article${F.length===1?"":"s"} across ${D.length} partition${D.length===1?"":"s"} (\u2264${H} agents at once) on ${Z.model}${Z.forced?" (forced)":""}\u2026 (esc to stop)`});let Jn=new Set;try{for await(let z of Zo({cwd:e,partitions:D,promptFor:re=>li(re,V,{rewrite:P||_t}),concurrency:H,profileName:i,allowProdWrites:Ct.current,model:Z.model,signal:Ot.signal}))if(z.type==="partition_status")z.status==="running"?oe(re=>re&&{...re,active:[...re.active,z.label],rows:He(re.rows,z.label,"active"),lastAt:Date.now()}):oe(re=>re&&{...re,active:re.active.filter(ue=>ue!==z.label),done:re.done+1,rows:He(re.rows,z.label,z.status==="done"?"done":"failed"),lastAt:Date.now()});else if(z.type==="partition_event"){let re=null;if(z.event.type==="tool"){let ue=Dc(z.event.name,z.event.input,D[z.index]?.paths??[]);ue&&!Jn.has(ue)&&(Jn.add(ue),re=z.label)}oe(ue=>{if(!ue)return ue;let Ne={...ue,lastAt:Date.now()};return z.event.type==="tool"?Ne.tools=ue.tools+1:z.event.type==="text"&&(Ne.chars=ue.chars+z.event.delta.length),re&&(Ne.rows=Sc(Ne.rows,re)),Ne})}else if(z.type==="run_done"){jt(Ge=>Ge+z.totalCostUsd),At(Ge=>Ge+z.results.reduce((Ue,Cd)=>Ue+Cd.outputTokens,0));let re=z.aborted?"Stopped. ":"",ue=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:z.aborted?"warn":z.ok?"ok":"warn",text:re+di(z.results,D,ue).join(`
|
|
328
|
+
`)}),!z.aborted&&z.ok)try{let Ge=(Jn.size>0?[...Jn]:F).map(Ue=>`${V}/${Ue}`);ps(e,Ge,{writtenCap:fs})}catch{}let Ne=z.aborted?null:ui(e,V,F);if(Ne&&d({kind:"note",tone:"warn",text:Ne}),!z.aborted&&z.ok){let Ge=w??b??"",Ue=Ge?` ${Ge}`:"";Et(Ne?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${Ue} --fix, then /review${Ue} --fix for editorial quality, then /publish --all (add /screenshot --all first if you want images).`:`Written. I\u2019d run /review${Ue} --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:Ne?`/check${Ue} --fix`:`/review${Ue} --fix`,reason:""})}}}catch(z){d({kind:"note",tone:"error",text:`Write run failed: ${z.message}`})}finally{Re.current=null,oe(null),S(!1),X(z=>z+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:w}=fi(e);if(u.length===0&&w===0){d({kind:"note",tone:"info",text:hi});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?
|
|
329
|
+
${u.map(v=>` \u2022 ${v.name} (${v.docCount} doc${v.docCount===1?"":"s"})`).join(`
|
|
330
|
+
`)}`}),nt(u.map(v=>`/draft ${v.name}`));return}let y="",x;if(b){let v=mi(u,b);v?y=v:x=b}else y=u[0]?.name??"";await ie(Po(y,x),{display:b?`/draft ${b}`:"/draft",quietUser:!0});return}case"pull":{if(!mr(l.trim()))return;let u=h.find(w=>w.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let y=Date.now(),x=await Yc({cwd:e,profileName:i});d({kind:"note",tone:"info",text:vo(x,Date.now()-y).join(`
|
|
331
|
+
`)});return}if(u==="--baseline"){let y=h.find(F=>!F.startsWith("--")),x=y?y.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 v=await fg({cwd:e,profileName:i,relPaths:x?[x]:void 0}),V=x?{rebaselined:[],skipped:[]}:await mg({cwd:e,profileName:i});if(v.baselined.length===0&&v.skipped.length===0&&V.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}v.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${v.baselined.length} article${v.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),V.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${V.rebaselined.length} article${V.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),v.skipped.length>0&&d({kind:"note",tone:"warn",text:`${v.skipped.length} skipped:
|
|
332
|
+
${v.skipped.map(F=>` - ${F.path} (${F.reason})`).join(`
|
|
333
|
+
`)}`}),X(F=>F+1);return}if(u==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let y=await ug({cwd:e,profileName:i}),x=y.onlyInLegacy.length===0&&y.onlyInManifest.length===0&&y.mappedMissingFromManifest.length===0,v=[`Legacy listing: ${y.legacyCount} \xB7 Manifest: ${y.manifestCount} \xB7 in both: ${y.inBoth}`];x?v.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(y.mappedMissingFromManifest.length&&v.push(`\u2717 ${y.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${y.mappedMissingFromManifest.slice(0,5).join(", ")}`),y.onlyInLegacy.length&&v.push(`\u26A0 ${y.onlyInLegacy.length} only in the legacy listing: ${y.onlyInLegacy.slice(0,5).join(", ")}`),y.onlyInManifest.length&&v.push(`\u26A0 ${y.onlyInManifest.length} only in the manifest: ${y.onlyInManifest.slice(0,5).join(", ")}`),v.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:x?"ok":"warn",text:v.join(`
|
|
334
|
+
`)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let w=h[0];if(w){let y=await pg({cwd:e,profileName:i,relPath:w.replace(/\\/g,"/")});Ae.current=[y],Kn();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let b=await zr({cwd:e,profileName:i});for(let y of Kr(b))d({kind:"note",tone:y.tone,text:y.text});X(y=>y+1)}catch(w){d({kind:"note",tone:"error",text:`Pull failed: ${w.message}`})}return}case"scope":{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:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Dt({cursor:0,rows:u.map(w=>({...w,checked:w.recommended}))});return}case"audit":{if(h[0]==="--auto"){let w=te(e);if(!w){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=h[1]!=="off";Vc({...w,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 yn();u.kind==="forward-to-agent"&&u.prompt&&await ie(u.prompt,{display:u.display,quietUser:!0});return}case"check":{let u=h.find(y=>!y.startsWith("--")),w=u?` ${u}`:"",b=zc({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 y=Jc(e,u);await ie(Wi(b),{display:`/check${w} --fix`,quietUser:!0});try{ps(e,y,{reviewedCap:fs})}catch{}let x=zc({cwd:e,scope:u});d({kind:"note",tone:x.length===0?"ok":"warn",text:x.length===0?"\u2713 Doc-checker: all issues resolved.":Io(x).join(`
|
|
335
|
+
`)}),Et(x.length===0?`Deterministic issues fixed. Next: /review${w} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${w} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${w} --fix`,reason:""});return}d({kind:"note",tone:b.length===0?"ok":"warn",text:Io(b).join(`
|
|
336
|
+
`)}),b.length>0&&Et(`Found ${b.length} doc issue${b.length===1?"":"s"} above. /check${w} --fix has the agent fix them in place (or /review${w} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${w} --fix`,reason:""});return}case"structure":{let u=Rn(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(`
|
|
337
|
+
`)});return}case"reorder":{let u=Hi(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}),Et("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let u=Fi(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=h.includes("--fix"),b=h.find(x=>!x.startsWith("--")),y=w?Jc(e,b):[];if(await ie(u.prompt,{display:u.display,quietUser:!0}),w)try{ps(e,y,{reviewedCap:fs})}catch{}if(w)Et("\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(v=>v!=="--fix").join(" ");Et(`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 xn();u.kind==="forward-to-agent"&&u.prompt&&await ie(u.prompt,{display:u.display,quietUser:!0});let w=Ti(e);w&&d({kind:"note",tone:"info",text:w.join(`
|
|
338
|
+
`)});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:Ft(Wt(e)).join(`
|
|
339
|
+
`)}),Nt(ft()),rn.current=Se(e).status==="current"||We(e);return}case"inbox":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Si(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(Di(),{display:"/inbox",quietUser:!0});return}case"feedback":{let u=Qc(e),w="";try{w=Yt(u)?Jo(u,"utf8"):""}catch{w=""}if(!/^## /m.test(w)){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 os(w.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&&hr(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:w}=wi(h);if(!w&&gi(e)===0){d({kind:"note",tone:"info",text:ki});return}let b=`/document${w?` ${w}`:""}${u?" --publish":""}`;await ie(yi(w,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(!mr(l.trim()))return;let{publish:u}=ji(h);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let w=await Ni({cwd:e,profileName:i});for(let y of Ii(w))d({kind:"note",tone:y.startsWith("\u2713")?"ok":y.startsWith("\u2139")?"info":"warn",text:y});let b=Cn(vn(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(Ei({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{pr.current=!0,d({kind:"note",tone:"info",text:`Updating ${gt}\u2026 (don\u2019t close this window)`}),Nn(!0),(await Eo().finally(()=>Nn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),K("/exit"),$s("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${jo}`});return}case"screenshot":{let u=Ci(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:Pi(Ri(e,u.scope),u.scope).join(`
|
|
340
|
+
`)});return}if(u.mode==="single"){let _=await Do(h);_.kind==="forward-to-agent"&&_.prompt&&await ie(_.prompt,{display:_.display,quietUser:!0});return}if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=u.mode==="scope"?u.scope:void 0,b=kg(e,{scope:w}).map(_=>_.id);if(b.length===0){d({kind:"note",tone:"info",text:w?`No screenshot placeholders under ${w}.`:"No screenshot placeholders found in the docs."});return}let y=6,x=yg(b,3),v=er(e,"standard");ot.current=Date.now(),bt(0),S(!0);let V=new AbortController;Re.current=V,oe({verb:"Authoring",unit:"spec",total:x.length,done:0,active:[],rows:Sn(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${y} agents at once) on ${v.model}${v.forced?" (forced)":""}\u2026 (esc to stop)`});let F=!1;try{for await(let _ of Zo({cwd:e,partitions:x,promptFor:Nl,concurrency:y,profileName:i,allowProdWrites:Ct.current,model:v.model,signal:V.signal}))if(_.type==="partition_status")_.status==="running"?oe(P=>P&&{...P,active:[...P.active,_.label],rows:He(P.rows,_.label,"active"),lastAt:Date.now()}):oe(P=>P&&{...P,active:P.active.filter(D=>D!==_.label),done:P.done+1,rows:He(P.rows,_.label,_.status==="done"?"done":"failed"),lastAt:Date.now()});else if(_.type==="partition_event")oe(P=>{if(!P)return P;let D={...P,lastAt:Date.now()};return _.event.type==="tool"?D.tools=P.tools+1:_.event.type==="text"&&(D.chars=P.chars+_.event.delta.length),D});else if(_.type==="run_done"){jt(Z=>Z+_.totalCostUsd),At(Z=>Z+_.results.reduce((_t,Ot)=>_t+Ot.outputTokens,0));let P=_.results.filter(Z=>Z.ok).length,D=_.aborted?"Stopped. ":"";F=!_.aborted&&u.setup;let H=_.aborted?"":F?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:_.aborted?"warn":_.ok?"ok":"warn",text:`${D}Authored specs \u2014 ${P}/${_.results.length} batches ok.${H}`})}}catch(_){d({kind:"note",tone:"error",text:`Spec authoring failed: ${_.message}`})}finally{Re.current=null,oe(null),S(!1),X(_=>_+1)}if(F){let _=await xn();_.kind==="forward-to-agent"&&_.prompt&&await ie(_.prompt,{display:_.display,quietUser:!0});let P=Ti(e);P&&d({kind:"note",tone:"info",text:P.join(`
|
|
341
|
+
`)})}return}case"reset":{let u=Li(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}On.current={repoName:Dn(e),targets:u,hadDevhints:Yt(Xc(e))},d({kind:"note",tone:"warn",text:Ui(e,u).join(`
|
|
342
|
+
`)}),me(Dn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${s} \u2014 type /help.`})}},[e,r,i,Kn,d,ke,ie,Vn,yr,Ls]),Xn=Y(l=>{let a=(l??T).trim();if($(""),In(null),$t(0),a.startsWith("/")&&(An.current=!1,Ve(),Zt(null),nt(h=>Ec(h,a))),!a||(bs(!1),Us(a))||Ms(a))return;sr.current.push(a);let s=Oc(a,xs.current);if(a.startsWith("/"))d({kind:"user",text:a}),cn(s);else if(Dg(s)){d({kind:"user",text:a});let h=Ag(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,Us,Ms,cn,ie]),Ws=Y(l=>{if(l.length>1){if(l.includes("\x1B"))return;let a=Nc(l);if(Ic(a)){let s=_c(++yd.current,a);xs.current.set(s,a),I(s)}else I(a);return}I(l)},[I]),It=Math.max(10,Ee-6),Fs=ls(()=>Xo(k.text,It),[k.text,It]),$r=Y(l=>g(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+l))})),[]),Qn=Y(l=>g(a=>({...a,pos:Mc(Xo(a.text,It),a.pos,l)})),[It]),dn=Y(l=>g(a=>({...a,pos:Uc(Xo(a.text,It),a.pos,l)})),[It]),xd=["\x1B[H","\x1B[1~","\x1BOH"],vd=["\x1B[F","\x1B[4~","\x1BOF"],Hs=Y((l,a)=>a.leftArrow?($r(-1),!0):a.rightArrow?($r(1),!0):l&&xd.includes(l)?(dn("start"),!0):l&&vd.includes(l)?(dn("end"),!0):a.ctrl&&l==="a"?(dn("start"),!0):a.ctrl&&l==="e"?(dn("end"),!0):!1,[$r,dn]);return Hh((l,a)=>{if(a.ctrl&&l==="c"){Ce.current?.close(),r();return}if(!M){if(E){if(a.escape){if(Re.current){if(!Re.current.signal.aborted){let s=(Ln?.verb??"work").toLowerCase(),h=Ln?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${s} run (finishing in-flight ${h}s)\u2026`}),Re.current.abort()}return}en.current||(en.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Ce.current?.interrupt());return}if(a.return){let s=T.trim();if(!s)return;dt.current.push(s),lr([...dt.current]),$("");return}if(Hs(l,a))return;if(a.upArrow){Qn(-1);return}if(a.downArrow){Qn(1);return}if(a.backspace||a.delete){C();return}l&&!a.ctrl&&!a.meta&&Ws(l);return}if(it){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(Ie.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ie.length){st(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Ie[it.cursor];st(null);let{lines:h,changed:u,effective:w}=bn(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&&(As(b=>b+1),Ce.current?.setModel(w));return}if(l==="s"){let s=Ie[it.cursor];st(null),Ce.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){st(null);return}return}if(Oe){if(a.upArrow){Rt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Rt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Oe.rows.length){Rt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return||l==="s"){let s=Oe.rows[Oe.cursor];Rt(null),br(s.name,a.return===!0);return}if(a.escape){Rt(null);return}return}if(Wn){if(a.escape){nn(null);return}if(a.leftArrow||a.tab&&a.shift){nn(s=>s&&{tab:(s.tab-1+Te.length)%Te.length});return}if(a.rightArrow||a.tab){nn(s=>s&&{tab:(s.tab+1)%Te.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Te.length){nn({tab:Number(l)-1});return}return}if(Le){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(l&&/^[1-9]$/.test(l)&&Number(l)<=Le.rows.length){Pt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Le.rows[Le.cursor].name;if(Pt(null),!Ar(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 w=yt(s);u=!!w&&!(et(w)&&!w.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(w=>w+1);return}if(a.escape){Pt(null);return}return}if(pe){if(a.upArrow){Tt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Tt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=pe.rows.length){Tt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=pe.rows[pe.cursor],{profile:h,projectId:u}=pe;Tt(null),Gn(h,u,s);return}if(a.escape){Tt(null);return}return}if(ge){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(l&&/^[1-9]$/.test(l)&&Number(l)<=ge.rows.length){at(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=ge.rows[ge.cursor],{profile:h}=ge;at(null),zn(h,s);return}if(a.escape){at(null);return}return}if(fe){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(l===" "){Dt(s=>s&&{...s,rows:s.rows.map((h,u)=>u===s.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let s=fe.rows.filter(h=>h.checked).map(h=>h.path);if(Dt(null),s.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Vr(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){Dt(null);return}return}if(Me){if(a.upArrow){lt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){lt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Me.rows.length){lt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Me.rows[Me.cursor],h=Me.run;lt(null),h(s.token);return}if(a.escape){lt(null);return}return}if(qe){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(l&&/^[1-9]$/.test(l)&&Number(l)<=qe.rows.length){St(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=qe.rows[qe.cursor];St(null),s.kind==="article"?yr(s.paths[0]):Vn(s.paths);return}if(a.escape){St(null);return}return}if(we){if(a.escape){ct(null);return}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(Math.max(0,qn.length-1),s.cursor+1)});return}if(a.return){let s=qn[we.cursor];if(s){ct(null);try{d({kind:"preview",name:Dn(s),text:id(Jo(cs(e,s),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${s}: ${h.message}`})}}return}if(a.backspace||a.delete){ct(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){ct(s=>s&&{...s,query:s.query+l,cursor:0});return}return}if(ye){if(a.escape){ut(null);return}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(Math.max(0,Bn.length-1),s.cursor+1)});return}if(a.return){let s=Bn[ye.cursor];if(s){ut(null),ke(s.uuid),_e.current={uuid:s.uuid,firstPrompt:s.firstPrompt,titleFired:!0},rt(s.name),ds(s.uuid),vt.current=[];let h=is(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){ut(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){ut(s=>s&&{...s,query:s.query+l,cursor:0});return}return}if(a.tab&&!T&&ae){$(ae),Ve();return}if(!T&&tt.length>0&&!rr&&l&&/^[1-9]$/.test(l)){let s=tt[Number(l)-1];if(s){$(wt(s));return}}if(!T&&(Fn||on)&&l==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let s=Fn!=null;os(Fn??on).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&&hr(null),u&&!s&&Ns(!0)});return}if(!Hs(l,a)){if(_s){if(a.upArrow){$t(s=>Math.max(0,s-1));return}if(a.downArrow){$t(s=>Math.min(ln.length-1,s+1));return}if(a.tab){$("/"+(ln[Jt]?.name??"")+" "),$t(0);return}if(a.return){let s=ln[Jt];if(s){let h=T.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Cc(s.usage)&&!h){$("/"+s.name+" "),$t(0);return}Xn("/"+s.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(T!==""&&xt===null){Qn(-1);return}let s=sr.current;if(!s.length)return;let h=xt===null?s.length-1:Math.max(0,xt-1);In(h),$(s[h]??"");return}if(a.downArrow){if(T!==""&&xt===null){Qn(1);return}let s=sr.current;if(xt===null)return;let h=xt+1;h>=s.length?(In(null),$("")):(In(h),$(s[h]??""));return}}if(a.return){Xn();return}if(a.backspace||a.delete){C();return}if(a.escape){$(""),$t(0),Ve(),nt([]),Zt(null),An.current=!0;return}l&&!a.ctrl&&!a.meta&&Ws(l)}}}),ve(()=>{if(E||M)return;let l=dt.current.shift();l!==void 0&&(lr([...dt.current]),Xn(l))},[E,M,Xn]),G(ne,{flexDirection:"column",width:Ee,children:[wr!==null&&G(ne,{marginTop:1,flexDirection:"column",children:[wr.truncated&&j(A,{dimColor:!0,children:"\u2026"}),j(A,{children:wr.text})]}),E&&(Ln?j(Fg,{p:Ln}):j(Mg,{startTime:ot.current,chars:wd})),!E&&Ps?j(Ug,{text:Ps}):null,j(ne,{borderStyle:"round",borderColor:Is.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:T?Fs.map((l,a)=>{let s=k.text.slice(l.start,l.end),h=a===Qo(Fs,k.pos),u=Math.min(k.pos,l.end)-l.start;return G(A,{children:[j(A,{color:q,children:a===0?"> ":" "}),h?G(tr,{children:[s.slice(0,u),j(zt,{ch:s[u]??" "}),s.slice(u+1)]}):s||" "]},`${a}-${l.start}`)}):G(A,{children:[j(A,{color:q,children:"> "}),cr?j(zt,{ch:" "}):ae&&!E&&Qt?G(tr,{children:[j(zt,{ch:Qt[0],dim:!0}),j(A,{color:"gray",children:Qt.slice(1)})]}):ae&&!E?G(tr,{children:[j(zt,{ch:ae[0],dim:!0}),j(A,{color:"gray",children:ae.slice(1)}),j(A,{dimColor:!0,children:" (tab)"})]}):(gr.isSetup||!hd)&&!E?G(tr,{children:[j(zt,{ch:gr.text[0],dim:!0}),j(A,{color:"gray",children:gr.text.slice(1)})]}):j(zt,{ch:" "})]})}),Rs.length>0&&j(ne,{flexDirection:"column",paddingX:1,children:Rs.map((l,a)=>j(A,{color:"gray",children:`\u29D7 queued: ${l}`},`${a}-${l.slice(0,24)}`))}),Wn?j(Pc,{tab:Wn.tab,width:Ee,version:o,engineVersion:sd}):it?G(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:q,bold:!0,children:"Select model"}),j(A,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ie.map((l,a)=>G(A,{color:a===it.cursor?q:void 0,children:[a===it.cursor?"\u276F ":" ",`${a+1}. ${l.label}${a===it.current?" \u2714":""}`.padEnd(16),j(A,{color:"gray",children:l.desc})]},l.label)),j(A,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Oe?G(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:q,bold:!0,children:"Switch connection profile"}),Oe.rows.map((l,a)=>G(A,{color:a===Oe.cursor?q:void 0,children:[a===Oe.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===Oe.current?" \u2714":""}`.padEnd(20),j(A,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?j(A,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),j(A,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Le?G(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:q,bold:!0,children:"Pick your Document360 environment"}),Le.rows.map((l,a)=>G(A,{color:a===Le.cursor?q:void 0,children:[a===Le.cursor?"\u276F ":" ",`${a+1}. ${l.name}`.padEnd(16),j(A,{color:"gray",children:l.apiUrl})]},l.name)),j(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):pe?G(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:q,bold:!0,children:"Switch workspace"}),j(A,{dimColor:!0,children:`environment ${pe.environment} \xB7 project ${pe.projectName??`${pe.projectId.slice(0,8)}\u2026`}`}),pe.rows.map((l,a)=>G(A,{color:a===pe.cursor?q:void 0,children:[a===pe.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===pe.current?" \u2714":""}`.padEnd(30),j(A,{color:"gray",children:l.type??""})]},l.id)),j(A,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ge?G(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:q,bold:!0,children:"Choose project"}),j(A,{dimColor:!0,children:`environment ${ge.environment}`}),ge.rows.map((l,a)=>G(A,{color:a===ge.cursor?q:void 0,children:[a===ge.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===ge.current?" \u2714":""}`.padEnd(30),j(A,{color:"gray",children:l.sub??""})]},l.id)),j(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?(()=>{let a=Math.min(Math.max(0,fe.cursor-Math.floor(7)),Math.max(0,fe.rows.length-14)),s=fe.rows.slice(a,a+14),h=fe.rows.filter(u=>u.checked).length;return G(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:q,bold:!0,children:`Which folders back the user docs? (${h} selected of ${fe.rows.length})`}),a>0?j(A,{dimColor:!0,children:` \u2191 ${a} more`}):null,s.map((u,w)=>{let b=a+w;return G(A,{color:b===fe.cursor?q:void 0,children:[b===fe.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Ee-34)),j(A,{color:"gray",children:xo(u)})]},u.path)}),a+14<fe.rows.length?j(A,{dimColor:!0,children:` \u2193 ${fe.rows.length-a-14} more`}):null,j(A,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Me?G(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:q,bold:!0,children:"Which category? (pick one to scope to)"}),Me.rows.map((l,a)=>{let s=a===Me.cursor,h=`${a+1}.`.padEnd(3);return G(A,{color:s?q:void 0,children:[s?"\u276F ":" ",`${h} ${l.label} (${l.count})`.padEnd(Math.min(44,Math.max(20,Ee-24))),j(A,{color:"gray",children:` ${l.token}`})]},l.token)}),j(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):qe?G(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),qe.rows.map((l,a)=>{let s=a===qe.cursor,h=l.indent?" ":" ",u=`${a+1}.`.padEnd(3);return G(A,{color:s?q:void 0,bold:l.kind==="category"&&!s,children:[s?"\u276F ":" ",`${h}${u} ${l.label}`.padEnd(Math.min(56,Ee-24)),l.note?j(A,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),j(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):we?G(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:q,bold:!0,children:`Preview article${we.query?` \u2014 filter: ${we.query}`:" (type to filter)"}`}),qn.length===0?j(A,{color:"gray",children:"no articles match"}):qn.map((l,a)=>G(A,{color:a===we.cursor?q:void 0,children:[a===we.cursor?"\u276F ":" ",l]},l)),j(A,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):ye?G(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:q,bold:!0,children:`Resume session${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),Bn.length===0?j(A,{color:"gray",children:"no sessions match"}):Bn.map((l,a)=>G(A,{color:a===ye.cursor?q:void 0,children:[a===ye.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),j(A,{color:a===ye.cursor?q:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ee-40))})]},l.uuid)),j(A,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):_s?G(ne,{flexDirection:"column",children:[ln.map((l,a)=>G(A,{color:a===Jt?q:void 0,children:[a===Jt?"\u276F ":" ",l.usage.padEnd(22)," ",j(A,{color:a===Jt?q:"gray",children:l.name==="model"&&dr?`${l.desc} (currently ${dr})`:l.desc})]},l.name)),j(A,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!E&&!T&&tt.length>0?G(ne,{flexDirection:"column",paddingX:1,children:[Cs?j(A,{color:q,children:Cs}):null,tt.map((l,a)=>{let s=wt(l),h=s.slice(0,Math.max(20,Ee-5)),u=Ee-h.length-7,w=u>=12?(jc(l)??xc(s)).slice(0,u):"";return G(A,{children:[j(A,{color:q,children:a+1})," ",h,w?j(A,{dimColor:!0,children:` \u2014 ${w}`}):null]},s)}),j(A,{dimColor:!0,children:`press 1-${tt.length} to fill \xB7 esc cancel`})]}):j(ne,{paddingX:1,children:G(A,{color:"gray",children:[Is.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${dr??"model n/a"}${t.kind==="api"?Ds>0?` \xB7 ${he(Ds)}`:"":Ss>0?` \xB7 ${Qe(Ss)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}U();import{jsx as Vg}from"react/jsx-runtime";async function cd(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Bg(t);r.kind==="none"&&(console.error(""),console.error(R("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}=qg(Vg(ld,{cwd:e,auth:r,profileName:n,version:o}));await i(),process.stdout.write(`
|
|
343
|
+
`),process.exit(0)}U();import{writeCrashLog as dd,isBenignTransportError as Gg}from"document360-engine";var ud=!1;function gs(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function pd(e){if(ud)return;ud=!0;let t=(n,o)=>{if(Gg(o)){dd({kind:n,level:"transport",message:gs(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=dd({kind:n,level:"fatal",message:gs(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
344
|
+
`+R(`\u2717 d360-writer crashed: ${gs(o)}`)+`
|
|
345
345
|
`),r&&process.stderr.write(f(` Crash details: ${r}`)+`
|
|
346
346
|
`+f(" Run: d360-writer logs")+`
|
|
347
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var
|
|
347
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Xg=zg(import.meta.url),nr=Xg("../package.json");pd("d360-writer");var De=new Yg;function ws(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}De.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=>{ws(e),await io({profile:e.profile,manual:e.manual})});De.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{ws(e),await ea({profile:e.profile})});De.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{ws(e),await Zs({profile:e.profile})});var ys=De.command("profile").description("Manage connection profiles for the current repo");ys.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>so(process.cwd()));ys.command("use <name>").description("Set the default profile for this repo").action(e=>ao(process.cwd(),e));ys.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>lo(process.cwd(),e));var fd=De.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");fd.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Lt(process.cwd(),e.profile));fd.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Gs(process.cwd(),e,t.profile)});var md=De.command("project").description("Choose the Document360 project for this repo (active profile's identity)");md.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>no(process.cwd(),e.profile));md.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await zs(process.cwd(),e,t.profile)});De.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(go(),Ta));await e()});De.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>ra());De.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(()=>(So(),Rl)),n=await t(process.cwd(),nr.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});De.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(nr.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(Kg.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 ia(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 mc(e.cwd,e.auth,e.profile,nr.version):await cd(e.cwd,e.auth,e.profile,nr.version)});De.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|