document360-writer 0.5.87 → 0.5.90
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 +112 -112
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var vd=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 Hs=(e,t)=>{for(var n in t)vd(e,n,{get:t[n],enumerable:!0})};import Ye from"picocolors";var F,Cd,Rd,Pd,qs,dn,f,v,O,N,_,le,Pe,U=Zn(()=>{"use strict";F="#7f56d9",[Cd,Rd,Pd]=[127,86,217],qs=e=>Ye.isColorSupported?`\x1B[38;2;${Cd};${Rd};${Pd}m${e}\x1B[39m`:e,dn=e=>Ye.bold(qs(e)),f=e=>Ye.dim(e),v=e=>Ye.red(e),O=e=>Ye.yellow(e),N=e=>Ye.green(e),_=qs,le=e=>Ye.gray(e),Pe=e=>Ye.bold(e)});import{existsSync as Mt,writeFileSync as pt,readFileSync as uu,readdirSync as pu}from"node:fs";import{join as fu}from"node:path";import{devHintsGuidePath as uo,hintsDir as aa,architectureDir as pa,messagesDir as Pr,creatorNotesPath as la,devhintsStatePath as fa,directivesPath as ca,DIRECTIVES_HEADER as mu,roadmapPath as da,ROADMAP_HEADER as hu,ensureDir as co,writeMessage as gu,listOpenForDev as yu}from"document360-engine";function ma(){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 wu(){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 Sr(){let e=process.cwd(),t=wa(e);if(Ht(t)&&!await gd({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=xa(e)??ha(e),o=await dn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await dn({message:"Capture directory (where document360-capture .spec.ts files live):",default:ka}),i=await dn({message:"Screenshot output directory:",default:ba}),c=await dn({message:"Default connection profile name:",default:"berlin"}),p=await dn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),y={projectId:o,docsDir:ya,captureDir:r,outputDir:i,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:va(e)},h=bd(e);h?.terminologyGlossary&&(y.terminologyGlossary=h.terminologyGlossary),ga(y,e),$a(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 xa(e){let t=fo(e,"package.json");if(!Ht(t))return null;try{return JSON.parse(wd(t,"utf8")).name??null}catch{return null}}function va(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Ht(fo(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=fo(e,n);Ht(o)&&!xd(o)&&t.push(n)}return t}function xd(e){try{return yd(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var mo=Qn(()=>{"use strict";U();Ke()});var xl={};Ws(xl,{doctorCommand:()=>kn,renderDoctorChecks:()=>$l,runDoctorChecks:()=>bl});import{existsSync as lf}from"node:fs";import{d360GetAll as cf,getAccessToken as uf,isExpired as bi,loadProfileMap as df,loadTokens as pf,packageSkillsDir as yl,projectConfigPath as ff,readProjectConfig as mf,DEFAULT_DOCS_DIR as hf,fetchManifestSummary as gf,resolveActiveProfile as wf,classifyClaudeAuth as yf,CLAUDE_CODE_SETUP_HINT as kl,resolveModelSetting as kf,probeModel as bf,detectAppType as $f,playbookSkillName as xf,D360AuthError as vf}from"document360-engine";async function bl(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=yf();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. ${kl}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:kl});let r=kf(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 bf(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=mf(e);if(!i)return t.push({level:"fail",label:`No ${ff(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${i.projectId}`});let c=(i.docsDir??hf).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 y=i.appType??$f(e);if(y){let T=i.appType?"from config":"auto-detected",P=y==="web"||y==="cli";t.push({level:"ok",label:`Genre: ${y} (${T})${P?` \u2192 ${xf(y)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else t.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let 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=pf(h.name);k?bi(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):bi(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=df(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(lf(yl())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${yl()}`,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&&(!bi(k)||k.refreshToken)){let T={profile:h.name,connection:h.connection};try{await uf(T);let S=await cf(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 gf(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 vf||/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 $l(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 kn(e,t){console.log(f("Running checks\u2026"));for(let n of $l(await bl(t.cwd)))console.log(n);return{kind:"continue"}}var Ro=Qn(()=>{"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 Mu}from"@inquirer/prompts";import{loginPkce as Uu,refreshTokens as Wu,toStoredTokens as Ys,clearTokens as Fu,decodeJwtClaims as Gs,isExpired as Hu,loadTokens as qu,saveTokens as zs,resolveActiveProfile as to,setProfileProject as Bu,readProjectConfig as Vu}from"document360-engine";U();import{select as Ru}from"@inquirer/prompts";import{resolveActiveProfile as Pu,setProfileProject as Tu,resolveProjectId as Su,listWorkspaces as Du}from"document360-engine";async function cn(e,t){let n=Pu(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Su(o);return{workspaces:await Du(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Hs=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function kr(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 Jn(e,t,n,o,r){Tu(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function qs(e,t,n){let o;try{o=await cn(e,n)}catch(i){return console.log(x(`Could not list workspaces: ${i.message}`)),1}let r=kr(o.workspaces,t);return r?(Jn(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 cn(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"):" "} ${Hs(h)} ${f(h.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Ru({message:"Select the Document360 workspace for this repo:",choices:o.map(h=>({name:`${Hs(h)}${h.id===c?" (current)":""}`,value:h.id}))}),y=o.find(h=>h.id===p);Jn(e,i,r,p,y?.name),console.log(N(`\u2713 Workspace set to "${y?.name??p}" for profile "${i}".`))}U();import{select as Au}from"@inquirer/prompts";import{resolveActiveProfile as ju,setProfileProject as Eu,listProjects as Nu}from"document360-engine";async function ze(e,t){let n=ju(e,t),o={profile:n.name,connection:n.connection};return{projects:await Nu(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Bs=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;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){Eu(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Vs(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=br(o.projects,t);return r?(Zn(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 eo(e,t){let n;try{n=await ze(e,t)}catch(y){console.log(x(`Could not list projects: ${y.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 y of o)console.log(` ${y.id===i?_("\u25CF"):" "} ${Bs(y)} ${f(y.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await Au({message:"Select the Document360 project for this repo:",choices:o.map(y=>({name:`${Bs(y)}${y.id===i?" (current)":""}`,value:y.id}))}),p=o.find(y=>y.id===c);Zn(e,r,c,p?.name),console.log(N(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}U();import Iu from"picocolors";function _u(e=process.env){return e.FORCE_HYPERLINK==="0"||!Iu.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 Lu(e,t=e,n){return _u(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Ou=/https?:\/\/[^\s\x1b]+/g;function un(e,t){return e.replace(Ou,n=>Lu(n,n,t))}function Ks(e){return{...Gs(e.idToken)??{},...Gs(e.accessToken)??{}}}function no(e){let t=Ks(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 oo(e){let t=to(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 Uu(n,{manual:e.manual,promptForRedirect:i=>Mu({message:i})},i=>console.log(un(i))),r=Ys(t.name,o);if(zs(r),await $r(r,t.name,i=>console.log(f(i))),console.log(""),console.log(N(`\u2713 Logged in to "${t.name}" as ${no(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{Vu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Ot(process.cwd(),t.name))}catch{}}async function $r(e,t,n){let r=Ks(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(to(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await ze(process.cwd(),t);c=p.find(y=>y.id===r)?.name}catch{}Bu(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Xs(e){let t=to(process.cwd(),e.profile),n=t.connection,o=qu(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":""}: ${no(o)}`),Hu(o))if(o.refreshToken)try{let r=Ys(t.name,await Wu(n,o.refreshToken));zs(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 Qs(e){let t=to(process.cwd(),e.profile);Fu(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 Js,writeProjectConfig as Gu,resolveActiveProfile as Yu,loadTokens as zu,isExpired as Ku}from"document360-engine";function ro(e){let t=Js(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=zu(n),y=p?Ku(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${c}${i} [${y}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function io(e,t){let n=Js(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,Gu(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(N(`\u2713 Default profile is now "${t}"${o}`))}function so(e,t){try{let n=Yu(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 Xu,readdirSync as Qu,statSync as Zs}from"node:fs";import{join as ea}from"node:path";import{apiLogDir as Ju}from"document360-engine";function ta(){let e=Ju();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Xu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Qu(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=(Zs(ea(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=(Zs(ea(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 Zu,resolveAuth as ed,findByName as td,slugify as nd,touchSession as od,upsertSession as rd,resolveActiveProfile as id}from"document360-engine";async function na(e,t,n,o,r,i){let c=ed(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=id(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 y;if(o){let $=td(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)),y=$.uuid,console.error(f(`Resuming "${$.name}"`))}let h=Zu({cwd:e,resume:y,profileName:r,allowProdWrites:i===!0}),k=y??null,D=1;for await(let $ of h.send(t))switch($.type){case"session":if(!k){k=$.sessionId;let T=new Date().toISOString();rd({uuid:k,name:nd(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&&od(k),process.stdout.write(`
|
|
217
|
-
`),process.exit(
|
|
210
|
+
`}function Wt(e){co(aa(e)),co(pa(e)),co(Pr(e));for(let n of[aa(e),Pr(e)]){let o=fu(n,".gitkeep");Mt(o)||pt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
211
|
+
`)}Mt(la(e))||pt(la(e),wu()),Mt(ca(e))||pt(ca(e),mu),Mt(da(e))||pt(da(e),hu),pt(uo(e),ma());let t=Se(e);return ga(e,new Date().toISOString()),t}async function ha(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 Tr(e){try{let t=uu(fa(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function ga(e,t){let o={...Tr(e)??{},emittedVersion:se,emittedAt:t};pt(fa(e),`${JSON.stringify(o,null,2)}
|
|
213
|
+
`)}function We(e){try{return pu(pa(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Se(e){let n=Tr(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=Tr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let i=o?.completedVersion??0;se>r&&(co(Pr(e)),pt(uo(e),ma()),ga(e,t),n.guideRefreshed=!0),se>i&&(yu(e).some(p=>p.kind==="request"&&p.subject.startsWith(ua))||(gu(e,{id:`onb${se}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${ua}${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 Sr(){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,Sr(),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,ua,Ke=Zn(()=>{"use strict";Ut="-".repeat(64),se=7;ua="Re-run dev\u2194docs onboarding (protocol v"});var Pa={};Hs(Pa,{initCommand:()=>Ar,scaffoldInit:()=>Dr});import{input as fn,confirm as ku}from"@inquirer/prompts";import{basename as ya,join as ho}from"node:path";import{existsSync as Ht,readFileSync as bu,readdirSync as $u,writeFileSync as xu}from"node:fs";import{writeProjectConfig as wa,readProjectConfig as vu,projectConfigPath as ka,writerDir as Cu,DEFAULT_DOCS_DIR as ba,DEFAULT_CAPTURE_DIR as $a,DEFAULT_OUTPUT_DIR as xa}from"document360-engine";function Dr(e,t="berlin"){let n=ka(e);if(Ht(n))return{created:!1,path:n,profileName:""};let o={projectId:Ca(e)??ya(e),docsDir:ba,captureDir:$a,outputDir:xa,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Ra(e)};return wa(o,e),va(e),{created:!0,path:n,profileName:t}}function va(e){let t=ho(Cu(e),".gitignore");Ht(t)||xu(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
216
|
+
`),"utf8")}async function Ar(){let e=process.cwd(),t=ka(e);if(Ht(t)&&!await ku({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Ca(e)??ya(e),o=await fn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await fn({message:"Capture directory (where document360-capture .spec.ts files live):",default:$a}),i=await fn({message:"Screenshot output directory:",default:xa}),c=await fn({message:"Default connection profile name:",default:"berlin"}),p=await fn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),h={projectId:o,docsDir:ba,captureDir:r,outputDir:i,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Ra(e)},k=vu(e);k?.terminologyGlossary&&(h.terminologyGlossary=k.terminologyGlossary),wa(h,e),va(e);let w=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 S of Ft(w))console.log(S);return console.log(""),console.log(`${f("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Ca(e){let t=ho(e,"package.json");if(!Ht(t))return null;try{return JSON.parse(bu(t,"utf8")).name??null}catch{return null}}function Ra(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)&&!Ru(o)&&t.push(n)}return t}function Ru(e){try{return $u(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var go=Zn(()=>{"use strict";U();Ke()});var Cl={};Hs(Cl,{doctorCommand:()=>$n,renderDoctorChecks:()=>vl,runDoctorChecks:()=>xl});import{existsSync as uf}from"node:fs";import{d360GetAll as pf,getAccessToken as ff,isExpired as xi,loadProfileMap as mf,loadTokens as hf,packageSkillsDir as bl,ENGINE_VERSION as gf,projectConfigPath as yf,readProjectConfig as wf,DEFAULT_DOCS_DIR as kf,fetchManifestSummary as bf,resolveActiveProfile as $f,classifyClaudeAuth as xf,CLAUDE_CODE_SETUP_HINT as $l,resolveModelSetting as vf,probeModel as Cf,detectAppType as Rf,playbookSkillName as Pf,D360AuthError as Tf}from"document360-engine";async function xl(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${gf}`});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=xf();r.state==="ready"?n.push({level:"ok",label:`Claude auth: ${r.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):r.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${$l}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:$l});let i=vf(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),r.state==="ready"){let x=await Cf(e,i.model??void 0);x.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(x.latencyMs/1e3).toFixed(1)}s`}):x.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 ${x.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=wf(e);if(!c)return n.push({level:"fail",label:`No ${yf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${c.projectId}`});let p=(c.docsDir??kf).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 h=c.authoritativeSourceFiles??[];n.push(h.length>0?{level:"ok",label:`Sources: docs grounded in ${h.length} path(s) (${h.slice(0,3).join(", ")}${h.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??Rf(e);if(k){let x=c.appType?"from config":"auto-detected",E=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${x})${E?` \u2192 ${Pf(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 w;try{w=$f(e),n.push({level:"ok",label:`Profile: ${w.name} (${w.connection.name})${w.production?" \u26A0 PRODUCTION":""}`})}catch(x){return n.push({level:"fail",label:`Profile config: ${x.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let S=hf(w.name);S?xi(S)&&!S.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):xi(S)?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(S.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${w.name})`}),n.push(w.project.workspaceId?{level:"ok",label:`Workspace: ${w.project.workspaceName??w.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let $=mf(e,w.name);$?$.projectId&&w.project.projectId&&$.projectId!==w.project.projectId?n.push({level:"fail",label:`Category map projectId (${$.projectId}) \u2260 profile projectId (${w.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 "${w.name}" (created on first /publish)`}),n.push(uf(bl())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${bl()}`,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)"}),S&&(!xi(S)||S.refreshToken)){let x={profile:w.name,connection:w.connection};try{await ff(x);let T=await pf(x,"/v3/projects");n.push({level:"ok",label:`API reachable (${w.connection.apiUrl}) \u2014 ${T.length} project(s) visible`})}catch(T){n.push({level:"fail",label:`API call failed: ${T.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let E=$?.projectId??w.project.projectId;if(E&&w.project.workspaceId)try{let T=await bf(x,E,w.project.workspaceId);if(T){let M=(T.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${w.connection.name} (${T.languages?.length??0} language${(T.languages?.length??0)===1?"":"s"}) \xB7 hash ${M||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${w.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(T){T instanceof Tf||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(T.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${w.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 (${T.message.slice(0,80)})`})}}return n}function vl(e){let t=[""];for(let r of e){let i=r.level==="ok"?N("\u2713"):r.level==="warn"?O("\u26A0"):v("\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"})`}`):v(`\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 vl(await xl(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var To=Zn(()=>{"use strict";Ke();U()});import{Command as Vg}from"commander";import{createRequire as Gg}from"node:module";import{AUTH_MODES as Yg}from"document360-engine";import{input as Wd}from"@inquirer/prompts";import{loginPkce as Fd,refreshTokens as Hd,toStoredTokens as Ks,clearTokens as qd,decodeJwtClaims as zs,isExpired as Bd,loadTokens as Vd,saveTokens as Xs,resolveActiveProfile as oo,setProfileProject as Gd,readProjectConfig as Yd}from"document360-engine";U();import{select as Td}from"@inquirer/prompts";import{resolveActiveProfile as Sd,setProfileProject as Dd,resolveProjectId as Ad,listWorkspaces as jd}from"document360-engine";async function un(e,t){let n=Sd(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Ad(o);return{workspaces:await jd(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Bs=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;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,r){Dd(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Vs(e,t,n){let o;try{o=await un(e,n)}catch(i){return console.log(v(`Could not list workspaces: ${i.message}`)),1}let r=$r(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(v(`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 un(e,t)}catch(k){console.log(v(`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?_("\u25CF"):" "} ${Bs(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Td({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${Bs(k)}${k.id===c?" (current)":""}`,value:k.id}))}),h=o.find(k=>k.id===p);eo(e,i,r,p,h?.name),console.log(N(`\u2713 Workspace set to "${h?.name??p}" for profile "${i}".`))}U();import{select as Ed}from"@inquirer/prompts";import{resolveActiveProfile as Nd,setProfileProject as Id,listProjects as _d}from"document360-engine";async function ze(e,t){let n=Nd(e,t),o={profile:n.name,connection:n.connection};return{projects:await _d(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Gs=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;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 to(e,t,n,o){Id(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Ys(e,t,n){let o;try{o=await ze(e,n)}catch(i){return console.log(v(`Could not list projects: ${i.message}`)),1}let r=xr(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(v(`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(h){console.log(v(`Could not list projects: ${h.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 h of o)console.log(` ${h.id===i?_("\u25CF"):" "} ${Gs(h)} ${f(h.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await Ed({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${Gs(h)}${h.id===i?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.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 Od from"picocolors";function Ld(e=process.env){return e.FORCE_HYPERLINK==="0"||!Od.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 Md(e,t=e,n){return Ld(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Ud=/https?:\/\/[^\s\x1b]+/g;function pn(e,t){return e.replace(Ud,n=>Md(n,n,t))}function Qs(e){return{...zs(e.idToken)??{},...zs(e.accessToken)??{}}}function ro(e){let t=Qs(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 Fd(n,{manual:e.manual,promptForRedirect:i=>Wd({message:i})},i=>console.log(pn(i))),r=Ks(t.name,o);if(Xs(r),await vr(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{Yd(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Lt(process.cwd(),t.name))}catch{}}async function vr(e,t,n){let r=Qs(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(h=>h.id===r)?.name}catch{}Gd(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Js(e){let t=oo(process.cwd(),e.profile),n=t.connection,o=Vd(t.name);if(!o){console.log(v(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${_(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${ro(o)}`),Bd(o))if(o.refreshToken)try{let r=Ks(t.name,await Hd(n,o.refreshToken));Xs(r),console.log(N(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(O(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(O("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function Zs(e){let t=oo(process.cwd(),e.profile);qd(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 ea,writeProjectConfig as zd,resolveActiveProfile as Kd,loadTokens as Xd,isExpired as Qd}from"document360-engine";function so(e){let t=ea(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(v("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?O(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Xd(n),h=p?Qd(p)&&!p.refreshToken?O("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${c}${i} [${h}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function ao(e,t){let n=ea(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(v(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,zd(n,e);let o=n.profiles[t].production?O(" \u26A0 PRODUCTION"):"";console.log(N(`\u2713 Default profile is now "${t}"${o}`))}function lo(e,t){try{let n=Kd(e,t);console.log(""),console.log(`Profile ${_(n.name)}${n.production?O(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(v(n.message)),process.exitCode=1}}U();import{existsSync as Jd,readdirSync as Zd,statSync as ta}from"node:fs";import{join as na}from"node:path";import{apiLogDir as eu}from"document360-engine";function oa(){let e=eu();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Jd(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Zd(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=(ta(na(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=(ta(na(e,r)).size/1024).toFixed(1);console.log(` ${v(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 tu,resolveAuth as nu,findByName as ou,slugify as ru,touchSession as iu,upsertSession as su,resolveActiveProfile as au}from"document360-engine";async function ra(e,t,n,o,r,i){let c=nu(n);c.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("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=au(e,r)}catch($){console.error(v(`Document360 profile error: ${$.message}`)),process.exit(2)}p.production&&(console.error(O(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),i||(console.error(v("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let h;if(o){let $=ou(e,o);$||(console.error(v(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),h=$.uuid,console.error(f(`Resuming "${$.name}"`))}let k=tu({cwd:e,resume:h,profileName:r,allowProdWrites:i===!0}),w=h??null,S=1;for await(let $ of k.send(t))switch($.type){case"session":if(!w){w=$.sessionId;let I=new Date().toISOString();su({uuid:w,name:ru(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":S=$.ok?0:1,console.error(f(`(${$.inputTokens}\u2192${$.outputTokens} tokens`+($.costUsd>0?`, $${$.costUsd<.01?$.costUsd.toFixed(4):$.costUsd.toFixed(2)}`:"")+")")),$.ok||console.error(v("agent finished with an error result"));break;case"error":console.error(""),console.error(v(`agent error: ${$.message}`)),process.exit(1)}w&&iu(w),process.stdout.write(`
|
|
217
|
+
`),process.exit(S)}import{createInterface as Qm}from"node:readline/promises";import{createSession as es,resolveAuth as Jm,getSession as Zm,setTitle as eh,slugify as th,touchSession as uc,upsertSession as nh,generateTitle as oh,resolveActiveProfile as pc,resolveModelSetting as rh,readProjectConfig as ih,resolveAndPersistAppType as sh,decodeJwtClaims as dc,isExpired as ah,loadTokens as lh,isDirectiveMention as ch,stripDirectiveMention as dh,appendDirective as uh,reconcileUpgradeActions as ph,stampArticles as fh,listArticleFiles as mh,CONTENT_CAP_VERSION as hh}from"document360-engine";import{ENGINE_VERSION as cu}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 lu(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 ia(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(lu(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function Cr(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:cu}:void 0;for(let o of ia(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 du}from"document360-engine";async function sa(e,t){let n=t.currentUuid(),o=n?du(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 Rr(){return{kind:"exit"}}go();U();import{readMcpConfig as jr,writeMcpConfig as Ta}from"document360-engine";async function yo(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Pu(),{kind:"continue"}):t==="add"?(Tu(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Su(e.slice(1)),{kind:"continue"}):(console.log(v(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Pu(){let e=jr(),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(` ${_(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(` ${_(n)} ${f(`(${o.type})`)} ${o.url}${i}`)}}console.log("")}function
|
|
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(` ${_(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(` ${_(n)} ${f(`(${o.type})`)} ${o.url}${i}`)}}console.log("")}function Tu(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(v("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(v(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=jr(),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 h=o[++p],k=h?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(v(`-H expects key:value (no spaces). Got: ${h??"(nothing)"}`));return}c[k[1].trim()]=k[2].trim()}else{console.log(v(`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,Ta(r),console.log(""),console.log(N(`\u2713 Registered "${t}" (${n})`)),console.log(O(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Su(e){let t=e[0];if(!t){console.log(v("Usage: /mcp remove <name>"));return}let n=jr();if(!n.servers[t]){console.log(v(`No server named "${t}".`));return}delete n.servers[t],Ta(n),console.log(N(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}U();import{readFileSync as qu}from"node:fs";import{join as Bu}from"node:path";import{select as Vu}from"@inquirer/prompts";import{computeSyncStatus as Wr,planPartitions as Gu,relatedArticlePaths as Yu,resolveModelForOperation as zu,runPartitioned as Ku,loadProfileMap as Xu,resolveActiveProfile as Qu,resolveCrossLinks as Ju,applyStructureOrder as La,orderSyncLine as Ma,applyRelatedArticles as Ua,relatedSyncLine as Wa}from"document360-engine";import Q from"picocolors";import Na from"wrap-ansi";import Lr from"string-width";U();import Xe from"picocolors";import Er from"wrap-ansi";import Nr from"string-width";var Sa=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Da=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Aa=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Du(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(Sa(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Da(t[o+1])){let p=Aa(r);o+=2;let h=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)h.push(Aa(t[o++]));n.push({kind:"table",header:p,rows:h});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 h=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(h),text:h.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])&&!Sa(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Da(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function Ir(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Xe.bold(t.slice(2,-2)):t.startsWith("`")?_(t.slice(1,-1)):Xe.italic(t.slice(1,-1)))}var Au=(e,t)=>e+" ".repeat(Math.max(0,t-Nr(e)));function ju(e,t,n){let o=e.length,r=e.map((x,E)=>Math.max(Nr(x),...t.map(T=>Nr(T[E]??"")))),i=Math.max(24,n),c=3*o+1,p=[...r],h=()=>p.reduce((x,E)=>x+E,0)+c,k=0;for(;h()>i&&k++<1e4;){let x=-1,E=6;for(let T=0;T<o;T++)p[T]>E&&(E=p[T],x=T);if(x===-1)break;p[x]-=1}let w=(x,E,T)=>Xe.gray(x+p.map(M=>"\u2500".repeat(M+2)).join(E)+T),S=Xe.gray("\u2502"),$=(x,E)=>{let T=p.map((J,X)=>{let ae=x[X]??"",kt=E?Xe.bold(ae):Ir(ae);return Er(kt,J,{hard:!0}).split(`
|
|
225
|
+
`)}),M=Math.max(...T.map(J=>J.length)),H=[];for(let J=0;J<M;J++)H.push(p.map((X,ae)=>`${S} ${Au(T[ae][J]??"",X)} `).join("")+S);return H.join(`
|
|
226
|
+
`)},I=[w("\u250C","\u252C","\u2510"),$(e,!0)];return I.push(t.length===0?w("\u2514","\u2534","\u2518"):w("\u251C","\u253C","\u2524")),t.forEach((x,E)=>{I.push($(x,!1)),I.push(E===t.length-1?w("\u2514","\u2534","\u2518"):w("\u251C","\u253C","\u2524"))}),I.join(`
|
|
227
|
+
`)}function Eu(e,t){switch(e.kind){case"heading":return Xe.bold(e.text);case"hr":return Xe.gray("\u2500".repeat(t));case"para":return Er(Ir(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]=Er(Ir(o.text),Math.max(10,t-i.length)).split(`
|
|
228
|
+
`);return` ${r} ${c}`+p.map(h=>`
|
|
229
|
+
${i}${h}`).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 ju(e.header,e.rows,t)}}function _r(e,t){let n=Math.max(20,t);return Du(e).map(o=>Eu(o,n)).join(`
|
|
232
|
+
|
|
233
|
+
`)}U();import Nu from"picocolors";var Iu=[127,86,217],_u=[22,38,43],ja={T:Iu,E:_u},mn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Or=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Ou=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Ea(){if(!Nu.isColorSupported)return[];let e=mn[0].length,t=[];for(let n=0;n<mn.length;n+=2){let o="";for(let r=0;r<e;r++){let i=ja[mn[n][r]],c=n+1<mn.length?ja[mn[n+1][r]]:void 0;i&&c?o+=`${Or(i)}${Ou(c)}\u2580\x1B[49m\x1B[39m`:i?o+=`${Or(i)}\u2580\x1B[39m`:c?o+=`${Or(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function hn(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 Lu(e,t){let n=[dn("\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=Ea();if(o.length===0)return n.join(`
|
|
234
|
+
`);let r=2,i=3,c=Lr(o[0]);if(!(t>=r+c+i+Math.max(...n.map(w=>Lr(w)))))return[...o.map(w=>" "+w),...n].join(`
|
|
235
|
+
`);let h=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let w=0;w<Math.max(o.length+h,n.length);w++){let S=o[w-h]??" ".repeat(c);k.push((" ".repeat(r)+S+" ".repeat(i)+(n[w]??"")).trimEnd())}return k.join(`
|
|
236
|
+
`)}var Mu={error:Q.red,warn:Q.yellow,ok:Q.green,info:Q.gray};function Mr(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Lu(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=>Na(k,i,{hard:!0}).split(`
|
|
238
|
+
`)),h=Math.max(0,p.length-c);return h>0&&(p=[...p.slice(0,c),Q.dim(`\u2026 +${h} more lines`)]),`
|
|
239
|
+
`+p.map((k,w)=>o+(w===0?_(" \u276F "):" ")+k+" ".repeat(Math.max(0,i-Lr(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
|
+
`+_r(e.text,n);case"tool":{let o=e.arg!==null?Q.gray(`${e.sep}(${e.arg})`):"";return`
|
|
242
|
+
`+Na(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=>_(pn(` \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
|
+
`+dn(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
247
|
+
|
|
248
|
+
`+_r(e.text,n);case"note":return`
|
|
249
|
+
`+Mu[e.tone](pn(e.text));case"done":return`
|
|
250
|
+
`+(e.ok?Q.magenta("\u2736 "):Q.red("\u2736 "))+Q.gray(`Cooked for ${hn(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${he(e.costUsd)}`:""))}}function Ia(e,t){return e.map(n=>Mr(n,t)).join(`
|
|
251
|
+
`)}import{resolveActiveProfile as Uu,loadTokens as Wu,isExpired as Fu,decodeJwtClaims as _a}from"document360-engine";function Hu(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Fe(e,t){try{let n=Uu(e,t),o=Wu(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Fu(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={..._a(o.idToken)??{},..._a(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 ${Hu(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var gn=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 Oa={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function yn(e){return e.filter(t=>t.path!==null&&t.status in Oa&&!t.link).map(t=>({path:t.path,label:Oa[t.status]}))}function wo(e){return e.filter(t=>t.link).length}function Hr(e,t){try{let n=Xu(e,Qu(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Ju(qu(Bu(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 Zu(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 Fa(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:`${Zu(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 ko(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),h=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"}`,w=$=>`${$} article${$===1?"":"s"}`,S=[];if(i.length===0)S.push(`Published ${w(c)} (${k}) successfully \xB7 ${h}.`),S.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{S.push(`Published ${p}/${w(c)} (${k}) \xB7 ${h}.`),S.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)S.push(` \u2717 ${$.label}${$.error?` \u2014 ${$.error}`:""}`)}return S}async function Ur(e,t){let n=Gu(t),{model:o}=zu(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${gn} agents at once) on ${o}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let r of Ku({cwd:e.cwd,partitions:n,promptFor:i=>ko(i.paths),concurrency:gn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:o}))if(r.type==="partition_status")r.status==="running"?console.log(f(` \u25B8 ${r.label} \u2014 publishing\u2026`)):r.status==="done"?console.log(N(` \u2713 ${r.label}`)):console.log(v(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let i=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of qr(r.results,n,i))console.log(r.ok?N(p):O(p));let c=Hr(e.cwd,e.profileName);c&&console.log(f(c));try{let p=Ma(await La({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}try{let p=Wa(await Ua({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}}}catch(r){console.log(v(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function bo(e,t,n){let o=Yu(e,n);if(o.length===0)return[];let r=new Set(yn((await Wr({cwd:e,profileName:t})).entries).map(i=>i.path));return o.filter(i=>r.has(i))}async function Ha(e,t){let n=Fe(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await bo(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 Ur(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await Wr({cwd:t?.cwd??process.cwd()}),i=yn(r.entries),c=wo(r.entries);if(c>0&&console.log(O(`\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=Ma(await La({cwd:t.cwd,profileName:t.profileName}));p&&console.log(f(p));let h=Wa(await Ua({cwd:t.cwd,profileName:t.profileName}));h&&console.log(f(h))}catch{}return{kind:"continue"}}return t?await Ur(t,i.map(p=>p.path)):{kind:"forward-to-agent",prompt:ko(i.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log(v(`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 Wr({cwd:t?.cwd??process.cwd()});r=yn(i.entries);let c=wo(i.entries);c>0&&console.log(O(`\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(v(`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(()=>Vu({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 Ur(t,r.map(i=>i.path))}return{kind:"forward-to-agent",prompt:Fr(o),display:`/publish ${o}`}}async function wn(){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 ep}from"@inquirer/prompts";import{inventoryRepo as tp,readProjectConfig as qa,writeProjectConfig as np}from"document360-engine";function Br(e,t){let n=qa(e);n&&(n.authoritativeSourceFiles=t,np(n,e))}function $o(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 Ba(e,t){let n=t?.cwd??process.cwd();if(!qa(n))return console.log(v("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=tp(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(_("Recommended documentation scope (run /scope in the REPL to choose):"));for(let i of o)console.log(` ${i.recommended?"\u25C9":"\u25CB"} ${i.path} ${f($o(i))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>ep({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(i=>({name:`${i.path} (${$o(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"};Br(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 lp}from"@inquirer/prompts";import{applyPull as Gr,computeSyncStatus as Ka,compareRemoteSources as cp,planPull as Xa,planImport as dp,applyImport as up,establishBaselines as pp,rebaselineServerMeta as fp,D360AuthError as mp}from"document360-engine";U();var Va=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:v,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:O,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:_,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:v,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:v,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 op(e){return e.path?e.path:`${e.title??"(untitled)"} ${le(`[${e.articleId}]`)}`}function rp(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 xo(e,t){let n=[],o=e.entries.filter(w=>w.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 w of o)n.push(` ${O("~")} ${O(w.path??"")} ${le(`\u2192 "${w.link.title}"`)}`)}for(let w of Va){let S=e.entries.filter($=>$.status===w.status&&!(w.status==="untracked-local"&&$.link));if(S.length!==0){n.push(""),n.push(Pe(w.header));for(let $ of S)n.push(` ${w.paint(w.mark)} ${w.paint(op($))}${$.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,h=i===r?N("\u2713 everything up to date"):[r>0?N(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...Va.map(w=>{let S=(e.counts[w.status]??0)-(w.status==="untracked-local"?p:0);return S>0?`${S} ${c[w.status]}`:null})].filter(Boolean).join(le(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${rp(t)}`:"";return n.push(h+le(` \xB7 ${i} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as ip}from"diff";import Ga from"picocolors";var Ya=80,sp="\x1B[48;2;74;28;28m",ap="\x1B[48;2;24;66;24m",za="\x1B[49m",Vr=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=ip("a","b",r,i,"","",{context:3}),h=0,k=0,w=[];p.hunks.forEach(($,I)=>{I>0&&w.push(Ga.gray(" \u2026"));let x=$.oldStart,E=$.newStart;for(let T of $.lines){let M=T[0],H=T.slice(1).slice(0,c);M==="-"?(k++,w.push(`${sp}${Vr(x++)} - ${H}${za}`)):M==="+"?(h++,w.push(`${ap}${Vr(E++)} + ${H}${za}`)):(w.push(Ga.gray(Vr(E))+" "+H),x++,E++)}});let S=w.slice(0,Ya);return{added:h,removed:k,lines:S,hidden:Math.max(0,w.length-Ya)}}async function Qa(e,t){let n=Fe(t.cwd,t.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await hp(t),{kind:"continue"};if(o==="--baseline")return await gp(t,e.filter(c=>c!=="--baseline")),{kind:"continue"};if(o==="--compare")return await yp(t),{kind:"continue"};if(o)return console.log(v(`Unknown option: ${o}`)),console.log(f("Usage: /pull pull portal edits + import new portal articles")),console.log(f(" /pull <path> pull one article (or resolve a conflict)")),console.log(f(" /pull --status drift report only (no writes)")),console.log(f(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await wp(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let i=await Yr({cwd:t.cwd,profileName:t.profileName});for(let c of zr(i))console.log(c.tone==="ok"?N(c.text):c.tone==="warn"?O(c.text):f(c.text));console.log("")}catch(r){r instanceof mp?console.log(v(r.message)):console.log(v(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Yr(e){let t=await Ka({cwd:e.cwd,profileName:e.profileName}),n={pulled:[],imported:[],conflicts:[],toPublish:0,failed:[]};for(let o of t.entries)if(o.status==="remote-ahead"&&o.path)try{let r=await Xa({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Gr({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 dp({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});up({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 vo=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,ht=e=>e===1?"":"s";function zr(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: ${vo(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${ht(e.imported.length)}: ${vo(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>. (${vo(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${ht(e.failed.length)} failed: ${vo(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 hp(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Ka({cwd:e.cwd,profileName:e.profileName});for(let o of xo(n,Date.now()-t))console.log(o);console.log("")}async function gp(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 pp({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await fp({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(O(`${o.skipped.length} skipped:`));for(let i of o.skipped)console.log(f(` - ${i.path} (${i.reason})`))}}async function yp(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await cp({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(v(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(O(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(O(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(f(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function wp(e,t){let n=t.replace(/\\/g,"/"),o=await Xa({cwd:e.cwd,profileName:e.profileName,relPath:n});console.log(""),console.log(`${_("\u25CF")} ${Pe(o.title)} ${le(`(${o.path})`)}`);for(let c of o.notes)console.log(O(` \u26A0 ${c}`));o.overwritesLocalChanges&&console.log(O(" \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.")),Gr({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(()=>lp({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}Gr({cwd:e.cwd,profileName:e.profileName},o),console.log(N(` \u2713 Pulled ${o.path} (sync base advanced).`))}U();import{statSync as kp}from"node:fs";import{resolve as bp}from"node:path";import{estimateBulkCost as $p,planPartitions as xp,readProjectConfig as vp,resolveModelForOperation as Cp,runPartitioned as Rp,trackedArticlePaths as Pp}from"document360-engine";var Kr=3;function Xr(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 Qr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Jr(e,t){return t.map(n=>{let o=0;try{o=kp(bp(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Zr(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 ei(e,t,n){let o=e.reduce((p,h)=>p+h.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 ti(e,t,n){let o=x=>t[x.index]?.paths.length??0,r=e.filter(x=>x.ok),i=e.filter(x=>!x.ok),c=e.reduce((x,E)=>x+o(E),0),p=r.reduce((x,E)=>x+o(E),0),h=e.reduce((x,E)=>x+E.costUsd,0),k=e.reduce((x,E)=>x+E.outputTokens,0),w=n==="api"?`${he(h)} total`:Qe(k),S=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,$=x=>`${x} article${x===1?"":"s"}`,I=[];if(i.length===0)I.push(`Converted ${$(c)} (${S}) successfully \xB7 ${w}.`);else{I.push(`Converted ${p}/${$(c)} (${S}) \xB7 ${w}.`),I.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let x of i)I.push(` \u2717 ${x.label}${x.error?` \u2014 ${x.error}`:""}`)}return I}async function Ja(e,t){if(!vp(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Xr(e),r=Pp(t.cwd,t.profileName);if(r.length===0)return console.log(v("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let i=Qr(r,n);if(i.length===0)return console.log(v(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=xp(i),p=`/convert${n?` --scope ${n}`:""} --run`,{model:h,forced:k}=Cp(t.cwd,"light");if(!o){let w=$p({files:Jr(t.cwd,i),op:"convert",model:h});n&&console.log(f(`Scope: ${n} (${i.length} of ${r.length} tracked articles).`));for(let S of ei(c,w,Kr))console.log(S);return console.log(f(`Model: ${h}${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${Kr} agents at once) on ${h}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let w of Rp({cwd:t.cwd,partitions:c,promptFor:Zr,concurrency:Kr,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:h}))if(w.type==="partition_status")w.status==="running"?console.log(f(` \u25B8 ${w.label} \u2014 converting\u2026`)):w.status==="done"?console.log(N(` \u2713 ${w.label}`)):console.log(v(` \u2717 ${w.label}`));else if(w.type==="run_done"){console.log("");let S=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let $ of ti(w.results,c,S))console.log(w.ok?N($):O($))}}catch(w){console.log(v(`Convert run failed: ${w.message}`))}return console.log(""),{kind:"continue"}}U();import{statSync as tl}from"node:fs";import{resolve as nl}from"node:path";import{estimateBulkCost as _p,lintDocs as Op,planPartitions as Lp,readDocsPlan as Mp,readProjectConfig as ol,DEFAULT_DOCS_DIR as Up,resolveModelForOperation as Wp,runPartitioned as Fp,stampArticles as Hp,CONTENT_CAP_VERSION as qp}from"document360-engine";import{readProjectConfig as Tp,loadProfileMap as Sp,resolveActiveProfile as Dp,desiredCategoryOrder as Ap,desiredArticleOrder as jp,DEFAULT_DOCS_DIR as Ep}from"document360-engine";var ni=e=>e.replace(/\\/g,"/"),Np=e=>ni(e).split("/").pop()??e;function Ip(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=Tp(e);if(!n)return[];let o=Dp(e,t),r=Sp(e,o.name);if(!r)return[];let i=ni(n.docsDir??Ep).replace(/\/+$/,""),c=new Map;for(let h of jp(r))c.set(h.categoryPath,(c.get(h.categoryPath)??0)+1);let p=[];for(let h of Ap(r)){let k=ni(h.path),w=k.startsWith(`${i}/`)?k.slice(i.length+1):k===i?"":k;w&&p.push({token:w,label:Ip(Np(k)),count:c.get(h.path)??0})}return p}catch{return[]}}function Za(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 Bt(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," "),h=k=>t==="write"?`/write --scope ${k}${c}`:`/${t} ${k}${c}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((k,w)=>k+w.count,0)} articles). Pick a target:`,` ${p} (everything)`,...r.map(k=>` ${h(k.token)} (${k.label} \xB7 ${k.count} article${k.count===1?"":"s"})`)]}function Co(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function el(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 Bp=3,Vp=8;function oi(e){return e===void 0||!Number.isFinite(e)?Bp:Math.max(1,Math.min(Math.floor(e),Vp))}function ri(e){let t,n,o=!1,r=!1,i,c=h=>{let k=Number(h);return h!==void 0&&Number.isFinite(k)?k:void 0};for(let h=0;h<e.length;h++){let k=e[h];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[++h]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?i=c(e[++h]):k?.startsWith("--concurrency=")?i=c(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=h=>h?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:i,rewrite:r}}function Gp(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Yp(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function ii(e,t,n){return n.filter(o=>{try{return tl(nl(e,t,o)).size===0}catch{return!0}})}function si(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+=tl(nl(e,c)).size}catch{}return{path:r,bytes:i}})}function ai(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}${y}`).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 li(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 ci(e,t,n){let o=x=>t[x.index]?.paths.length??0,r=e.filter(x=>x.ok),i=e.filter(x=>!x.ok),c=e.reduce((x,E)=>x+o(E),0),p=r.reduce((x,E)=>x+o(E),0),h=e.reduce((x,E)=>x+E.costUsd,0),k=e.reduce((x,E)=>x+E.outputTokens,0),w=n==="api"?`${he(h)} total`:Qe(k),S=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,$=x=>`${x} article${x===1?"":"s"}`,I=[];if(i.length===0)I.push(`Wrote ${$(c)} (${S}) successfully \xB7 ${w}.`),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)} (${S}) \xB7 ${w}.`),I.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let x of i)I.push(` \u2717 ${x.label}${x.error?` \u2014 ${x.error}`:""}`)}return I}function di(e,t,n){try{let o=Op({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 ui(e,t,n){let o=(ol(e)?.docsDir??Up).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Gp(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=Yp(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=ii(e,o,i);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"",h=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${h} --rewrite to regenerate them all.`}}return{docsDir:o,targets:c,planCount:r.length}}async function rl(e,t){if(!ol(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Co(e)){for(let M of Za(t.cwd,t.profileName))console.log(f(M));return{kind:"continue"}}if(Je("write",e)){let M=Bt(t.cwd,"write",e,t.profileName);if(M.length>0){for(let H of M)console.log(f(H));return{kind:"continue"}}}let n=Mp(t.cwd);if(n.length===0)return console.log(v("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:i,concurrency:c,rewrite:p}=ri(e),{docsDir:h,targets:k,reason:w,rewriting:S}=ui(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(w?O(w):O("Nothing to write.")),{kind:"continue"};S&&console.log(O(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let $=Lp(k),I=oi(c),{model:x,forced:E}=Wp(t.cwd,"standard"),T=!!r;if(i&&!T){let M=_p({files:si(t.cwd,n,k),op:"write",model:x});o&&console.log(f(`Scope: ${o} (${k.length} pending).`));for(let H of li($,M,I))console.log(H);return console.log(f(`Model: ${x}${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 ${x}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let M of Fp({cwd:t.cwd,partitions:$,promptFor:H=>ai(H,h,{rewrite:S||T}),concurrency:I,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:x}))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(v(` \u2717 ${M.label}`));else if(M.type==="run_done"){console.log("");let H=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let X of ci(M.results,$,H))console.log(M.ok?N(X):O(X));if(M.ok)try{Hp(t.cwd,k.map(X=>`${h}/${X}`),{writtenCap:qp})}catch{}let J=di(t.cwd,h,k);J&&console.log(O(J))}}catch(M){console.log(v(`Write run failed: ${M.message}`))}return console.log(""),{kind:"continue"}}U();import{existsSync as zp,readdirSync as il,statSync as sl}from"node:fs";import{join as al}from"node:path";import{inputDir as Kp,readProjectConfig as Xp}from"document360-engine";var ll=/\.(md|markdown|pdf|txt)$/i;function pi(e){let t=Kp(e);if(!zp(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of il(t)){let i=al(t,r),c=!1;try{c=sl(i).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=Qp(i);p>0&&n.push({name:r,docCount:p})}else ll.test(r)&&o++}return n.sort((r,i)=>r.name.localeCompare(i.name)),{features:n,looseDocs:o}}function Qp(e){let t=0;for(let n of il(e))try{sl(al(e,n)).isFile()&&ll.test(n)&&t++}catch{}return t}function fi(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 Ro(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 mi="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function cl(e,t){let n=t?.cwd??process.cwd();if(!Xp(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=pi(n);if(o.length===0&&r===0)return console.log(f(mi)),{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 h of o)console.log(` ${h.name} ${f(`(${h.docCount} doc${h.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Ro(p),display:p?`/draft ${p}`:"/draft"}}let c=fi(o,i);return{kind:"forward-to-agent",prompt:Ro(c??"",c?void 0:i),display:`/draft ${i}`}}U();import{listOpenForDocs as Jp,readProjectConfig as Zp}from"document360-engine";function hi(e){try{return Jp(e).filter(t=>t.kind==="request").length}catch{return 0}}function gi(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 wi="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 dl(e,t){let n=t?.cwd??process.cwd();if(!Zp(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=gi(e);if(!r&&hi(n)===0)return console.log(f(wi)),{kind:"continue"};let i=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:yi(r,o),display:i}}U();import{search as ef}from"@inquirer/prompts";import{findByName as tf,getSession as nf,listSessions as of,relativeTime as pl}from"document360-engine";async function fl(e,t){let n=of(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=tf(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(v(`No session matches "${o}".`)),ul(n),{kind:"continue"})}if(!process.stdin.isTTY)return ul(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>ef({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} ${pl(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=nf(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function ul(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${f(pl(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}U();import{renameSession as rf}from"document360-engine";function ki(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 ml(e,t){let n=ki(e.join(" "));if(!n)return console.log(v("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(rf(o,n)?console.log(N(`\u2713 Session renamed to "${n}"`)):console.log(v("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 hl,readProjectConfig as sf,writeProjectConfig as af}from"document360-engine";U();function bi(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=sf(e);if(!o)return"No .d360-writer/config.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return hl().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},af(o,e),null):`Unknown environment "${r}". Known: ${hl().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function gl(e,t){let n=e[0];if(!n)return so(t.cwd),{kind:"continue"};if(n==="add"){let o=bi(t.cwd,e[1],e[2]);return o?(console.log(v(o)),{kind:"continue"}):(console.log(N(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/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 lf}from"@inquirer/prompts";import{readProjectConfig as cf,readUserConfig as yl,resolveModelSetting as $i,writeUserConfig as wl}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 Po(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 df(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=()=>$i(e).model;if(t==="default"){let i=yl();return i.defaultModel?(delete i.defaultModel,wl(i),{lines:[`\u2713 Personal model override cleared \u2014 now: ${$i(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}}wl({...yl(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=cf(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 kl(e,t){let n=e[0]?.trim();if(!n){let c=$i(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${_(c.model)}${c.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${df(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Po(c),h;try{h=await t.withPausedInput(()=>lf({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:w,effective:S}=bn(t.cwd,h??"default");for(let $ of k)console.log($.startsWith("\u26A0")?O($):$.startsWith("\u2713")?N($):f($));return w&&await t.setModel(S),{kind:"continue"}}let{lines:o,changed:r,effective:i}=bn(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?O(c):c.startsWith("\u2713")?N(c):f(c));return r&&await t.setModel(i),{kind:"continue"}}To();async function Rl(e,t){return await t.withPausedInput(()=>Lt(t.cwd)),{kind:"clear"}}async function Pl(e,t){return await t.withPausedInput(()=>no(t.cwd,t.profileName)),{kind:"clear"}}U();import{resolveActiveProfile as Sf}from"document360-engine";async function Tl(e,t){let n=!1;try{n=Sf(t.cwd).production}catch{}return n?(console.log(O("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}U();var Sl=async(e,t)=>{try{await t.withPausedInput(()=>io({}))}catch(n){console.log(v(`Login failed: ${n.message}`))}return{kind:"continue"}};U();import{resolveActiveProfile as Df,clearTokens as Af,clearProfileProject as jf}from"document360-engine";async function Dl(e,t){let n;try{n=Df(t.cwd,t.profileName).name}catch(r){return console.log(v(r.message)),{kind:"continue"}}let o=Af(n);return jf(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 Al}from"node:fs";import{isAbsolute as Ef,join as Nf,resolve as If}from"node:path";import{readProjectConfig as _f,screenshotPlaceholderIds as Of,DEFAULT_CAPTURE_DIR as Lf,DEFAULT_OUTPUT_DIR as Mf}from"document360-engine";var jl=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function vi(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?jl(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:jl(o),setup:t}:{mode:"single",id:o}}function Ci(e,t){let n=_f(e),o=n?.captureDir??Lf,r=n?.outputDir??Mf,i=(c,p)=>Ef(c)?Nf(c,p):If(e,c,p);return Of(e,{scope:t}).map(({id:c,file:p})=>{let h=Al(i(r,`${c}.png`))?"captured":Al(i(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:h}})}var Uf={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Wf={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Ri(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(` ${Uf[c.state]} ${c.id.padEnd(34)} ${Wf[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function El(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 So(e,t){let n=vi(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of Ri(Ci(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 Ff,readFileSync as Hf}from"node:fs";import{isAbsolute as qf,join as Bf,resolve as Vf}from"node:path";import{readProjectConfig as Gf,DEFAULT_CAPTURE_DIR as Yf}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 Nl="-".repeat(64);function Pi(e){let t=Yf;try{let w=Gf(e);w?.captureDir&&(t=w.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=qf(t)?Bf(t,"CAPTURE-TESTID-REQUESTS.json"):Vf(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Ff(n))return null;let o;try{let w=JSON.parse(Hf(n,"utf8").replace(/^/,""));o=Array.isArray(w?.requests)?w.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(w=>w.file).filter(Boolean)).size,i=o.length,c=`${i} data-testid attribute${i===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,h=`${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.","",Nl,`Read ${h} 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.",Nl]}Ke();U();import{listOpenForDocs as zf,readProjectConfig as Kf}from"document360-engine";function Ti(e){try{return zf(e).length}catch{return 0}}function Si(){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 Il(e,t){let n=t?.cwd??process.cwd();return Kf(n)?Ti(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:Si(),display:"/inbox"}:(console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{listOpenHints as Xf,listOpenForDocs as Qf,listOpenDirectives as Jf,readProjectConfig as Zf,computeSyncStatus as em,planPull as tm,applyPull as nm,planImport as om,applyImport as rm}from"document360-engine";function vn(e){let t=0,n=0,o=0,r=0;try{t=Xf(e).length}catch{}try{let i=Qf(e);n=i.filter(c=>c.kind==="request").length,o=i.filter(c=>c.kind==="answer").length}catch{}try{r=Jf(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 Ai(e){return{publish:e.includes("--publish")}}function ji({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 im={status:em,plan:tm,apply:nm,planImport:om,applyImport:rm};async function Ei(e,t=im){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 Di=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Do=e=>e===1?"":"s";function Ni(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${Do(e.pulled.length)} into local: ${Di(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Do(e.imported.length)} into local drafts: ${Di(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Do(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Di(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${Do(e.failed.length)} failed \u2014 left for /pull.`),t}async function _l(e,t){let n=t?.cwd??process.cwd();if(!Zf(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Fe(n,t?.profileName);if(!o.ok)return console.log(v(o.reason)),{kind:"continue"};let{publish:r}=Ai(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let i=await Ei({cwd:n,profileName:t?.profileName});for(let p of Ni(i))console.log(p.startsWith("\u2713")?N(p):p.startsWith("\u2139")?f(p):O(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:ji({publish:r}),display:`/catch-up${r?" --publish":""}`}}U();import{spawn as sm}from"node:child_process";var gt="document360-writer",Ao=`npm i -g ${gt}@latest`;async function jo(){let e=process.platform==="win32";return new Promise(t=>{try{let n=sm(`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 Ol(){return console.log(f(`Updating ${gt}\u2026`)),(await jo()).ok?console.log(N("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(v(`Update failed \u2014 run manually: ${Ao}`)),{kind:"continue"}}U();Ke();import{existsSync as Ii,rmSync as am}from"node:fs";import{basename as Ll,resolve as _i}from"node:path";import{execFileSync as lm}from"node:child_process";import{input as cm}from"@inquirer/prompts";import{readProjectConfig as dm,devHintsGuidePath as um}from"document360-engine";var pm=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],fm=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Eo=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Ml=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Ul(e){let t=Eo(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Ml(t)?!0:fm.has(t)}function Oi(e){let t=null;try{t=dm(e)}catch{t=null}let n=new Set(pm);for(let o of[Eo(t?.docsDir),Eo(t?.captureDir),Eo(t?.outputDir)])o&&Ml(o)&&n.add(o);return[...n].filter(o=>Ul(o)&&Ii(_i(e,o)))}function Li(e,t){let n=[],o=[];for(let r of t){if(!Ul(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{am(_i(e,r),{recursive:!0,force:!0}),n.push(r)}catch(i){o.push({path:r,error:i.message})}}return{removed:n,failed:o}}function Wl(e,t){try{return lm("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 mm(e){return Wl(e,".d360-writer/hints")}function hm(e){return Wl(e,".d360-writer/messages")}function Mi(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=mm(e),o=hm(e),r=Ii(_i(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: ${Ll(e)}`]}async function Fl(e,t){let n=Oi(t.cwd);for(let h of Mi(t.cwd,n))console.log(n.length===0?f(h):h);if(n.length===0)return{kind:"continue"};let o=Ll(t.cwd);if((await t.withPausedInput(()=>cm({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(O("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let i=Ii(um(t.cwd)),{removed:c,failed:p}=Li(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 h of p)console.log(v(` \u2717 ${h.path}: ${h.error}`));if(i){for(let h of mo())console.log(h);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 gm}from"document360-engine";function No(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 Ui(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(_(` 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
|
|
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 Hl(e,t){let n=e.includes("--fix"),o=e.find(c=>!c.startsWith("--")),r=o?` ${o}`:"",i=gm({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:Ui(i),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let c of No(i))console.log(i.length===0?N(c):O(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 xm,loadStyleGuide as vm,buildReviewPrompt as Cm,readProjectConfig as Rm,DEFAULT_DOCS_DIR as Pm}from"document360-engine";U();import{readProjectConfig as ym,loadProfileMap as wm,resolveActiveProfile as km,desiredCategoryOrder as bm,desiredArticleOrder as $m}from"document360-engine";function ql(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Bl=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Rn(e,t){try{if(!ym(e))return[];let n=km(e,t),o=wm(e,n.name);if(!o)return[];let r=new Map;for(let c of $m(o)){let p=r.get(c.categoryPath);p?p.push(c):r.set(c.categoryPath,[c])}let i=[];for(let c of bm(o)){i.push(ql(Bl(c.path)));for(let p of(r.get(c.path)??[]).sort((h,k)=>h.order-k.order))i.push(` ${ql(Bl(p.path))}`)}return i}catch{return[]}}async function Vl(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(_("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Wi(e,t){let n=Rm(e);if(!n)return null;let o=(n.docsDir??Pm).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),i=t.find(w=>!w.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),c=xm({cwd:e}),p=i?c.filter(w=>w.path===`${o}/${i}`||w.path.startsWith(`${o}/${i}/`)):c,h=i?"":Rn(e).join(`
|
|
286
|
+
`);return{prompt:Cm({docsRoot:o,scope:i,styleGuide:vm(e),deterministicFindings:p,fix:r,structure:h||void 0}),display:`/review${i?` ${i}`:""}${r?" --fix":""}`}}async function Gl(e,t){if(Je("review",e)){let o=Bt(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=Wi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{readProjectConfig as Tm}from"document360-engine";function Fi(e,t){if(!Tm(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 Yl(e,t){if(Je("reorder",e)){let o=Bt(t.cwd,"reorder",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(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{readProjectConfig as Sm,writeProjectConfig as zl,isAppType as Dm,playbookSkillName as Am,detectAppType as Kl}from"document360-engine";var Xl=["web","cli","service","library"],jm=new Set(["web","cli"]);function Hi(e){return jm.has(e)?`${Am(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Io(e,t){let n=t.cwd,o=Sm(n);if(!o)return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let i=o.appType??Kl(n);if(i){let c=o.appType?"set in config":"auto-detected";console.log(`${_("Genre:")} ${i} (${c}) \u2014 ${Hi(i)}`)}else console.log(O("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${Xl.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(f("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:i,...c}=o;zl(c,n);let p=Kl(n);return console.log(N(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${Hi(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return Dm(r)?(zl({...o,appType:r},n),console.log(N(`\u2713 Genre set to ${r} \u2014 ${Hi(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(v(`Unknown genre "${r}". Choose one of: ${Xl.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}U();import{listRoadmap as Ql,roadmapProgress as Jl,stampRoadmapDone as Em}from"document360-engine";function qi(e){let t=Ql(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=Jl(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 Bi(e,t){if(!t.trim())return{ok:!1,line:"Usage: /roadmap done <step title>"};if(!Em(e,t,{doneAt:new Date().toISOString()})){let r=Ql(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=Jl(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 Zl(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Bi(n,e.slice(1).join(" ").trim());return console.log(r.ok?N(r.line):O(r.line)),{kind:"continue"}}let o=qi(n);console.log(_(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?f(r):r);return{kind:"continue"}}var ec={help:Cr,"?":Cr,clear:sa,exit:Rr,quit:Rr,init:Ar,mcp:yo,publish:Ha,audit:wn,scope:Ba,pull:Qa,convert:Ja,write:rl,draft:cl,document:dl,resume:fl,rename:ml,profile:gl,model:kl,doctor:$n,workspace:Rl,project:Pl,"allow-prod":Tl,login:Sl,logout:Dl,screenshot:So,"capture-setup":xn,devhints:ha,inbox:Il,"catch-up":_l,update:Ol,reset:Fl,check:Hl,review:Gl,reorder:Yl,structure:Vl,genre:Io,roadmap:Zl};function tc(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 Nm="Or just tell me what to write or update.",Im='\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 _o(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Vi(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var _m={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 Om(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:_m,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 nc(e,t){let n=t.filter(i=>i.bullet).map(i=>` \u2022 ${i.bullet}`),o=t[0],r=[];o.lead?r.push(Vi(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(" "),Nm].join(`
|
|
289
|
+
`)}function Pn(e){if(!e.ready)return{kind:"idle"};let t=Om(e);if(!e.hasDocs){let r=t[0];return r&&(r.lead?.kind==="cmd"||r.picker)?{kind:"recommend",rec:{note:nc("\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:Im,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:nc("Welcome back \u2014 where your docs stand:",t),tone:n.tone??"info",lead:n.lead,picker:n.picker}}}import{existsSync as Gi,readdirSync as zi}from"node:fs";import{spawnSync as Lm}from"node:child_process";import{join as Oo}from"node:path";import{readProjectConfig as rc,resolveActiveProfile as ic,loadTokens as Mm,isExpired as Um,loadProfileMap as sc,countLocalAhead as Wm,readDocsPlan as Fm,devHintsGuidePath as Hm,DEFAULT_DOCS_DIR as Yi,roadmapProgress as qm}from"document360-engine";Ke();function oc(e){try{return zi(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Ki(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>oc(Oo(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&oc(Oo(e,o)))}function Xi(e,t){try{let n=rc(e);if(!n)return!1;let o=ic(e,t),r=sc(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let i=Oo(e,(n.docsDir??Yi).replace(/\/+$/,""));return!!(Gi(i)&&zi(i).length>0||Gi(Hm(e)))}catch{return!1}}function Tn(e,t,n){try{let o=rc(e);if(!o)return null;let r=ic(e,t),i=Mm(r.name),c=!!i&&(!Um(i)||!!i.refreshToken),p=Xi(e,t)||!Ki(e,o.authoritativeSourceFiles),h=sc(e,r.name),k=h?Object.keys(h.articles).length:0,w=Oo(e,(o.docsDir??Yi).replace(/\/+$/,"")),S=!1;try{S=Gi(w)&&zi(w).length>0}catch{}let $=0;if(h?.lastAnalyzedCommit)try{let J=Lm("git",["rev-list","--count",`${h.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});J.status===0&&($=parseInt((J.stdout||"").trim(),10)||0)}catch{}let I=0;try{let J=Fm(e);if(J.length>0){let X=(o.docsDir??Yi).replace(/\/+$/,"");I=ii(e,X,J.map(ae=>ae.path)).length}}catch{}let x=vn(e),E=Cn({...x,directives:0}),T=Wm(e,t),M=Se(e),H=qm(e);return{ready:c&&p&&!n.claudeMissing,hasDocs:S,tracked:k,pendingText:E,directives:x.directives,behind:$,pendingWrites:I,localAhead:T,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:M.status,devhintsCompletedVersion:M.completedVersion,devhintsToVersion:se,builderStarted:We(e),genreUnknown:n.genreUnknown,roadmap:H}}catch{return null}}function Qi(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 Lo(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 Qi(`${i+1}. ${r.feature}`,76))o.push(n(c));o.push(n());for(let c of Qi(r.why,73))o.push(n(` ${c}`));o.push(n());for(let c of Qi(`\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 Bm={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"},lc=160,Zi=200,cc=40;function $e(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function ac(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),cc)}`);return t.length>4&&n.push("\u2026"),$e(n.join(", "),lc)}var Ze=e=>typeof e=="string"&&e?e:null,Ji=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Vm(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 Gm(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=Vm(t.local_path);return n("Create article",`"${$e(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Ze(t.title),r=Ji(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)",Ji(t.article_id)?`id ${Ji(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 Mo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...i]=e.split("__"),c=i.join("__");if(r==="document360"){let k=Gm(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:ac(t)}}let n=Bm[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:$e(o,lc)}:{title:e,sep:"",arg:ac(t)}}function Ym(e){if(e===null||typeof e!="object")return typeof e=="string"?e:null;let t=e;for(let n of["name","title","slug","id"])if(typeof t[n]=="string"&&t[n])return t[n];return null}function zm(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Ym).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>$e(r,Zi))]}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),cc)}`);return n.length>0?[$e(n.join(" \xB7 "),Zi)]:null}return null}function Km(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 Xm(e,t,n){switch(e){case"d360_create_article":{let o=Km(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 Uo(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=Xm(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let i=zm(r)??r.split(`
|
|
291
|
+
`);return{lines:i.slice(0,t).map(c=>$e(c,Zi)),hidden:Math.max(0,i.length-t)}}function Wo(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Fo(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 Ho(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 gh=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function yh(e,t,n,o){if(gh.test(e))try{let r=pc(o),i=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=Fo(t,n),p=Ho(n);e.endsWith("publish_article")&&p&&console.log(_(` \u2B95 Live: ${p}`)),c&&i&&console.log(_(` \u2B95 Preview: ${Wo(r.connection.portalUrl,i,c,r.project.languageCode??"en")}`))}catch{}}async function fc(e=process.cwd(),t="auto",n,o){let r=Jm(t);r.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${_("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${_('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),wh(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=es({cwd:e,profileName:n,allowProdWrites:i}),p={uuid:null,firstPrompt:null,titleFired:!1},h=Qm({input:process.stdin,output:process.stdout}),k=[],w=null,S=!1;h.on("line",x=>{if(w){let E=w;w=null,E(x)}else k.push(x)}),h.on("close",()=>{if(S=!0,w){let x=w;w=null,x(null)}});function $(){return k.length>0?Promise.resolve(k.shift()):S?Promise.resolve(null):(process.stdout.write(_("> ")),new Promise(x=>{w=x}))}let I={cwd:e,version:o,profileName:n,allowProdWrites:()=>i,restartAgent:()=>{c.close(),c=es({cwd:e,profileName:n,allowProdWrites:i}),p={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>p.uuid,setPendingName:x=>{p.pendingName=x},setModel:async x=>c.setModel(x),withPausedInput:async x=>{h.pause();try{return await x()}finally{h.resume()}}};try{for(;;){let x=await $();if(x===null)break;let E=x.trim();if(E){if(E.startsWith("/")){let T=tc(E);if(!T)continue;let M=ec[T.name];if(!M){console.log(v(`Unknown command: /${T.name}`)),console.log(f("Type /help for the list."));continue}let H=await M(T.args,I);if(H.kind==="exit")break;if(H.kind==="clear"){I.restartAgent();continue}if(H.kind==="allow-prod"){i=!0,I.restartAgent(),console.log(N("\u2713 Production writes authorized for this session.")),console.log("");continue}if(H.kind==="resume"){c.close(),c=es({cwd:e,resume:H.uuid,profileName:n,allowProdWrites:i});let J=Zm(H.uuid);p={uuid:H.uuid,firstPrompt:J?.firstPrompt??null,titleFired:!0},uc(H.uuid),console.log(N(`\u2713 Resumed "${H.name}"`)),console.log("");continue}if(H.kind==="forward-to-agent"){p.firstPrompt||(p.firstPrompt=H.display??H.prompt);let J=(H.display??"").trim().split(/\s+/),X=(J[0]==="/check"||J[0]==="/review")&&J.includes("--fix"),ae=J.slice(1).find(Xt=>!Xt.startsWith("--")),kt=X?mh(e,ae):[];if(await ts(c,H.prompt,r,p,e),X)try{fh(e,kt,{reviewedCap:hh})}catch{}}else kh(e,n);continue}if(ch(E)){let T=dh(E);if(T){try{uh(e,{title:T,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}p.firstPrompt||(p.firstPrompt=E),await ts(c,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${T}". 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 "${T}" and the article path(s) you wrote.`,r,p,e);continue}}p.firstPrompt||(p.firstPrompt=E),await ts(c,E,r,p,e)}}}finally{c.close(),h.close()}}function wh(e,t){console.log(""),console.log(dn("document360-writer")),console.log(f(` cwd: ${e}`));let n=rh(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(bh(e,t)),!ih(e))console.log(O(" 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(O(` ${r}`))}catch{}try{let r=sh(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=ph(e);for(let i of Lo(r.applied))console.log(O(` ${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"?O:f;for(let p of i.rec.note.split(`
|
|
292
|
+
`))console.log(c(` ${p}`));i.rec.picker&&console.log(_(` 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 kh(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: ${Vi(o.rec.lead)}`))}catch{}}function bh(e,t){try{let n=pc(e,t),o=n.production?O(" \u26A0 PRODUCTION"):"",r=lh(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let i={...dc(r.idToken)??{},...dc(r.accessToken)??{}},c=i.email??i.preferred_username??"signed in";return ah(r)&&!r.refreshToken?O(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function $h(){console.error(""),console.error(`Sign in with your Claude subscription: run ${_("claude")} once, then retry.`),console.error(` (No Claude Code? ${_("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${_("https://console.anthropic.com/settings/keys")}`)}function xh(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;nh({uuid:t,name:r??th(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function vh(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||oh(o,t).then(r=>{r&&eh(n,r)}).catch(()=>{})}async function ts(e,t,n,o,r){let i=new Map;for await(let c of e.send(t))Ch(c,o,r,n,i)}function Ch(e,t,n,o,r){switch(e.type){case"session":t.uuid||xh(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=Mo(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=Uo(e.output,4,e.isError?void 0:i.name,i.input),p=e.isError?v:le;c.lines.forEach((h,k)=>console.log(p((k===0?" \u23BF ":" ")+h))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||yh(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&&(uc(t.uuid),t.titleFired||vh(t,n));break;case"error":console.error(""),console.error(v(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&$h();break}}import{render as Fg}from"ink";import{resolveAuth as Hg}from"document360-engine";import{useCallback as G,useEffect as ve,useMemo as as,useRef as ee,useState as W}from"react";import{Box as ne,Text as D,useApp as Uh,useInput as Wh,useStdout as Fh}from"ink";import{existsSync as Gt,readFileSync as Qo,readdirSync as Hh}from"node:fs";import{basename as Dn,isAbsolute as qh,join as ls}from"node:path";import{createSession as Fc,classifyClaudeAuth as fs,CLAUDE_CODE_SETUP_HINT as Bh,loginPkce as Vh,toStoredTokens as Gh,saveTokens as Yh,getAccessToken as zh,resolveActiveProfile as xe,resolveProjectId as Kh,getArticle as Xh,decodeJwtClaims as zt,isExpired as et,loadTokens as wt,clearTokens as Qh,clearProfileProject as Jh,setTitle as Zh,slugify as eg,touchSession as cs,upsertSession as tg,generateTitle as Hc,findByName as ng,listSessions as og,renameSession as rg,suggestNextAction as ig,readProjectConfig as te,writeProjectConfig as qc,resolveAndPersistAppType as sg,detectAppType as ag,resolveModelSetting as ms,loadProfileMap as Bc,applyPull as lg,computeSyncStatus as Vc,lintDocs as Gc,compareRemoteSources as cg,planPull as dg,establishBaselines as ug,rebaselineServerMeta as pg,inventoryRepo as fg,knownEnvironments as mg,resolveEnvironment as hg,planPartitions as ds,partitionEvenly as gg,screenshotPlaceholderIds as yg,trackedArticlePaths as wg,runPartitioned as Jo,estimateBulkCost as Yc,resolveModelForOperation as Zo,readDocsPlan as kg,checkForUpdate as bg,detectInstallKind as $g,isSelfUpdatable as xg,devHintsGuidePath as zc,toolFeedbackPath as Kc,reconcileToolFeedback as vg,reconcileUpgradeActions as Cg,stampArticles as us,listArticleFiles as Xc,CONTENT_CAP_VERSION as ps,ENGINE_VERSION as rd,DEFAULT_DOCS_DIR as id,setProfileProject as Rg,writeCrashLog as Pg,applyStructureOrder as Qc,orderSyncLine as Jc,applyRelatedArticles as Zc,relatedSyncLine as ed}from"document360-engine";Ke();import{spawn as mc}from"node:child_process";function Rh(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Ph(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?mc([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):mc(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 ns(e){for(let[t,n]of Rh())if(await Ph(t,n,e))return!0;return!1}var Th=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function os(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){Th.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 Sh,mkdirSync as Dh,readFileSync as Ah,writeFileSync as jh}from"node:fs";import{join as hc}from"node:path";import{writerDir as Eh}from"document360-engine";function gc(e){return hc(Eh(e),".sessions")}function yc(e,t){return hc(gc(e),`${t}.json`)}function wc(e,t,n){try{Dh(gc(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");jh(yc(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function rs(e,t){try{let n=yc(e,t);if(!Sh(n))return[];let o=JSON.parse(Ah(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Nh=e=>`\x1B]0;${e}\x07`,Ih=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function kc(e){process.stdout.isTTY&&process.stdout.write(e)}function Vt(e){kc(Nh(e))}function qo(e){kc(Ih(e))}var Bo=["\xB7 "," \xB7"],Vo="\u{1F7E3}";To();go();var Go=[{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"}],bc={"/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 $c(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(bc[n])return bc[n];let o=Go.find(r=>r.name===t);return o?o.desc:""}function xc(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Go.filter(n=>n.name.startsWith(t))}function vc(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}U();import{Box as Cc,Text as ce}from"ink";import{jsx as de,jsxs as Yo}from"react/jsx-runtime";function _h({row:e}){switch(e.t){case"head":return de(ce,{color:F,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 Yo(ce,{children:[de(ce,{color:F,children:`${e.n}. `}),e.s]});case"cmd":return Yo(ce,{children:[" ",de(ce,{color:F,children:e.name.padEnd(20)}),de(ce,{dimColor:!0,children:e.s})]});case"gap":return de(ce,{children:" "})}}function Rc({tab:e,width:t,version:n,engineVersion:o}){let r=Te[e]??Te[0],i=6+Te.reduce((p,h)=>p+h.label.length+4,0),c="\u2500".repeat(Math.min(i,Math.max(t-1,20)));return Yo(Cc,{flexDirection:"column",paddingX:1,children:[Yo(ce,{children:[de(ce,{color:F,bold:!0,children:"Help "}),Te.map((p,h)=>h===e?de(ce,{color:"white",backgroundColor:F,bold:!0,children:` ${p.label} `},p.key):de(ce,{dimColor:!0,children:` ${p.label} `},p.key))]}),de(ce,{color:F,children:c}),de(Cc,{flexDirection:"column",marginTop:1,children:r.rows.map((p,h)=>de(_h,{row:p},h))}),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 Oh=/^(?:\d+[.)]|[-*•])\s+/;function Pc(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(Oh,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let h=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!h||!o.has(h[1].toLowerCase()))continue;let k=`/${h[1].toLowerCase()}${h[2]?` ${h[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 Tc(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Lh=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Sc(e,t,n){if(!Lh.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 is(e){return e.replace(/^[\w.-]+\//,"")}var zo=16,Dc={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function yt(e){return typeof e=="string"?e:e.cmd}function Ac(e){return typeof e=="string"?void 0:e.desc}function ss(e){return e.trim().split(/\s+/).slice(1).join(" ")}function jc(e,t){let n=ss(t);return e.some(r=>yt(r).trim()===t.trim()||!!n&&ss(yt(r))===n)?e.filter(r=>yt(r).trim()!==t.trim()&&!(n&&ss(yt(r))===n)):[]}import{isDirectiveMention as Tg,stripDirectiveMention as Sg,appendDirective as Dg}from"document360-engine";var Mh=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Ec(e){return e.replace(/\r\n?/g,`
|
|
300
|
+
`)}function Nc(e){return e.includes(`
|
|
301
|
+
`)||e.length>200}function Ic(e,t){let n=t.split(`
|
|
302
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function _c(e,t){return e.replace(Mh,n=>t.get(n)??n)}function Oc(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Ko(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 Xo(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Lc(e,t,n){let o=Xo(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 Mc(e,t,n){let o=e[Xo(e,t)];return n==="start"?o.start:o.end}function Uc(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 h=i-t;return{text:[h>0?p.slice(h*o):p,...r.slice(c+1)].join(`
|
|
305
|
+
`),truncated:c>0||h>0}}}return{text:e,truncated:!1}}function Wc(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 er,jsx as A,jsxs as V}from"react/jsx-runtime";var Ag={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},td=` 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 m=s("ready-decision",()=>
|
|
308
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function jg(e,t,n,o){let r=fs(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=ms(e),p=te(e),h=(p?.docsDir??id).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${h}/ + config`,w={version:t,engineVersion:rd,claude:i,model:c.model,modelSource:Ag[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 w;try{let S=xe(e,o);w.profile=S.name,w.apiUrl=S.connection.apiUrl,w.prod=S.production,w.project=S.project.projectName??S.project.projectId??"(chosen at login)";let $=wt(S.name);if($){let I={...zt($.idToken)??{},...zt($.accessToken)??{}},x=I.email??I.preferred_username??"signed in";et($)?$.refreshToken&&(w.who=x,w.loggedOut=!1,w.sessionHint="session expired \u2014 refreshing\u2026"):(w.who=x,w.loggedOut=!1,w.sessionHint=`session valid until ${new Date($.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return w}function Eg(e,t){try{let n=xe(e,t),o=wt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...zt(o.idToken)??{},...zt(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 nd=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Kt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ng="Ask me to write or update an article\u2026";function Yt({ch:e,dim:t}){let[n,o]=W(!0);return ve(()=>{let r=setInterval(()=>o(i=>!i),530);return()=>clearInterval(r)},[]),A(D,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Ig=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function od(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var _g=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Og({startTime:e,chars:t}){let[n,o]=W(0);ve(()=>{let h=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(h)},[]);let r=Kt[n%Kt.length],i=nd[Math.floor(n/16)%nd.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return V(ne,{children:[A(D,{color:F,children:` ${r} ${i}\u2026 `}),A(D,{color:"gray",children:`(${hn(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function Lg({text:e}){let[t,n]=W(0);return ve(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),A(ne,{paddingX:1,children:A(D,{color:F,children:`${Kt[t%Kt.length]} ${e}`})})}var Mg=12e4;function Ug({p:e}){let[t,n]=W(0);ve(()=>{let T=setInterval(()=>n(M=>M+1),150);return()=>clearInterval(T)},[]);let o=Kt[t%Kt.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>=Mg,h=e.verb??"Converting",k=e.unit??"article",w=e.rows.reduce((T,M)=>T+M.items,0),S=h.toLowerCase(),$=e.rows,I=0;if($.length>zo){let T=$.findIndex(H=>H.status==="active"||H.status==="pending"),M=Math.max(0,Math.min(T-2,$.length-zo));I=$.slice(0,M).filter(H=>H.status==="done").length,$=$.slice(M,M+zo)}let x=Math.min(40,Math.max(...$.map(T=>is(T.label).length),0)),E=T=>T==="failed"?"red":T==="active"?F:void 0;return V(ne,{flexDirection:"column",children:[V(ne,{children:[A(D,{color:F,children:` ${o} ${h} ${w} ${k}${w===1?"":"s"} `}),A(D,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${hn(r)} \xB7 esc to stop`})]}),I>0&&A(D,{dimColor:!0,children:` \u2714 +${I} done`}),$.map(T=>V(D,{color:E(T.status),dimColor:T.status==="done"||T.status==="pending",children:[` ${Dc[T.status]} ${is(T.label).padEnd(x)}`,T.status==="active"&&T.itemsDone!==void 0?` (${T.itemsDone}/${T.items} ${k}${T.items===1?"":"s"})`:T.status!=="pending"?` (${T.items} ${k}${T.items===1?"":"s"})`:"",T.status==="active"?` \u2190 ${S}\u2026`:""]},T.label)),p&&A(D,{color:"yellow",children:` \u26A0 no activity for ${hn(i)} \u2014 press esc to stop if it's wedged`})]})}var Wg=10800*1e3;function sd({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Uh(),[i,c]=W(n),[p,h]=W(null),[k,w]=W({text:"",pos:0}),S=k.text,$=G(l=>{w(a=>{let s=typeof l=="function"?l(a.text):l;return{text:s,pos:s.length}})},[]),I=G(l=>{w(a=>({text:a.text.slice(0,a.pos)+l+a.text.slice(a.pos),pos:a.pos+l.length}))},[]),x=G(()=>{w(l=>{if(l.pos===0)return l;let a=l.text.slice(0,l.pos),s=Oc(a)??a.slice(0,-1);return{text:s+l.text.slice(l.pos),pos:s.length}})},[]),[E,T]=W(!1),[M,H]=W(!1),[J,X]=W(0),[ae,kt]=W(null),[Xt,ws]=W(null),[tt,nt]=W([]),An=ee(!1),nr=ee(!1),[or,ks]=W(!1),jn=ee(0),[fd,En]=W(!1),[md,Nn]=W(!1),[rr,bs]=W(null),[hd,bt]=W(0),ot=ee(0),[Qt,$t]=W(0),[xt,In]=W(null),$s=ee(new Map),gd=ee(0),vt=ee([]),Ce=ee(null);Ce.current===null&&(Ce.current=Fc({cwd:e,profileName:i,allowProdWrites:!1}));let _e=ee({uuid:null,firstPrompt:null,titleFired:!1}),_n=ee(new Map),Ct=ee(!1),ir=ee([]),Ae=ee([]),On=ee(null),[xs,rt]=W(null),sr=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),[vs,Jt]=W(null),[ye,ct]=W(null),[fe,Dt]=W(null),[Cs,ar]=W([]),dt=ee([]),Zt=ee(!1),Re=ee(null),[Ln,oe]=W(null),[Rs,Ps]=W(null),Mn=ee(!1),Un=ee(null),en=ee(null),[we,ut]=W(null),[Wn,tn]=W(null),lr=!!(Le||pe||ge||qe||Me||ye||fe||we||Wn),[Ts,At]=W(0),[Ss,jt]=W(0),[yd,Ds]=W(0),cr=as(()=>{try{let l=ms(e);return l.source==="auto"?`${l.model} (auto)`:l.model}catch{return null}},[e,yd]),{stdout:je}=Fh(),[,wd]=W(0),As=ee(`${je.columns??80}x${je.rows??24}`),Be=G(()=>Math.max(20,(je.columns??80)-1),[je]),u=G(l=>{vt.current.push(l),console.log(Mr(l,Be()))},[Be]),me=G((l,a)=>{jn.current++,kt(l),ws(a??null)},[]),Ve=G(()=>{jn.current++,kt(null),ws(null)},[]),K=G(l=>me(l,_o({kind:"cmd",cmd:l,reason:""})),[me]),js=G((l,a)=>{!a?.silent&&l.note&&u({kind:"note",tone:l.tone,text:l.note}),l.picker&&(nt(l.picker.options.map(s=>({cmd:s.cmd,desc:s.desc}))),Jt(l.picker.title)),l.lead&&me(l.lead.kind==="cmd"?l.lead.cmd:l.lead.text,_o(l.lead))},[u,me]),Et=G((l,a,s="info")=>{l&&u({kind:"note",tone:s,text:l}),a&&me(a.kind==="cmd"?a.cmd:a.text,_o(a))},[u,me]),[nn,dr]=W(null),[kd,Es]=W(!1),Nt=G(l=>{dr(l),Es(!1),u({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),ur=ee(!1),pr=G(async()=>{try{if(ur.current||!xg($g())||te(e)?.mode==="engineer")return;let l=await bg({pkg:gt,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;ur.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${gt} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),Nn(!0),(await jo().finally(()=>Nn(!1))).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),K("/exit"),bs(l.latest)):u({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${Ao}`})}catch{}},[e,o,u,K]),fr=G(l=>{let a=Fe(e,i);return a.ok?!0:(u({kind:"note",tone:"warn",text:a.reason}),en.current=l,K("/login"),!1)},[e,i,u,K]),[Fn,mr]=W(null),on=ee(!0),Hn=ee(0),rn=ee(0);ve(()=>{let l=setInterval(()=>{if(on.current){Hn.current=0,rn.current=0;return}if(!E)try{if(!Gt(zc(e)))return;if(Se(e).status==="current"){on.current=!0,Hn.current=0,rn.current=0,u({kind:"note",tone:"ok",text:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs."}),dr(null),me("write the docs for this repo");return}Hn.current+=1;let a=Hn.current;if((a===4||a%15===0)&&rn.current<3){rn.current+=1;let s=rn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";u({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,u]),ve(()=>{let l=xs??Dn(e);if(!E){qo(0),Vt(`${Vo} ${l}`);return}qo(3);let a=0;Vt(`${Bo[0]} ${l}`);let s=setInterval(()=>{a=(a+1)%Bo.length,Vt(`${Bo[a]} ${l}`)},400);return()=>clearInterval(s)},[E,e,xs]),ve(()=>()=>qo(0),[]);let sn=G(l=>{let a=Tn(e,i,{claudeMissing:fs(t).state==="missing",allowAutoAudit:l,genreUnknown:nr.current});return a?Pn(a):{kind:"idle"}},[e,i,t]);ve(()=>{let l=performance.now(),a=[],s=(y,C)=>{let P=performance.now();try{return C()}finally{let z=Math.round(performance.now()-P);z>=80&&a.push(`${y}: ${z}ms`)}};u({kind:"banner",info:s("banner",()=>jg(e,o,t,i))});let g=fs(t).state==="missing";if(g&&u({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
|
|
309
|
+
${Bh}
|
|
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)){u({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
311
|
+
${td}`}),K(g?"/doctor":"/init");return}g&&K("/doctor");try{let y=xe(e,i),C=wt(y.name);C&&et(C)&&C.refreshToken?zh({profile:y.name,connection:y.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),X(P=>P+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),K("/login")}):(!C||et(C))&&(u({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),C=xe(e,i),P=wt(C.name);y&&P&&!et(P)&&Ki(e,y.authoritativeSourceFiles)&&!Xi(e,i)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),K("/scope"))}catch{}try{let y=s("resolve-genre",()=>sg(e));y.persisted&&y.appType?u({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)&&(nr.current=!0)}catch{}let d=Se(e);try{if(s("reconcile-devhints",()=>po(e)),d.status!=="current"&&!We(e)){let y=fo(e);y.length&&(u({kind:"note",tone:"warn",text:y.join(`
|
|
312
|
+
`)}),Nt(ft()),on.current=!1)}}catch{}try{let y=s("reconcile-feedback",()=>vg(e));y.archived>0&&u({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",()=>Cg(e));y.applied.length>0&&u({kind:"note",tone:"warn",text:Lo(y.applied).join(`
|
|
313
|
+
`)})}catch{}let m=s("ready-decision",()=>sn(!0));m.kind==="autoAudit"?(u({kind:"note",tone:"info",text:m.note}),wn().then(y=>{y.kind==="forward-to-agent"&&y.prompt&&ie(y.prompt,{display:y.display,quietUser:!0})})):m.kind==="recommend"&&js(m.rec);let b=Math.round(performance.now()-l);b>=800&&Pg({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(
|
|
325
|
-
`:"",
|
|
326
|
-
Model: ${
|
|
327
|
-
`)+
|
|
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${m} --fix has the agent fix them in place (or /review${m} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${m} --fix`,reason:""});return}case"structure":{let
|
|
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:d({kind:"note",tone:"error",text:`Unknown command: /${s} \u2014 type /help.`})}},[e,r,i,Yn,d,ke,ie,qn,hr,Is]),zn=V(l=>{let a=(l??D).trim();if($(""),Nn(null),$t(0),a.startsWith("/")&&(Dn.current=!1,Ve(),Xt(null),nt(g=>Ac(g,a))),!a||(ws(!1),Ls(a))||_s(a))return;nr.current.push(a);let s=Ic(a,ks.current);if(a.startsWith("/"))d({kind:"user",text:a}),sn(s);else if(Cg(s)){d({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,Ls,_s,sn,ie]),Os=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let a=jc(l);if(Ec(a)){let s=Nc(++mu.current,a);ks.current.set(s,a),T(s)}else T(a);return}T(l)},[T]),It=Math.max(10,Ee-6),Ms=rs(()=>Yo(h.text,It),[h.text,It]),yr=V(l=>k(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+l))})),[]),Kn=V(l=>k(a=>({...a,pos:Lc(Yo(a.text,It),a.pos,l)})),[It]),an=V(l=>k(a=>({...a,pos:Oc(Yo(a.text,It),a.pos,l)})),[It]),yu=["\x1B[H","\x1B[1~","\x1BOH"],ku=["\x1B[F","\x1B[4~","\x1BOF"],Us=V((l,a)=>a.leftArrow?(yr(-1),!0):a.rightArrow?(yr(1),!0):l&&yu.includes(l)?(an("start"),!0):l&&ku.includes(l)?(an("end"),!0):a.ctrl&&l==="a"?(an("start"),!0):a.ctrl&&l==="e"?(an("end"),!0):!1,[yr,an]);return Lh((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";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${s} run (finishing in-flight ${g}s)\u2026`}),Re.current.abort()}return}Qt.current||(Qt.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Ce.current?.interrupt());return}if(a.return){let s=D.trim();if(!s)return;ut.current.push(s),rr([...ut.current]),$("");return}if(Us(l,a))return;if(a.upArrow){Kn(-1);return}if(a.downArrow){Kn(1);return}if(a.backspace||a.delete){P();return}l&&!a.ctrl&&!a.meta&&Os(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:u,effective:m}=yn(e,s.value??"default");for(let b of g)d({kind:"note",tone:b.startsWith("\u26A0")?"warn":b.startsWith("\u2713")?"ok":"info",text:b});u&&(Ts(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),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(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){Zt(null);return}if(a.leftArrow||a.tab&&a.shift){Zt(s=>s&&{tab:(s.tab-1+Te.length)%Te.length});return}if(a.rightArrow||a.tab){Zt(s=>s&&{tab:(s.tab+1)%Te.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Te.length){Zt({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),!Tr(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 m=yt(s);u=!!m&&!(et(m)&&!m.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"),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:u}=pe;Tt(null),Bn(g,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:g}=ge;at(null),Gn(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,u)=>u===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){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Hr(e,s),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${s.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let g of s)d({kind:"note",tone:"info",text:` ${g}`});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],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"?hr(s.paths[0]):qn(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,Fn.length-1),s.cursor+1)});return}if(a.return){let s=Fn[we.cursor];if(s){ct(null);try{d({kind:"preview",name:Sn(s),text:tu(is(ss(e,s),"utf8"))})}catch(g){d({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(ye){if(a.escape){dt(null);return}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(Math.max(0,Hn.length-1),s.cursor+1)});return}if(a.return){let s=Hn[ye.cursor];if(s){dt(null),ke(s.uuid),_e.current={uuid:s.uuid,firstPrompt:s.firstPrompt,titleFired:!0},rt(s.name),as(s.uuid),vt.current=[];let g=ts(e,s.uuid);for(let u of g)d(u);d({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){dt(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){dt(s=>s&&{...s,query:s.query+l,cursor:0});return}return}if(a.tab&&!D&&ae){$(ae),Ve();return}if(!D&&tt.length>0&&!er&&l&&/^[1-9]$/.test(l)){let s=tt[Number(l)-1];if(s){$(wt(s));return}}if(!D&&(dr||en)&&l==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let s=dr!=null;fc(dr??en).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&&pr(null),u&&!s&&As(!0)});return}if(!Us(l,a)){if(Es){if(a.upArrow){$t(s=>Math.max(0,s-1));return}if(a.downArrow){$t(s=>Math.min(rn.length-1,s+1));return}if(a.tab){$("/"+(rn[Kt]?.name??"")+" "),$t(0);return}if(a.return){let s=rn[Kt];if(s){let g=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(xc(s.usage)&&!g){$("/"+s.name+" "),$t(0);return}zn("/"+s.name+(g?" "+g:""));return}}}else{if(a.upArrow){if(D!==""&&xt===null){Kn(-1);return}let s=nr.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){Kn(1);return}let s=nr.current;if(xt===null)return;let g=xt+1;g>=s.length?(Nn(null),$("")):(Nn(g),$(s[g]??""));return}}if(a.return){zn();return}if(a.backspace||a.delete){P();return}if(a.escape){$(""),$t(0),Ve(),nt([]),Xt(null),Dn.current=!0;return}l&&!a.ctrl&&!a.meta&&Os(l)}}}),ve(()=>{if(S||O)return;let l=ut.current.shift();l!==void 0&&(rr([...ut.current]),zn(l))},[S,O,zn]),B(ne,{flexDirection:"column",width:Ee,children:[mr!==null&&B(ne,{marginTop:1,flexDirection:"column",children:[mr.truncated&&j(A,{dimColor:!0,children:"\u2026"}),j(A,{children:mr.text})]}),S&&(Ln?j(Lg,{p:Ln}):j(Ng,{startTime:ot.current,chars:fu})),!S&&vs?j(Ig,{text:vs}):null,j(ne,{borderStyle:"round",borderColor:js.prod?"yellow":F,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?Ms.map((l,a)=>{let s=h.text.slice(l.start,l.end),g=a===zo(Ms,h.pos),u=Math.min(h.pos,l.end)-l.start;return B(A,{children:[j(A,{color:F,children:a===0?"> ":" "}),g?B(Qo,{children:[s.slice(0,u),j(Gt,{ch:s[u]??" "}),s.slice(u+1)]}):s||" "]},`${a}-${l.start}`)}):B(A,{children:[j(A,{color:F,children:"> "}),ir?j(Gt,{ch:" "}):ae&&!S&&Jo?B(Qo,{children:[j(Gt,{ch:Jo[0],dim:!0}),j(A,{color:"gray",children:Jo.slice(1)})]}):ae&&!S?B(Qo,{children:[j(Gt,{ch:ae[0],dim:!0}),j(A,{color:"gray",children:ae.slice(1)}),j(A,{dimColor:!0,children:" (tab)"})]}):(fr.isSetup||!du)&&!S?B(Qo,{children:[j(Gt,{ch:fr.text[0],dim:!0}),j(A,{color:"gray",children:fr.text.slice(1)})]}):j(Gt,{ch:" "})]})}),xs.length>0&&j(ne,{flexDirection:"column",paddingX:1,children:xs.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(u=>u.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((u,m)=>{let b=a+m;return B(A,{color:b===fe.cursor?F:void 0,children:[b===fe.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Ee-34)),j(A,{color:"gray",children:ko(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?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?" ":" ",u=`${a+1}.`.padEnd(3);return B(A,{color:s?F:void 0,bold:l.kind==="category"&&!s,children:[s?"\u276F ":" ",`${g}${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?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:`Preview article${we.query?` \u2014 filter: ${we.query}`:" (type to filter)"}`}),Fn.length===0?j(A,{color:"gray",children:"no articles match"}):Fn.map((l,a)=>B(A,{color:a===we.cursor?F:void 0,children:[a===we.cursor?"\u276F ":" ",l]},l)),j(A,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):ye?B(ne,{flexDirection:"column",paddingX:1,children:[j(A,{color:F,bold:!0,children:`Resume session${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),Hn.length===0?j(A,{color:"gray",children:"no sessions match"}):Hn.map((l,a)=>B(A,{color:a===ye.cursor?F:void 0,children:[a===ye.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),j(A,{color:a===ye.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"})]}):Es?B(ne,{flexDirection:"column",children:[rn.map((l,a)=>B(A,{color:a===Kt?F:void 0,children:[a===Kt?"\u276F ":" ",l.usage.padEnd(22)," ",j(A,{color:a===Kt?F:"gray",children:l.name==="model"&&sr?`${l.desc} (currently ${sr})`: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:[$s?j(A,{color:F,children:$s}):null,tt.map((l,a)=>{let s=wt(l),g=s.slice(0,Math.max(20,Ee-5)),u=Ee-g.length-7,m=u>=12?(Dc(l)??bc(s)).slice(0,u):"";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:[js.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${sr??"model n/a"}${t.kind==="api"?Ps>0?` \xB7 ${he(Ps)}`:"":Rs>0?` \xB7 ${Qe(Rs)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}U();import{jsx as Wg}from"react/jsx-runtime";async function ru(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(ou,{cwd:e,auth:r,profileName:n,version:o}));await i(),process.stdout.write(`
|
|
343
|
-
`),process.exit(0)}U();import{writeCrashLog as
|
|
344
|
-
`+
|
|
315
|
+
cwd: ${e}`}),pr()},[]),ve(()=>{let l=setInterval(()=>{pr()},Wg);return()=>clearInterval(l)},[pr]),ve(()=>{if(E||or||An.current||ae!==null||tt.length>0||S!==""||nn!==null||Ae.current.length>0||On.current||lr)return;let l=sn(!1);l.kind==="recommend"&&(l.rec.lead||l.rec.picker)&&js(l.rec,{silent:!0})},[E,ae,tt,S,nn,lr,J,sn,or]),ve(()=>{let l=null,a=null,s=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${je.columns??80}x${je.rows??24}`;g!==As.current&&(As.current=g,wd(d=>d+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Ia(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),Ns=as(()=>Eg(e,i),[e,i,J]),hr=(()=>{if(md)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(rr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${rr?` v${rr}`:""}\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(nn)return kd?{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=ls(e,(l.docsDir??id).replace(/\/+$/,"")),s=(()=>{try{return Gt(a)&&Hh(a).length>0}catch{return!1}})();try{let g=xe(e,i),d=wt(g.name);if(!(!!d&&!(et(d)&&!d.refreshToken)))return{text:`Sign in with /login (profile "${g.name}")\u2026`,isSetup:!0};if(!g.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!g.project.workspaceId&&!s)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return s?{text:Ng,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),an=xc(S),Is=an.length>0&&!E,gr=p!==null?Uc(p,8,Ee):null,qn=ye?ye.paths.filter(l=>!ye.query||l.toLowerCase().includes(ye.query.toLowerCase())).slice(0,8):[],Bn=we?we.sessions.filter(l=>{let a=we.query.toLowerCase();return!a||l.name.toLowerCase().includes(a)||l.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],ke=G((l,a)=>{Ce.current?.close(),Ce.current=Fc({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]),_s=G((l,a,s)=>{if(Ig.test(l))try{let g=xe(e,i),d=typeof a.project_id=="string"&&a.project_id||g.project.projectId,m=Fo(a,s),b=[],y=Ho(s);l.endsWith("publish_article")&&y&&b.push(`Live: ${y}`),m&&d&&b.push(`Preview: ${Wo(g.connection.portalUrl,d,m,g.project.languageCode??"en")}`),b.length>0&&u({kind:"link",lines:b})}catch{}},[e,i,u]),ie=G(async(l,a)=>{En(!0),An.current=!1,Ve(),nt([]),Jt(null),dr(null);let s=jn.current;a?.quietUser||u({kind:"user",text:a?.echoDisplay&&a.display?a.display:l});let g=_e.current;g.firstPrompt||(g.firstPrompt=a?.display??l),ot.current=Date.now(),bt(0),T(!0),_n.current.clear();let d="",m=!1,b=!1,y="",C={num:0,closed:!1,cueSeen:!1},P=null,z=()=>{P||(P=setTimeout(()=>{P=null,h(y.length>0?y:null)},60))},q=()=>{P&&clearTimeout(P),P=null,h(null)},L=()=>{if(y.trim()){let R=os(y.trimEnd(),C);u({kind:"assistant",text:R})}y="",q()};try{for await(let R of Ce.current.send(l))if(R.type==="session"){if(!g.uuid){g.uuid=R.sessionId;let j=new Date().toISOString(),B=sr.current,Z=B??eg(g.firstPrompt??"session");tg({uuid:R.sessionId,name:Z,renamed:!!B,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:j,updatedAt:j}),rt(Z),sr.current=null}}else if(R.type==="text"){y+=R.delta,d+=R.delta;let j=Wc(y);if(j>0){let B=y.slice(0,j).trimEnd();B&&u({kind:"assistant",text:os(B,C)}),y=y.slice(j)}z(),bt(B=>B+R.delta.length)}else if(R.type==="tool"){m=!0;let j=Mo(R.name,R.input);j&&(L(),u({kind:"tool",title:j.title,sep:j.sep,arg:j.arg}),_n.current.set(R.id,{name:R.name,input:R.input}))}else if(R.type==="article_diff"){let j=mt(R.oldContent,R.newContent,Be());j&&(L(),u({kind:"diff",added:j.added,removed:j.removed,lines:j.lines,hidden:j.hidden}))}else if(R.type==="tool_result"){R.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(R.output)&&(Mn.current=!0);let j=_n.current.get(R.id);if(j){_n.current.delete(R.id),L();let B=Uo(R.output,4,R.isError?void 0:j.name,j.input);u({kind:"tool-result",lines:B.lines,hidden:B.hidden,isError:R.isError}),R.isError||_s(j.name,j.input,R.output)}}else if(R.type==="result"){if(L(),At(j=>j+R.outputTokens),jt(j=>j+R.costUsd),u({kind:"done",seconds:Math.round((Date.now()-ot.current)/1e3),tokens:R.outputTokens,costUsd:R.costUsd,ok:R.ok}),!b&&!m&&!d.trim()&&!Zt.current&&u({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),R.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(d))try{let j=Kc(e);if(Gt(j)){let B=Qo(j,"utf8").trim();B&&(mr(B),u({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(R.ok&&C.cueSeen)ks(!0),nt([]);else{let j=R.ok?Pc(d,Go.map(B=>B.name)):[];if(j.length>0)K(j[0]);else if(R.ok&&d.trim()){let B=sn(!1);B.kind==="recommend"&&(B.rec.lead||B.rec.picker)||ig(l,d,e).then(Z=>{Z&&jn.current===s&&me(Z)}).catch(()=>{})}}if(g.uuid&&(cs(g.uuid),!g.titleFired)){g.titleFired=!0;let j=g.uuid,B=g.firstPrompt;B&&Hc(B,e).then(Z=>{Z&&(Zh(j,Z),rt(Z))}).catch(()=>{})}}else R.type==="error"&&(L(),b=!0,R.kind==="auth"&&(Mn.current=!0),u({kind:"note",text:`agent error: ${R.message}`,tone:"error"}))}finally{T(!1),q(),X(R=>R+1),_e.current.uuid&&wc(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")),Zt.current&&(Zt.current=!1,dt.current.length>0&&(u({kind:"note",tone:"info",text:`(${dt.current.length} queued message(s) discarded)`}),dt.current=[],ar([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,_s,Be,me,K,Ve,sn]),Vn=G(async l=>{let a=ds(l),s=Zo(e,"standard");ot.current=Date.now(),bt(0),T(!0);let g=new AbortController;Re.current=g,oe({verb:"Publishing",total:a.length,done:0,active:[],rows:Sn(a),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${a.length} partition${a.length===1?"":"s"} (\u2264${gn} agents at once) on ${s.model}\u2026 (esc to stop)`});try{for await(let d of Jo({cwd:e,partitions:a,promptFor:m=>ko(m.paths),concurrency:gn,profileName:i,allowProdWrites:Ct.current,model:s.model,signal:g.signal}))if(d.type==="partition_status")d.status==="running"?oe(m=>m&&{...m,active:[...m.active,d.label],rows:He(m.rows,d.label,"active"),lastAt:Date.now()}):oe(m=>m&&{...m,active:m.active.filter(b=>b!==d.label),done:m.done+1,rows:He(m.rows,d.label,d.status==="done"?"done":"failed"),lastAt:Date.now()});else if(d.type==="partition_event")oe(m=>{if(!m)return m;let b={...m,lastAt:Date.now()};return d.event.type==="tool"?b.tools=m.tools+1:d.event.type==="text"&&(b.chars=m.chars+d.event.delta.length),b});else if(d.type==="run_done"){jt(C=>C+d.totalCostUsd),At(C=>C+d.results.reduce((P,z)=>P+z.outputTokens,0));let m=d.aborted?"Stopped. ":"",b=t.kind==="api"?"api":"subscription";u({kind:"note",tone:d.aborted?"warn":d.ok?"ok":"warn",text:m+qr(d.results,a,b).join(`
|
|
316
|
+
`)});let y=Hr(e,i);if(y&&u({kind:"note",tone:"info",text:y}),!d.aborted){try{let C=await Qc({cwd:e,profileName:i}),P=Jc(C);P?u({kind:"note",tone:"info",text:P}):C.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${C.skipped}`})}catch(C){u({kind:"note",tone:"warn",text:`Order sync failed: ${C.message}`})}try{let C=ed(await Zc({cwd:e,profileName:i}));C&&u({kind:"note",tone:"info",text:C})}catch(C){u({kind:"note",tone:"warn",text:`Related-articles sync failed: ${C.message}`})}}}}catch(d){u({kind:"note",tone:"error",text:`Publish run failed: ${d.message}`})}finally{Re.current=null,oe(null),T(!1),X(d=>d+1)}},[e,i,u,t]),yr=G(async l=>{await ie(Fr(l),{display:`/publish ${l}`,quietUser:!0});try{let a=await bo(e,i,l.replace(/\\/g,"/"));a.length>0&&(Jt(`Related articles not yet published (${a.length}):`),nt([`/publish --related ${l}`,...a.map(s=>`/publish ${s}`)]))}catch{}},[e,i,ie]),wr=G(l=>{let a=wt(l);if(!a||et(a)&&!a.refreshToken)return null;let s={...zt(a.idToken)??{},...zt(a.accessToken)??{}};return s.email??s.preferred_username??"signed in"},[]),kr=G((l,a)=>{if(a){let s=te(e);s&&(s.defaultProfile=l,qc(s,e))}c(l),ke(void 0,l),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),wr(l)||(u({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 sign in with /login.`}),K("/login")),X(s=>s+1)},[e,u,ke,wr,K]),Gn=G((l,a,s)=>{eo(e,l,a,s.id,s.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${s.name??s.id}" (agent restarted).`}),ke(),Bc(e,l)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({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:"}),u({kind:"note",tone:"info",text:Ft(Wt(e)).join(`
|
|
317
|
+
`)}),Nt(ft()),on.current=Se(e).status==="current"||We(e),u({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,u,ke,Nt]),Yn=G(async l=>{let a;try{a=await un(e,l)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),K("/workspace");return}if(a.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let s=a.workspaces.filter(d=>(d.workspace_type??"").toLowerCase()!=="apidocumentation"),g=s.length>0?s:a.workspaces;if(g.length===1){let d=g[0],m=a.workspaces.length-g.length;u({kind:"note",tone:"ok",text:`Selected the "${d.name??d.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),Gn(a.profile,a.projectId,d);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),K("/workspace")},[e,u,Gn,K]),zn=G((l,a)=>{to(e,l,a.id,a.name),u({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),ke(),Yn(l)},[e,u,ke,Yn]),Os=G(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),g=s.find(d=>d.id===a.project.projectId);g?.name&&Rg(e,a.name,{projectName:g.name})}catch{}await Yn(a.name);return}try{let{projects:s}=await ze(e,a.name);if(s.length===1){let g=s[0];u({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),zn(a.name,{id:g.id,name:g.name});return}if(s.length>1){let g=s.map(d=>({id:d.id,name:d.name??d.id,sub:d.sub_domain}));u({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),at({cursor:0,current:-1,rows:g,profile:a.name,environment:a.connection.name});return}}catch{}u({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),K("/project")}},[e,u,Yn,zn,K]),Kn=G(()=>{let l=Ae.current[0];if(!l)return;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let s of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${s}`});l.overwritesLocalChanges&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let a=mt(l.oldContent,l.newContent,Be());u(a?{kind:"diff",added:a.added,removed:a.removed,lines:a.lines,hidden:a.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,Be]),Ls=G(l=>{if(Ae.current.length===0)return!1;let a=l.trim().toLowerCase();if(a==="y"||a==="yes"){let s=Ae.current.shift();try{lg({cwd:e,profileName:i},s),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${s.path} (sync base advanced).`}),Ae.current.length===0&&K("/pull")}catch(g){u({kind:"note",tone:"error",text:`Pull failed: ${g.message}`})}}else if(a==="n"||a==="no"){let s=Ae.current.shift();u({kind:"note",tone:"info",text:`Skipped ${s.path}.`})}else{let s=Ae.current.length;return Ae.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${s} article(s) left untouched).`}),!0}return Kn(),!0},[e,i,Kn,u]),Ms=G(l=>{let a=On.current;if(!a)return!1;if(On.current=null,Ve(),l.trim()!==a.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:s,failed:g}=Li(e,a.targets);u({kind:"note",tone:g.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 d of g)u({kind:"note",tone:"error",text:` \u2717 ${d.path}: ${d.error}`});return a.hadDevhints&&(u({kind:"note",tone:"warn",text:mo().join(`
|
|
318
|
+
`)}),Nt(Sr())),u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
319
|
+
${td}`}),K("/init"),En(!1),!0},[e,u,Nt,Ve,K]),ln=G(async l=>{let a=l.slice(1).trim().split(/\s+/),s=(a[0]??"").toLowerCase(),g=a.slice(1);if(En(!0),Co(g)&&["write","check","review","reorder"].includes(s)){let d=kn(e,i);if(d.length===0){u({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let m=b=>s==="write"?`/write ${el(g,b).join(" ")}`.trim():`/${s} ${[b,...g.filter(y=>y!=="--scope")].join(" ")}`.trim();if(d.length===1){ln(m(d[0].token));return}lt({cursor:0,rows:d,run:b=>{ln(m(b))}});return}if(Je(s,g)){let d=kn(e,i);if(d.length>1){let m=g.filter(P=>P.startsWith("--")).join(" "),b=P=>`/${s}${P?` ${s==="write"?`--scope ${P}`:P}`:""}${m?` ${m}`:""} ${P?"":"--all"}`.replace(/\s+/g," ").trim(),y=d.reduce((P,z)=>P+z.count,0),C={token:"",label:s==="review"?`Everything \u2014 all ${y} articles + structure (IA) review`:s==="reorder"?`Everything \u2014 reorder all ${d.length} categories`:`Everything \u2014 rewrite all ${y} planned articles`,count:y};lt({cursor:0,rows:[C,...d],run:P=>{ln(b(P))}});return}}switch(s){case"help":tn({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"),u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let d;try{d=xe(e,i)}catch(m){u({kind:"note",tone:"error",text:m.message});return}u({kind:"note",tone:"info",text:`Profile "${d.name}" \u2192 ${d.connection.name} (${d.connection.apiUrl})${d.production?" \u26A0 PRODUCTION":""}`}),H(!0);try{let m=await Vh(d.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},y=>u({kind:"note",tone:"info",text:y})),b=Gh(d.name,m);if(Yh(b),await vr(b,d.name,y=>u({kind:"note",tone:"info",text:y})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${d.name}" as ${ro(b)}`}),await Os(i),en.current){let y=en.current;en.current=null;let C=Fe(e,i);C.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${y}.`}),K(y)):(u({kind:"note",tone:"warn",text:`${C.reason} (then ${y}.)`}),K("/login"),en.current=y)}else Un.current&&(me(Un.current,"\u21E5 tab to re-send your last prompt\u2026"),Un.current=null)}catch(m){u({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{H(!1),X(m=>m+1)}return}case"allow-prod":{let d=!1;try{d=xe(e,i).production}catch{}if(!d){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Ct.current=!0,ke(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let d=ki(g.join(" ")),m=_e.current.uuid;if(!m){if(!d){u({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}sr.current=d,rt(d),Vt(`${Vo} ${d}`),u({kind:"note",tone:"ok",text:`Session will be named "${d}" once it starts.`});return}if(!d){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let b=_e.current.firstPrompt??"";Hc(b,e).then(y=>{y?(me(`/rename ${y}`),u({kind:"note",tone:"info",text:`Suggestion: "${y}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}rg(m,d),rt(d),Vt(`${Vo} ${d}`),u({kind:"note",tone:"ok",text:`Session renamed to "${d}".`});return}case"profile":{let d=g[0],m=te(e);if(!d){let b=Object.entries(m?.profiles??{});if(b.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let y=b.map(([z,q])=>({name:z,env:q.connection?.environment??"custom",prod:q.production===!0,who:wr(z)})),C=i??m?.defaultProfile,P=Math.max(0,y.findIndex(z=>z.name===C));Rt({cursor:P,current:P,rows:y});return}if(d==="add"){let b=bi(e,g[1],g[2]);if(b){u({kind:"note",tone:"error",text:b});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),kr(g[1],!1);return}if(!m?.profiles?.[d]){u({kind:"note",tone:"error",text:`Unknown profile "${d}". Create it: /profile add ${d} <environment>`});return}kr(d,!0);return}case"doctor":await $n(g,{cwd:e,version:o});return;case"genre":{await Io(g,{cwd:e});try{nr.current=!(te(e)?.appType??ag(e))}catch{}X(d=>d+1);return}case"roadmap":{if(g[0]?.toLowerCase()==="done"){let d=Bi(e,g.slice(1).join(" ").trim());u({kind:"note",tone:d.ok?"ok":"warn",text:d.line}),X(m=>m+1);return}u({kind:"note",tone:"info",text:qi(e).join(`
|
|
320
|
+
`)});return}case"mcp":await yo(g);return;case"init":{if(te(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let d=mg().map(m=>({name:m,apiUrl:hg(m).apiUrl}));Pt({cursor:0,rows:d});return}case"resume":{let d=g.join(" ").trim(),m=og(e).filter(C=>C.uuid!==_e.current.uuid);if(!d){if(!m.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}ut({query:"",cursor:0,sessions:m});return}let b=ng(e,d);if(!b){u({kind:"note",tone:"error",text:`No session matches "${d}".`});return}ke(b.uuid),_e.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},rt(b.name),cs(b.uuid),vt.current=[];let y=rs(e,b.uuid);for(let C of y)u(C);u({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 d=g.join(" ").trim(),m;try{m=await un(e,i)}catch(y){u({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!d){let y=m.workspaces.map(P=>({id:P.id,name:P.name??P.id,type:P.workspace_type}));if(y.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let C=Math.max(0,y.findIndex(P=>P.id===m.current));Tt({cursor:C,current:C,rows:y,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let b=$r(m.workspaces,d);if(!b){u({kind:"note",tone:"error",text:`No workspace matches "${d}".`});return}Gn(m.profile,m.projectId,b);return}case"project":{let d=g.join(" ").trim(),m;try{m=await ze(e,i)}catch(y){u({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!d){let y=m.projects.map(P=>({id:P.id,name:P.name??P.id,sub:P.sub_domain}));if(y.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let C=y.findIndex(P=>P.id===m.current);at({cursor:Math.max(0,C),current:C,rows:y,profile:m.profile,environment:m.environment});return}let b=xr(m.projects,d);if(!b){u({kind:"note",tone:"error",text:`No project matches "${d}". Available: ${m.projects.map(y=>y.name??y.id).join(", ")}`});return}zn(m.profile,b);return}case"logout":{let d;try{d=xe(e,i).name}catch(b){u({kind:"note",tone:"error",text:b.message});return}let m=Qh(d);Jh(e,d),ke(),X(b=>b+1),u({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${d}" and cleared its project/workspace selection.`:`Profile "${d}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),K("/login");return}case"publish":{if(!fr(l.trim()))return;if(g[0]==="--related"&&g[1]){let m=await bo(e,i,g[1].replace(/\\/g,"/"));if(m.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Vn(m);return}if(g[0]&&g[0]!=="--all"){await yr(g[0]);return}let d=g[0]==="--all";u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Vc({cwd:e,profileName:i}),b=yn(m.entries),y=wo(m.entries);if(y>0&&u({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){u({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 C=m.counts["unknown-base"]??0;C>0&&u({kind:"note",tone:"info",text:`(${C} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Ps("Reconciling structure on Document360 (order + related articles)\u2026");try{let P=await Qc({cwd:e,profileName:i}),z=ed(await Zc({cwd:e,profileName:i})),q=Jc(P);q?u({kind:"note",tone:"info",text:q}):P.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${P.skipped}`}),z&&u({kind:"note",tone:"info",text:z}),u({kind:"note",tone:"ok",text:q||z?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(q||z)&&K("/structure")}catch(P){u({kind:"note",tone:"warn",text:`Structure sync failed: ${P.message}`})}finally{Ps(null)}return}if(d){await Vn(b.map(C=>C.path));return}St({cursor:0,rows:Fa(b)})}catch(m){u({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let d=g.join(" ").trim();if(!d){let b=[];try{b=Object.keys(Bc(e,xe(e,i).name)?.articles??{})}catch{}if(b.length===0){u({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 m=qh(d)?d:ls(e,d);if(Gt(m)){try{u({kind:"preview",name:Dn(m),text:od(Qo(m,"utf8"))})}catch(b){u({kind:"note",tone:"error",text:`Could not read ${m}: ${b.message}`})}return}if(_g.test(d)){try{let b=xe(e,i),y={profile:b.name,connection:b.connection},C=b.project.projectId??Kh(y),P=await Xh(y,C,d);u({kind:"preview",name:P.title??d,text:P.content??"*(article has no content)*"})}catch(b){u({kind:"note",tone:"error",text:`Could not fetch article: ${b.message}`})}return}u({kind:"note",tone:"error",text:`"${d}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let d=g[0]?.trim();if(!d){let C=Po(ms(e));st({cursor:C,current:C});return}let{lines:m,changed:b,effective:y}=bn(e,d);for(let C of m)u({kind:"note",tone:C.startsWith("\u26A0")?"warn":C.startsWith("\u2713")?"ok":"info",text:C});b&&(Ds(C=>C+1),Ce.current?.setModel(y));return}case"convert":{if(!te(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:d,run:m}=Xr(g),b=wg(e,i);if(b.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let y=Qr(b,d);if(y.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${d}". (${b.length} are tracked overall.)`});return}let C=ds(y),P=3,z=`/convert${d?` --scope ${d}`:""} --run`,q=Zo(e,"light");if(!m){let R=Yc({files:Jr(e,y),op:"convert",model:q.model}),j=d?`Scope: ${d} (${y.length} of ${b.length} tracked)
|
|
321
|
+
`:"",B=`
|
|
322
|
+
Model: ${q.model}${q.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:j+ei(C,R,P).join(`
|
|
323
|
+
`)+B}),K(z);return}ot.current=Date.now(),bt(0),T(!0);let L=new AbortController;Re.current=L,oe({verb:"Converting",total:C.length,done:0,active:[],rows:Sn(C),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${y.length} articles across ${C.length} partitions (\u2264${P} agents at once) on ${q.model}\u2026 (esc to stop)`});try{for await(let R of Jo({cwd:e,partitions:C,promptFor:Zr,concurrency:P,profileName:i,allowProdWrites:Ct.current,model:q.model,signal:L.signal}))if(R.type==="partition_status")R.status==="running"?oe(j=>j&&{...j,active:[...j.active,R.label],rows:He(j.rows,R.label,"active"),lastAt:Date.now()}):oe(j=>j&&{...j,active:j.active.filter(B=>B!==R.label),done:j.done+1,rows:He(j.rows,R.label,R.status==="done"?"done":"failed"),lastAt:Date.now()});else if(R.type==="partition_event")oe(j=>{if(!j)return j;let B={...j,lastAt:Date.now()};return R.event.type==="tool"?B.tools=j.tools+1:R.event.type==="text"&&(B.chars=j.chars+R.event.delta.length),B});else if(R.type==="run_done"){jt(Z=>Z+R.totalCostUsd),At(Z=>Z+R.results.reduce((_t,Ot)=>_t+Ot.outputTokens,0));let j=R.aborted?"Stopped. ":"",B=t.kind==="api"?"api":"subscription";u({kind:"note",tone:R.aborted?"warn":R.ok?"ok":"warn",text:j+ti(R.results,C,B).join(`
|
|
324
|
+
`)})}}catch(R){u({kind:"note",tone:"error",text:`Convert run failed: ${R.message}`})}finally{Re.current=null,oe(null),T(!1),X(R=>R+1)}return}case"write":{if(!te(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=kg(e);if(d.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:b,preview:y,concurrency:C,rewrite:P}=ri(g),{docsDir:z,targets:q,reason:L,rewriting:R}=ui(e,d,{scope:m,path:b,rewrite:P});if(q.length===0){u({kind:"note",tone:"warn",text:L??"Nothing to write."});return}R&&u({kind:"note",tone:"warn",text:`--rewrite: regenerating ${q.length} already-written article${q.length===1?"":"s"} (overwrites them; git has your baseline).`});let j=ds(q),B=oi(C),Z=Zo(e,"standard"),_t=!!b;if(y&&!_t){let Y=Yc({files:si(e,d,q),op:"write",model:Z.model}),re=m?`Scope: ${m} (${q.length} pending)
|
|
325
|
+
`:"",ue=`
|
|
326
|
+
Model: ${Z.model}${Z.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:re+li(j,Y,B).join(`
|
|
327
|
+
`)+ue}),K(`/write${m?` --scope ${m}`:""}`);return}ot.current=Date.now(),bt(0),T(!0);let Ot=new AbortController;Re.current=Ot,oe({verb:"Writing",total:j.length,done:0,active:[],rows:Sn(j),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${q.length} article${q.length===1?"":"s"} across ${j.length} partition${j.length===1?"":"s"} (\u2264${B} agents at once) on ${Z.model}${Z.forced?" (forced)":""}\u2026 (esc to stop)`});let Jn=new Set;try{for await(let Y of Jo({cwd:e,partitions:j,promptFor:re=>ai(re,z,{rewrite:R||_t}),concurrency:B,profileName:i,allowProdWrites:Ct.current,model:Z.model,signal:Ot.signal}))if(Y.type==="partition_status")Y.status==="running"?oe(re=>re&&{...re,active:[...re.active,Y.label],rows:He(re.rows,Y.label,"active"),lastAt:Date.now()}):oe(re=>re&&{...re,active:re.active.filter(ue=>ue!==Y.label),done:re.done+1,rows:He(re.rows,Y.label,Y.status==="done"?"done":"failed"),lastAt:Date.now()});else if(Y.type==="partition_event"){let re=null;if(Y.event.type==="tool"){let ue=Sc(Y.event.name,Y.event.input,j[Y.index]?.paths??[]);ue&&!Jn.has(ue)&&(Jn.add(ue),re=Y.label)}oe(ue=>{if(!ue)return ue;let Ne={...ue,lastAt:Date.now()};return Y.event.type==="tool"?Ne.tools=ue.tools+1:Y.event.type==="text"&&(Ne.chars=ue.chars+Y.event.delta.length),re&&(Ne.rows=Tc(Ne.rows,re)),Ne})}else if(Y.type==="run_done"){jt(Ge=>Ge+Y.totalCostUsd),At(Ge=>Ge+Y.results.reduce((Ue,xd)=>Ue+xd.outputTokens,0));let re=Y.aborted?"Stopped. ":"",ue=t.kind==="api"?"api":"subscription";if(u({kind:"note",tone:Y.aborted?"warn":Y.ok?"ok":"warn",text:re+ci(Y.results,j,ue).join(`
|
|
328
|
+
`)}),!Y.aborted&&Y.ok)try{let Ge=(Jn.size>0?[...Jn]:q).map(Ue=>`${z}/${Ue}`);us(e,Ge,{writtenCap:ps})}catch{}let Ne=Y.aborted?null:di(e,z,q);if(Ne&&u({kind:"note",tone:"warn",text:Ne}),!Y.aborted&&Y.ok){let Ge=m??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(Y){u({kind:"note",tone:"error",text:`Write run failed: ${Y.message}`})}finally{Re.current=null,oe(null),T(!1),X(Y=>Y+1)}return}case"draft":{if(!te(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:d,looseDocs:m}=pi(e);if(d.length===0&&m===0){u({kind:"note",tone:"info",text:mi});return}let b=g.join(" ").trim();if(!b&&d.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
329
|
+
${d.map(P=>` \u2022 ${P.name} (${P.docCount} doc${P.docCount===1?"":"s"})`).join(`
|
|
330
|
+
`)}`}),nt(d.map(P=>`/draft ${P.name}`));return}let y="",C;if(b){let P=fi(d,b);P?y=P:C=b}else y=d[0]?.name??"";await ie(Ro(y,C),{display:b?`/draft ${b}`:"/draft",quietUser:!0});return}case"pull":{if(!fr(l.trim()))return;let d=g.find(m=>m.startsWith("--"));try{if(d==="--status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let y=Date.now(),C=await Vc({cwd:e,profileName:i});u({kind:"note",tone:"info",text:xo(C,Date.now()-y).join(`
|
|
331
|
+
`)});return}if(d==="--baseline"){let y=g.find(q=>!q.startsWith("--")),C=y?y.replace(/\\/g,"/"):void 0;u({kind:"note",tone:"info",text:C?`Setting the sync baseline for ${C}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let P=await ug({cwd:e,profileName:i,relPaths:C?[C]:void 0}),z=C?{rebaselined:[],skipped:[]}:await pg({cwd:e,profileName:i});if(P.baselined.length===0&&P.skipped.length===0&&z.rebaselined.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}P.baselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Baselined ${P.baselined.length} article${P.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),z.rebaselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${z.rebaselined.length} article${z.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),P.skipped.length>0&&u({kind:"note",tone:"warn",text:`${P.skipped.length} skipped:
|
|
332
|
+
${P.skipped.map(q=>` - ${q.path} (${q.reason})`).join(`
|
|
333
|
+
`)}`}),X(q=>q+1);return}if(d==="--compare"){u({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let y=await cg({cwd:e,profileName:i}),C=y.onlyInLegacy.length===0&&y.onlyInManifest.length===0&&y.mappedMissingFromManifest.length===0,P=[`Legacy listing: ${y.legacyCount} \xB7 Manifest: ${y.manifestCount} \xB7 in both: ${y.inBoth}`];C?P.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(y.mappedMissingFromManifest.length&&P.push(`\u2717 ${y.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${y.mappedMissingFromManifest.slice(0,5).join(", ")}`),y.onlyInLegacy.length&&P.push(`\u26A0 ${y.onlyInLegacy.length} only in the legacy listing: ${y.onlyInLegacy.slice(0,5).join(", ")}`),y.onlyInManifest.length&&P.push(`\u26A0 ${y.onlyInManifest.length} only in the manifest: ${y.onlyInManifest.slice(0,5).join(", ")}`),P.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),u({kind:"note",tone:C?"ok":"warn",text:P.join(`
|
|
334
|
+
`)});return}if(d){u({kind:"note",tone:"error",text:`Unknown option: ${d} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=g[0];if(m){let y=await dg({cwd:e,profileName:i,relPath:m.replace(/\\/g,"/")});Ae.current=[y],Kn();return}u({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let b=await Yr({cwd:e,profileName:i});for(let y of zr(b))u({kind:"note",tone:y.tone,text:y.text});X(y=>y+1)}catch(m){u({kind:"note",tone:"error",text:`Pull failed: ${m.message}`})}return}case"scope":{if(!te(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=fg(e);if(d.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Dt({cursor:0,rows:d.map(m=>({...m,checked:m.recommended}))});return}case"audit":{if(g[0]==="--auto"){let m=te(e);if(!m){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=g[1]!=="off";qc({...m,autoAudit:b},e),u({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 d=await wn();d.kind==="forward-to-agent"&&d.prompt&&await ie(d.prompt,{display:d.display,quietUser:!0});return}case"check":{let d=g.find(y=>!y.startsWith("--")),m=d?` ${d}`:"",b=Gc({cwd:e,scope:d});if(g.includes("--fix")){if(b.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}u({kind:"note",tone:"info",text:`Fixing ${b.length} doc issue${b.length===1?"":"s"}\u2026`});let y=Xc(e,d);await ie(Ui(b),{display:`/check${m} --fix`,quietUser:!0});try{us(e,y,{reviewedCap:ps})}catch{}let C=Gc({cwd:e,scope:d});u({kind:"note",tone:C.length===0?"ok":"warn",text:C.length===0?"\u2713 Doc-checker: all issues resolved.":No(C).join(`
|
|
335
|
+
`)}),Et(C.length===0?`Deterministic issues fixed. Next: /review${m} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${m} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${m} --fix`,reason:""});return}u({kind:"note",tone:b.length===0?"ok":"warn",text:No(b).join(`
|
|
336
|
+
`)}),b.length>0&&Et(`Found ${b.length} doc issue${b.length===1?"":"s"} above. /check${m} --fix has the agent fix them in place (or /review${m} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${m} --fix`,reason:""});return}case"structure":{let d=Rn(e,i);if(d.length===0){u({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}u({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...d].join(`
|
|
337
|
+
`)});return}case"reorder":{let d=Fi(e,g);if(!d){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ie(d.prompt,{display:d.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 d=Wi(e,g);if(!d){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=g.includes("--fix"),b=g.find(C=>!C.startsWith("--")),y=m?Xc(e,b):[];if(await ie(d.prompt,{display:d.display,quietUser:!0}),m)try{us(e,y,{reviewedCap:ps})}catch{}if(m)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 C=g.filter(P=>P!=="--fix").join(" ");Et(`The review listed issues above. /review${C?` ${C}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${C?` ${C}`:""} --fix`,reason:""})}return}case"capture-setup":{let d=await xn();d.kind==="forward-to-agent"&&d.prompt&&await ie(d.prompt,{display:d.display,quietUser:!0});let m=Pi(e);m&&u({kind:"note",tone:"info",text:m.join(`
|
|
338
|
+
`)});return}case"devhints":{if(!te(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:Ft(Wt(e)).join(`
|
|
339
|
+
`)}),Nt(ft()),on.current=Se(e).status==="current"||We(e);return}case"inbox":{if(!te(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Ti(e)===0){u({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(Si(),{display:"/inbox",quietUser:!0});return}case"feedback":{let d=Kc(e),m="";try{m=Gt(d)?Qo(d,"utf8"):""}catch{m=""}if(!/^## /m.test(m)){u({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 ns(m.trim());u({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 ${d} and copy it manually.`}),b&&mr(null);return}case"document":{if(!te(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:d,what:m}=gi(g);if(!m&&hi(e)===0){u({kind:"note",tone:"info",text:wi});return}let b=`/document${m?` ${m}`:""}${d?" --publish":""}`;await ie(yi(m,d),{display:b,quietUser:!0});return}case"catch-up":{if(!te(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!fr(l.trim()))return;let{publish:d}=Ai(g);u({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let m=await Ei({cwd:e,profileName:i});for(let y of Ni(m))u({kind:"note",tone:y.startsWith("\u2713")?"ok":y.startsWith("\u2139")?"info":"warn",text:y});let b=Cn(vn(e));u({kind:"note",tone:"info",text:b?`Catching up on ${b}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ie(ji({publish:d}),{display:`/catch-up${d?" --publish":""}`,quietUser:!0});return}case"update":{ur.current=!0,u({kind:"note",tone:"info",text:`Updating ${gt}\u2026 (don\u2019t close this window)`}),Nn(!0),(await jo().finally(()=>Nn(!1))).ok?(u({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),K("/exit"),bs("")):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Ao}`});return}case"screenshot":{let d=vi(g);if(d.mode==="list"){if(!te(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:Ri(Ci(e,d.scope),d.scope).join(`
|
|
340
|
+
`)});return}if(d.mode==="single"){let L=await So(g);L.kind==="forward-to-agent"&&L.prompt&&await ie(L.prompt,{display:L.display,quietUser:!0});return}if(!te(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=d.mode==="scope"?d.scope:void 0,b=yg(e,{scope:m}).map(L=>L.id);if(b.length===0){u({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let y=6,C=gg(b,3),P=Zo(e,"standard");ot.current=Date.now(),bt(0),T(!0);let z=new AbortController;Re.current=z,oe({verb:"Authoring",unit:"spec",total:C.length,done:0,active:[],rows:Sn(C),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${b.length} screenshot spec${b.length===1?"":"s"} across ${C.length} partition${C.length===1?"":"s"} (\u2264${y} agents at once) on ${P.model}${P.forced?" (forced)":""}\u2026 (esc to stop)`});let q=!1;try{for await(let L of Jo({cwd:e,partitions:C,promptFor:El,concurrency:y,profileName:i,allowProdWrites:Ct.current,model:P.model,signal:z.signal}))if(L.type==="partition_status")L.status==="running"?oe(R=>R&&{...R,active:[...R.active,L.label],rows:He(R.rows,L.label,"active"),lastAt:Date.now()}):oe(R=>R&&{...R,active:R.active.filter(j=>j!==L.label),done:R.done+1,rows:He(R.rows,L.label,L.status==="done"?"done":"failed"),lastAt:Date.now()});else if(L.type==="partition_event")oe(R=>{if(!R)return R;let j={...R,lastAt:Date.now()};return L.event.type==="tool"?j.tools=R.tools+1:L.event.type==="text"&&(j.chars=R.chars+L.event.delta.length),j});else if(L.type==="run_done"){jt(Z=>Z+L.totalCostUsd),At(Z=>Z+L.results.reduce((_t,Ot)=>_t+Ot.outputTokens,0));let R=L.results.filter(Z=>Z.ok).length,j=L.aborted?"Stopped. ":"";q=!L.aborted&&d.setup;let B=L.aborted?"":q?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";u({kind:"note",tone:L.aborted?"warn":L.ok?"ok":"warn",text:`${j}Authored specs \u2014 ${R}/${L.results.length} batches ok.${B}`})}}catch(L){u({kind:"note",tone:"error",text:`Spec authoring failed: ${L.message}`})}finally{Re.current=null,oe(null),T(!1),X(L=>L+1)}if(q){let L=await xn();L.kind==="forward-to-agent"&&L.prompt&&await ie(L.prompt,{display:L.display,quietUser:!0});let R=Pi(e);R&&u({kind:"note",tone:"info",text:R.join(`
|
|
341
|
+
`)})}return}case"reset":{let d=Oi(e);if(d.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}On.current={repoName:Dn(e),targets:d,hadDevhints:Gt(zc(e))},u({kind:"note",tone:"warn",text:Mi(e,d).join(`
|
|
342
|
+
`)}),me(Dn(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${s} \u2014 type /help.`})}},[e,r,i,Kn,u,ke,ie,Vn,yr,Os]),Xn=G(l=>{let a=(l??S).trim();if($(""),In(null),$t(0),a.startsWith("/")&&(An.current=!1,Ve(),Jt(null),nt(g=>jc(g,a))),!a||(ks(!1),Ms(a))||Ls(a))return;ir.current.push(a);let s=_c(a,$s.current);if(a.startsWith("/"))u({kind:"user",text:a}),ln(s);else if(Tg(s)){u({kind:"user",text:a});let g=Sg(s);if(!g)ie(s,{display:a,quietUser:!0});else{try{Dg(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})},[S,Ms,Ls,ln,ie]),Us=G(l=>{if(l.length>1){if(l.includes("\x1B"))return;let a=Ec(l);if(Nc(a)){let s=Ic(++gd.current,a);$s.current.set(s,a),I(s)}else I(a);return}I(l)},[I]),It=Math.max(10,Ee-6),Ws=as(()=>Ko(k.text,It),[k.text,It]),br=G(l=>w(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+l))})),[]),Qn=G(l=>w(a=>({...a,pos:Lc(Ko(a.text,It),a.pos,l)})),[It]),cn=G(l=>w(a=>({...a,pos:Mc(Ko(a.text,It),a.pos,l)})),[It]),bd=["\x1B[H","\x1B[1~","\x1BOH"],$d=["\x1B[F","\x1B[4~","\x1BOF"],Fs=G((l,a)=>a.leftArrow?(br(-1),!0):a.rightArrow?(br(1),!0):l&&bd.includes(l)?(cn("start"),!0):l&&$d.includes(l)?(cn("end"),!0):a.ctrl&&l==="a"?(cn("start"),!0):a.ctrl&&l==="e"?(cn("end"),!0):!1,[br,cn]);return Wh((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(),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}Zt.current||(Zt.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Ce.current?.interrupt());return}if(a.return){let s=S.trim();if(!s)return;dt.current.push(s),ar([...dt.current]),$("");return}if(Fs(l,a))return;if(a.upArrow){Qn(-1);return}if(a.downArrow){Qn(1);return}if(a.backspace||a.delete){x();return}l&&!a.ctrl&&!a.meta&&Us(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}=bn(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&&(Ds(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(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),kr(s.name,a.return===!0);return}if(a.escape){Rt(null);return}return}if(Wn){if(a.escape){tn(null);return}if(a.leftArrow||a.tab&&a.shift){tn(s=>s&&{tab:(s.tab-1+Te.length)%Te.length});return}if(a.rightArrow||a.tab){tn(s=>s&&{tab:(s.tab+1)%Te.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Te.length){tn({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),!Dr(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"),X(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),Gn(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),zn(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}Br(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"?yr(s.paths[0]):Vn(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,qn.length-1),s.cursor+1)});return}if(a.return){let s=qn[ye.cursor];if(s){ct(null);try{u({kind:"preview",name:Dn(s),text:od(Qo(ls(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,Bn.length-1),s.cursor+1)});return}if(a.return){let s=Bn[we.cursor];if(s){ut(null),ke(s.uuid),_e.current={uuid:s.uuid,firstPrompt:s.firstPrompt,titleFired:!0},rt(s.name),cs(s.uuid),vt.current=[];let g=rs(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&&!S&&ae){$(ae),Ve();return}if(!S&&tt.length>0&&!or&&l&&/^[1-9]$/.test(l)){let s=tt[Number(l)-1];if(s){$(yt(s));return}}if(!S&&(Fn||nn)&&l==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let s=Fn!=null;ns(Fn??nn).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&&mr(null),d&&!s&&Es(!0)});return}if(!Fs(l,a)){if(Is){if(a.upArrow){$t(s=>Math.max(0,s-1));return}if(a.downArrow){$t(s=>Math.min(an.length-1,s+1));return}if(a.tab){$("/"+(an[Qt]?.name??"")+" "),$t(0);return}if(a.return){let s=an[Qt];if(s){let g=S.trim().slice(1).split(/\s+/).slice(1).join(" ");if(vc(s.usage)&&!g){$("/"+s.name+" "),$t(0);return}Xn("/"+s.name+(g?" "+g:""));return}}}else{if(a.upArrow){if(S!==""&&xt===null){Qn(-1);return}let s=ir.current;if(!s.length)return;let g=xt===null?s.length-1:Math.max(0,xt-1);In(g),$(s[g]??"");return}if(a.downArrow){if(S!==""&&xt===null){Qn(1);return}let s=ir.current;if(xt===null)return;let g=xt+1;g>=s.length?(In(null),$("")):(In(g),$(s[g]??""));return}}if(a.return){Xn();return}if(a.backspace||a.delete){x();return}if(a.escape){$(""),$t(0),Ve(),nt([]),Jt(null),An.current=!0;return}l&&!a.ctrl&&!a.meta&&Us(l)}}}),ve(()=>{if(E||M)return;let l=dt.current.shift();l!==void 0&&(ar([...dt.current]),Xn(l))},[E,M,Xn]),V(ne,{flexDirection:"column",width:Ee,children:[gr!==null&&V(ne,{marginTop:1,flexDirection:"column",children:[gr.truncated&&A(D,{dimColor:!0,children:"\u2026"}),A(D,{children:gr.text})]}),E&&(Ln?A(Ug,{p:Ln}):A(Og,{startTime:ot.current,chars:hd})),!E&&Rs?A(Lg,{text:Rs}):null,A(ne,{borderStyle:"round",borderColor:Ns.prod?"yellow":F,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:S?Ws.map((l,a)=>{let s=k.text.slice(l.start,l.end),g=a===Xo(Ws,k.pos),d=Math.min(k.pos,l.end)-l.start;return V(D,{children:[A(D,{color:F,children:a===0?"> ":" "}),g?V(er,{children:[s.slice(0,d),A(Yt,{ch:s[d]??" "}),s.slice(d+1)]}):s||" "]},`${a}-${l.start}`)}):V(D,{children:[A(D,{color:F,children:"> "}),lr?A(Yt,{ch:" "}):ae&&!E&&Xt?V(er,{children:[A(Yt,{ch:Xt[0],dim:!0}),A(D,{color:"gray",children:Xt.slice(1)})]}):ae&&!E?V(er,{children:[A(Yt,{ch:ae[0],dim:!0}),A(D,{color:"gray",children:ae.slice(1)}),A(D,{dimColor:!0,children:" (tab)"})]}):(hr.isSetup||!fd)&&!E?V(er,{children:[A(Yt,{ch:hr.text[0],dim:!0}),A(D,{color:"gray",children:hr.text.slice(1)})]}):A(Yt,{ch:" "})]})}),Cs.length>0&&A(ne,{flexDirection:"column",paddingX:1,children:Cs.map((l,a)=>A(D,{color:"gray",children:`\u29D7 queued: ${l}`},`${a}-${l.slice(0,24)}`))}),Wn?A(Rc,{tab:Wn.tab,width:Ee,version:o,engineVersion:rd}):it?V(ne,{flexDirection:"column",paddingX:1,children:[A(D,{color:F,bold:!0,children:"Select model"}),A(D,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ie.map((l,a)=>V(D,{color:a===it.cursor?F:void 0,children:[a===it.cursor?"\u276F ":" ",`${a+1}. ${l.label}${a===it.current?" \u2714":""}`.padEnd(16),A(D,{color:"gray",children:l.desc})]},l.label)),A(D,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Oe?V(ne,{flexDirection:"column",paddingX:1,children:[A(D,{color:F,bold:!0,children:"Switch connection profile"}),Oe.rows.map((l,a)=>V(D,{color:a===Oe.cursor?F:void 0,children:[a===Oe.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===Oe.current?" \u2714":""}`.padEnd(20),A(D,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?A(D,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),A(D,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Le?V(ne,{flexDirection:"column",paddingX:1,children:[A(D,{color:F,bold:!0,children:"Pick your Document360 environment"}),Le.rows.map((l,a)=>V(D,{color:a===Le.cursor?F:void 0,children:[a===Le.cursor?"\u276F ":" ",`${a+1}. ${l.name}`.padEnd(16),A(D,{color:"gray",children:l.apiUrl})]},l.name)),A(D,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):pe?V(ne,{flexDirection:"column",paddingX:1,children:[A(D,{color:F,bold:!0,children:"Switch workspace"}),A(D,{dimColor:!0,children:`environment ${pe.environment} \xB7 project ${pe.projectName??`${pe.projectId.slice(0,8)}\u2026`}`}),pe.rows.map((l,a)=>V(D,{color:a===pe.cursor?F:void 0,children:[a===pe.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===pe.current?" \u2714":""}`.padEnd(30),A(D,{color:"gray",children:l.type??""})]},l.id)),A(D,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ge?V(ne,{flexDirection:"column",paddingX:1,children:[A(D,{color:F,bold:!0,children:"Choose project"}),A(D,{dimColor:!0,children:`environment ${ge.environment}`}),ge.rows.map((l,a)=>V(D,{color:a===ge.cursor?F:void 0,children:[a===ge.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===ge.current?" \u2714":""}`.padEnd(30),A(D,{color:"gray",children:l.sub??""})]},l.id)),A(D,{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 V(ne,{flexDirection:"column",paddingX:1,children:[A(D,{color:F,bold:!0,children:`Which folders back the user docs? (${g} selected of ${fe.rows.length})`}),a>0?A(D,{dimColor:!0,children:` \u2191 ${a} more`}):null,s.map((d,m)=>{let b=a+m;return V(D,{color:b===fe.cursor?F:void 0,children:[b===fe.cursor?"\u276F ":" ",d.checked?"\u25C9 ":"\u25CB ",d.path.padEnd(Math.min(48,Ee-34)),A(D,{color:"gray",children:$o(d)})]},d.path)}),a+14<fe.rows.length?A(D,{dimColor:!0,children:` \u2193 ${fe.rows.length-a-14} more`}):null,A(D,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Me?V(ne,{flexDirection:"column",paddingX:1,children:[A(D,{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 V(D,{color:s?F:void 0,children:[s?"\u276F ":" ",`${g} ${l.label} (${l.count})`.padEnd(Math.min(44,Math.max(20,Ee-24))),A(D,{color:"gray",children:` ${l.token}`})]},l.token)}),A(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):qe?V(ne,{flexDirection:"column",paddingX:1,children:[A(D,{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 V(D,{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?A(D,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),A(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ye?V(ne,{flexDirection:"column",paddingX:1,children:[A(D,{color:F,bold:!0,children:`Preview article${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),qn.length===0?A(D,{color:"gray",children:"no articles match"}):qn.map((l,a)=>V(D,{color:a===ye.cursor?F:void 0,children:[a===ye.cursor?"\u276F ":" ",l]},l)),A(D,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):we?V(ne,{flexDirection:"column",paddingX:1,children:[A(D,{color:F,bold:!0,children:`Resume session${we.query?` \u2014 filter: ${we.query}`:" (type to filter)"}`}),Bn.length===0?A(D,{color:"gray",children:"no sessions match"}):Bn.map((l,a)=>V(D,{color:a===we.cursor?F:void 0,children:[a===we.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),A(D,{color:a===we.cursor?F:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ee-40))})]},l.uuid)),A(D,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Is?V(ne,{flexDirection:"column",children:[an.map((l,a)=>V(D,{color:a===Qt?F:void 0,children:[a===Qt?"\u276F ":" ",l.usage.padEnd(22)," ",A(D,{color:a===Qt?F:"gray",children:l.name==="model"&&cr?`${l.desc} (currently ${cr})`:l.desc})]},l.name)),A(D,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!E&&!S&&tt.length>0?V(ne,{flexDirection:"column",paddingX:1,children:[vs?A(D,{color:F,children:vs}):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?(Ac(l)??$c(s)).slice(0,d):"";return V(D,{children:[A(D,{color:F,children:a+1})," ",g,m?A(D,{dimColor:!0,children:` \u2014 ${m}`}):null]},s)}),A(D,{dimColor:!0,children:`press 1-${tt.length} to fill \xB7 esc cancel`})]}):A(ne,{paddingX:1,children:V(D,{color:"gray",children:[Ns.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${cr??"model n/a"}${t.kind==="api"?Ss>0?` \xB7 ${he(Ss)}`:"":Ts>0?` \xB7 ${Qe(Ts)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}U();import{jsx as qg}from"react/jsx-runtime";async function ad(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Hg(t);r.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:i}=Fg(qg(sd,{cwd:e,auth:r,profileName:n,version:o}));await i(),process.stdout.write(`
|
|
343
|
+
`),process.exit(0)}U();import{writeCrashLog as ld,isBenignTransportError as Bg}from"document360-engine";var cd=!1;function hs(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function dd(e){if(cd)return;cd=!0;let t=(n,o)=>{if(Bg(o)){ld({kind:n,level:"transport",message:hs(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=ld({kind:n,level:"fatal",message:hs(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
344
|
+
`+v(`\u2717 d360-writer crashed: ${hs(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 zg=Gg(import.meta.url),tr=zg("../package.json");dd("d360-writer");var De=new Vg;function gs(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=>{gs(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=>{gs(e),await Zs({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=>{gs(e),await Js({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 ud=De.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");ud.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));ud.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Vs(process.cwd(),e,t.profile)});var pd=De.command("project").description("Choose the Document360 project for this repo (active profile's identity)");pd.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));pd.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Ys(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(),Pa));await e()});De.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>oa());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(()=>(To(),Cl)),n=await t(process.cwd(),tr.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(tr.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(Yg.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 ra(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 fc(e.cwd,e.auth,e.profile,tr.version):await ad(e.cwd,e.auth,e.profile,tr.version)});De.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|