document360-writer 0.4.43 → 0.4.45
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 +75 -75
- package/dist/lib/checklist.d.ts +18 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,68 +1,68 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var ki=Object.defineProperty;var Jo=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var wi=(e,t)=>{for(var n in t)ki(e,n,{get:t[n],enumerable:!0})};import Ae from"picocolors";var B,yi,xi,$i,Ko,mt,f,x,L,E,R,Q,Pe,H=Jo(()=>{"use strict";B="#7f56d9",[yi,xi,$i]=[127,86,217],Ko=e=>Ae.isColorSupported?`\x1B[38;2;${yi};${xi};${$i}m${e}\x1B[39m`:e,mt=e=>Ae.bold(Ko(e)),f=e=>Ae.dim(e),x=e=>Ae.red(e),L=e=>Ae.yellow(e),E=e=>Ae.green(e),R=Ko,Q=e=>Ae.gray(e),Pe=e=>Ae.bold(e)});var os={};wi(os,{doctorCommand:()=>vt,renderDoctorChecks:()=>ns,runDoctorChecks:()=>ts});import{existsSync as ll}from"node:fs";import{d360GetAll as cl,getAccessToken as ul,isExpired as io,loadProfileMap as dl,loadTokens as pl,packageSkillsDir as es,projectConfigPath as fl,readProjectConfig as ml,resolveActiveProfile as gl,resolveAuth as hl,resolveModelSetting as kl}from"document360-engine";async function ts(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=hl("auto");t.push(o.kind==="none"?{level:"fail",label:"Claude auth: not configured",fix:"Set ANTHROPIC_API_KEY, or sign in to Claude Code once (subscription reuse)"}:{level:"ok",label:`Claude auth: ${o.kind==="api"?"API key":"subscription"}`});let r=kl(e);t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`});let s=ml(e);if(!s)return t.push({level:"fail",label:`No ${fl(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??"user-docs").replace(/\/+$/,"");t.push(s.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let d=s.authoritativeSourceFiles??[];t.push(d.length>0?{level:"ok",label:`Sources: docs grounded in ${d.length} path(s) (${d.slice(0,3).join(", ")}${d.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let g;try{g=gl(e),t.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(I){return t.push({level:"fail",label:`Profile config: ${I.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=pl(g.name);k?io(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):io(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 ${g.name})`}),t.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let y=dl(e,g.name);if(y?y.projectId&&g.project.projectId&&y.projectId!==g.project.projectId?t.push({level:"fail",label:`Category map projectId (${y.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(y.articles).length} articles, ${Object.keys(y.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),t.push(ll(es())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${es()}`,fix:"Reinstall document360-writer (broken install)"}),k&&(!io(k)||k.refreshToken)){let I={profile:g.name,connection:g.connection};try{await ul(I);let b=await cl(I,"/v3/projects");t.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${b.length} project(s) visible`})}catch(b){t.push({level:"fail",label:`API call failed: ${b.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}}return t}function ns(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?L("\u26A0"):x("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${R(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?E(`\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 vt(e,t){console.log(f("Running checks\u2026"));for(let n of ns(await ts(t.cwd)))console.log(n);return{kind:"continue"}}var nn=Jo(()=>{"use strict";H()});import{Command as Cu}from"commander";import{createRequire as Pu}from"node:module";import{AUTH_MODES as Su}from"document360-engine";import{input as Ei}from"@inquirer/prompts";import{loginPkce as Di,refreshTokens as Ii,toStoredTokens as tr,clearTokens as Ni,decodeJwtClaims as er,isExpired as _i,loadTokens as Mi,saveTokens as nr,resolveActiveProfile as Ft,setProfileProject as Li,readProjectConfig as Oi}from"document360-engine";H();import{select as bi}from"@inquirer/prompts";import{resolveActiveProfile as vi,setProfileProject as Ci,resolveProjectId as Pi,listWorkspaces as Si}from"document360-engine";async function gt(e,t){let n=vi(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Pi(o);return{workspaces:await Si(o,r),projectId:r,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Qo=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function jn(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 Wt(e,t,n,o,r){Ci(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Zo(e,t,n){let o;try{o=await gt(e,n)}catch(s){return console.log(x(`Could not list workspaces: ${s.message}`)),1}let r=jn(o.workspaces,t);return r?(Wt(e,o.profile,o.projectId,r.id,r.name),console.log(E(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(x(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function tt(e,t){let n;try{n=await gt(e,t)}catch(k){console.log(x(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===c?R("\u25CF"):" "} ${Qo(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let d=await bi({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${Qo(k)}${k.id===c?" (current)":""}`,value:k.id}))}),g=o.find(k=>k.id===d);Wt(e,s,r,d,g?.name),console.log(E(`\u2713 Workspace set to "${g?.name??d}" for profile "${s}".`))}H();import Ti from"picocolors";function Ri(e=process.env){return e.FORCE_HYPERLINK==="0"||!Ti.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 ji(e,t=e,n){return Ri(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Ai=/https?:\/\/[^\s\x1b]+/g;function ht(e,t){return e.replace(Ai,n=>ji(n,n,t))}function or(e){return{...er(e.idToken)??{},...er(e.accessToken)??{}}}function Ht(e){let t=or(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 Bt(e){let t=Ft(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 Di(n,{manual:e.manual,promptForRedirect:s=>Ei({message:s})},s=>console.log(ht(s))),r=tr(t.name,o);if(nr(r),An(r,t.name,s=>console.log(f(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${Ht(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{Oi(process.cwd())?.profiles?.[t.name]&&(console.log(""),await tt(process.cwd(),t.name))}catch{}}function An(e,t,n){let r=or(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Ft(process.cwd(),t).project.projectId)return;Li(process.cwd(),t,{projectId:r}),n(` Project ${r} written to profile "${t}".`)}catch{}}async function rr(e){let t=Ft(process.cwd(),e.profile),n=t.connection,o=Mi(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 ${R(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Ht(o)}`),_i(o))if(o.refreshToken)try{let r=tr(t.name,await Ii(n,o.refreshToken));nr(r),console.log(E(`\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 sr(e){let t=Ft(process.cwd(),e.profile);Ni(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}H();import{readProjectConfig as ir,writeProjectConfig as Ui,resolveActiveProfile as Wi,loadTokens as Fi,isExpired as Hi}from"document360-engine";function qt(e){let t=ir(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(x("No profiles in .d360-writer.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?R("\u25CF "):" ",s=o.production?L(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",d=Fi(n),g=d?Hi(d)&&!d.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${R(n)} \u2192 ${c}${s} [${g}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Gt(e,t){let n=ir(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,Ui(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function zt(e,t){try{let n=Wi(e,t);console.log(""),console.log(`Profile ${R(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}}H();import{existsSync as Bi,readdirSync as qi,statSync as Gi}from"node:fs";import{join as zi}from"node:path";import{apiLogDir as Yi}from"document360-engine";function ar(){let e=Yi();if(console.log(""),console.log(`Document360 API logs: ${R(e)}`),!Bi(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=qi(e).filter(n=>n.endsWith(".jsonl")).sort().reverse();t.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let n of t.slice(0,14)){let o=(Gi(zi(e,n)).size/1024).toFixed(1);console.log(` ${n} ${f(`${o} KB`)}`)}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}H();import{createSession as Vi,resolveAuth as Xi,findByName as Ji,slugify as Ki,touchSession as Qi,upsertSession as Zi,resolveActiveProfile as ea}from"document360-engine";async function lr(e,t,n,o,r,s){let c=Xi(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 ${R("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${R("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let d=null;try{d=ea(e,r)}catch(b){console.error(x(`Document360 profile error: ${b.message}`)),process.exit(2)}d.production&&(console.error(L(`\u26A0 Profile "${d.name}" is PRODUCTION.`)),s||(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 g;if(o){let b=Ji(e,o);b||(console.error(x(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),g=b.uuid,console.error(f(`Resuming "${b.name}"`))}let k=Vi({cwd:e,resume:g,profileName:r,allowProdWrites:s===!0}),y=g??null,I=1;for await(let b of k.send(t))switch(b.type){case"session":if(!y){y=b.sessionId;let C=new Date().toISOString();Zi({uuid:y,name:Ki(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:C,updatedAt:C})}break;case"text":process.stdout.write(b.delta);break;case"tool":console.error(Q(` \u2699 ${b.name}`));break;case"result":I=b.ok?0:1,console.error(f(`(${b.inputTokens}\u2192${b.outputTokens} tokens`+(b.costUsd>0?`, $${b.costUsd<.01?b.costUsd.toFixed(4):b.costUsd.toFixed(2)}`:"")+")")),b.ok||console.error(x("agent finished with an error result"));break;case"error":console.error(""),console.error(x(`agent error: ${b.message}`)),process.exit(1)}y&&Qi(y),process.stdout.write(`
|
|
3
|
-
`),process.exit(
|
|
4
|
-
(conversation reset \u2014 "${
|
|
2
|
+
var bi=Object.defineProperty;var er=(e,t,o)=>()=>{if(o)throw o[0];try{return e&&(t=e(e=0)),t}catch(n){throw o=[n],n}};var vi=(e,t)=>{for(var o in t)bi(e,o,{get:t[o],enumerable:!0})};import Ae from"picocolors";var G,Ci,Pi,Si,tr,gt,f,b,O,_,j,Z,Pe,q=er(()=>{"use strict";G="#7f56d9",[Ci,Pi,Si]=[127,86,217],tr=e=>Ae.isColorSupported?`\x1B[38;2;${Ci};${Pi};${Si}m${e}\x1B[39m`:e,gt=e=>Ae.bold(tr(e)),f=e=>Ae.dim(e),b=e=>Ae.red(e),O=e=>Ae.yellow(e),_=e=>Ae.green(e),j=tr,Z=e=>Ae.gray(e),Pe=e=>Ae.bold(e)});var as={};vi(as,{doctorCommand:()=>Ct,renderDoctorChecks:()=>is,runDoctorChecks:()=>ss});import{existsSync as fl}from"node:fs";import{d360GetAll as ml,getAccessToken as gl,isExpired as un,loadProfileMap as hl,loadTokens as kl,packageSkillsDir as rs,projectConfigPath as wl,readProjectConfig as yl,resolveActiveProfile as xl,resolveAuth as $l,resolveModelSetting as bl}from"document360-engine";async function ss(e){let t=[],o=Number(process.versions.node.split(".")[0]);t.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 n=$l("auto");t.push(n.kind==="none"?{level:"fail",label:"Claude auth: not configured",fix:"Set ANTHROPIC_API_KEY, or sign in to Claude Code once (subscription reuse)"}:{level:"ok",label:`Claude auth: ${n.kind==="api"?"API key":"subscription"}`});let r=bl(e);t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`});let s=yl(e);if(!s)return t.push({level:"fail",label:`No ${wl(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??"user-docs").replace(/\/+$/,"");t.push(s.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let d=s.authoritativeSourceFiles??[];t.push(d.length>0?{level:"ok",label:`Sources: docs grounded in ${d.length} path(s) (${d.slice(0,3).join(", ")}${d.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let m;try{m=xl(e),t.push({level:"ok",label:`Profile: ${m.name} (${m.connection.name})${m.production?" \u26A0 PRODUCTION":""}`})}catch(E){return t.push({level:"fail",label:`Profile config: ${E.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=kl(m.name);k?un(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):un(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 ${m.name})`}),t.push(m.project.workspaceId?{level:"ok",label:`Workspace: ${m.project.workspaceName??m.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let y=hl(e,m.name);if(y?y.projectId&&m.project.projectId&&y.projectId!==m.project.projectId?t.push({level:"fail",label:`Category map projectId (${y.projectId}) \u2260 profile projectId (${m.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(y.articles).length} articles, ${Object.keys(y.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${m.name}" (created on first /publish)`}),t.push(fl(rs())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${rs()}`,fix:"Reinstall document360-writer (broken install)"}),k&&(!un(k)||k.refreshToken)){let E={profile:m.name,connection:m.connection};try{await gl(E);let x=await ml(E,"/v3/projects");t.push({level:"ok",label:`API reachable (${m.connection.apiUrl}) \u2014 ${x.length} project(s) visible`})}catch(x){t.push({level:"fail",label:`API call failed: ${x.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}}return t}function is(e){let t=[""];for(let r of e){let s=r.level==="ok"?_("\u2713"):r.level==="warn"?O("\u26A0"):b("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${j(r.fix)}`)}let o=e.filter(r=>r.level==="fail").length,n=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(o===0?_(`\u2713 ${n===0?"All checks passed":`Healthy (${n} warning${n===1?"":"s"})`}`):b(`\u2717 ${o} problem${o===1?"":"s"} found`)),t.push(""),t}async function Ct(e,t){console.log(f("Running checks\u2026"));for(let o of is(await ss(t.cwd)))console.log(o);return{kind:"continue"}}var no=er(()=>{"use strict";q()});import{Command as ju}from"commander";import{createRequire as Au}from"node:module";import{AUTH_MODES as Eu}from"document360-engine";import{input as Mi}from"@inquirer/prompts";import{loginPkce as Li,refreshTokens as Oi,toStoredTokens as sr,clearTokens as Ui,decodeJwtClaims as rr,isExpired as Wi,loadTokens as Hi,saveTokens as ir,resolveActiveProfile as Ft,setProfileProject as Fi,readProjectConfig as Bi}from"document360-engine";q();import{select as Ti}from"@inquirer/prompts";import{resolveActiveProfile as Ri,setProfileProject as ji,resolveProjectId as Ai,listWorkspaces as Ei}from"document360-engine";async function ht(e,t){let o=Ri(e,t),n={profile:o.name,connection:o.connection},r=o.project.projectId??Ai(n);return{workspaces:await Ei(n,r),projectId:r,profile:o.name,environment:o.connection.name,current:o.project.workspaceId}}var or=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Do(e,t){let o=t.toLowerCase();return e.find(n=>(n.name??"").toLowerCase()===o)??e.find(n=>(n.name??"").toLowerCase().startsWith(o))??e.find(n=>n.id.startsWith(t))}function Ht(e,t,o,n,r){ji(e,t,{projectId:o,workspaceId:n,workspaceName:r})}async function nr(e,t,o){let n;try{n=await ht(e,o)}catch(s){return console.log(b(`Could not list workspaces: ${s.message}`)),1}let r=Do(n.workspaces,t);return r?(Ht(e,n.profile,n.projectId,r.id,r.name),console.log(_(`\u2713 Workspace set to "${r.name??r.id}" for profile "${n.profile}".`)),0):(console.log(b(`No workspace matches "${t}". Available: ${n.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function ot(e,t){let o;try{o=await ht(e,t)}catch(k){console.log(b(`Could not list workspaces: ${k.message}`));return}let{workspaces:n,projectId:r,profile:s,current:c}=o;if(n.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of n)console.log(` ${k.id===c?j("\u25CF"):" "} ${or(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let d=await Ti({message:"Select the Document360 workspace for this repo:",choices:n.map(k=>({name:`${or(k)}${k.id===c?" (current)":""}`,value:k.id}))}),m=n.find(k=>k.id===d);Ht(e,s,r,d,m?.name),console.log(_(`\u2713 Workspace set to "${m?.name??d}" for profile "${s}".`))}q();import Di from"picocolors";function Ii(e=process.env){return e.FORCE_HYPERLINK==="0"||!Di.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 _i(e,t=e,o){return Ii(o)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Ni=/https?:\/\/[^\s\x1b]+/g;function kt(e,t){return e.replace(Ni,o=>_i(o,o,t))}function ar(e){return{...rr(e.idToken)??{},...rr(e.accessToken)??{}}}function Bt(e){let t=ar(e),o=t.email??t.preferred_username??t.sub??"unknown",n=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${o}${n}`}async function qt(e){let t=Ft(process.cwd(),e.profile),o=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${o.name} (${o.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let n=await Li(o,{manual:e.manual,promptForRedirect:s=>Mi({message:s})},s=>console.log(kt(s))),r=sr(t.name,n);if(ir(r),Io(r,t.name,s=>console.log(f(s))),console.log(""),console.log(_(`\u2713 Logged in to "${t.name}" as ${Bt(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{Bi(process.cwd())?.profiles?.[t.name]&&(console.log(""),await ot(process.cwd(),t.name))}catch{}}function Io(e,t,o){let r=ar(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Ft(process.cwd(),t).project.projectId)return;Fi(process.cwd(),t,{projectId:r}),o(` Project ${r} written to profile "${t}".`)}catch{}}async function lr(e){let t=Ft(process.cwd(),e.profile),o=t.connection,n=Hi(t.name);if(!n){console.log(b(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${j(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Bt(n)}`),Wi(n))if(n.refreshToken)try{let r=sr(t.name,await Oi(o,n.refreshToken));ir(r),console.log(_(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(O(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(O("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${n.expiresAt}`))}async function cr(e){let t=Ft(process.cwd(),e.profile);Ui(t.name)?console.log(_(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}q();import{readProjectConfig as ur,writeProjectConfig as qi,resolveActiveProfile as Gi,loadTokens as zi,isExpired as Yi}from"document360-engine";function Gt(e){let t=ur(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(b("No profiles in .d360-writer.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[o,n]of Object.entries(t.profiles)){let r=o===t.defaultProfile?j("\u25CF "):" ",s=n.production?O(" \u26A0 PRODUCTION"):"",c=n.connection.environment??"(inline)",d=zi(o),m=d?Yi(d)&&!d.refreshToken?O("expired"):f("logged in"):f("not logged in");console.log(`${r}${j(o)} \u2192 ${c}${s} [${m}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function zt(e,t){let o=ur(e);if(!o?.profiles?.[t]){let r=o?.profiles?Object.keys(o.profiles).join(", "):"(none \u2014 run init)";console.log(b(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}o.defaultProfile=t,qi(o,e);let n=o.profiles[t].production?O(" \u26A0 PRODUCTION"):"";console.log(_(`\u2713 Default profile is now "${t}"${n}`))}function Yt(e,t){try{let o=Gi(e,t);console.log(""),console.log(`Profile ${j(o.name)}${o.production?O(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${o.connection.apiUrl}`)),console.log(f(` identity: ${o.connection.authorizationUrl}`)),console.log(f(` clientId: ${o.connection.clientId}`)),console.log(f(` scopes: ${o.connection.scopes.join(" ")}`)),console.log(f(` project: ${o.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${o.project.workspaceId?" "+o.project.workspaceId:" (none)"}`)),console.log("")}catch(o){console.log(b(o.message)),process.exitCode=1}}q();import{existsSync as Vi,readdirSync as Xi,statSync as Ki}from"node:fs";import{join as Ji}from"node:path";import{apiLogDir as Qi}from"document360-engine";function dr(){let e=Qi();if(console.log(""),console.log(`Document360 API logs: ${j(e)}`),!Vi(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Xi(e).filter(o=>o.endsWith(".jsonl")).sort().reverse();t.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let o of t.slice(0,14)){let n=(Ki(Ji(e,o)).size/1024).toFixed(1);console.log(` ${o} ${f(`${n} KB`)}`)}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}q();import{createSession as Zi,resolveAuth as ea,findByName as ta,slugify as oa,touchSession as na,upsertSession as ra,resolveActiveProfile as sa}from"document360-engine";async function pr(e,t,o,n,r,s){let c=ea(o);c.kind==="none"&&(console.error(""),console.error(b("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${j("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${j("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let d=null;try{d=sa(e,r)}catch(x){console.error(b(`Document360 profile error: ${x.message}`)),process.exit(2)}d.production&&(console.error(O(`\u26A0 Profile "${d.name}" is PRODUCTION.`)),s||(console.error(b("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let m;if(n){let x=ta(e,n);x||(console.error(b(`No saved session matches "${n}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),m=x.uuid,console.error(f(`Resuming "${x.name}"`))}let k=Zi({cwd:e,resume:m,profileName:r,allowProdWrites:s===!0}),y=m??null,E=1;for await(let x of k.send(t))switch(x.type){case"session":if(!y){y=x.sessionId;let v=new Date().toISOString();ra({uuid:y,name:oa(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:v,updatedAt:v})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(Z(` \u2699 ${x.name}`));break;case"result":E=x.ok?0:1,console.error(f(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error(b("agent finished with an error result"));break;case"error":console.error(""),console.error(b(`agent error: ${x.message}`)),process.exit(1)}y&&na(y),process.stdout.write(`
|
|
3
|
+
`),process.exit(E)}import{createInterface as cc}from"node:readline/promises";import{createSession as Cn,resolveAuth as uc,getSession as dc,setTitle as pc,slugify as fc,touchSession as Ds,upsertSession as mc,generateTitle as gc,resolveActiveProfile as Is,resolveModelSetting as hc,readProjectConfig as kc,decodeJwtClaims as As,isExpired as wc,loadTokens as yc}from"document360-engine";var wt=[{name:"init",usage:"/init",desc:"Pick an environment & scaffold .d360-writer.json",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Set up the dev\u2192docs hint channel (guide + paste block for your repo agent)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"write",usage:"/write [--all|--scope <cat>|<path>] [--run]",desc:"Author the planned articles in parallel (bare = preview + cost; --run starts)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"audit",usage:"/audit",desc:"Gap analysis: code vs docs vs Document360 (what changed)",group:"publish"},{name:"sync",usage:"/sync [pull <path>|--all]",desc:"Drift report local vs Document360; pull portal edits",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],ia=[{key:"start",label:"Start here"},{key:"docs",label:"Write & screenshots"},{key:"publish",label:"Publish & keep in sync"},{key:"setup",label:"Setup & health"},{key:"session",label:"Session"}];function Vt(){let e=Math.max(...wt.map(o=>o.usage.length))+2,t=["document360-writer \u2014 commands","",'New here? /init \u2192 "write the docs for this repo" \u2192 /publish',""," Screenshots are optional \u2014 add them anytime:"," /screenshot --all \u2192 d360-capture capture \u2192 re-/publish"];for(let{key:o,label:n}of ia){t.push("",n);for(let r of wt.filter(s=>s.group===o))t.push(` ${r.usage.padEnd(e)}${r.desc}`)}return t.push("","Tip: anything not starting with / is sent to the agent."),t}function fr(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return wt.filter(o=>o.name.startsWith(t))}function mr(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}async function _o(){console.log("");for(let e of Vt())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}q();import{getSession as aa}from"document360-engine";async function gr(e,t){let o=t.currentUuid(),n=o?aa(o):void 0;return console.log(n?f(`
|
|
4
|
+
(conversation reset \u2014 "${n.name}" is still available via /resume)
|
|
5
5
|
`):f(`
|
|
6
6
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
7
|
-
`)),{kind:"clear"}}async function
|
|
8
|
-
`),"utf8")}async function
|
|
7
|
+
`)),{kind:"clear"}}async function No(){return{kind:"exit"}}q();import{input as yt,confirm as la}from"@inquirer/prompts";import{basename as hr,join as Xt}from"node:path";import{existsSync as nt,readFileSync as ca,readdirSync as ua,writeFileSync as da}from"node:fs";import{writeProjectConfig as kr,readProjectConfig as pa,projectConfigPath as wr,writerDir as fa}from"document360-engine";function yr(e,t="berlin"){let o=wr(e);if(nt(o))return{created:!1,path:o,profileName:""};let n={projectId:br(e)??hr(e),captureDir:"user-docs/_capture",outputDir:"user-docs/_screenshots",profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:vr(e)};return kr(n,e),xr(e),{created:!0,path:o,profileName:t}}function xr(e){let t=Xt(fa(e),".gitignore");nt(t)||da(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
8
|
+
`),"utf8")}async function $r(){let e=process.cwd(),t=wr(e);if(nt(t)&&!await la({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let o=br(e)??hr(e),n=await yt({message:"Project ID (used to scope sessions, screenshots, etc.):",default:o}),r=await yt({message:"Capture directory (where document360-capture .spec.ts files live):",default:"user-docs/_capture"}),s=await yt({message:"Screenshot output directory:",default:"user-docs/_screenshots"}),c=await yt({message:"Default connection profile name:",default:"berlin"}),d=await yt({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),m={projectId:n,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:d},production:!1}},defaultProfile:c,authoritativeSourceFiles:vr(e)},k=pa(e);return k?.terminologyGlossary&&(m.terminologyGlossary=k.terminologyGlossary),kr(m,e),xr(e),console.log(""),console.log(_(`\u2713 Wrote ${t}`)),console.log(""),console.log("Next:"),console.log(` ${j(`d360-writer login --profile ${c}`)} ${f("(sign in; pick the project)")}`),console.log(' Then ask the agent: "analyze this repo and propose a docs structure"'),console.log(""),{kind:"continue"}}function br(e){let t=Xt(e,"package.json");if(!nt(t))return null;try{return JSON.parse(ca(t,"utf8")).name??null}catch{return null}}function vr(e){let t=[];for(let o of["README.md","ARCHITECTURE.md","CLAUDE.md"])nt(Xt(e,o))&&t.push(o);for(let o of["src","api","docs"]){let n=Xt(e,o);nt(n)&&!ma(n)&&t.push(o)}return t}function ma(e){try{return ua(e,{withFileTypes:!0}).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).length>6}catch{return!1}}q();import{readMcpConfig as Mo,writeMcpConfig as Cr}from"document360-engine";async function Kt(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(ga(),{kind:"continue"}):t==="add"?(ha(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(ka(e.slice(1)),{kind:"continue"}):(console.log(b(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function ga(){let e=Mo(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
|
|
9
9
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
10
|
-
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let
|
|
11
|
-
`)}var
|
|
12
|
-
`)}async function
|
|
13
|
-
`),display:"/audit"}}
|
|
14
|
-
`);return
|
|
15
|
-
`)||
|
|
16
|
-
`},r=
|
|
17
|
-
`),
|
|
18
|
-
`)}),
|
|
19
|
-
`)},
|
|
20
|
-
`)}function
|
|
21
|
-
`);return" \u2022 "+
|
|
10
|
+
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let o of t){let n=e.servers[o];if(n.type==="stdio")console.log(` ${j(o)} ${f("(stdio)")} ${n.command} ${(n.args??[]).join(" ")}`);else{let r=Object.keys(n.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${j(o)} ${f(`(${n.type})`)} ${n.url}${s}`)}}console.log("")}function ha(e){let[t,o,...n]=e;if(!t||!o||n.length===0){console.log(b("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(o!=="stdio"&&o!=="http"&&o!=="sse"){console.log(b(`Unknown transport: ${o}. Use stdio, http, or sse.`));return}let r=Mo(),s;if(o==="stdio")s={type:"stdio",command:n[0],args:n.slice(1)};else{let c={};for(let d=1;d<n.length;d++)if(n[d]==="-H"||n[d]==="--header"){let m=n[++d],k=m?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(b(`-H expects key:value (no spaces). Got: ${m??"(nothing)"}`));return}c[k[1].trim()]=k[2].trim()}else{console.log(b(`Unexpected argument: ${n[d]}. After the URL, only -H key:value is allowed.`));return}s={type:o,url:n[0],headers:Object.keys(c).length>0?c:void 0}}r.servers[t]=s,Cr(r),console.log(""),console.log(_(`\u2713 Registered "${t}" (${o})`)),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 ka(e){let t=e[0];if(!t){console.log(b("Usage: /mcp remove <name>"));return}let o=Mo();if(!o.servers[t]){console.log(b(`No server named "${t}".`));return}delete o.servers[t],Cr(o),console.log(_(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}q();import{select as wa}from"@inquirer/prompts";import{computeSyncStatus as Pr}from"document360-engine";function Qt(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, strip every <!-- SCREENSHOT ... --> block while keeping the visible [Screenshot: ...] line, normalize cross-article links).","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself \u2014 do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
|
|
11
|
+
`)}var Sr={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Jt(e){return e.filter(t=>t.path!==null&&t.status in Sr).map(t=>({path:t.path,label:Sr[t.status]}))}function xt(e){return[`Run the publish-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures) and remind me drafts need review in the portal."].join(`
|
|
12
|
+
`)}async function Tr(e,t){let o=e[0];if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let n=Jt((await Pr({cwd:t?.cwd??process.cwd()})).entries);return n.length===0?(console.log(_("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):{kind:"forward-to-agent",prompt:xt(n.map(r=>r.path)),display:"/publish --all"}}catch(n){return console.log(b(`Could not compute sync status: ${n.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let n;try{n=Jt((await Pr({cwd:t?.cwd??process.cwd()})).entries)}catch(r){return console.log(b(`Could not compute sync status: ${r.message}`)),console.log(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(n.length===0)return console.log(_("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(f(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let r of n)console.log(` ${r.path} ${f(`(${r.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>wa({message:"Publish which article?",choices:[...n.length>1?[{name:`All ${n.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...n.map(r=>({name:r.path,value:r.path,description:r.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return{kind:"forward-to-agent",prompt:xt(n.map(r=>r.path)),display:"/publish --all"}}return{kind:"forward-to-agent",prompt:Qt(o),display:`/publish ${o}`}}async function Zt(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | adopt) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
|
|
13
|
+
`),display:"/audit"}}q();import{checkbox as ya}from"@inquirer/prompts";import{inventoryRepo as xa,readProjectConfig as Rr,writeProjectConfig as $a}from"document360-engine";function Lo(e,t){let o=Rr(e);o&&(o.authoritativeSourceFiles=t,$a(o,e))}function eo(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 jr(e,t){let o=t?.cwd??process.cwd();if(!Rr(o))return console.log(b("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let n=xa(o);if(n.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(j("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of n)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(eo(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>ya({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:n.map(s=>({name:`${s.path} (${eo(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(f("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};Lo(o,r),console.log(_(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}q();import{confirm as Sa}from"@inquirer/prompts";import{applyPull as _r,computeSyncStatus as Nr,planPull as Ta,D360AuthError as Ra}from"document360-engine";q();var Ar=[{status:"conflict",header:"Conflicts \u2014 both sides changed; pick a direction (/sync pull <path> or /publish <path>):",paint:b,mark:"!"},{status:"local-ahead",header:"Local ahead \u2014 push with /publish <path>:",paint:O,mark:"M"},{status:"remote-ahead",header:"Remote ahead \u2014 pull with /sync pull <path>:",paint:j,mark:"M"},{status:"deleted-local",header:"Deleted locally \u2014 still on Document360 (pull to restore, or remove from the map):",paint:b,mark:"D"},{status:"deleted-remote",header:"Deleted on Document360 \u2014 still local (publish to recreate, or delete the file):",paint:b,mark:"D"},{status:"orphaned",header:"Orphaned map entries \u2014 gone on both sides (remove from d360-category-map.json):",paint:Z,mark:"X"},{status:"untracked-local",header:"Untracked local articles \u2014 publish to start tracking:",paint:f,mark:"?"},{status:"untracked-remote",header:"Untracked Document360 articles \u2014 no local file maps to them:",paint:f,mark:"?"},{status:"unknown-base",header:"No sync base recorded yet \u2014 the next /publish or /sync pull of each records one:",paint:Z,mark:"\xB7"}];function ba(e){return e.path?e.path:`${e.title??"(untitled)"} ${Z(`[${e.articleId}]`)}`}function to(e){let t=[];for(let c of Ar){let d=e.entries.filter(m=>m.status===c.status);if(d.length!==0){t.push(""),t.push(Pe(c.header));for(let m of d)t.push(` ${c.paint(c.mark)} ${c.paint(ba(m))}${m.detail?Z(` (${m.detail})`):""}`)}}let o=e.counts["in-sync"]??0,n=e.entries.length;t.push("");let r={"in-sync":"in sync","local-ahead":"local ahead","remote-ahead":"remote ahead",conflict:"conflicts","untracked-local":"untracked local","untracked-remote":"untracked remote","deleted-local":"deleted locally","deleted-remote":"deleted on D360",orphaned:"orphaned","unknown-base":"no base yet"},s=n===o?_("\u2713 everything in sync"):[o>0?_(`\u2713 ${o} in sync`):null,...Ar.map(c=>{let d=e.counts[c.status]??0;return d>0?`${d} ${r[c.status]}`:null})].filter(Boolean).join(Z(" \xB7 "));return t.push(s+Z(` \xB7 ${n} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/`)),t}import{structuredPatch as va}from"diff";import Er from"picocolors";var Dr=80,Ca="\x1B[48;2;74;28;28m",Pa="\x1B[48;2;24;66;24m",Ir="\x1B[49m",Oo=e=>String(e).padStart(5);function He(e,t,o){let n=x=>{let v=x.replace(/\r\n/g,`
|
|
14
|
+
`);return v.endsWith(`
|
|
15
|
+
`)||v===""?v:v+`
|
|
16
|
+
`},r=n(e),s=n(t);if(r===s)return null;let c=Math.max(20,o-10),d=va("a","b",r,s,"","",{context:3}),m=0,k=0,y=[];d.hunks.forEach((x,v)=>{v>0&&y.push(Er.gray(" \u2026"));let $=x.oldStart,D=x.newStart;for(let N of x.lines){let H=N[0],Q=N.slice(1).slice(0,c);H==="-"?(k++,y.push(`${Ca}${Oo($++)} - ${Q}${Ir}`)):H==="+"?(m++,y.push(`${Pa}${Oo(D++)} + ${Q}${Ir}`)):(y.push(Er.gray(Oo(D))+" "+Q),$++,D++)}});let E=y.slice(0,Dr);return{added:m,removed:k,lines:E,hidden:Math.max(0,y.length-Dr)}}async function Mr(e,t){let o=(e[0]??"status").toLowerCase();try{if(o==="status")return await ja(t.cwd),{kind:"continue"};if(o==="pull")return await Aa(t,e.slice(1)),{kind:"continue"};console.log(b(`Unknown subcommand: /sync ${o}`)),console.log(f("Usage: /sync drift report (local vs Document360)")),console.log(f(" /sync pull <path> pull portal edits into the local file")),console.log(f(" /sync pull --all pull every remote-ahead article"))}catch(n){n instanceof Ra?console.log(b(n.message)):console.log(b(`Sync failed: ${n.message}`))}return{kind:"continue"}}async function ja(e){console.log(f("Checking Document360 for drift\u2026"));let t=await Nr({cwd:e});for(let o of to(t))console.log(o);console.log("")}async function Aa(e,t){let o=t[0];if(!o){console.log(b("Usage: /sync pull <article-path> | --all"));return}let n;if(o==="--all"){if(console.log(f("Checking Document360 for drift\u2026")),n=(await Nr({cwd:e.cwd})).entries.filter(s=>s.status==="remote-ahead"&&s.path).map(s=>s.path),n.length===0){console.log(_("\u2713 Nothing is remote-ahead \u2014 no pulls needed.")),console.log(f(" (conflicts are never bulk-pulled; pull them one by one: /sync pull <path>)"));return}console.log(`${Pe(String(n.length))} article(s) are remote-ahead.`)}else n=[o.replace(/\\/g,"/")];for(let r of n){let s=await Ta({cwd:e.cwd,relPath:r});console.log(""),console.log(`${j("\u25CF")} ${Pe(s.title)} ${Z(`(${s.path})`)}`);for(let k of s.notes)console.log(O(` \u26A0 ${k}`));s.overwritesLocalChanges&&console.log(O(" \u26A0 This OVERWRITES local edits made since the last sync."));let c=He(s.oldContent,s.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!c){console.log(f(" Local file already matches the remote content \u2014 advancing the sync base only.")),_r({cwd:e.cwd},s);continue}let d=k=>k===1?"":"s";console.log(Z(` \u23BF Added ${c.added} line${d(c.added)}, removed ${c.removed} line${d(c.removed)}`));for(let k of c.lines)console.log(k);if(c.hidden>0&&console.log(f(` \u2026 +${c.hidden} more diff lines`)),!await e.withPausedInput(()=>Sa({message:`Write ${s.path}?`,default:!s.overwritesLocalChanges}))){console.log(f(" Skipped."));continue}_r({cwd:e.cwd},s),console.log(_(` \u2713 Pulled ${s.path} (sync base advanced).`))}console.log("")}q();import{statSync as Ha}from"node:fs";import{resolve as Fa}from"node:path";import{estimateBulkCost as Ba,planPartitions as qa,readProjectConfig as Ga,resolveModelForOperation as za,runPartitioned as Ya,trackedArticlePaths as Va}from"document360-engine";import z from"picocolors";import Fr from"wrap-ansi";import qo from"string-width";q();import Ee from"picocolors";import Uo from"wrap-ansi";import Wo from"string-width";var Lr=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Or=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Ur=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Ea(e){let t=e.replace(/\r/g,"").split(`
|
|
17
|
+
`),o=[],n=0;for(;n<t.length;){let r=t[n];if(/^\s*```/.test(r)){let d=[];for(n++;n<t.length&&!/^\s*```/.test(t[n]);)d.push(t[n++]);n++,o.push({kind:"code",lines:d});continue}if(Lr(r)){o.push({kind:"hr"}),n++;continue}if(r.includes("|")&&n+1<t.length&&Or(t[n+1])){let d=Ur(r);n+=2;let m=[];for(;n<t.length&&t[n].includes("|")&&t[n].trim()!=="";)m.push(Ur(t[n++]));o.push({kind:"table",header:d,rows:m});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){o.push({kind:"heading",level:s[1].length,text:s[2]}),n++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let d=[];for(;n<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[n]);)d.push(t[n++].replace(/^\s*([-*]|\d+\.)\s+/,""));o.push({kind:"list",items:d});continue}if(r.trim()===""){n++;continue}let c=[];for(;n<t.length&&t[n].trim()!==""&&!/^\s*```/.test(t[n])&&!/^(#{1,6})\s/.test(t[n])&&!/^\s*([-*]|\d+\.)\s+/.test(t[n])&&!Lr(t[n])&&!(t[n].includes("|")&&n+1<t.length&&Or(t[n+1]));)c.push(t[n++]);o.push({kind:"para",text:c.join(" ")})}return o}function Ho(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ee.bold(t.slice(2,-2)):t.startsWith("`")?j(t.slice(1,-1)):Ee.italic(t.slice(1,-1)))}var Da=(e,t)=>e+" ".repeat(Math.max(0,t-Wo(e)));function Ia(e,t,o){let n=e.length,r=e.map(($,D)=>Math.max(Wo($),...t.map(N=>Wo(N[D]??"")))),s=Math.max(24,o),c=3*n+1,d=[...r],m=()=>d.reduce(($,D)=>$+D,0)+c,k=0;for(;m()>s&&k++<1e4;){let $=-1,D=6;for(let N=0;N<n;N++)d[N]>D&&(D=d[N],$=N);if($===-1)break;d[$]-=1}let y=($,D,N)=>Ee.gray($+d.map(H=>"\u2500".repeat(H+2)).join(D)+N),E=Ee.gray("\u2502"),x=($,D)=>{let N=d.map((me,ye)=>{let ge=$[ye]??"",he=D?Ee.bold(ge):Ho(ge);return Uo(he,me,{hard:!0}).split(`
|
|
18
|
+
`)}),H=Math.max(...N.map(me=>me.length)),Q=[];for(let me=0;me<H;me++)Q.push(d.map((ye,ge)=>`${E} ${Da(N[ge][me]??"",ye)} `).join("")+E);return Q.join(`
|
|
19
|
+
`)},v=[y("\u250C","\u252C","\u2510"),x(e,!0)];return v.push(t.length===0?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524")),t.forEach(($,D)=>{v.push(x($,!1)),v.push(D===t.length-1?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524"))}),v.join(`
|
|
20
|
+
`)}function _a(e,t){switch(e.kind){case"heading":return Ee.bold(e.text);case"hr":return Ee.gray("\u2500".repeat(t));case"para":return Uo(Ho(e.text),t);case"list":return e.items.map(o=>{let[n="",...r]=Uo(Ho(o),Math.max(10,t-4)).split(`
|
|
21
|
+
`);return" \u2022 "+n+r.map(s=>`
|
|
22
22
|
`+s).join("")}).join(`
|
|
23
|
-
`);case"code":return e.lines.map(
|
|
24
|
-
`);case"table":return
|
|
23
|
+
`);case"code":return e.lines.map(o=>Ee.gray(" "+o)).join(`
|
|
24
|
+
`);case"table":return Ia(e.header,e.rows,t)}}function Fo(e,t){let o=Math.max(20,t);return Ea(e).map(n=>_a(n,o)).join(`
|
|
25
25
|
|
|
26
|
-
`)}
|
|
27
|
-
`);let r=2,s=3,c=
|
|
28
|
-
`);let
|
|
29
|
-
`)}var
|
|
30
|
-
`).flatMap(k=>
|
|
31
|
-
`)),
|
|
32
|
-
`+d.map((k,y)=>
|
|
26
|
+
`)}q();import Na from"picocolors";var Ma=[127,86,217],La=[22,38,43],Wr={T:Ma,E:La},$t=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Bo=([e,t,o])=>`\x1B[38;2;${e};${t};${o}m`,Oa=([e,t,o])=>`\x1B[48;2;${e};${t};${o}m`;function Hr(){if(!Na.isColorSupported)return[];let e=$t[0].length,t=[];for(let o=0;o<$t.length;o+=2){let n="";for(let r=0;r<e;r++){let s=Wr[$t[o][r]],c=o+1<$t.length?Wr[$t[o+1][r]]:void 0;s&&c?n+=`${Bo(s)}${Oa(c)}\u2580\x1B[49m\x1B[39m`:s?n+=`${Bo(s)}\u2580\x1B[39m`:c?n+=`${Bo(c)}\u2584\x1B[39m`:n+=" "}t.push(n)}return t}function bt(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function fe(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function st(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var rt=(e,t)=>` ${e.padEnd(13)}${t}`;function Ua(e,t){let o=[gt("\u270E document360-writer")+z.gray(` v${e.version}`),z.gray(" Reads your code, writes your docs."),"",rt("Claude:",`${e.claude}${z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),rt("Document360:",e.configured?e.loggedOut?z.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?z.gray(` (${e.sessionHint})`):""}`:z.yellow("not set up \u2014 run /init")),rt("Profile:",e.configured?`${e.profile}${z.gray(` (${e.apiUrl})`)}${e.prod?z.bold(z.yellow(" \u26A0 PRODUCTION")):""}`:z.gray("\u2014 (run /init)")),rt("Project:",e.project),rt("Mode:",z.gray(e.mode)),rt("cwd:",z.gray(e.cwd))],n=Hr();if(n.length===0)return o.join(`
|
|
27
|
+
`);let r=2,s=3,c=qo(n[0]);if(!(t>=r+c+s+Math.max(...o.map(y=>qo(y)))))return[...n.map(y=>" "+y),...o].join(`
|
|
28
|
+
`);let m=Math.max(0,Math.floor((o.length-n.length)/2)),k=[];for(let y=0;y<Math.max(n.length+m,o.length);y++){let E=n[y-m]??" ".repeat(c);k.push((" ".repeat(r)+E+" ".repeat(s)+(o[y]??"")).trimEnd())}return k.join(`
|
|
29
|
+
`)}var Wa={error:z.red,warn:z.yellow,ok:z.green,info:z.gray};function Go(e,t){let o=Math.max(20,t);switch(e.kind){case"banner":return Ua(e.info,o);case"user":{let n="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,o-4),c=50,d=e.text.split(`
|
|
30
|
+
`).flatMap(k=>Fr(k,s,{hard:!0}).split(`
|
|
31
|
+
`)),m=Math.max(0,d.length-c);return m>0&&(d=[...d.slice(0,c),z.dim(`\u2026 +${m} more lines`)]),`
|
|
32
|
+
`+d.map((k,y)=>n+(y===0?j(" \u276F "):" ")+k+" ".repeat(Math.max(0,s-qo(k))+1)+r).join(`
|
|
33
33
|
`)}case"assistant":return`
|
|
34
|
-
`+
|
|
35
|
-
`+
|
|
36
|
-
`)}case"diff":{let
|
|
37
|
-
`)}case"link":return e.lines.map(
|
|
34
|
+
`+Fo(e.text,o);case"tool":{let n=e.arg!==null?z.gray(`${e.sep}(${e.arg})`):"";return`
|
|
35
|
+
`+Fr(z.green("\u25CF ")+z.bold(e.title)+n,o)}case"tool-result":{let n=e.isError?z.red:z.gray,r=e.lines.map((s,c)=>n((c===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(z.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
36
|
+
`)}case"diff":{let n=c=>c===1?"":"s",s=[z.gray(` \u23BF Added ${e.added} line${n(e.added)}, removed ${e.removed} line${n(e.removed)}`),...e.lines];return e.hidden>0&&s.push(z.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
|
|
37
|
+
`)}case"link":return e.lines.map(n=>j(kt(` \u2B95 ${n}`))).join(`
|
|
38
38
|
`);case"preview":return`
|
|
39
|
-
`+
|
|
39
|
+
`+gt(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
40
40
|
|
|
41
|
-
`+
|
|
42
|
-
`+
|
|
43
|
-
`+(e.ok?
|
|
44
|
-
`)}var
|
|
41
|
+
`+Fo(e.text,o);case"note":return`
|
|
42
|
+
`+Wa[e.tone](kt(e.text));case"done":return`
|
|
43
|
+
`+(e.ok?z.magenta("\u2736 "):z.red("\u2736 "))+z.gray(`Cooked for ${bt(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${fe(e.costUsd)}`:""))}}function Br(e,t){return e.map(o=>Go(o,t)).join(`
|
|
44
|
+
`)}var zo=3;function Yo(e){let t,o=!1;for(let r=0;r<e.length;r++){let s=e[r];s==="--run"||s==="--yes"?o=!0:s==="--scope"?t=e[++r]:s?.startsWith("--scope=")&&(t=s.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:o}}function Vo(e,t){return t?e.filter(o=>{let n=o.replace(/\\/g,"/");return n===t||n.startsWith(`${t}/`)}):e}function Xo(e,t){return t.map(o=>{let n=0;try{n=Ha(Fa(e,o)).size}catch{n=0}return{path:o,bytes:n}})}function Ko(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite \u2014 be efficient:
|
|
45
45
|
- Read ONLY the article files listed below. Do NOT read source code, other articles, or fetch the live portal \u2014 you already have everything you need.
|
|
46
46
|
- Convert in place: wrap callouts, FAQs, tabs, accordions, and media embeds per the d360-markdown skill. Preserve all wording, headings, and structure; change only GFM\u2192DFM syntax.
|
|
47
47
|
- Publish each as a draft with a single update call. Do NOT re-read, re-verify, or polish after converting, and skip articles already in DFM.
|
|
48
48
|
- Work only on these files:
|
|
49
49
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
50
|
-
`)}function
|
|
50
|
+
`)}function Jo(e,t,o){let n=e.reduce((d,m)=>d+m.paths.length,0),[r,s]=t.usd;return[`Convert ${n} article${n===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${o} agents at once):`,...e.map(d=>` \u2022 ${d.label} \u2014 ${d.paths.length} article${d.paths.length===1?"":"s"}`),"",`Estimated cost: ${fe(r)}\u2013${fe(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Qo(e,t,o){let n=$=>t[$.index]?.paths.length??0,r=e.filter($=>$.ok),s=e.filter($=>!$.ok),c=e.reduce(($,D)=>$+n(D),0),d=r.reduce(($,D)=>$+n(D),0),m=e.reduce(($,D)=>$+D.costUsd,0),k=e.reduce(($,D)=>$+D.outputTokens,0),y=o==="api"?`${fe(m)} total`:st(k),E=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=$=>`${$} article${$===1?"":"s"}`,v=[];if(s.length===0)v.push(`Converted ${x(c)} (${E}) successfully \xB7 ${y}.`);else{v.push(`Converted ${d}/${x(c)} (${E}) \xB7 ${y}.`),v.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let $ of s)v.push(` \u2717 ${$.label}${$.error?` \u2014 ${$.error}`:""}`)}return v}async function qr(e,t){if(!Ga(t.cwd))return console.log(b("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:o,run:n}=Yo(e),r=Va(t.cwd,t.profileName);if(r.length===0)return console.log(b("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Vo(r,o);if(s.length===0)return console.log(b(`No tracked articles under "${o}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=qa(s),d=`/convert${o?` --scope ${o}`:""} --run`,{model:m,forced:k}=za(t.cwd,"light");if(!n){let y=Ba({files:Xo(t.cwd,s),op:"convert",model:m});o&&console.log(f(`Scope: ${o} (${s.length} of ${r.length} tracked articles).`));for(let E of Jo(c,y,zo))console.log(E);return console.log(f(`Model: ${m}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${d} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${c.length} partitions (\u2264${zo} agents at once) on ${m}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let y of Ya({cwd:t.cwd,partitions:c,promptFor:Ko,concurrency:zo,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:m}))if(y.type==="partition_status")y.status==="running"?console.log(f(` \u25B8 ${y.label} \u2014 converting\u2026`)):y.status==="done"?console.log(_(` \u2713 ${y.label}`)):console.log(b(` \u2717 ${y.label}`));else if(y.type==="run_done"){console.log("");let E=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let x of Qo(y.results,c,E))console.log(y.ok?_(x):O(x))}}catch(y){console.log(b(`Convert run failed: ${y.message}`))}return console.log(""),{kind:"continue"}}q();import{statSync as Gr}from"node:fs";import{resolve as zr}from"node:path";import{estimateBulkCost as Xa,planPartitions as Ka,readDocsPlan as Ja,readProjectConfig as Yr,resolveModelForOperation as Qa,runPartitioned as Za}from"document360-engine";var Zo=5;function en(e){let t,o,n=!1;for(let s=0;s<e.length;s++){let c=e[s];if(c==="--run"||c==="--yes")n=!0;else{if(c==="--all")continue;c==="--scope"?t=e[++s]:c?.startsWith("--scope=")?t=c.slice(8):c&&!c.startsWith("--")&&(o=c)}}let r=s=>s?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:r(t),path:r(o),run:n}}function el(e,t){let o=e.replace(/\\/g,"/").replace(/\/+$/,""),n=`${t.replace(/\/+$/,"")}/`;return o.startsWith(n)?o.slice(n.length):o}function tl(e,t){return t?e.filter(o=>{let n=o.replace(/\\/g,"/");return n===t||n.startsWith(`${t}/`)}):e}function ol(e,t,o){return o.filter(n=>{try{return Gr(zr(e,t,n)).size===0}catch{return!0}})}function tn(e,t,o){let n=new Map(t.map(r=>[r.path,r]));return o.map(r=>{let s=1;for(let c of n.get(r)?.sources??[])try{s+=Gr(zr(e,c)).size}catch{}return{path:r,bytes:s}})}function on(e,t){return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
51
51
|
- It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose and the source files it draws from (AGENT-PLAN.md has the same table).
|
|
52
52
|
- Read ONLY those source files plus any shared context you genuinely need, and ground every statement in them. Never invent UI labels, routes, or behaviour \u2014 if the source does not say it, omit it.
|
|
53
53
|
- Write the finished article to ${t}/<path>, following the write-article structure and the project terminologyGlossary. Add the \`sources:\` frontmatter listing the files you actually read.
|
|
54
54
|
- Emit \`<!-- SCREENSHOT -->\` placeholders where a visual helps, but do NOT author capture specs now.
|
|
55
55
|
- Each article is independent. Do NOT write, edit, or publish any article not in this list, and do NOT publish to Document360 \u2014 these are local drafts.
|
|
56
56
|
Articles:
|
|
57
|
-
`+e.paths.map(
|
|
58
|
-
`)}function eo(e,t,n){let o=e.reduce((c,d)=>c+d.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${fe(r)}\u2013${fe(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write --run to start."]}function to(e,t,n){let o=$=>t[$.index]?.paths.length??0,r=e.filter($=>$.ok),s=e.filter($=>!$.ok),c=e.reduce(($,N)=>$+o(N),0),d=r.reduce(($,N)=>$+o(N),0),g=e.reduce(($,N)=>$+N.costUsd,0),k=e.reduce(($,N)=>$+N.outputTokens,0),y=n==="api"?`${fe(g)} total`:rt(k),I=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=$=>`${$} article${$===1?"":"s"}`,C=[];if(s.length===0)C.push(`Wrote ${b(c)} (${I}) successfully \xB7 ${y}.`),C.push("Review them in the docs tree, then /publish when ready.");else{C.push(`Wrote ${d}/${b(c)} (${I}) \xB7 ${y}.`),C.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let $ of s)C.push(` \u2717 ${$.label}${$.error?` \u2014 ${$.error}`:""}`)}return C}function no(e,t,n){let o=(Br(e)?.docsDir??"user-docs").replace(/\/+$/,""),r=t.map(d=>d.path);if(n.path){let d=Xa(n.path,o);return r.includes(d)?{docsDir:o,targets:[d],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${d}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=Ja(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};let c=Ka(e,o,s);if(c.length===0){let d=n.scope?` under "${n.scope}"`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${d} are already written. Use /write <path> to rewrite one.`}}return{docsDir:o,targets:c,planCount:r.length}}async function qr(e,t){if(!Br(t.cwd))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=za(t.cwd);if(n.length===0)return console.log(x("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,run:s}=Kn(e),{docsDir:c,targets:d,reason:g}=no(t.cwd,n,{scope:o,path:r});if(d.length===0)return console.log(g?L(g):L("Nothing to write.")),{kind:"continue"};let k=Ga(d),{model:y,forced:I}=Ya(t.cwd,"standard");if(!s&&!!!r){let C=qa({files:Qn(t.cwd,n,d),op:"write",model:y});o&&console.log(f(`Scope: ${o} (${d.length} pending).`));for(let $ of eo(k,C,Jn))console.log($);return console.log(f(`Model: ${y}${I?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:" --all"} --run to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${d.length} article${d.length===1?"":"s"} across ${k.length} partition${k.length===1?"":"s"} (\u2264${Jn} agents at once) on ${y}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let C of Va({cwd:t.cwd,partitions:k,promptFor:$=>Zn($,c),concurrency:Jn,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:y}))if(C.type==="partition_status")C.status==="running"?console.log(f(` \u25B8 ${C.label} \u2014 writing\u2026`)):C.status==="done"?console.log(E(` \u2713 ${C.label}`)):console.log(x(` \u2717 ${C.label}`));else if(C.type==="run_done"){console.log("");let $=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let N of to(C.results,k,$))console.log(C.ok?E(N):L(N))}}catch(C){console.log(x(`Write run failed: ${C.message}`))}return console.log(""),{kind:"continue"}}H();import{search as Qa}from"@inquirer/prompts";import{findByName as Za,getSession as el,listSessions as tl,relativeTime as zr}from"document360-engine";async function Yr(e,t){let n=tl(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=Za(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(x(`No session matches "${o}".`)),Gr(n),{kind:"continue"})}if(!process.stdin.isTTY)return Gr(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Qa({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return n.filter(d=>!c||d.name.toLowerCase().includes(c)||d.firstPrompt.toLowerCase().includes(c)).map(d=>({name:`${d.name} ${zr(d.updatedAt)}`,value:d.uuid,description:d.firstPrompt.slice(0,100)}))}})),r=el(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Gr(e){console.log("");for(let t of e.slice(0,15))console.log(` ${R(t.name)} ${f(zr(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}H();import{renameSession as nl}from"document360-engine";function oo(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 Vr(e,t){let n=oo(e.join(" "));if(!n)return console.log(x("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(nl(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log(x("Could not find the current session record.")),{kind:"continue"}):(console.log(x("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as Xr,readProjectConfig as ol,writeProjectConfig as rl}from"document360-engine";H();function ro(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=ol(e);if(!o)return"No .d360-writer.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return Xr().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},rl(o,e),null):`Unknown environment "${r}". Known: ${Xr().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function Jr(e,t){let n=e[0];if(!n)return qt(t.cwd),{kind:"continue"};if(n==="add"){let o=ro(t.cwd,e[1],e[2]);return o?(console.log(x(o)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${R(`/profile ${e[1]}`)} then ${R("/login")}`),{kind:"continue"})}return Gt(t.cwd,n),zt(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}H();import{select as sl}from"@inquirer/prompts";import{readProjectConfig as il,readUserConfig as Kr,resolveModelSetting as so,writeUserConfig as Qr}from"document360-engine";var we=[{value:null,label:"Auto",desc:"Engine right-sizes per task \u2014 Sonnet for routine work, Opus for analysis (recommended)"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus 4.8 \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet 4.6 \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku 4.5 \xB7 fastest for quick answers"}];function tn(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=we.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function al(e){switch(e.source){case"project":return".d360-writer.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"claude-settings":return"Claude Code's own settings (~/.claude/settings.json)";case"claude-default":return"Claude Code default (no override configured)"}}function bt(e,t){let n=()=>{let s=so(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Kr();return s.defaultModel?(delete s.defaultModel,Qr(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${so(e).model??"Claude Code default"} (applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}Qr({...Kr(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=il(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function Zr(e,t){let n=e[0]?.trim();if(!n){let c=so(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${R(c.model??"Claude Code default")}`),console.log(f(` source: ${al(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let d=tn(c),g;try{g=await t.withPausedInput(()=>sl({message:`Select model (current: ${c.model??"Claude Code default"})`,default:we[d].value,choices:we.map((b,C)=>({name:`${b.label}${C===d?" \u2714":""}`,value:b.value,description:b.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:y,effective:I}=bt(t.cwd,g??"default");for(let b of k)console.log(b.startsWith("\u26A0")?L(b):b.startsWith("\u2713")?E(b):f(b));return y&&await t.setModel(I),{kind:"continue"}}let{lines:o,changed:r,effective:s}=bt(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?L(c):c.startsWith("\u2713")?E(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}nn();async function rs(e,t){return await t.withPausedInput(()=>tt(t.cwd)),{kind:"clear"}}H();import{select as wl}from"@inquirer/prompts";import{resolveActiveProfile as yl,setProfileProject as xl,listProjects as $l}from"document360-engine";async function ao(e,t){let n=yl(e,t),o={profile:n.name,connection:n.connection};return{projects:await $l(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ss=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function is(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 lo(e,t,n){xl(e,t,{projectId:n,workspaceId:void 0,workspaceName:void 0})}async function as(e,t){let n;try{n=await ao(e,t)}catch(g){console.log(x(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===s?R("\u25CF"):" "} ${ss(g)} ${f(g.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await wl({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${ss(g)}${g.id===s?" (current)":""}`,value:g.id}))});lo(e,r,c);let d=o.find(g=>g.id===c);console.log(E(`\u2713 Project set to "${d?.name??c}" for profile "${r}". Next: pick a workspace.`))}async function ls(e,t){return await t.withPausedInput(()=>as(t.cwd,t.profileName)),{kind:"clear"}}H();import{resolveActiveProfile as bl}from"document360-engine";async function cs(e,t){let n=!1;try{n=bl(t.cwd).production}catch{}return n?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}H();var us=async(e,t)=>{try{await t.withPausedInput(()=>Bt({}))}catch(n){console.log(x(`Login failed: ${n.message}`))}return{kind:"continue"}};H();import{resolveActiveProfile as vl,clearTokens as Cl,clearProfileProject as Pl}from"document360-engine";async function ds(e,t){let n;try{n=vl(t.cwd,t.profileName).name}catch(r){return console.log(x(r.message)),{kind:"continue"}}let o=Cl(n);return Pl(t.cwd,n),console.log(o?E(`\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 ps}from"node:fs";import{isAbsolute as Sl,join as Tl,resolve as Rl}from"node:path";import{readProjectConfig as jl,screenshotPlaceholderIds as Al}from"document360-engine";var fs=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function co(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?fs(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:fs(o),setup:t}:{mode:"single",id:o}}function uo(e,t){let n=jl(e),o=n?.captureDir??"user-docs/_capture",r=n?.outputDir??"user-docs/_screenshots",s=(c,d)=>Sl(c)?Tl(c,d):Rl(e,c,d);return Al(e,{scope:t}).map(({id:c,file:d})=>{let g=ps(s(r,`${c}.png`))?"captured":ps(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:d,state:g}})}var El={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Dl={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function po(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(s=>s.file))].sort(),o=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of n){r.push(s);for(let c of e.filter(d=>d.file===s))r.push(` ${El[c.state]} ${c.id.padEnd(34)} ${Dl[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function ms(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(`
|
|
57
|
+
`+e.paths.map(o=>`- ${o}`).join(`
|
|
58
|
+
`)}function nn(e,t,o){let n=e.reduce((c,d)=>c+d.paths.length,0),[r,s]=t.usd;return[`Write ${n} article${n===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${o} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${fe(r)}\u2013${fe(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write --run to start."]}function rn(e,t,o){let n=$=>t[$.index]?.paths.length??0,r=e.filter($=>$.ok),s=e.filter($=>!$.ok),c=e.reduce(($,D)=>$+n(D),0),d=r.reduce(($,D)=>$+n(D),0),m=e.reduce(($,D)=>$+D.costUsd,0),k=e.reduce(($,D)=>$+D.outputTokens,0),y=o==="api"?`${fe(m)} total`:st(k),E=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=$=>`${$} article${$===1?"":"s"}`,v=[];if(s.length===0)v.push(`Wrote ${x(c)} (${E}) successfully \xB7 ${y}.`),v.push("Review them in the docs tree, then /publish when ready.");else{v.push(`Wrote ${d}/${x(c)} (${E}) \xB7 ${y}.`),v.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let $ of s)v.push(` \u2717 ${$.label}${$.error?` \u2014 ${$.error}`:""}`)}return v}function sn(e,t,o){let n=(Yr(e)?.docsDir??"user-docs").replace(/\/+$/,""),r=t.map(d=>d.path);if(o.path){let d=el(o.path,n);return r.includes(d)?{docsDir:n,targets:[d],planCount:r.length}:{docsDir:n,targets:[],planCount:r.length,reason:`"${d}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=tl(r,o.scope);if(o.scope&&s.length===0)return{docsDir:n,targets:[],planCount:r.length,reason:`No planned articles under "${o.scope}".`};let c=ol(e,n,s);if(c.length===0){let d=o.scope?` under "${o.scope}"`:"";return{docsDir:n,targets:[],planCount:r.length,reason:`All planned articles${d} are already written. Use /write <path> to rewrite one.`}}return{docsDir:n,targets:c,planCount:r.length}}async function Vr(e,t){if(!Yr(t.cwd))return console.log(b("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ja(t.cwd);if(o.length===0)return console.log(b("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:n,path:r,run:s}=en(e),{docsDir:c,targets:d,reason:m}=sn(t.cwd,o,{scope:n,path:r});if(d.length===0)return console.log(m?O(m):O("Nothing to write.")),{kind:"continue"};let k=Ka(d),{model:y,forced:E}=Qa(t.cwd,"standard");if(!s&&!!!r){let v=Xa({files:tn(t.cwd,o,d),op:"write",model:y});n&&console.log(f(`Scope: ${n} (${d.length} pending).`));for(let $ of nn(k,v,Zo))console.log($);return console.log(f(`Model: ${y}${E?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${n?` --scope ${n}`:" --all"} --run to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${d.length} article${d.length===1?"":"s"} across ${k.length} partition${k.length===1?"":"s"} (\u2264${Zo} agents at once) on ${y}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let v of Za({cwd:t.cwd,partitions:k,promptFor:$=>on($,c),concurrency:Zo,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:y}))if(v.type==="partition_status")v.status==="running"?console.log(f(` \u25B8 ${v.label} \u2014 writing\u2026`)):v.status==="done"?console.log(_(` \u2713 ${v.label}`)):console.log(b(` \u2717 ${v.label}`));else if(v.type==="run_done"){console.log("");let $=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let D of rn(v.results,k,$))console.log(v.ok?_(D):O(D))}}catch(v){console.log(b(`Write run failed: ${v.message}`))}return console.log(""),{kind:"continue"}}q();import{search as nl}from"@inquirer/prompts";import{findByName as rl,getSession as sl,listSessions as il,relativeTime as Kr}from"document360-engine";async function Jr(e,t){let o=il(t.cwd).filter(n=>n.uuid!==t.currentUuid());if(o.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 n=e.join(" "),r=rl(t.cwd,n);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(b(`No session matches "${n}".`)),Xr(o),{kind:"continue"})}if(!process.stdin.isTTY)return Xr(o),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let n=await t.withPausedInput(()=>nl({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return o.filter(d=>!c||d.name.toLowerCase().includes(c)||d.firstPrompt.toLowerCase().includes(c)).map(d=>({name:`${d.name} ${Kr(d.updatedAt)}`,value:d.uuid,description:d.firstPrompt.slice(0,100)}))}})),r=sl(n);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Xr(e){console.log("");for(let t of e.slice(0,15))console.log(` ${j(t.name)} ${f(Kr(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}q();import{renameSession as al}from"document360-engine";function an(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 Qr(e,t){let o=an(e.join(" "));if(!o)return console.log(b("Usage: /rename <new name>")),{kind:"continue"};let n=t.currentUuid();return n?(al(n,o)?console.log(_(`\u2713 Session renamed to "${o}"`)):console.log(b("Could not find the current session record.")),{kind:"continue"}):(console.log(b("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as Zr,readProjectConfig as ll,writeProjectConfig as cl}from"document360-engine";q();function ln(e,t,o){if(!t)return"Usage: /profile add <name> [environment]";let n=ll(e);if(!n)return"No .d360-writer.json \u2014 run /init first.";if(n.profiles?.[t])return`Profile "${t}" already exists.`;let r=o??t;return Zr().includes(r)?(n.profiles={...n.profiles,[t]:{connection:{environment:r},production:!1}},cl(n,e),null):`Unknown environment "${r}". Known: ${Zr().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function es(e,t){let o=e[0];if(!o)return Gt(t.cwd),{kind:"continue"};if(o==="add"){let n=ln(t.cwd,e[1],e[2]);return n?(console.log(b(n)),{kind:"continue"}):(console.log(_(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${j(`/profile ${e[1]}`)} then ${j("/login")}`),{kind:"continue"})}return zt(t.cwd,o),Yt(t.cwd,o),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}q();import{select as ul}from"@inquirer/prompts";import{readProjectConfig as dl,readUserConfig as ts,resolveModelSetting as cn,writeUserConfig as os}from"document360-engine";var we=[{value:null,label:"Auto",desc:"Engine right-sizes per task \u2014 Sonnet for routine work, Opus for analysis (recommended)"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus 4.8 \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet 4.6 \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku 4.5 \xB7 fastest for quick answers"}];function oo(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),o=we.findIndex(n=>n.value!==null&&(n.value===t||n.label.toLowerCase()===t||t.includes(n.label.toLowerCase())));return o>=0?o:0}function pl(e){switch(e.source){case"project":return".d360-writer.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"claude-settings":return"Claude Code's own settings (~/.claude/settings.json)";case"claude-default":return"Claude Code default (no override configured)"}}function vt(e,t){let o=()=>{let s=cn(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=ts();return s.defaultModel?(delete s.defaultModel,os(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${cn(e).model??"Claude Code default"} (applies from your next message)`],changed:!0,effective:o()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}os({...ts(),defaultModel:t});let n=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=dl(e)?.defaultModel;return r&&n.push(`\u26A0 .d360-writer.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:n,changed:!0,effective:o()}}async function ns(e,t){let o=e[0]?.trim();if(!o){let c=cn(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${j(c.model??"Claude Code default")}`),console.log(f(` source: ${pl(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let d=oo(c),m;try{m=await t.withPausedInput(()=>ul({message:`Select model (current: ${c.model??"Claude Code default"})`,default:we[d].value,choices:we.map((x,v)=>({name:`${x.label}${v===d?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:y,effective:E}=vt(t.cwd,m??"default");for(let x of k)console.log(x.startsWith("\u26A0")?O(x):x.startsWith("\u2713")?_(x):f(x));return y&&await t.setModel(E),{kind:"continue"}}let{lines:n,changed:r,effective:s}=vt(t.cwd,o);for(let c of n)console.log(c.startsWith("\u26A0")?O(c):c.startsWith("\u2713")?_(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}no();async function ls(e,t){return await t.withPausedInput(()=>ot(t.cwd)),{kind:"clear"}}q();import{select as vl}from"@inquirer/prompts";import{resolveActiveProfile as Cl,setProfileProject as Pl,listProjects as Sl}from"document360-engine";async function dn(e,t){let o=Cl(e,t),n={profile:o.name,connection:o.connection};return{projects:await Sl(n),profile:o.name,environment:o.connection.name,current:o.project.projectId}}var cs=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function us(e,t){let o=t.toLowerCase();return e.find(n=>(n.name??"").toLowerCase()===o)??e.find(n=>(n.name??"").toLowerCase().startsWith(o))??e.find(n=>n.id.startsWith(t))}function pn(e,t,o){Pl(e,t,{projectId:o,workspaceId:void 0,workspaceName:void 0})}async function ds(e,t){let o;try{o=await dn(e,t)}catch(m){console.log(b(`Could not list projects: ${m.message}`));return}let{projects:n,profile:r,current:s}=o;if(n.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let m of n)console.log(` ${m.id===s?j("\u25CF"):" "} ${cs(m)} ${f(m.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await vl({message:"Select the Document360 project for this repo:",choices:n.map(m=>({name:`${cs(m)}${m.id===s?" (current)":""}`,value:m.id}))});pn(e,r,c);let d=n.find(m=>m.id===c);console.log(_(`\u2713 Project set to "${d?.name??c}" for profile "${r}". Next: pick a workspace.`))}async function ps(e,t){return await t.withPausedInput(()=>ds(t.cwd,t.profileName)),{kind:"clear"}}q();import{resolveActiveProfile as Tl}from"document360-engine";async function fs(e,t){let o=!1;try{o=Tl(t.cwd).production}catch{}return o?(console.log(O("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}q();var ms=async(e,t)=>{try{await t.withPausedInput(()=>qt({}))}catch(o){console.log(b(`Login failed: ${o.message}`))}return{kind:"continue"}};q();import{resolveActiveProfile as Rl,clearTokens as jl,clearProfileProject as Al}from"document360-engine";async function gs(e,t){let o;try{o=Rl(t.cwd,t.profileName).name}catch(r){return console.log(b(r.message)),{kind:"continue"}}let n=jl(o);return Al(t.cwd,o),console.log(n?_(`\u2713 Signed out of "${o}" and cleared its project/workspace selection.`):f(`Profile "${o}" 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 hs}from"node:fs";import{isAbsolute as El,join as Dl,resolve as Il}from"node:path";import{readProjectConfig as _l,screenshotPlaceholderIds as Nl}from"document360-engine";var ks=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function fn(e){let t=!e.includes("--no-setup"),o=e.filter(r=>r!=="--no-setup");if(o[0]==="--list")return{mode:"list",scope:o[1]?ks(o[1]):void 0};let n=o[0];return!n||n==="--all"?{mode:"all",setup:t}:/[\\/]/.test(n)||n.endsWith(".md")?{mode:"scope",scope:ks(n),setup:t}:{mode:"single",id:n}}function mn(e,t){let o=_l(e),n=o?.captureDir??"user-docs/_capture",r=o?.outputDir??"user-docs/_screenshots",s=(c,d)=>El(c)?Dl(c,d):Il(e,c,d);return Nl(e,{scope:t}).map(({id:c,file:d})=>{let m=hs(s(r,`${c}.png`))?"captured":hs(s(n,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:d,state:m}})}var Ml={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Ll={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function gn(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let o=[...new Set(e.map(s=>s.file))].sort(),n=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${o.length} article${o.length===1?"":"s"} \xB7 ${n} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of o){r.push(s);for(let c of e.filter(d=>d.file===s))r.push(` ${Ml[c.state]} ${c.id.padEnd(34)} ${Ll[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function ws(e){return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(t=>`- ${t}`).join(`
|
|
59
59
|
`),"","For each: locate its <!-- SCREENSHOT --> block in user-docs/**/*.md; read the product source for","EXACT routes + stable data-testid selectors (never guess); enter the prepared context via","captureScope(); guard data prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts","(skip-with-TODO if a stable selector is missing). Do NOT run other skills. Report the specs you","wrote and any TODO data-testids."].join(`
|
|
60
|
-
`)}async function
|
|
61
|
-
`),display:`/screenshot ${
|
|
62
|
-
`),s=
|
|
63
|
-
`),display:"/capture-setup"}}var
|
|
60
|
+
`)}async function ro(e,t){let o=fn(e);if(o.mode==="list"){let c=t?.cwd??process.cwd();for(let d of gn(mn(c,o.scope),o.scope))console.log(d);return{kind:"continue"}}if(o.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${o.id}\`.`,"Locate its <!-- SCREENSHOT --> block in user-docs/**/*.md, then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${o.id}.spec.ts. Report the spec path and any TODO data-testids or data to stage.`].join(`
|
|
61
|
+
`),display:`/screenshot ${o.id}`};let r=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${o.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${o.scope}`:"every <!-- SCREENSHOT --> placeholder across user-docs/**/*.md"}.`,"Follow that skill exactly for each: read the SCREENSHOT block; read the product source for EXACT routes","and stable data-testid selectors (never guess); enter the prepared context via captureScope(); guard data",`prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts.${o.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`].join(`
|
|
62
|
+
`),s=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as Ol,readFileSync as Ul}from"node:fs";import{isAbsolute as Wl,join as Hl,resolve as Fl}from"node:path";import{readProjectConfig as Bl}from"document360-engine";async function Pt(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across user-docs/**/*.md, read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-SETUP.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
|
|
63
|
+
`),display:"/capture-setup"}}var ys="-".repeat(64);function hn(e){let t="user-docs/_capture";try{let y=Bl(e);y?.captureDir&&(t=y.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let o=Wl(t)?Hl(t,"CAPTURE-TESTID-REQUESTS.json"):Fl(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Ol(o))return null;let n;try{let y=JSON.parse(Ul(o,"utf8").replace(/^/,""));n=Array.isArray(y?.requests)?y.requests:[]}catch{return null}if(n.length===0)return null;let r=new Set(n.map(y=>y.file).filter(Boolean)).size,s=n.length,c=`${s} data-testid attribute${s===1?"":"s"}`,d=`${r} source file${r===1?"":"s"}`,m=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${c} requested across ${d}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",ys,`Read ${m} and ${k}. They list ${c} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",ys]}import{writeFileSync as ql}from"node:fs";import{devHintsGuidePath as Gl,hintsDir as zl,ensureDir as Yl}from"document360-engine";var xs="-".repeat(64),Vl=1;function kn(){return`# Dev \u2192 Docs hints \u2014 protocol guide
|
|
64
64
|
|
|
65
|
-
<!-- Guide version: ${
|
|
65
|
+
<!-- Guide version: ${Vl} \xB7 maintained by document360-writer (/devhints). -->
|
|
66
66
|
|
|
67
67
|
This repo's user documentation is written by **document360-writer**, a separate documentation agent.
|
|
68
68
|
It can read your code, but it can't read your *intent* \u2014 why a change matters to an end user, the
|
|
@@ -119,39 +119,39 @@ Prose: what you built and the gotchas a code diff would miss \u2014 e.g. "the bu
|
|
|
119
119
|
- Keep the body about user-facing intent, not implementation. Don't propose docs structure.
|
|
120
120
|
|
|
121
121
|
That's it \u2014 drop the file and keep building. The docs agent picks it up on its next analysis run.
|
|
122
|
-
`}async function
|
|
123
|
-
`).filter(
|
|
124
|
-
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(
|
|
125
|
-
`);return{lines:s.slice(0,t).map(c=>
|
|
122
|
+
`}async function $s(e,t){Yl(zl(t.cwd)),ql(Gl(t.cwd),kn());for(let o of wn())console.log(o);return{kind:"continue"}}function wn(){return["\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md and created the .d360-writer/hints/ inbox.","","\u{1F4CB} One-time setup \u2014 connect this repo's coding agent to the docs agent."," Add the block below to your SOURCE repo's agent memory (CLAUDE.md / AGENTS.md), then commit"," .d360-writer/DEV-HINTS-GUIDE.md so teammates' agents get the same instruction:","",xs,"## Documentation hints (for the docs agent)","","When you ship a user-facing change (new/changed/removed screen, button, flow, setting, API field,","CLI flag, or permission), record a doc hint so the documentation team's agent can update the help","center. How: read `.d360-writer/DEV-HINTS-GUIDE.md` and follow it \u2014 create one markdown file under","`.d360-writer/hints/`. Do this as part of finishing the feature. Skip it only for changes with no","user-visible effect (refactors, tests, build, deps).",xs,"","Then keep building as usual. On its next analysis run (/audit), the docs agent reads open hints,","verifies each against your code, writes/updates the docs, and marks the hint consumed."]}q();import{existsSync as Xl,rmSync as Kl}from"node:fs";import{basename as bs,resolve as vs}from"node:path";import{execFileSync as Jl}from"node:child_process";import{input as Ql}from"@inquirer/prompts";import{readProjectConfig as Zl}from"document360-engine";var ec=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"];function yn(e){let t=null;try{t=Zl(e)}catch{t=null}let o=s=>s?.replace(/\\/g,"/").replace(/\/+$/,""),n=o(t?.docsDir)??"user-docs",r=new Set([n]);for(let s of[o(t?.captureDir),o(t?.outputDir)])s&&s!==n&&!s.startsWith(`${n}/`)&&r.add(s);return[...r,...ec].filter(s=>Xl(vs(e,s)))}function xn(e,t){let o=[],n=[];for(let r of t)try{Kl(vs(e,r),{recursive:!0,force:!0}),o.push(r)}catch(s){n.push({path:r,error:s.message})}return{removed:o,failed:n}}function tc(e){try{return Jl("git",["status","--porcelain","--",".d360-writer/hints"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
123
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function $n(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let o=tc(e);return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(n=>` \u2022 ${n}`),"",...o>0?[`\u26A0 ${o} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${bs(e)}`]}async function Cs(e,t){let o=yn(t.cwd);for(let d of $n(t.cwd,o))console.log(o.length===0?f(d):d);if(o.length===0)return{kind:"continue"};let n=bs(t.cwd);if((await t.withPausedInput(()=>Ql({message:`Type "${n}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==n)return console.log(O("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let{removed:s,failed:c}=xn(t.cwd,o);console.log(_(`\u2713 Reset complete \u2014 removed ${s.length} item${s.length===1?"":"s"}. The repo is back to its original state.`));for(let d of c)console.log(b(` \u2717 ${d.path}: ${d.error}`));return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}var Ps={help:_o,"?":_o,clear:gr,exit:No,quit:No,init:$r,mcp:Kt,publish:Tr,audit:Zt,scope:jr,sync:Mr,convert:qr,write:Vr,resume:Jr,rename:Qr,profile:es,model:ns,doctor:Ct,workspace:ls,project:ps,"allow-prod":fs,login:ms,logout:gs,screenshot:ro,"capture-setup":Pt,devhints:$s,reset:Cs};function Ss(e){let t=e.trim();if(!t.startsWith("/"))return null;let o=t.slice(1).split(/\s+/),n=(o[0]??"").toLowerCase();return n?{name:n,args:o.slice(1)}:null}q();var oc={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"},Rs=160,vn=200,js=40;function ae(e,t){let o=e.replace(/\s+/g," ").trim();return o.length<=t?o:o.slice(0,t-1)+"\u2026"}function Ts(e){let t=Object.entries(e).filter(([,n])=>n!=null&&n!=="");if(t.length===0)return null;let o=t.slice(0,4).map(([n,r])=>`${n}: ${ae(typeof r=="string"?r:JSON.stringify(r),js)}`);return t.length>4&&o.push("\u2026"),ae(o.join(", "),Rs)}var De=e=>typeof e=="string"&&e?e:null,bn=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function nc(e){let t=De(e)?.replace(/\\/g,"/");if(!t)return null;let o=t.split("/").filter(Boolean);if(o.length<2)return null;let n=o[o.length-2],r=n.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?n:r.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function rc(e,t){let o=(n,r)=>({title:`Document360: ${n}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let n=De(t.title);if(!n)return null;let r=nc(t.local_path);return o("Create article",`"${ae(n,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let n=De(t.title),r=bn(t.article_id);return o("Update article",n?`"${ae(n,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return o("Fork article (new draft)",bn(t.article_id)?`id ${bn(t.article_id)}\u2026`:null);case"d360_publish_article":{let n=t.version_number;return o("Publish article LIVE",typeof n=="number"?`v${n}`:null)}case"d360_unpublish_article":return o("Unpublish article",null);case"d360_create_category":return o("Create category",De(t.name)?`"${ae(De(t.name),60)}"`:null);case"d360_upload_drive_file":{let n=De(t.file_path);return o("Upload image",n?ae(n.replace(/\\/g,"/").split("/").pop()??n,60):null)}case"d360_sync_status":return o("Check sync status",null);default:return null}}function so(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),c=s.join("__");if(r==="document360"){let k=rc(c,t);if(k)return k}let d=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${d}`,sep:" ",arg:Ts(t)}}let o=oc[e],n=o?t[o]:void 0;return typeof n=="string"&&n?{title:e,sep:"",arg:ae(n,Rs)}:{title:e,sep:"",arg:Ts(t)}}function sc(e){if(e===null||typeof e!="object")return typeof e=="string"?e:null;let t=e;for(let o of["name","title","slug","id"])if(typeof t[o]=="string"&&t[o])return t[o];return null}function ic(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let o=t.map(sc).filter(r=>r!==null),n=`${t.length} item${t.length===1?"":"s"}`;return o.length===0?[n]:[n,...o.map(r=>ae(r,vn))]}if(t!==null&&typeof t=="object"){let o=Object.entries(t).filter(([,n])=>n!==null&&(typeof n=="string"||typeof n=="number"||typeof n=="boolean")).slice(0,6).map(([n,r])=>`${n}: ${ae(String(r),js)}`);return o.length>0?[ae(o.join(" \xB7 "),vn)]:null}return null}function ac(e){let t=De(e)?.replace(/\\/g,"/");if(!t)return null;let o=t.split("/").filter(Boolean);return o.length>1?o.slice(1).join("/"):t}function lc(e,t,o){switch(e){case"d360_create_article":{let n=ac(t?.local_path);return[`\u2713 draft created${n?` \xB7 ${n}`:""}`]}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 n=De(t?.name);return[`\u2713 category created${n?` \xB7 "${n}"`:""}`]}case"d360_upload_drive_file":{let n=o.match(/https?:\/\/\S+/);return[`\u2713 uploaded${n?` \xB7 ${ae(n[0],120)}`:""}`]}default:return null}}function io(e,t=4,o,n){let r=e.replace(/\r\n/g,`
|
|
124
|
+
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(o?.startsWith("mcp__document360__")){let c=lc(o.slice(18),n,r);if(c)return{lines:c,hidden:0}}let s=ic(r)??r.split(`
|
|
125
|
+
`);return{lines:s.slice(0,t).map(c=>ae(c,vn)),hidden:Math.max(0,s.length-t)}}function ao(e,t,o,n="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${n}/${o}`}function lo(e,t){if(typeof e.article_id=="string"&&e.article_id)return e.article_id;try{let o=JSON.parse(t),r=(Array.isArray(o)?o[0]:o)?.id;return typeof r=="string"&&r?r:null}catch{return null}}function co(e){try{let t=JSON.parse(e),n=(Array.isArray(t)?t[0]:t)?.url;return typeof n=="string"&&/^https?:\/\//.test(n)?n:null}catch{return null}}var xc=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function $c(e,t,o,n){if(xc.test(e))try{let r=Is(n),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=lo(t,o),d=co(o);e.endsWith("publish_article")&&d&&console.log(j(` \u2B95 Live: ${d}`)),c&&s&&console.log(j(` \u2B95 Preview: ${ao(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function _s(e=process.cwd(),t="auto",o){let n=uc(t);n.kind==="none"&&(console.error(""),console.error(b("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${j("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${j('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${j("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${j("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),bc(e,o),n.kind==="subscription"&&(n.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,s=Cn({cwd:e,profileName:o,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},d=cc({input:process.stdin,output:process.stdout}),m=[],k=null,y=!1;d.on("line",v=>{if(k){let $=k;k=null,$(v)}else m.push(v)}),d.on("close",()=>{if(y=!0,k){let v=k;k=null,v(null)}});function E(){return m.length>0?Promise.resolve(m.shift()):y?Promise.resolve(null):(process.stdout.write(j("> ")),new Promise(v=>{k=v}))}let x={cwd:e,profileName:o,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=Cn({cwd:e,profileName:o,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setModel:async v=>s.setModel(v),withPausedInput:async v=>{d.pause();try{return await v()}finally{d.resume()}}};try{for(;;){let v=await E();if(v===null)break;let $=v.trim();if($){if($.startsWith("/")){let D=Ss($);if(!D)continue;let N=Ps[D.name];if(!N){console.log(b(`Unknown command: /${D.name}`)),console.log(f("Type /help for the list."));continue}let H=await N(D.args,x);if(H.kind==="exit")break;if(H.kind==="clear"){x.restartAgent();continue}if(H.kind==="allow-prod"){r=!0,x.restartAgent(),console.log(_("\u2713 Production writes authorized for this session.")),console.log("");continue}if(H.kind==="resume"){s.close(),s=Cn({cwd:e,resume:H.uuid,profileName:o,allowProdWrites:r});let Q=dc(H.uuid);c={uuid:H.uuid,firstPrompt:Q?.firstPrompt??null,titleFired:!0},Ds(H.uuid),console.log(_(`\u2713 Resumed "${H.name}"`)),console.log("");continue}H.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=H.display??H.prompt),await Es(s,H.prompt,n,c,e));continue}c.firstPrompt||(c.firstPrompt=$),await Es(s,$,n,c,e)}}}finally{s.close(),d.close()}}function bc(e,t){console.log(""),console.log(gt("document360-writer")),console.log(f(` cwd: ${e}`));let o=hc(e);console.log(f(` model: ${o.model??"auto (engine right-sizes per task)"}${o.model?` (${o.source})`:""}`)),console.log(vc(e,t)),kc(e)||console.log(O(" First run: /init \u2192 /login \u2192 /workspace, then ask for a docs analysis.")),console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function vc(e,t){try{let o=Is(e,t),n=o.production?O(" \u26A0 PRODUCTION"):"",r=yc(o.name);if(!r)return f(` Document360: profile "${o.name}"${n} \u2014 not logged in (d360-writer login)`);let s={...As(r.idToken)??{},...As(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return wc(r)&&!r.refreshToken?O(` Document360: profile "${o.name}"${n} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${o.name}"${n}`)}catch(o){return f(` Document360: ${o.message.split(".")[0]}`)}}function Cc(){console.error(""),console.error(`Sign in with your Claude subscription: run ${j("claude")} once, then retry.`),console.error(` (No Claude Code? ${j("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${j("https://console.anthropic.com/settings/keys")}`)}function Pc(e,t,o){e.uuid=t;let n=new Date().toISOString();mc({uuid:t,name:fc(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:o,firstPrompt:e.firstPrompt??"",createdAt:n,updatedAt:n})}function Sc(e,t){e.titleFired=!0;let o=e.uuid,n=e.firstPrompt;!o||!n||gc(n,t).then(r=>{r&&pc(o,r)}).catch(()=>{})}async function Es(e,t,o,n,r){let s=new Map;for await(let c of e.send(t))Tc(c,n,r,o,s)}function Tc(e,t,o,n,r){switch(e.type){case"session":t.uuid||Pc(t,e.sessionId,o);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=so(e.name,e.input);s&&(process.stdout.write(`
|
|
126
126
|
|
|
127
|
-
`),console.log(`${
|
|
128
|
-
`),console.log(f(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(
|
|
129
|
-
`)){let c=s.trim().replace(
|
|
130
|
-
`)}function
|
|
131
|
-
`)||e.length>200}function
|
|
132
|
-
`).length;return`[Pasted text #${e} +${
|
|
133
|
-
`)){if(s.length===0)
|
|
134
|
-
`),s=0;for(let c=r.length-1;c>=0;c--){let d=r[c];if(s+=Math.max(1,Math.ceil(d.length/
|
|
135
|
-
`),truncated:c>0||
|
|
136
|
-
`)){let s=
|
|
127
|
+
`),console.log(`${_("\u25CF")} ${Pe(s.title)}${s.arg!==null?Z(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=He(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=d=>d===1?"":"s";console.log(Z(` \u23BF Added ${s.added} line${c(s.added)}, removed ${s.removed} line${c(s.removed)}`));for(let d of s.lines)console.log(d);s.hidden>0&&console.log(f(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let c=io(e.output,4,e.isError?void 0:s.name,s.input),d=e.isError?b:Z;c.lines.forEach((m,k)=>console.log(d((k===0?" \u23BF ":" ")+m))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||$c(s.name,s.input,e.output,o);break}case"result":process.stdout.write(`
|
|
128
|
+
`),console.log(f(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Ds(t.uuid),t.titleFired||Sc(t,o));break;case"error":console.error(""),console.error(b(`agent error: ${e.message}`)),n.kind==="subscription"&&e.kind==="auth"&&Cc();break}}import{render as Su}from"ink";import{resolveAuth as Tu}from"document360-engine";import{useCallback as V,useEffect as _e,useMemo as ko,useRef as J,useState as B}from"react";import{Box as K,Text as C,useApp as Lc,useInput as Oc,useStdout as Uc}from"ink";import{existsSync as Js,readFileSync as Qs,readdirSync as li,writeFileSync as Wc}from"node:fs";import{basename as wo,isAbsolute as Hc,join as Tt}from"node:path";import{createSession as Zs,loginPkce as Fc,toStoredTokens as Bc,saveTokens as qc,getAccessToken as Gc,resolveActiveProfile as le,resolveProjectId as zc,getArticle as Yc,decodeJwtClaims as it,isExpired as Ie,loadTokens as Be,clearTokens as Vc,clearProfileProject as Xc,setTitle as Kc,slugify as Jc,touchSession as Rn,upsertSession as Qc,generateTitle as ei,findByName as Zc,listSessions as eu,renameSession as tu,suggestNextAction as ou,readProjectConfig as ne,writeProjectConfig as nu,resolveModelSetting as In,loadProfileMap as ti,applyPull as ru,computeSyncStatus as jn,planPull as su,inventoryRepo as iu,knownEnvironments as au,resolveEnvironment as lu,planPartitions as oi,partitionEvenly as cu,screenshotPlaceholderIds as uu,trackedArticlePaths as du,runPartitioned as An,estimateBulkCost as ni,resolveModelForOperation as En,readDocsPlan as pu,ensureDir as fu,hintsDir as mu,devHintsGuidePath as gu}from"document360-engine";import{existsSync as Rc,mkdirSync as jc,readFileSync as Ac,writeFileSync as Ec}from"node:fs";import{join as Ns}from"node:path";import{writerDir as Dc}from"document360-engine";function Ms(e){return Ns(Dc(e),".sessions")}function Ls(e,t){return Ns(Ms(e),`${t}.json`)}function Os(e,t,o){try{jc(Ms(e),{recursive:!0});let n=o.filter(r=>r.kind!=="banner");Ec(Ls(e,t),JSON.stringify({v:1,items:n}),"utf8")}catch{}}function Pn(e,t){try{let o=Ls(e,t);if(!Rc(o))return[];let n=JSON.parse(Ac(o,"utf8"));return Array.isArray(n.items)?n.items:[]}catch{return[]}}var Ic=e=>`\x1B]0;${e}\x07`,_c=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Us(e){process.stdout.isTTY&&process.stdout.write(e)}function St(e){Us(Ic(e))}function uo(e){Us(_c(e))}var po=["\xB7 "," \xB7"],Sn="\u{1F7E3}";no();var Nc=/^(?:\d+[.)]|[-*•])\s+/;function Ws(e,t,o=4){let n=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
129
|
+
`)){let c=s.trim().replace(Nc,""),d=c.match(/^`([^`]+)`$/);d&&(c=d[1].trim());let m=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!m||!n.has(m[1].toLowerCase()))continue;let k=`/${m[1].toLowerCase()}${m[2]?` ${m[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=o)break}return r}q();function fo(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Fe(e,t,o){return e.map(n=>n.label===t?{...n,status:o}:n)}function Tn(e){return e.replace(/^[\w.-]+\//,"")}var mo=16,Hs={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};var Mc=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Fs(e){return e.replace(/\r\n?/g,`
|
|
130
|
+
`)}function Bs(e){return e.includes(`
|
|
131
|
+
`)||e.length>200}function qs(e,t){let o=t.split(`
|
|
132
|
+
`).length;return`[Pasted text #${e} +${o} line${o===1?"":"s"}]`}function Gs(e,t){return e.replace(Mc,o=>t.get(o)??o)}function zs(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function go(e,t){let o=Math.max(1,t),n=[],r=0;for(let s of e.split(`
|
|
133
|
+
`)){if(s.length===0)n.push({start:r,end:r});else for(let c=0;c<s.length;c+=o)n.push({start:r+c,end:r+Math.min(c+o,s.length)});r+=s.length+1}return n.length>0?n:[{start:0,end:0}]}function ho(e,t){let o=0;for(let n=0;n<e.length&&e[n].start<=t;n++)o=n;return o}function Ys(e,t,o){let n=ho(e,t),r=n+o;if(r<0||r>=e.length)return t;let s=Math.min(t,e[n].end)-e[n].start;return Math.min(e[r].start+s,e[r].end)}function Vs(e,t,o){let n=e[ho(e,t)];return o==="start"?n.start:n.end}function Xs(e,t,o){let n=Math.max(1,o),r=e.split(`
|
|
134
|
+
`),s=0;for(let c=r.length-1;c>=0;c--){let d=r[c];if(s+=Math.max(1,Math.ceil(d.length/n)),s>=t){let m=s-t;return{text:[m>0?d.slice(m*n):d,...r.slice(c+1)].join(`
|
|
135
|
+
`),truncated:c>0||m>0}}}return{text:e,truncated:!1}}function Ks(e){let t=!1,o=0,n=0;for(let r of e.split(`
|
|
136
|
+
`)){let s=n+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(o=s+1),n=s+1}return o}import{Fragment as Dn,jsx as S,jsxs as W}from"react/jsx-runtime";var hu={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},ri=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
137
137
|
2. /login signs in to that environment
|
|
138
138
|
3. /project then /workspace \u2014 pick the project and where articles go
|
|
139
|
-
Press 1 to start.`;function
|
|
140
|
-
${
|
|
141
|
-
${
|
|
142
|
-
`)});return;case"exit":case"quit":ce.current?.close(),r();return;case"clear":
|
|
143
|
-
`:"",ee=`
|
|
144
|
-
Model: ${_.model}${_.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:W+Vn(D,j,M).join(`
|
|
145
|
-
`)+ee}),X([A]);return}Be.current=Date.now(),at(0),G(!0);let P=new AbortController;ve.current=P,Z({total:D.length,done:0,active:[],tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${T.length} articles across ${D.length} partitions (\u2264${M} agents at once) on ${_.model}\u2026 (esc to stop)`});try{for await(let j of So({cwd:e,partitions:D,promptFor:Yn,concurrency:M,profileName:s,allowProdWrites:ct.current,model:_.model,signal:P.signal}))if(j.type==="partition_status")j.status==="running"?(Z(W=>W&&{...W,active:[...W.active,j.label],lastAt:Date.now()}),u({kind:"note",tone:"info",text:` \u25B8 ${j.label} \u2014 converting\u2026`})):(Z(W=>W&&{...W,active:W.active.filter(ee=>ee!==j.label),done:W.done+1,lastAt:Date.now()}),u({kind:"note",tone:j.status==="done"?"ok":"error",text:` ${j.status==="done"?"\u2713":"\u2717"} ${j.label}`}));else if(j.type==="partition_event")Z(W=>{if(!W)return W;let ee={...W,lastAt:Date.now()};return j.event.type==="tool"?ee.tools=W.tools+1:j.event.type==="text"&&(ee.chars=W.chars+j.event.delta.length),ee});else if(j.type==="run_done"){dt(O=>O+j.totalCostUsd),ut(O=>O+j.results.reduce((Y,te)=>Y+te.outputTokens,0));let W=j.aborted?"Stopped. ":"",ee=t.kind==="api"?"api":"subscription";u({kind:"note",tone:j.aborted?"warn":j.ok?"ok":"warn",text:W+Xn(j.results,D,ee).join(`
|
|
146
|
-
`)})}}catch(j){u({kind:"note",tone:"error",text:`Convert run failed: ${j.message}`})}finally{ve.current=null,Z(null),G(!1)}return}case"write":{if(!ne(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=au(e);if(p.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:w,run:T}=Kn(h),{docsDir:D,targets:M,reason:A}=no(e,p,{scope:m,path:w});if(M.length===0){u({kind:"note",tone:"warn",text:A??"Nothing to write."});return}let _=Ks(M),P=5,j=To(e,"standard");if(!T&&!!!w){let O=Qs({files:Qn(e,p,M),op:"write",model:j.model}),Y=m?`Scope: ${m} (${M.length} pending)
|
|
139
|
+
Press 1 to start.`;function ku(e,t,o,n){let r=o.kind==="api"?"API key":o.kind==="subscription"?"subscription":"not configured",s=In(e),c=ne(e),d=(c?.docsDir??"user-docs").replace(/\/+$/,""),m=c?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${d}/ + config`,k={version:t,claude:r,model:s.model??"Claude Code default model",modelSource:hu[s.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:c!==null,mode:m};if(c===null)return k;try{let y=le(e,n);k.profile=y.name,k.apiUrl=y.connection.apiUrl,k.prod=y.production,k.project=y.project.projectId??"(chosen at login)";let E=Be(y.name);if(E){let x={...it(E.idToken)??{},...it(E.accessToken)??{}},v=x.email??x.preferred_username??"signed in";Ie(E)?E.refreshToken&&(k.who=v,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=v,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(E.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function wu(e,t){try{let o=le(e,t),n=Be(o.name);if(!n)return{text:`profile "${o.name}" \u2014 not logged in (/login)`,prod:o.production};let r={...it(n.idToken)??{},...it(n.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return Ie(n)&&!n.refreshToken?{text:`profile "${o.name}" \u2014 session expired (/login)`,prod:o.production}:{text:`${s} \xB7 profile "${o.name}"`,prod:o.production}}catch(o){return{text:o.message.split(".")[0],prod:!1}}}var si=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],xo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],yu="Ask me to write or update an article\u2026";function yo({ch:e,dim:t}){let[o,n]=B(!0);return _e(()=>{let r=setInterval(()=>n(s=>!s),530);return()=>clearInterval(r)},[]),S(C,{inverse:o,color:t&&!o?"gray":void 0,children:e})}var xu=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function ii(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var $u=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ai(e){try{return li(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function bu(e,t){let o=t??[];return o.length===0?["src","api","services","packages","modules"].some(n=>ai(Tt(e,n))):o.some(n=>!n.includes("/")&&!n.endsWith(".md")&&ai(Tt(e,n)))}function vu({startTime:e,chars:t}){let[o,n]=B(0);_e(()=>{let m=setInterval(()=>n(k=>k+1),120);return()=>clearInterval(m)},[]);let r=xo[o%xo.length],s=si[Math.floor(o/16)%si.length],c=Math.floor((Date.now()-e)/1e3),d=Math.round(t/4);return W(K,{children:[S(C,{color:G,children:` ${r} ${s}\u2026 `}),S(C,{color:"gray",children:`(${bt(c)} \xB7 ~${d} tokens \xB7 esc to interrupt)`})]})}var Cu=12e4;function Pu({p:e}){let[t,o]=B(0);_e(()=>{let N=setInterval(()=>o(H=>H+1),150);return()=>clearInterval(N)},[]);let n=xo[t%xo.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),d=Date.now()-e.lastAt>=Cu,m=e.verb??"Converting",k=e.unit??"article",y=e.rows.reduce((N,H)=>N+H.items,0),E=m.toLowerCase(),x=e.rows,v=0;if(x.length>mo){let N=x.findIndex(Q=>Q.status==="active"||Q.status==="pending"),H=Math.max(0,Math.min(N-2,x.length-mo));v=x.slice(0,H).filter(Q=>Q.status==="done").length,x=x.slice(H,H+mo)}let $=Math.min(40,Math.max(...x.map(N=>Tn(N.label).length),0)),D=N=>N==="failed"?"red":N==="active"?G:void 0;return W(K,{flexDirection:"column",children:[W(K,{children:[S(C,{color:G,children:` ${n} ${m} ${y} ${k}${y===1?"":"s"} `}),S(C,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${bt(r)} \xB7 esc to stop`})]}),v>0&&S(C,{dimColor:!0,children:` \u2714 +${v} done`}),x.map(N=>W(C,{color:D(N.status),dimColor:N.status==="done"||N.status==="pending",children:[` ${Hs[N.status]} ${Tn(N.label).padEnd($)}`,N.status!=="pending"?` (${N.items} ${k}${N.items===1?"":"s"})`:"",N.status==="active"?` \u2190 ${E}\u2026`:""]},N.label)),d&&S(C,{color:"yellow",children:` \u26A0 no activity for ${bt(s)} \u2014 press esc to stop if it's wedged`})]})}function ci({cwd:e,auth:t,profileName:o,version:n}){let{exit:r}=Lc(),[s,c]=B(o),[d,m]=B(null),[k,y]=B({text:"",pos:0}),E=k.text,x=V(l=>{y(a=>{let i=typeof l=="function"?l(a.text):l;return{text:i,pos:i.length}})},[]),v=V(l=>{y(a=>({text:a.text.slice(0,a.pos)+l+a.text.slice(a.pos),pos:a.pos+l.length}))},[]),$=V(()=>{y(l=>{if(l.pos===0)return l;let a=l.text.slice(0,l.pos),i=zs(a)??a.slice(0,-1);return{text:i+l.text.slice(l.pos),pos:i.length}})},[]),[D,N]=B(!1),[H,Q]=B(!1),[me,ye]=B(0),[ge,he]=B(null),[at,X]=B([]),Rt=J(0),[fi,jt]=B(!1),[mi,lt]=B(0),qe=J(0),[ct,Ge]=B(0),[ze,At]=B(null),Mn=J(new Map),gi=J(0),Ye=J([]),ce=J(null);ce.current===null&&(ce.current=Zs({cwd:e,profileName:s,allowProdWrites:!1}));let xe=J({uuid:null,firstPrompt:null,titleFired:!1}),Et=J(new Map),ut=J(!1),$o=J([]),Te=J([]),bo=J(null),[Ln,Ve]=B(null),[Ne,Me]=B(null),[$e,Xe]=B(null),[Re,Ke]=B(null),[re,Je]=B(null),[ue,Qe]=B(null),[be,Ze]=B(null),[de,Le]=B(null),[se,et]=B(null),[On,vo]=B([]),Oe=J([]),Dt=J(!1),ve=J(null),[Un,ee]=B(null),It=J(!1),_t=J(null),[pe,Ue]=B(null),[Wn,dt]=B(0),[Hn,pt]=B(0),[hi,Fn]=B(0),Co=ko(()=>{try{return In(e).model??"auto"}catch{return null}},[e,hi]),{stdout:ke}=Uc(),[,ki]=B(0),Bn=J(`${ke.columns??80}x${ke.rows??24}`),je=V(()=>Math.max(20,(ke.columns??80)-1),[ke]),u=V(l=>{Ye.current.push(l),console.log(Go(l,je()))},[je]);_e(()=>{let l=`d360-writer \xB7 ${Ln??wo(e)}`;if(!D){uo(0),St(`${Sn} ${l}`);return}uo(3);let a=0;St(`${po[0]} ${l}`);let i=setInterval(()=>{a=(a+1)%po.length,St(`${po[a]} ${l}`)},400);return()=>clearInterval(i)},[D,e,Ln]),_e(()=>()=>uo(0),[]),_e(()=>{if(u({kind:"banner",info:ku(e,n,t,s)}),!ne(e)){u({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
140
|
+
${ri}`}),X(["/init"]);return}try{let l=le(e,s),a=Be(l.name);a&&Ie(a)&&a.refreshToken?Gc({profile:l.name,connection:l.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),ye(i=>i+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),X(["/login"])}):(!a||Ie(a))&&(u({kind:"note",tone:"warn",text:`Profile "${l.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),X(["/login"]))}catch{}try{let l=ne(e),a=le(e,s),i=Be(a.name);l&&i&&!Ie(i)&&bu(e,l.authoritativeSourceFiles)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),X(["/scope"]))}catch{}},[]),_e(()=>{let l=null,a=null,i=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let h=`${ke.columns??80}x${ke.rows??24}`;h!==Bn.current&&(Bn.current=h,ki(p=>p+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Br(Ye.current,je())+"\x1B[?2026l")},80))},400)};return ke.on("resize",i),()=>{l&&clearTimeout(l),a&&clearTimeout(a),ke.off("resize",i)}},[ke,je]);let We=Math.max(20,(ke.columns??80)-1),qn=ko(()=>wu(e,s),[e,s,me]),Po=ko(()=>{let l=ne(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let a=Tt(e,(l.docsDir??"user-docs").replace(/\/+$/,"")),i=(()=>{try{return Js(a)&&li(a).length>0}catch{return!1}})();try{let h=le(e,s),p=Be(h.name);if(!(!!p&&!(Ie(p)&&!p.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${h.name}")\u2026`,isSetup:!0};if(!h.project.workspaceId&&!i)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return i?{text:yu,isSetup:!1}:{text:"Let's get started \u2014 try: write the docs for this repo",isSetup:!1}},[e,s,me]),ft=fr(E),Gn=ft.length>0&&!D,So=d!==null?Xs(d,8,We):null,Nt=de?de.paths.filter(l=>!de.query||l.toLowerCase().includes(de.query.toLowerCase())).slice(0,8):[],Mt=pe?pe.sessions.filter(l=>{let a=pe.query.toLowerCase();return!a||l.name.toLowerCase().includes(a)||l.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],ie=V((l,a)=>{ce.current?.close(),ce.current=Zs({cwd:e,resume:l,profileName:a??s,allowProdWrites:ut.current}),l||(xe.current={uuid:null,firstPrompt:null,titleFired:!1},Ve(null)),dt(0),pt(0)},[e,s]),zn=V((l,a,i)=>{if(xu.test(l))try{let h=le(e,s),p=typeof a.project_id=="string"&&a.project_id||h.project.projectId,g=lo(a,i),w=[],T=co(i);l.endsWith("publish_article")&&T&&w.push(`Live: ${T}`),g&&p&&w.push(`Preview: ${ao(h.connection.portalUrl,p,g,h.project.languageCode??"en")}`),w.length>0&&u({kind:"link",lines:w})}catch{}},[e,s,u]),Ce=V(async(l,a)=>{jt(!0),he(null),X([]);let i=++Rt.current;u({kind:"user",text:a?.echoDisplay&&a.display?a.display:l});let h=xe.current;h.firstPrompt||(h.firstPrompt=a?.display??l),qe.current=Date.now(),lt(0),N(!0),Et.current.clear();let p="",g="",w=null,T=()=>{w||(w=setTimeout(()=>{w=null,m(g.length>0?g:null)},60))},A=()=>{w&&clearTimeout(w),w=null,m(null)},L=()=>{if(g.trim()){let I=g.trimEnd();u({kind:"assistant",text:I})}g="",A()};try{for await(let I of ce.current.send(l))if(I.type==="session"){if(!h.uuid){h.uuid=I.sessionId;let M=new Date().toISOString(),P=Jc(h.firstPrompt??"session");Qc({uuid:I.sessionId,name:P,renamed:!1,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:M,updatedAt:M}),Ve(P)}}else if(I.type==="text"){g+=I.delta,p+=I.delta;let M=Ks(g);if(M>0){let P=g.slice(0,M).trimEnd();P&&u({kind:"assistant",text:P}),g=g.slice(M)}T(),lt(P=>P+I.delta.length)}else if(I.type==="tool"){let M=so(I.name,I.input);M&&(L(),u({kind:"tool",title:M.title,sep:M.sep,arg:M.arg}),Et.current.set(I.id,{name:I.name,input:I.input}))}else if(I.type==="article_diff"){let M=He(I.oldContent,I.newContent,je());M&&(L(),u({kind:"diff",added:M.added,removed:M.removed,lines:M.lines,hidden:M.hidden}))}else if(I.type==="tool_result"){I.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(I.output)&&(It.current=!0);let M=Et.current.get(I.id);if(M){Et.current.delete(I.id),L();let P=io(I.output,4,I.isError?void 0:M.name,M.input);u({kind:"tool-result",lines:P.lines,hidden:P.hidden,isError:I.isError}),I.isError||zn(M.name,M.input,I.output)}}else if(I.type==="result"){L(),dt(P=>P+I.outputTokens),pt(P=>P+I.costUsd),u({kind:"done",seconds:Math.round((Date.now()-qe.current)/1e3),tokens:I.outputTokens,costUsd:I.costUsd,ok:I.ok});let M=I.ok?Ws(p,wt.map(P=>P.name)):[];if(M.length>0?X(M):I.ok&&p.trim()&&ou(l,p,e).then(P=>{P&&Rt.current===i&&he(P)}).catch(()=>{}),h.uuid&&(Rn(h.uuid),!h.titleFired)){h.titleFired=!0;let P=h.uuid,R=h.firstPrompt;R&&ei(R,e).then(U=>{U&&(Kc(P,U),Ve(U))}).catch(()=>{})}}else I.type==="error"&&(L(),I.kind==="auth"&&(It.current=!0),u({kind:"note",text:`agent error: ${I.message}`,tone:"error"}))}finally{N(!1),A(),xe.current.uuid&&Os(e,xe.current.uuid,Ye.current),It.current&&(It.current=!1,_t.current=a?.display??l,X(["/login"])),Dt.current&&(Dt.current=!1,Oe.current.length>0&&(u({kind:"note",tone:"info",text:`(${Oe.current.length} queued message(s) discarded)`}),Oe.current=[],vo([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,zn,je]),To=V(l=>{let a=Be(l);if(!a||Ie(a)&&!a.refreshToken)return null;let i={...it(a.idToken)??{},...it(a.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),Ro=V((l,a)=>{if(a){let i=ne(e);i&&(i.defaultProfile=l,nu(i,e))}c(l),ie(void 0,l),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),To(l)||(u({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),X(["/login"])),ye(i=>i+1)},[e,u,ie,To]),Lt=V((l,a,i)=>{Ht(e,l,a,i.id,i.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),ie(),ti(e,l)||(u({kind:"note",tone:"info",text:"Setup complete. Press tab to start with a docs analysis."}),he("analyze this repo and propose a docs structure"))},[e,u,ie]),jo=V(async l=>{let a;try{a=await ht(e,l)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),X(["/workspace"]);return}if(a.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=a.workspaces.filter(p=>(p.workspace_type??"").toLowerCase()!=="apidocumentation"),h=i.length>0?i:a.workspaces;if(h.length===1){let p=h[0],g=a.workspaces.length-h.length;u({kind:"note",tone:"ok",text:`Selected the "${p.name??p.id}" workspace${g>0?" (skipped the API-documentation workspace)":""}.`}),Lt(a.profile,a.projectId,p);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),X(["/workspace"])},[e,u,Lt]),Yn=V((l,a)=>{pn(e,l,a.id),u({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),ie(),jo(l)},[e,u,ie,jo]),Ot=V(()=>{let l=Te.current[0];if(!l)return;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let i of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${i}`});l.overwritesLocalChanges&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let a=He(l.oldContent,l.newContent,je());u(a?{kind:"diff",added:a.added,removed:a.removed,lines:a.lines,hidden:a.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,je]),Vn=V(l=>{if(Te.current.length===0)return!1;let a=l.trim().toLowerCase();if(a==="y"||a==="yes"){let i=Te.current.shift();try{ru({cwd:e,profileName:s},i),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${i.path} (sync base advanced).`}),Te.current.length===0&&X(h=>h.length>0?h:["/sync"])}catch(h){u({kind:"note",tone:"error",text:`Pull failed: ${h.message}`})}}else if(a==="n"||a==="no"){let i=Te.current.shift();u({kind:"note",tone:"info",text:`Skipped ${i.path}.`})}else{let i=Te.current.length;return Te.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${i} article(s) left untouched).`}),!0}return Ot(),!0},[e,s,Ot,u]),Xn=V(l=>{let a=bo.current;if(!a)return!1;if(bo.current=null,l.trim()!==a.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:h}=xn(e,a.targets);u({kind:"note",tone:h.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`});for(let p of h)u({kind:"note",tone:"error",text:` \u2717 ${p.path}: ${p.error}`});return u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
141
|
+
${ri}`}),X(["/init"]),jt(!1),!0},[e,u]),Kn=V(async l=>{let a=l.slice(1).trim().split(/\s+/),i=(a[0]??"").toLowerCase(),h=a.slice(1);switch(jt(!0),i){case"help":u({kind:"note",tone:"info",text:Vt().join(`
|
|
142
|
+
`)});return;case"exit":case"quit":ce.current?.close(),r();return;case"clear":ie(),Ye.current=[],jt(!1),he(null),Rt.current++,u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let p;try{p=le(e,s)}catch(g){u({kind:"note",tone:"error",text:g.message});return}u({kind:"note",tone:"info",text:`Profile "${p.name}" \u2192 ${p.connection.name} (${p.connection.apiUrl})${p.production?" \u26A0 PRODUCTION":""}`}),Q(!0);try{let g=await Fc(p.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},A=>u({kind:"note",tone:"info",text:A})),w=Bc(p.name,g);qc(w),Io(w,p.name,A=>u({kind:"note",tone:"info",text:A})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${p.name}" as ${Bt(w)}`});let T=(()=>{try{return le(e,s)}catch{return p}})();T.project.workspaceId||(T.project.projectId?await jo(T.name):(u({kind:"note",tone:"info",text:"Next: pick the Document360 project."}),X(["/project"]))),_t.current&&(he(_t.current),_t.current=null,u({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(g){u({kind:"note",tone:"error",text:`Login failed: ${g.message}`})}finally{Q(!1),ye(g=>g+1)}return}case"allow-prod":{let p=!1;try{p=le(e,s).production}catch{}if(!p){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}ut.current=!0,ie(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let p=an(h.join(" ")),g=xe.current.uuid;if(!g){u({kind:"note",tone:"error",text:"Send a message first \u2014 sessions save once the agent replies."});return}if(!p){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=xe.current.firstPrompt??"";ei(w,e).then(T=>{T?(he(`/rename ${T}`),u({kind:"note",tone:"info",text:`Suggestion: "${T}" \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}tu(g,p),Ve(p),St(`${Sn} d360-writer \xB7 ${p}`),u({kind:"note",tone:"ok",text:`Session renamed to "${p}".`});return}case"profile":{let p=h[0],g=ne(e);if(!p){let w=Object.entries(g?.profiles??{});if(w.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let T=w.map(([I,M])=>({name:I,env:M.connection?.environment??"custom",prod:M.production===!0,who:To(I)})),A=s??g?.defaultProfile,L=Math.max(0,T.findIndex(I=>I.name===A));Xe({cursor:L,current:L,rows:T});return}if(p==="add"){let w=ln(e,h[1],h[2]);if(w){u({kind:"note",tone:"error",text:w});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),Ro(h[1],!1);return}if(!g?.profiles?.[p]){u({kind:"note",tone:"error",text:`Unknown profile "${p}". Create it: /profile add ${p} <environment>`});return}Ro(p,!0);return}case"doctor":await Ct(h,{cwd:e});return;case"mcp":await Kt(h);return;case"init":{if(ne(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer.json directly (or d360-writer init for the CLI wizard)."});return}let p=au().map(g=>({name:g,apiUrl:lu(g).apiUrl}));Ke({cursor:0,rows:p});return}case"resume":{let p=h.join(" ").trim(),g=eu(e).filter(A=>A.uuid!==xe.current.uuid);if(!p){if(!g.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Ue({query:"",cursor:0,sessions:g});return}let w=Zc(e,p);if(!w){u({kind:"note",tone:"error",text:`No session matches "${p}".`});return}ie(w.uuid),xe.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},Ve(w.name),Rn(w.uuid),Ye.current=[];let T=Pn(e,w.uuid);for(let A of T)u(A);u({kind:"note",tone:"ok",text:T.length?`Resumed "${w.name}" \u2014 restored ${T.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let p=h.join(" ").trim(),g;try{g=await ht(e,s)}catch(T){u({kind:"note",tone:"error",text:`Could not list workspaces: ${T.message}`});return}if(!p){let T=g.workspaces.map(L=>({id:L.id,name:L.name??L.id,type:L.workspace_type}));if(T.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let A=Math.max(0,T.findIndex(L=>L.id===g.current));Je({cursor:A,current:A,rows:T,profile:g.profile,projectId:g.projectId,environment:g.environment});return}let w=Do(g.workspaces,p);if(!w){u({kind:"note",tone:"error",text:`No workspace matches "${p}".`});return}Lt(g.profile,g.projectId,w);return}case"project":{let p=h.join(" ").trim(),g;try{g=await dn(e,s)}catch(T){u({kind:"note",tone:"error",text:`Could not list projects: ${T.message} (signed in? try /login)`});return}if(!p){let T=g.projects.map(L=>({id:L.id,name:L.name??L.id,sub:L.sub_domain}));if(T.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let A=T.findIndex(L=>L.id===g.current);Qe({cursor:Math.max(0,A),current:A,rows:T,profile:g.profile,environment:g.environment});return}let w=us(g.projects,p);if(!w){u({kind:"note",tone:"error",text:`No project matches "${p}". Available: ${g.projects.map(T=>T.name??T.id).join(", ")}`});return}Yn(g.profile,w);return}case"logout":{let p;try{p=le(e,s).name}catch(w){u({kind:"note",tone:"error",text:w.message});return}let g=Vc(p);Xc(e,p),ie(),ye(w=>w+1),u({kind:"note",tone:g?"ok":"info",text:g?`\u2713 Signed out of "${p}" and cleared its project/workspace selection.`:`Profile "${p}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),X(["/login"]);return}case"publish":{if(h[0]&&h[0]!=="--all"){await Ce(Qt(h[0]),{display:`/publish ${h[0]}`,echoDisplay:!0});return}let p=h[0]==="--all";u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let g=await jn({cwd:e,profileName:s}),w=Jt(g.entries);if(w.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let A=g.counts["unknown-base"]??0;A>0&&u({kind:"note",tone:"info",text:`(${A} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(p){await Ce(xt(w.map(A=>A.path)),{display:"/publish --all",echoDisplay:!0});return}let T=w.length>1?[{path:"--all",label:`publish all ${w.length} candidates in one run`},...w]:w;Ze({cursor:0,rows:T})}catch(g){u({kind:"note",tone:"error",text:`Could not compute sync status: ${g.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let p=h.join(" ").trim();if(!p){let w=[];try{w=Object.keys(ti(e,le(e,s).name)?.articles??{})}catch{}if(w.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Le({query:"",cursor:0,paths:w});return}let g=Hc(p)?p:Tt(e,p);if(Js(g)){try{u({kind:"preview",name:wo(g),text:ii(Qs(g,"utf8"))})}catch(w){u({kind:"note",tone:"error",text:`Could not read ${g}: ${w.message}`})}return}if($u.test(p)){try{let w=le(e,s),T={profile:w.name,connection:w.connection},A=w.project.projectId??zc(T),L=await Yc(T,A,p);u({kind:"preview",name:L.title??p,text:L.content??"*(article has no content)*"})}catch(w){u({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}u({kind:"note",tone:"error",text:`"${p}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let p=h[0]?.trim();if(!p){let A=oo(In(e));Me({cursor:A,current:A});return}let{lines:g,changed:w,effective:T}=vt(e,p);for(let A of g)u({kind:"note",tone:A.startsWith("\u26A0")?"warn":A.startsWith("\u2713")?"ok":"info",text:A});w&&(Fn(A=>A+1),ce.current?.setModel(T));return}case"convert":{if(!ne(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:p,run:g}=Yo(h),w=du(e,s);if(w.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let T=Vo(w,p);if(T.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${p}". (${w.length} are tracked overall.)`});return}let A=oi(T),L=3,I=`/convert${p?` --scope ${p}`:""} --run`,M=En(e,"light");if(!g){let R=ni({files:Xo(e,T),op:"convert",model:M.model}),U=p?`Scope: ${p} (${T.length} of ${w.length} tracked)
|
|
147
143
|
`:"",te=`
|
|
148
|
-
Model: ${
|
|
149
|
-
`)+te}),X([
|
|
150
|
-
`)})}}catch(
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
`)})
|
|
154
|
-
`)})
|
|
155
|
-
`)})
|
|
156
|
-
`)});return}default:u({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Lt,u,se,Ce]),Ot=V(l=>{let a=(l??I).trim();if(b(""),jt(null),qe(0),a.startsWith("/")){let h=m=>m.trim().split(/\s+/).slice(1).join(" "),p=h(a);X(m=>m.filter(w=>w.trim()!==a&&!(p&&h(w)===p)))}if(!a||Go(a)||qo(a))return;wn.current.push(a);let i=Ws(a,Do.current);a.startsWith("/")?zo(i):Ce(i,{display:a})},[I,Go,qo,zo,Ce]),Yo=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let a=Ls(l);if(Os(a)){let i=Us(++ui.current,a);Do.current.set(i,a),C(i)}else C(a);return}C(l)},[C]),et=Math.max(10,We-6),Vo=mn(()=>pn(k.text,et),[k.text,et]),Tn=V(l=>y(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+l))})),[]),Ut=V(l=>y(a=>({...a,pos:Hs(pn(a.text,et),a.pos,l)})),[et]),ft=V(l=>y(a=>({...a,pos:Bs(pn(a.text,et),a.pos,l)})),[et]),fi=["\x1B[H","\x1B[1~","\x1BOH"],mi=["\x1B[F","\x1B[4~","\x1BOF"],Xo=V((l,a)=>a.leftArrow?(Tn(-1),!0):a.rightArrow?(Tn(1),!0):l&&fi.includes(l)?(ft("start"),!0):l&&mi.includes(l)?(ft("end"),!0):a.ctrl&&l==="a"?(ft("start"),!0):a.ctrl&&l==="e"?(ft("end"),!0):!1,[Tn,ft]);return Ic((l,a)=>{if(a.ctrl&&l==="c"){ce.current?.close(),r();return}if(!z){if(N){if(a.escape){if(ve.current){ve.current.signal.aborted||(u({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),ve.current.abort());return}Et.current||(Et.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),ce.current?.interrupt());return}if(a.return){let i=I.trim();if(!i)return;Oe.current.push(i),xn([...Oe.current]),b("");return}if(Xo(l,a))return;if(a.upArrow){Ut(-1);return}if(a.downArrow){Ut(1);return}if(a.backspace||a.delete){$();return}l&&!a.ctrl&&!a.meta&&Yo(l);return}if(_e){if(a.upArrow){Me(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Me(i=>i&&{...i,cursor:Math.min(we.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=we.length){Me(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=we[_e.cursor];Me(null);let{lines:h,changed:p,effective:m}=bt(e,i.value??"default");for(let w of h)u({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});p&&(Oo(w=>w+1),ce.current?.setModel(m));return}if(l==="s"){let i=we[_e.cursor];Me(null),ce.current?.setModel(i.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){Me(null);return}return}if($e){if(a.upArrow){Ve(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ve(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=$e.rows.length){Ve(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return||l==="s"){let i=$e.rows[$e.cursor];Ve(null),Pn(i.name,a.return===!0);return}if(a.escape){Ve(null);return}return}if(Re){if(a.upArrow){Xe(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Xe(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.rows.length){Xe(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=Re.rows[Re.cursor].name;if(Xe(null),!gr(e,i).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${i}").`});let p=!1;try{let m=He(i);p=!!m&&!(Ie(m)&&!m.refreshToken)}catch{}p?(u({kind:"note",tone:"info",text:`Already signed in to ${i} \u2014 next: pick a workspace.`}),X(["/workspace"])):(u({kind:"note",tone:"info",text:`Next: sign in to Document360 (${i}).`}),X(["/login"])),ye(m=>m+1);return}if(a.escape){Xe(null);return}return}if(oe){if(a.upArrow){Je(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Je(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=oe.rows.length){Je(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=oe.rows[oe.cursor],{profile:h,projectId:p}=oe;Je(null),Mt(h,p,i);return}if(a.escape){Je(null);return}return}if(ue){if(a.upArrow){Ke(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ke(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ue.rows.length){Ke(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=ue.rows[ue.cursor],{profile:h}=ue;Ke(null),Bo(h,i);return}if(a.escape){Ke(null);return}return}if(re){if(a.upArrow){Ze(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ze(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l===" "){Ze(i=>i&&{...i,rows:i.rows.map((h,p)=>p===i.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let i=re.rows.filter(h=>h.checked).map(h=>h.path);if(Ze(null),i.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Nn(e,i),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer.json`});for(let h of i)u({kind:"note",tone:"info",text:` ${h}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){Ze(null);return}return}if(be){if(a.upArrow){Qe(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Qe(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=be.rows.length){Qe(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=be.rows[be.cursor],h=be.rows.filter(p=>p.path!=="--all").map(p=>p.path);Qe(null),Ce(i.path==="--all"?yt(h):Kt(i.path),{display:i.path==="--all"?"/publish --all":`/publish ${i.path}`,echoDisplay:!0});return}if(a.escape){Qe(null);return}return}if(de){if(a.escape){Le(null);return}if(a.upArrow){Le(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Le(i=>i&&{...i,cursor:Math.min(Math.max(0,Nt.length-1),i.cursor+1)});return}if(a.return){let i=Nt[de.cursor];if(i){Le(null);try{u({kind:"preview",name:gn(i),text:ti(Ys(St(e,i),"utf8"))})}catch(h){u({kind:"note",tone:"error",text:`Could not read ${i}: ${h.message}`})}}return}if(a.backspace||a.delete){Le(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){Le(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(pe){if(a.escape){Ue(null);return}if(a.upArrow){Ue(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ue(i=>i&&{...i,cursor:Math.min(Math.max(0,_t.length-1),i.cursor+1)});return}if(a.return){let i=_t[pe.cursor];if(i){Ue(null),se(i.uuid),xe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},Ye(i.name),Co(i.uuid),ze.current=[];let h=bo(e,i.uuid);for(let p of h)u(p);u({kind:"note",tone:"ok",text:h.length?`Resumed "${i.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){Ue(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){Ue(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(a.tab&&!I&&ge){b(ge),he(null),Tt.current++;return}if(!I&&it.length>0&&l&&/^[1-9]$/.test(l)){let i=it[Number(l)-1];if(i){b(i);return}}if(!Xo(l,a)){if(Fo){if(a.upArrow){qe(i=>Math.max(0,i-1));return}if(a.downArrow){qe(i=>Math.min(pt.length-1,i+1));return}if(a.tab){b("/"+(pt[lt]?.name??"")+" "),qe(0);return}if(a.return){let i=pt[lt];if(i){let h=I.trim().slice(1).split(/\s+/).slice(1).join(" ");if(ur(i.usage)&&!h){b("/"+i.name+" "),qe(0);return}Ot("/"+i.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(I!==""&&Ge===null){Ut(-1);return}let i=wn.current;if(!i.length)return;let h=Ge===null?i.length-1:Math.max(0,Ge-1);jt(h),b(i[h]??"");return}if(a.downArrow){if(I!==""&&Ge===null){Ut(1);return}let i=wn.current;if(Ge===null)return;let h=Ge+1;h>=i.length?(jt(null),b("")):(jt(h),b(i[h]??""));return}}if(a.return){Ot();return}if(a.backspace||a.delete){$();return}if(a.escape){b(""),qe(0),he(null),X([]);return}l&&!a.ctrl&&!a.meta&&Yo(l)}}}),Ne(()=>{if(N||z)return;let l=Oe.current.shift();l!==void 0&&(xn([...Oe.current]),Ot(l))},[N,z,Ot]),U(J,{flexDirection:"column",width:We,children:[vn!==null&&U(J,{marginTop:1,flexDirection:"column",children:[vn.truncated&&S(v,{dimColor:!0,children:"\u2026"}),S(v,{children:vn.text})]}),N&&(_o?S(xu,{p:_o}):S(wu,{startTime:Be.current,chars:ci})),S(J,{borderStyle:"round",borderColor:Wo.prod?"yellow":B,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:I?Vo.map((l,a)=>{let i=k.text.slice(l.start,l.end),h=a===fn(Vo,k.pos),p=Math.min(k.pos,l.end)-l.start;return U(v,{children:[S(v,{color:B,children:a===0?"> ":" "}),h?U(Ro,{children:[i.slice(0,p),S(hn,{ch:i[p]??" "}),i.slice(p+1)]}):i||" "]},`${a}-${l.start}`)}):U(v,{children:[S(v,{color:B,children:"> "}),ge&&!N?U(Ro,{children:[S(hn,{ch:ge[0],dim:!0}),S(v,{color:"gray",children:ge.slice(1)}),S(v,{dimColor:!0,children:" (tab)"})]}):bn.isSetup||!li?U(Ro,{children:[S(hn,{ch:bn.text[0],dim:!0}),S(v,{color:"gray",children:bn.text.slice(1)})]}):S(hn,{ch:" "})]})}),No.length>0&&S(J,{flexDirection:"column",paddingX:1,children:No.map((l,a)=>S(v,{color:"gray",children:`\u29D7 queued: ${l}`},`${a}-${l.slice(0,24)}`))}),_e?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Select model"}),S(v,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),we.map((l,a)=>U(v,{color:a===_e.cursor?B:void 0,children:[a===_e.cursor?"\u276F ":" ",`${a+1}. ${l.label}${a===_e.current?" \u2714":""}`.padEnd(16),S(v,{color:"gray",children:l.desc})]},l.label)),S(v,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):$e?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Switch connection profile"}),$e.rows.map((l,a)=>U(v,{color:a===$e.cursor?B:void 0,children:[a===$e.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===$e.current?" \u2714":""}`.padEnd(20),S(v,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?S(v,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),S(v,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Re?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Pick your Document360 environment"}),Re.rows.map((l,a)=>U(v,{color:a===Re.cursor?B:void 0,children:[a===Re.cursor?"\u276F ":" ",`${a+1}. ${l.name}`.padEnd(16),S(v,{color:"gray",children:l.apiUrl})]},l.name)),S(v,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):oe?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Switch workspace"}),S(v,{dimColor:!0,children:`environment ${oe.environment} \xB7 project ${oe.projectId.slice(0,8)}\u2026`}),oe.rows.map((l,a)=>U(v,{color:a===oe.cursor?B:void 0,children:[a===oe.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===oe.current?" \u2714":""}`.padEnd(30),S(v,{color:"gray",children:l.type??""})]},l.id)),S(v,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ue?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Choose project"}),S(v,{dimColor:!0,children:`environment ${ue.environment}`}),ue.rows.map((l,a)=>U(v,{color:a===ue.cursor?B:void 0,children:[a===ue.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===ue.current?" \u2714":""}`.padEnd(30),S(v,{color:"gray",children:l.sub??""})]},l.id)),S(v,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):re?(()=>{let a=Math.min(Math.max(0,re.cursor-Math.floor(7)),Math.max(0,re.rows.length-14)),i=re.rows.slice(a,a+14),h=re.rows.filter(p=>p.checked).length;return U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:`Which folders back the user docs? (${h} selected of ${re.rows.length})`}),a>0?S(v,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((p,m)=>{let w=a+m;return U(v,{color:w===re.cursor?B:void 0,children:[w===re.cursor?"\u276F ":" ",p.checked?"\u25C9 ":"\u25CB ",p.path.padEnd(Math.min(48,We-34)),S(v,{color:"gray",children:Zt(p)})]},p.path)}),a+14<re.rows.length?S(v,{dimColor:!0,children:` \u2193 ${re.rows.length-a-14} more`}):null,S(v,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():be?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Publish which article?"}),be.rows.map((l,a)=>U(v,{color:a===be.cursor?B:void 0,children:[a===be.cursor?"\u276F ":" ",`${a+1}. ${l.path}`.padEnd(Math.min(56,We-30)),S(v,{color:"gray",children:l.label})]},l.path)),S(v,{dimColor:!0,children:"enter publish (draft) \xB7 esc cancel"})]}):de?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:`Preview article${de.query?` \u2014 filter: ${de.query}`:" (type to filter)"}`}),Nt.length===0?S(v,{color:"gray",children:"no articles match"}):Nt.map((l,a)=>U(v,{color:a===de.cursor?B:void 0,children:[a===de.cursor?"\u276F ":" ",l]},l)),S(v,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):pe?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:`Resume session${pe.query?` \u2014 filter: ${pe.query}`:" (type to filter)"}`}),_t.length===0?S(v,{color:"gray",children:"no sessions match"}):_t.map((l,a)=>U(v,{color:a===pe.cursor?B:void 0,children:[a===pe.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),S(v,{color:a===pe.cursor?B:"gray",children:l.firstPrompt.slice(0,Math.max(10,We-40))})]},l.uuid)),S(v,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Fo?S(J,{flexDirection:"column",children:pt.map((l,a)=>U(v,{color:a===lt?B:void 0,children:[a===lt?"\u276F ":" ",l.usage.padEnd(22)," ",S(v,{color:a===lt?B:"gray",children:l.name==="model"&&$n?`${l.desc} (currently ${$n})`:l.desc})]},l.name))}):!I&&it.length>0?U(J,{flexDirection:"column",paddingX:1,children:[it.map((l,a)=>U(v,{children:[S(v,{color:B,children:a+1})," ",l.slice(0,Math.max(20,We-5))]},l)),S(v,{dimColor:!0,children:`press 1-${it.length} to fill the command \xB7 esc dismiss`})]}):S(J,{paddingX:1,children:U(v,{color:"gray",children:[Wo.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${$n??"model n/a"}${t.kind==="api"?Lo>0?` \xB7 ${fe(Lo)}`:"":Mo>0?` \xB7 ${rt(Mo)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}H();import{jsx as vu}from"react/jsx-runtime";async function si(e=process.cwd(),t="auto",n,o="0.0.0"){let r=bu(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 ${R("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${R("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=$u(vu(ri,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
157
|
-
`)
|
|
144
|
+
Model: ${M.model}${M.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:U+Jo(A,R,L).join(`
|
|
145
|
+
`)+te}),X([I]);return}qe.current=Date.now(),lt(0),N(!0);let P=new AbortController;ve.current=P,ee({verb:"Converting",total:A.length,done:0,active:[],rows:fo(A),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${T.length} articles across ${A.length} partitions (\u2264${L} agents at once) on ${M.model}\u2026 (esc to stop)`});try{for await(let R of An({cwd:e,partitions:A,promptFor:Ko,concurrency:L,profileName:s,allowProdWrites:ut.current,model:M.model,signal:P.signal}))if(R.type==="partition_status")R.status==="running"?ee(U=>U&&{...U,active:[...U.active,R.label],rows:Fe(U.rows,R.label,"active"),lastAt:Date.now()}):ee(U=>U&&{...U,active:U.active.filter(te=>te!==R.label),done:U.done+1,rows:Fe(U.rows,R.label,R.status==="done"?"done":"failed"),lastAt:Date.now()});else if(R.type==="partition_event")ee(U=>{if(!U)return U;let te={...U,lastAt:Date.now()};return R.event.type==="tool"?te.tools=U.tools+1:R.event.type==="text"&&(te.chars=U.chars+R.event.delta.length),te});else if(R.type==="run_done"){pt(F=>F+R.totalCostUsd),dt(F=>F+R.results.reduce((Y,oe)=>Y+oe.outputTokens,0));let U=R.aborted?"Stopped. ":"",te=t.kind==="api"?"api":"subscription";u({kind:"note",tone:R.aborted?"warn":R.ok?"ok":"warn",text:U+Qo(R.results,A,te).join(`
|
|
146
|
+
`)})}}catch(R){u({kind:"note",tone:"error",text:`Convert run failed: ${R.message}`})}finally{ve.current=null,ee(null),N(!1)}return}case"write":{if(!ne(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=pu(e);if(p.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:g,path:w,run:T}=en(h),{docsDir:A,targets:L,reason:I}=sn(e,p,{scope:g,path:w});if(L.length===0){u({kind:"note",tone:"warn",text:I??"Nothing to write."});return}let M=oi(L),P=5,R=En(e,"standard");if(!T&&!!!w){let F=ni({files:tn(e,p,L),op:"write",model:R.model}),Y=g?`Scope: ${g} (${L.length} pending)
|
|
147
|
+
`:"",oe=`
|
|
148
|
+
Model: ${R.model}${R.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:Y+nn(M,F,P).join(`
|
|
149
|
+
`)+oe}),X([`/write${g?` --scope ${g}`:" --all"} --run`]);return}qe.current=Date.now(),lt(0),N(!0);let te=new AbortController;ve.current=te,ee({verb:"Writing",total:M.length,done:0,active:[],rows:fo(M),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${L.length} article${L.length===1?"":"s"} across ${M.length} partition${M.length===1?"":"s"} (\u2264${P} agents at once) on ${R.model}${R.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let F of An({cwd:e,partitions:M,promptFor:Y=>on(Y,A),concurrency:P,profileName:s,allowProdWrites:ut.current,model:R.model,signal:te.signal}))if(F.type==="partition_status")F.status==="running"?ee(Y=>Y&&{...Y,active:[...Y.active,F.label],rows:Fe(Y.rows,F.label,"active"),lastAt:Date.now()}):ee(Y=>Y&&{...Y,active:Y.active.filter(oe=>oe!==F.label),done:Y.done+1,rows:Fe(Y.rows,F.label,F.status==="done"?"done":"failed"),lastAt:Date.now()});else if(F.type==="partition_event")ee(Y=>{if(!Y)return Y;let oe={...Y,lastAt:Date.now()};return F.event.type==="tool"?oe.tools=Y.tools+1:F.event.type==="text"&&(oe.chars=Y.chars+F.event.delta.length),oe});else if(F.type==="run_done"){pt(Eo=>Eo+F.totalCostUsd),dt(Eo=>Eo+F.results.reduce((xi,$i)=>xi+$i.outputTokens,0));let Y=F.aborted?"Stopped. ":"",oe=t.kind==="api"?"api":"subscription";u({kind:"note",tone:F.aborted?"warn":F.ok?"ok":"warn",text:Y+rn(F.results,M,oe).join(`
|
|
150
|
+
`)})}}catch(F){u({kind:"note",tone:"error",text:`Write run failed: ${F.message}`})}finally{ve.current=null,ee(null),N(!1)}return}case"sync":{let p=(h[0]??"status").toLowerCase();try{if(p==="status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let g=await jn({cwd:e,profileName:s});u({kind:"note",tone:"info",text:to(g).join(`
|
|
151
|
+
`)});return}if(p==="pull"){let g=h[1];if(!g){u({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let w;if(g==="--all"){if(u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),w=(await jn({cwd:e,profileName:s})).entries.filter(L=>L.status==="remote-ahead"&&L.path).map(L=>L.path),w.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing is remote-ahead \u2014 no pulls needed. (Conflicts are never bulk-pulled; pull them one by one.)"});return}}else w=[g.replace(/\\/g,"/")];let T=[];for(let A of w)T.push(await su({cwd:e,profileName:s,relPath:A}));Te.current=T,Ot();return}u({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${p} \u2014 use /sync or /sync pull <path>|--all.`})}catch(g){u({kind:"note",tone:"error",text:`Sync failed: ${g.message}`})}return}case"scope":{if(!ne(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=iu(e);if(p.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}et({cursor:0,rows:p.map(g=>({...g,checked:g.recommended}))});return}case"audit":case"capture-setup":{let g=await(i==="audit"?Zt:Pt)(h,void 0);if(g.kind==="forward-to-agent"&&g.prompt&&await Ce(g.prompt,{display:g.display,echoDisplay:!0}),i==="capture-setup"){let w=hn(e);w&&u({kind:"note",tone:"info",text:w.join(`
|
|
152
|
+
`)})}return}case"devhints":{if(!ne(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}fu(mu(e)),Wc(gu(e),kn()),u({kind:"note",tone:"info",text:wn().join(`
|
|
153
|
+
`)});return}case"screenshot":{let p=fn(h);if(p.mode==="list"){if(!ne(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:gn(mn(e,p.scope),p.scope).join(`
|
|
154
|
+
`)});return}if(p.mode==="single"){let P=await ro(h);P.kind==="forward-to-agent"&&P.prompt&&await Ce(P.prompt,{display:P.display,echoDisplay:!0});return}if(!ne(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let g=p.mode==="scope"?p.scope:void 0,w=uu(e,{scope:g}).map(P=>P.id);if(w.length===0){u({kind:"note",tone:"info",text:g?`No screenshot placeholders under ${g}.`:"No screenshot placeholders found in the docs."});return}let T=6,A=cu(w,3),L=En(e,"standard");qe.current=Date.now(),lt(0),N(!0);let I=new AbortController;ve.current=I,ee({verb:"Authoring",unit:"spec",total:A.length,done:0,active:[],rows:fo(A),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${w.length} screenshot spec${w.length===1?"":"s"} across ${A.length} partition${A.length===1?"":"s"} (\u2264${T} agents at once) on ${L.model}${L.forced?" (forced)":""}\u2026 (esc to stop)`});let M=!1;try{for await(let P of An({cwd:e,partitions:A,promptFor:ws,concurrency:T,profileName:s,allowProdWrites:ut.current,model:L.model,signal:I.signal}))if(P.type==="partition_status")P.status==="running"?ee(R=>R&&{...R,active:[...R.active,P.label],rows:Fe(R.rows,P.label,"active"),lastAt:Date.now()}):ee(R=>R&&{...R,active:R.active.filter(U=>U!==P.label),done:R.done+1,rows:Fe(R.rows,P.label,P.status==="done"?"done":"failed"),lastAt:Date.now()});else if(P.type==="partition_event")ee(R=>{if(!R)return R;let U={...R,lastAt:Date.now()};return P.event.type==="tool"?U.tools=R.tools+1:P.event.type==="text"&&(U.chars=R.chars+P.event.delta.length),U});else if(P.type==="run_done"){pt(F=>F+P.totalCostUsd),dt(F=>F+P.results.reduce((Y,oe)=>Y+oe.outputTokens,0));let R=P.results.filter(F=>F.ok).length,U=P.aborted?"Stopped. ":"";M=!P.aborted&&p.setup;let te=P.aborted?"":M?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";u({kind:"note",tone:P.aborted?"warn":P.ok?"ok":"warn",text:`${U}Authored specs \u2014 ${R}/${P.results.length} batches ok.${te}`})}}catch(P){u({kind:"note",tone:"error",text:`Spec authoring failed: ${P.message}`})}finally{ve.current=null,ee(null),N(!1)}if(M){let P=await Pt();P.kind==="forward-to-agent"&&P.prompt&&await Ce(P.prompt,{display:P.display,echoDisplay:!0});let R=hn(e);R&&u({kind:"note",tone:"info",text:R.join(`
|
|
155
|
+
`)})}return}case"reset":{let p=yn(e);if(p.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}bo.current={repoName:wo(e),targets:p},u({kind:"note",tone:"warn",text:$n(e,p).join(`
|
|
156
|
+
`)});return}default:u({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Ot,u,ie,Ce]),Ut=V(l=>{let a=(l??E).trim();if(x(""),At(null),Ge(0),a.startsWith("/")){let h=g=>g.trim().split(/\s+/).slice(1).join(" "),p=h(a);X(g=>g.filter(w=>w.trim()!==a&&!(p&&h(w)===p)))}if(!a||Xn(a)||Vn(a))return;$o.current.push(a);let i=Gs(a,Mn.current);a.startsWith("/")?Kn(i):Ce(i,{display:a})},[E,Xn,Vn,Kn,Ce]),Jn=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let a=Fs(l);if(Bs(a)){let i=qs(++gi.current,a);Mn.current.set(i,a),v(i)}else v(a);return}v(l)},[v]),tt=Math.max(10,We-6),Qn=ko(()=>go(k.text,tt),[k.text,tt]),Ao=V(l=>y(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+l))})),[]),Wt=V(l=>y(a=>({...a,pos:Ys(go(a.text,tt),a.pos,l)})),[tt]),mt=V(l=>y(a=>({...a,pos:Vs(go(a.text,tt),a.pos,l)})),[tt]),wi=["\x1B[H","\x1B[1~","\x1BOH"],yi=["\x1B[F","\x1B[4~","\x1BOF"],Zn=V((l,a)=>a.leftArrow?(Ao(-1),!0):a.rightArrow?(Ao(1),!0):l&&wi.includes(l)?(mt("start"),!0):l&&yi.includes(l)?(mt("end"),!0):a.ctrl&&l==="a"?(mt("start"),!0):a.ctrl&&l==="e"?(mt("end"),!0):!1,[Ao,mt]);return Oc((l,a)=>{if(a.ctrl&&l==="c"){ce.current?.close(),r();return}if(!H){if(D){if(a.escape){if(ve.current){ve.current.signal.aborted||(u({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),ve.current.abort());return}Dt.current||(Dt.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),ce.current?.interrupt());return}if(a.return){let i=E.trim();if(!i)return;Oe.current.push(i),vo([...Oe.current]),x("");return}if(Zn(l,a))return;if(a.upArrow){Wt(-1);return}if(a.downArrow){Wt(1);return}if(a.backspace||a.delete){$();return}l&&!a.ctrl&&!a.meta&&Jn(l);return}if(Ne){if(a.upArrow){Me(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Me(i=>i&&{...i,cursor:Math.min(we.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=we.length){Me(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=we[Ne.cursor];Me(null);let{lines:h,changed:p,effective:g}=vt(e,i.value??"default");for(let w of h)u({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});p&&(Fn(w=>w+1),ce.current?.setModel(g));return}if(l==="s"){let i=we[Ne.cursor];Me(null),ce.current?.setModel(i.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){Me(null);return}return}if($e){if(a.upArrow){Xe(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Xe(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=$e.rows.length){Xe(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return||l==="s"){let i=$e.rows[$e.cursor];Xe(null),Ro(i.name,a.return===!0);return}if(a.escape){Xe(null);return}return}if(Re){if(a.upArrow){Ke(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ke(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.rows.length){Ke(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=Re.rows[Re.cursor].name;if(Ke(null),!yr(e,i).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${i}").`});let p=!1;try{let g=Be(i);p=!!g&&!(Ie(g)&&!g.refreshToken)}catch{}p?(u({kind:"note",tone:"info",text:`Already signed in to ${i} \u2014 next: pick a workspace.`}),X(["/workspace"])):(u({kind:"note",tone:"info",text:`Next: sign in to Document360 (${i}).`}),X(["/login"])),ye(g=>g+1);return}if(a.escape){Ke(null);return}return}if(re){if(a.upArrow){Je(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Je(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=re.rows.length){Je(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=re.rows[re.cursor],{profile:h,projectId:p}=re;Je(null),Lt(h,p,i);return}if(a.escape){Je(null);return}return}if(ue){if(a.upArrow){Qe(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Qe(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ue.rows.length){Qe(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=ue.rows[ue.cursor],{profile:h}=ue;Qe(null),Yn(h,i);return}if(a.escape){Qe(null);return}return}if(se){if(a.upArrow){et(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){et(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l===" "){et(i=>i&&{...i,rows:i.rows.map((h,p)=>p===i.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let i=se.rows.filter(h=>h.checked).map(h=>h.path);if(et(null),i.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Lo(e,i),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer.json`});for(let h of i)u({kind:"note",tone:"info",text:` ${h}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){et(null);return}return}if(be){if(a.upArrow){Ze(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ze(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=be.rows.length){Ze(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=be.rows[be.cursor],h=be.rows.filter(p=>p.path!=="--all").map(p=>p.path);Ze(null),Ce(i.path==="--all"?xt(h):Qt(i.path),{display:i.path==="--all"?"/publish --all":`/publish ${i.path}`,echoDisplay:!0});return}if(a.escape){Ze(null);return}return}if(de){if(a.escape){Le(null);return}if(a.upArrow){Le(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Le(i=>i&&{...i,cursor:Math.min(Math.max(0,Nt.length-1),i.cursor+1)});return}if(a.return){let i=Nt[de.cursor];if(i){Le(null);try{u({kind:"preview",name:wo(i),text:ii(Qs(Tt(e,i),"utf8"))})}catch(h){u({kind:"note",tone:"error",text:`Could not read ${i}: ${h.message}`})}}return}if(a.backspace||a.delete){Le(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){Le(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(pe){if(a.escape){Ue(null);return}if(a.upArrow){Ue(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ue(i=>i&&{...i,cursor:Math.min(Math.max(0,Mt.length-1),i.cursor+1)});return}if(a.return){let i=Mt[pe.cursor];if(i){Ue(null),ie(i.uuid),xe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},Ve(i.name),Rn(i.uuid),Ye.current=[];let h=Pn(e,i.uuid);for(let p of h)u(p);u({kind:"note",tone:"ok",text:h.length?`Resumed "${i.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){Ue(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){Ue(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(a.tab&&!E&&ge){x(ge),he(null),Rt.current++;return}if(!E&&at.length>0&&l&&/^[1-9]$/.test(l)){let i=at[Number(l)-1];if(i){x(i);return}}if(!Zn(l,a)){if(Gn){if(a.upArrow){Ge(i=>Math.max(0,i-1));return}if(a.downArrow){Ge(i=>Math.min(ft.length-1,i+1));return}if(a.tab){x("/"+(ft[ct]?.name??"")+" "),Ge(0);return}if(a.return){let i=ft[ct];if(i){let h=E.trim().slice(1).split(/\s+/).slice(1).join(" ");if(mr(i.usage)&&!h){x("/"+i.name+" "),Ge(0);return}Ut("/"+i.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(E!==""&&ze===null){Wt(-1);return}let i=$o.current;if(!i.length)return;let h=ze===null?i.length-1:Math.max(0,ze-1);At(h),x(i[h]??"");return}if(a.downArrow){if(E!==""&&ze===null){Wt(1);return}let i=$o.current;if(ze===null)return;let h=ze+1;h>=i.length?(At(null),x("")):(At(h),x(i[h]??""));return}}if(a.return){Ut();return}if(a.backspace||a.delete){$();return}if(a.escape){x(""),Ge(0),he(null),X([]);return}l&&!a.ctrl&&!a.meta&&Jn(l)}}}),_e(()=>{if(D||H)return;let l=Oe.current.shift();l!==void 0&&(vo([...Oe.current]),Ut(l))},[D,H,Ut]),W(K,{flexDirection:"column",width:We,children:[So!==null&&W(K,{marginTop:1,flexDirection:"column",children:[So.truncated&&S(C,{dimColor:!0,children:"\u2026"}),S(C,{children:So.text})]}),D&&(Un?S(Pu,{p:Un}):S(vu,{startTime:qe.current,chars:mi})),S(K,{borderStyle:"round",borderColor:qn.prod?"yellow":G,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:E?Qn.map((l,a)=>{let i=k.text.slice(l.start,l.end),h=a===ho(Qn,k.pos),p=Math.min(k.pos,l.end)-l.start;return W(C,{children:[S(C,{color:G,children:a===0?"> ":" "}),h?W(Dn,{children:[i.slice(0,p),S(yo,{ch:i[p]??" "}),i.slice(p+1)]}):i||" "]},`${a}-${l.start}`)}):W(C,{children:[S(C,{color:G,children:"> "}),ge&&!D?W(Dn,{children:[S(yo,{ch:ge[0],dim:!0}),S(C,{color:"gray",children:ge.slice(1)}),S(C,{dimColor:!0,children:" (tab)"})]}):Po.isSetup||!fi?W(Dn,{children:[S(yo,{ch:Po.text[0],dim:!0}),S(C,{color:"gray",children:Po.text.slice(1)})]}):S(yo,{ch:" "})]})}),On.length>0&&S(K,{flexDirection:"column",paddingX:1,children:On.map((l,a)=>S(C,{color:"gray",children:`\u29D7 queued: ${l}`},`${a}-${l.slice(0,24)}`))}),Ne?W(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Select model"}),S(C,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),we.map((l,a)=>W(C,{color:a===Ne.cursor?G:void 0,children:[a===Ne.cursor?"\u276F ":" ",`${a+1}. ${l.label}${a===Ne.current?" \u2714":""}`.padEnd(16),S(C,{color:"gray",children:l.desc})]},l.label)),S(C,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):$e?W(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Switch connection profile"}),$e.rows.map((l,a)=>W(C,{color:a===$e.cursor?G:void 0,children:[a===$e.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===$e.current?" \u2714":""}`.padEnd(20),S(C,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?S(C,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),S(C,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Re?W(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Pick your Document360 environment"}),Re.rows.map((l,a)=>W(C,{color:a===Re.cursor?G:void 0,children:[a===Re.cursor?"\u276F ":" ",`${a+1}. ${l.name}`.padEnd(16),S(C,{color:"gray",children:l.apiUrl})]},l.name)),S(C,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):re?W(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Switch workspace"}),S(C,{dimColor:!0,children:`environment ${re.environment} \xB7 project ${re.projectId.slice(0,8)}\u2026`}),re.rows.map((l,a)=>W(C,{color:a===re.cursor?G:void 0,children:[a===re.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===re.current?" \u2714":""}`.padEnd(30),S(C,{color:"gray",children:l.type??""})]},l.id)),S(C,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ue?W(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Choose project"}),S(C,{dimColor:!0,children:`environment ${ue.environment}`}),ue.rows.map((l,a)=>W(C,{color:a===ue.cursor?G:void 0,children:[a===ue.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===ue.current?" \u2714":""}`.padEnd(30),S(C,{color:"gray",children:l.sub??""})]},l.id)),S(C,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):se?(()=>{let a=Math.min(Math.max(0,se.cursor-Math.floor(7)),Math.max(0,se.rows.length-14)),i=se.rows.slice(a,a+14),h=se.rows.filter(p=>p.checked).length;return W(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:`Which folders back the user docs? (${h} selected of ${se.rows.length})`}),a>0?S(C,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((p,g)=>{let w=a+g;return W(C,{color:w===se.cursor?G:void 0,children:[w===se.cursor?"\u276F ":" ",p.checked?"\u25C9 ":"\u25CB ",p.path.padEnd(Math.min(48,We-34)),S(C,{color:"gray",children:eo(p)})]},p.path)}),a+14<se.rows.length?S(C,{dimColor:!0,children:` \u2193 ${se.rows.length-a-14} more`}):null,S(C,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():be?W(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:"Publish which article?"}),be.rows.map((l,a)=>W(C,{color:a===be.cursor?G:void 0,children:[a===be.cursor?"\u276F ":" ",`${a+1}. ${l.path}`.padEnd(Math.min(56,We-30)),S(C,{color:"gray",children:l.label})]},l.path)),S(C,{dimColor:!0,children:"enter publish (draft) \xB7 esc cancel"})]}):de?W(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:`Preview article${de.query?` \u2014 filter: ${de.query}`:" (type to filter)"}`}),Nt.length===0?S(C,{color:"gray",children:"no articles match"}):Nt.map((l,a)=>W(C,{color:a===de.cursor?G:void 0,children:[a===de.cursor?"\u276F ":" ",l]},l)),S(C,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):pe?W(K,{flexDirection:"column",paddingX:1,children:[S(C,{color:G,bold:!0,children:`Resume session${pe.query?` \u2014 filter: ${pe.query}`:" (type to filter)"}`}),Mt.length===0?S(C,{color:"gray",children:"no sessions match"}):Mt.map((l,a)=>W(C,{color:a===pe.cursor?G:void 0,children:[a===pe.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),S(C,{color:a===pe.cursor?G:"gray",children:l.firstPrompt.slice(0,Math.max(10,We-40))})]},l.uuid)),S(C,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Gn?S(K,{flexDirection:"column",children:ft.map((l,a)=>W(C,{color:a===ct?G:void 0,children:[a===ct?"\u276F ":" ",l.usage.padEnd(22)," ",S(C,{color:a===ct?G:"gray",children:l.name==="model"&&Co?`${l.desc} (currently ${Co})`:l.desc})]},l.name))}):!E&&at.length>0?W(K,{flexDirection:"column",paddingX:1,children:[at.map((l,a)=>W(C,{children:[S(C,{color:G,children:a+1})," ",l.slice(0,Math.max(20,We-5))]},l)),S(C,{dimColor:!0,children:`press 1-${at.length} to fill the command \xB7 esc dismiss`})]}):S(K,{paddingX:1,children:W(C,{color:"gray",children:[qn.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Co??"model n/a"}${t.kind==="api"?Hn>0?` \xB7 ${fe(Hn)}`:"":Wn>0?` \xB7 ${st(Wn)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}q();import{jsx as Ru}from"react/jsx-runtime";async function ui(e=process.cwd(),t="auto",o,n="0.0.0"){let r=Tu(t);r.kind==="none"&&(console.error(""),console.error(b("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${j("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${j("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Su(Ru(ci,{cwd:e,auth:r,profileName:o,version:n}));await s(),process.stdout.write(`
|
|
157
|
+
`),process.exit(0)}var Du=Au(import.meta.url),di=Du("../package.json"),Se=new ju;function _n(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Se.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{_n(e),await qt({profile:e.profile,manual:e.manual})});Se.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{_n(e),await cr({profile:e.profile})});Se.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{_n(e),await lr({profile:e.profile})});var Nn=Se.command("profile").description("Manage connection profiles for the current repo");Nn.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Gt(process.cwd()));Nn.command("use <name>").description("Set the default profile for this repo").action(e=>zt(process.cwd(),e));Nn.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Yt(process.cwd(),e));var pi=Se.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");pi.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>ot(process.cwd(),e.profile));pi.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await nr(process.cwd(),e,t.profile)});Se.command("logs").description("Show the Document360 API log files (send these to support when reporting a problem)").action(()=>dr());Se.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(no(),as)),o=await t(process.cwd());for(let n of e(o))console.log(n);process.exitCode=o.some(n=>n.level==="fail")?1:0});Se.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(di.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(Eu.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 pr(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 _s(e.cwd,e.auth,e.profile):await ui(e.cwd,e.auth,e.profile,di.version)});Se.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export type ChecklistStatus = 'pending' | 'active' | 'done' | 'failed';
|
|
2
|
+
export type ChecklistRow = {
|
|
3
|
+
label: string;
|
|
4
|
+
items: number;
|
|
5
|
+
status: ChecklistStatus;
|
|
6
|
+
};
|
|
7
|
+
/** Build the initial (all-pending) checklist rows from a partition plan. */
|
|
8
|
+
export declare function checklistRows(partitions: {
|
|
9
|
+
label: string;
|
|
10
|
+
paths: string[];
|
|
11
|
+
}[]): ChecklistRow[];
|
|
12
|
+
/** Return rows with the named partition set to `status` (immutable; for setConvertProgress updaters). */
|
|
13
|
+
export declare function withRowStatus(rows: ChecklistRow[], label: string, status: ChecklistStatus): ChecklistRow[];
|
|
14
|
+
/** Strip a leading docs-dir path segment so a category row reads "01-getting-started", not
|
|
15
|
+
"user-docs/01-…". Only matches a path-like token (no spaces) so "chunk 1/3" is left intact. */
|
|
16
|
+
export declare function rowLabel(label: string): string;
|
|
17
|
+
export declare const CHECKLIST_MAX_ROWS = 16;
|
|
18
|
+
export declare const ROW_MARK: Record<ChecklistStatus, string>;
|
package/package.json
CHANGED