document360-writer 0.5.133 → 0.5.134
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 +9 -9
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -277,13 +277,13 @@ try {
|
|
|
277
277
|
}
|
|
278
278
|
`;Ga="Re-run dev\u2194docs onboarding (protocol v"});var al={};$a(al,{initCommand:()=>ns,scaffoldInit:()=>ts});import{input as Tn,confirm as vp}from"@inquirer/prompts";import{basename as Ja,join as No}from"node:path";import{existsSync as tn,readFileSync as Cp,readdirSync as Rp,writeFileSync as Sp}from"node:fs";import{writeProjectConfig as Za,readProjectConfig as Pp,projectConfigPath as el,writerDir as Tp,DEFAULT_DOCS_DIR as tl,DEFAULT_CAPTURE_DIR as nl,DEFAULT_OUTPUT_DIR as ol}from"document360-engine";function ts(e,t="berlin"){let n=el(e);if(tn(n))return{created:!1,path:n,profileName:""};let o={projectId:sl(e)??Ja(e),docsDir:tl,captureDir:nl,outputDir:ol,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:il(e)};return Za(o,e),rl(e),{created:!0,path:n,profileName:t}}function rl(e){let t=No(Tp(e),".gitignore");tn(t)||Sp(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
279
279
|
`),"utf8")}async function ns(){let e=process.cwd(),t=el(e);if(tn(t)&&!await vp({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(m("init cancelled.")),{kind:"continue"};let n=sl(e)??Ja(e),o=await Tn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Tn({message:"Capture directory (where document360-capture .spec.ts files live):",default:nl}),s=await Tn({message:"Screenshot output directory:",default:ol}),a=await Tn({message:"Default connection profile name:",default:"berlin"}),u=await Tn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:tl,captureDir:r,outputDir:s,profiles:{[a]:{connection:{environment:u},production:!1}},defaultProfile:a,authoritativeSourceFiles:il(e)},b=Pp(e);b?.terminologyGlossary&&(g.terminologyGlossary=b.terminologyGlossary),Za(g,e),rl(e);let y=Zt(e);console.log(""),console.log(E(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${L(`d360-writer login --profile ${a}`)} ${m("(sign in; project & workspace auto-selected)")}`),console.log("");for(let P of en(y))console.log(P);return console.log(""),console.log(`${m("Then ask:")} ${L('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function sl(e){let t=No(e,"package.json");if(!tn(t))return null;try{return JSON.parse(Cp(t,"utf8")).name??null}catch{return null}}function il(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])tn(No(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=No(e,n);tn(o)&&!Dp(o)&&t.push(n)}return t}function Dp(e){try{return Rp(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Io=ko(()=>{"use strict";q();st()});var mc={};$a(mc,{doctorCommand:()=>Ln,renderDoctorChecks:()=>fc,runDoctorChecks:()=>hc});import{existsSync as $f}from"node:fs";import{d360GetAll as xf,getAccessToken as vf,isExpired as Qs,loadProfileMap as Cf,loadTokens as Rf,packageSkillsDir as uc,ENGINE_VERSION as Sf,projectConfigPath as Pf,readProjectConfig as Tf,DEFAULT_DOCS_DIR as Df,fetchManifestSummary as Af,resolveActiveProfile as jf,classifyClaudeAuth as Ef,CLAUDE_CODE_SETUP_HINT as pc,resolveModelSetting as Nf,probeModel as If,detectAppType as _f,playbookSkillName as Lf,D360AuthError as Of}from"document360-engine";async function hc(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Sf}`});let o=Number(process.versions.node.split(".")[0]);n.push(o>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let r=Ef();r.state==="ready"?n.push({level:"ok",label:`Claude auth: ${r.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):r.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${pc}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:pc});let s=Nf(e);if(n.push({level:"ok",label:`Model: ${s.model} (${s.source==="auto"?"auto \u2014 right-sized for docs; /model to change":s.source})`}),r.state==="ready"){let C=await If(e,s.model??void 0);C.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(C.latencyMs/1e3).toFixed(1)}s`}):C.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${C.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let a=Tf(e);if(!a)return n.push({level:"fail",label:`No ${Pf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let u=(a.docsDir??Df).replace(/\/+$/,"");n.push(a.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 ${u}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let g=a.authoritativeSourceFiles??[];n.push(g.length>0?{level:"ok",label:`Sources: docs grounded in ${g.length} path(s) (${g.slice(0,3).join(", ")}${g.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 b=a.appType??_f(e);if(b){let C=a.appType?"from config":"auto-detected",N=b==="web"||b==="cli";n.push({level:"ok",label:`Genre: ${b} (${C})${N?` \u2192 ${Lf(b)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let y;try{y=jf(e),n.push({level:"ok",label:`Profile: ${y.name} (${y.connection.name})${y.production?" \u26A0 PRODUCTION":""}`})}catch(C){return n.push({level:"fail",label:`Profile config: ${C.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let P=Rf(y.name);P?Qs(P)&&!P.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Qs(P)?n.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(P.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${y.name})`}),n.push(y.project.workspaceId?{level:"ok",label:`Workspace: ${y.project.workspaceName??y.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let x=Cf(e,y.name);x?x.projectId&&y.project.projectId&&x.projectId!==y.project.projectId?n.push({level:"fail",label:`Category map projectId (${x.projectId}) \u2260 profile projectId (${y.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(x.articles).length} articles, ${Object.keys(x.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${y.name}" (created on first /publish)`}),n.push($f(uc())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${uc()}`,fix:"Reinstall document360-writer (broken install)"});let _=Ie(e);if(_.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${le})`}):_.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${_.completedVersion}, current is v${le}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),P&&(!Qs(P)||P.refreshToken)){let C={profile:y.name,connection:y.connection};try{await vf(C);let D=await xf(C,"/v3/projects");n.push({level:"ok",label:`API reachable (${y.connection.apiUrl}) \u2014 ${D.length} project(s) visible`})}catch(D){n.push({level:"fail",label:`API call failed: ${D.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=x?.projectId??y.project.projectId;if(N&&y.project.workspaceId)try{let D=await Af(C,N,y.project.workspaceId);if(D){let W=(D.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${y.connection.name} (${D.languages?.length??0} language${(D.languages?.length??0)===1?"":"s"}) \xB7 hash ${W||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${y.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(D){D instanceof Of||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(D.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${y.project.projectName??N})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${D.message.slice(0,80)})`})}}return n}function fc(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?M("\u26A0"):v("\u2717");t.push(` ${s} ${r.label}${r.detail?m(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${m("fix:")} ${L(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?E(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):v(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Ln(e,t){console.log(m("Running checks\u2026"));for(let n of fc(await hc(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var zo=ko(()=>{"use strict";st();q()});import{Command as ay}from"commander";import{createRequire as ly}from"node:module";import{AUTH_MODES as cy}from"document360-engine";import{input as Bu}from"@inquirer/prompts";import{loginPkce as Vu,refreshTokens as Gu,toStoredTokens as Ta,clearTokens as Yu,decodeJwtClaims as Pa,isExpired as zu,loadTokens as Ku,saveTokens as Da,resolveActiveProfile as vo,setProfileProject as Xu,readProjectConfig as Qu}from"document360-engine";q();import{select as ju}from"@inquirer/prompts";import{resolveActiveProfile as Eu,setProfileProject as Nu,resolveProjectId as Iu,listWorkspaces as _u}from"document360-engine";async function Rn(e,t){let n=Eu(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Iu(o);return{workspaces:await _u(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var va=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Yr(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 bo(e,t,n,o,r){Nu(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Ca(e,t,n){let o;try{o=await Rn(e,n)}catch(s){return console.log(v(`Could not list workspaces: ${s.message}`)),1}let r=Yr(o.workspaces,t);return r?(bo(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(v(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Xt(e,t){let n;try{n=await Rn(e,t)}catch(b){console.log(v(`Could not list workspaces: ${b.message}`));return}let{workspaces:o,projectId:r,profile:s,current:a}=n;if(o.length===0){console.log(m("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let b of o)console.log(` ${b.id===a?L("\u25CF"):" "} ${va(b)} ${m(b.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let u=await ju({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${va(b)}${b.id===a?" (current)":""}`,value:b.id}))}),g=o.find(b=>b.id===u);bo(e,s,r,u,g?.name),console.log(E(`\u2713 Workspace set to "${g?.name??u}" for profile "${s}".`))}q();import{select as Lu}from"@inquirer/prompts";import{resolveActiveProfile as Ou,setProfileProject as Mu,listProjects as Uu}from"document360-engine";async function ot(e,t){let n=Ou(e,t),o={profile:n.name,connection:n.connection};return{projects:await Uu(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Ra=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function zr(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 $o(e,t,n,o){Mu(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Sa(e,t,n){let o;try{o=await ot(e,n)}catch(s){return console.log(v(`Could not list projects: ${s.message}`)),1}let r=zr(o.projects,t);return r?($o(e,o.profile,r.id,r.name),console.log(E(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(v(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function xo(e,t){let n;try{n=await ot(e,t)}catch(g){console.log(v(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(m("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===s?L("\u25CF"):" "} ${Ra(g)} ${m(g.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let a=await Lu({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${Ra(g)}${g.id===s?" (current)":""}`,value:g.id}))}),u=o.find(g=>g.id===a);$o(e,r,a,u?.name),console.log(E(`\u2713 Project set to "${u?.name??a}" for profile "${r}". Next: pick a workspace.`))}q();import Wu from"picocolors";function Fu(e=process.env){return e.FORCE_HYPERLINK==="0"||!Wu.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 qu(e,t=e,n){return Fu(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Hu=/https?:\/\/[^\s\x1b]+/g;function Sn(e,t){return e.replace(Hu,n=>qu(n,n,t))}function Aa(e){return{...Pa(e.idToken)??{},...Pa(e.accessToken)??{}}}function Co(e){let t=Aa(e),n=t.email??t.preferred_username??t.sub??"unknown",o=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${n}${o}`}async function Ro(e){let t=vo(process.cwd(),e.profile),n=t.connection;console.log(m(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Vu(n,{manual:e.manual,promptForRedirect:s=>Bu({message:s})},s=>console.log(Sn(s))),r=Ta(t.name,o);if(Da(r),await Kr(r,t.name,s=>console.log(m(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${Co(r)}`)),console.log(m(` access token expires: ${r.expiresAt}`)),console.log(m(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Qu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Xt(process.cwd(),t.name))}catch{}}async function Kr(e,t,n){let r=Aa(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(vo(process.cwd(),t).project.projectId)return;let a;try{let{projects:u}=await ot(process.cwd(),t);a=u.find(g=>g.id===r)?.name}catch{}Xu(process.cwd(),t,{projectId:r,projectName:a}),n(` Project "${a??r}" written to profile "${t}".`)}catch{}}async function ja(e){let t=vo(process.cwd(),e.profile),n=t.connection,o=Ku(t.name);if(!o){console.log(v(`Not logged in to Document360 (profile "${t.name}").`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${L(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Co(o)}`),zu(o))if(o.refreshToken)try{let r=Ta(t.name,await Gu(n,o.refreshToken));Da(r),console.log(E(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(M(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(M("Session expired (no refresh token).")),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(m(` expires: ${o.expiresAt}`))}async function Ea(e){let t=vo(process.cwd(),e.profile);Yu(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(m(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}q();import{readProjectConfig as Na,writeProjectConfig as Ju,resolveActiveProfile as Zu,loadTokens as ep,isExpired as tp}from"document360-engine";function So(e){let t=Na(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(v("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?L("\u25CF "):" ",s=o.production?M(" \u26A0 PRODUCTION"):"",a=o.connection.environment??"(inline)",u=ep(n),g=u?tp(u)&&!u.refreshToken?M("expired"):m("logged in"):m("not logged in");console.log(`${r}${L(n)} \u2192 ${a}${s} [${g}]`)}console.log(""),console.log(m("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Po(e,t){let n=Na(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(v(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Ju(n,e);let o=n.profiles[t].production?M(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function To(e,t){try{let n=Zu(e,t);console.log(""),console.log(`Profile ${L(n.name)}${n.production?M(" \u26A0 PRODUCTION"):""}`),console.log(m(` api: ${n.connection.apiUrl}`)),console.log(m(` identity: ${n.connection.authorizationUrl}`)),console.log(m(` clientId: ${n.connection.clientId}`)),console.log(m(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(m(` project: ${n.project.projectId??"(set at login)"}`)),console.log(m(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(v(n.message)),process.exitCode=1}}q();import{existsSync as np,readdirSync as op,statSync as Ia}from"node:fs";import{join as _a}from"node:path";import{apiLogDir as rp}from"document360-engine";function La(){let e=rp();if(console.log(""),console.log(`Document360 API logs: ${L(e)}`),!np(e)){console.log(m(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=op(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(m(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Ia(_a(e,r)).size/1024).toFixed(1);console.log(` ${r} ${m(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${m("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Ia(_a(e,r)).size/1024).toFixed(1);console.log(` ${v(r)} ${m(`${s} KB`)}`)}}console.log(""),console.log(m("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(m("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}q();import{createSession as sp,resolveAuth as ip,findByName as ap,slugify as lp,touchSession as cp,upsertSession as dp,resolveActiveProfile as up}from"document360-engine";async function Oa(e,t,n,o,r,s){let a=ip(n);a.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),process.exit(2)),a.kind==="subscription"&&console.error(m("Using your Claude subscription (no API key set)."));let u=null;try{u=up(e,r)}catch(x){console.error(v(`Document360 profile error: ${x.message}`)),process.exit(2)}u.production&&(console.error(M(`\u26A0 Profile "${u.name}" is PRODUCTION.`)),s||(console.error(v("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(m(" --yes given \u2014 proceeding against production.")));let g;if(o){let x=ap(e,o);x||(console.error(v(`No saved session matches "${o}" in this repo.`)),console.error(m("List sessions inside the REPL with /resume.")),process.exit(2)),g=x.uuid,console.error(m(`Resuming "${x.name}"`))}let b=sp({cwd:e,resume:g,profileName:r,allowProdWrites:s===!0}),y=g??null,P=1;for await(let x of b.send(t))switch(x.type){case"session":if(!y){y=x.sessionId;let _=new Date().toISOString();dp({uuid:y,name:lp(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:_,updatedAt:_})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(ae(` \u2699 ${x.name}`));break;case"result":P=x.ok?0:1,console.error(m(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error(v("agent finished with an error result"));break;case"error":console.error(""),console.error(v(`agent error: ${x.message}`)),process.exit(1)}y&&cp(y),process.stdout.write(`
|
|
280
|
-
`),process.exit(P)}import{createInterface as mg}from"node:readline/promises";import{createSession as Ei,resolveAuth as gg,getSession as wg,setTitle as yg,slugify as kg,touchSession as wd,upsertSession as bg,generateTitle as $g,resolveActiveProfile as yd,resolveModelSetting as xg,readProjectConfig as vg,resolveAndPersistAppType as Cg,decodeJwtClaims as gd,isExpired as Rg,loadTokens as Sg,isDirectiveMention as Pg,stripDirectiveMention as Tg,appendDirective as Dg,reconcileUpgradeActions as Ag,stampArticles as jg,listArticleFiles as Eg,CONTENT_CAP_VERSION as Ng}from"document360-engine";import{ENGINE_VERSION as hp}from"document360-engine";var Ne=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot author --all to write the capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then /screenshot capture \u2014 the writer drives a real browser that signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Bare: pick what to do next (author or capture, per shot)."},{t:"cmd",name:"/screenshot author",s:"Write capture specs (<id>, a path, or --all)."},{t:"cmd",name:"/screenshot capture",s:"Take the screenshots (<id>, a path, or --all; bare = pick ready specs)."},{t:"cmd",name:"/screenshot
|
|
280
|
+
`),process.exit(P)}import{createInterface as mg}from"node:readline/promises";import{createSession as Ei,resolveAuth as gg,getSession as wg,setTitle as yg,slugify as kg,touchSession as wd,upsertSession as bg,generateTitle as $g,resolveActiveProfile as yd,resolveModelSetting as xg,readProjectConfig as vg,resolveAndPersistAppType as Cg,decodeJwtClaims as gd,isExpired as Rg,loadTokens as Sg,isDirectiveMention as Pg,stripDirectiveMention as Tg,appendDirective as Dg,reconcileUpgradeActions as Ag,stampArticles as jg,listArticleFiles as Eg,CONTENT_CAP_VERSION as Ng}from"document360-engine";import{ENGINE_VERSION as hp}from"document360-engine";var Ne=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot author --all to write the capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then /screenshot capture \u2014 the writer drives a real browser that signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Bare: pick what to do next (author or capture, per shot)."},{t:"cmd",name:"/screenshot author",s:"Write capture specs (<id>, a path, or --all)."},{t:"cmd",name:"/screenshot capture",s:"Take the screenshots (<id>, a path, or --all; bare = pick ready specs)."},{t:"cmd",name:"/screenshot checklist",s:"What to stage + dev test-id requests (a report; auto-runs after bulk authoring)."},{t:"cmd",name:"/screenshot list",s:"Read-only status of every shot (\u25CB placeholder \xB7 \u25D0 spec \xB7 \u25CF captured)."},{t:"gap"},{t:"dim",s:"One-time setup in the app repo: npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth (real login, once per machine)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress + the next step (`done` marks the next step finished)."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"The screenshot pipeline: bare = pick; author / capture / checklist / list."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function pp(e){switch(e.t){case"head":return e.s;case"text":return` ${e.s}`;case"dim":return` ${e.s}`;case"sub":return e.s;case"good":return` ${e.s}`;case"step":return` ${e.n}. ${e.s}`;case"cmd":return` ${e.name.padEnd(20)} ${e.s}`;case"gap":return""}}function Ma(e){let n=[e?`document360-writer \u2014 help \xB7 v${e.version} \xB7 engine v${e.engineVersion}`:"document360-writer \u2014 help",""];for(let o of Ne){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(pp(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function Xr(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:hp}:void 0;for(let o of Ma(n))console.log(o);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}q();import{getSession as fp}from"document360-engine";async function Ua(e,t){let n=t.currentUuid(),o=n?fp(n):void 0;return console.log(o?m(`
|
|
281
281
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
282
282
|
`):m(`
|
|
283
283
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
284
284
|
`)),{kind:"clear"}}async function Qr(){return{kind:"exit"}}Io();q();import{readMcpConfig as os,writeMcpConfig as ll}from"document360-engine";async function _o(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Ap(),{kind:"continue"}):t==="add"?(jp(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Ep(e.slice(1)),{kind:"continue"}):(console.log(v(`Unknown /mcp subcommand: ${t}`)),console.log(m("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Ap(){let e=os(),t=Object.keys(e.servers);if(t.length===0){console.log(m(`
|
|
285
285
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
286
|
-
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${L(n)} ${m("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?m(` [headers: ${r.join(", ")}]`):"";console.log(` ${L(n)} ${m(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function jp(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(v("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(v(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=os(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let a={};for(let u=1;u<o.length;u++)if(o[u]==="-H"||o[u]==="--header"){let g=o[++u],b=g?.match(/^([^:=]+)[:=](.+)$/);if(!b){console.log(v(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}a[b[1].trim()]=b[2].trim()}else{console.log(v(`Unexpected argument: ${o[u]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(a).length>0?a:void 0}}r.servers[t]=s,ll(r),console.log(""),console.log(E(`\u2713 Registered "${t}" (${n})`)),console.log(M(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(m(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Ep(e){let t=e[0];if(!t){console.log(v("Usage: /mcp remove <name>"));return}let n=os();if(!n.servers[t]){console.log(v(`No server named "${t}".`));return}delete n.servers[t],ll(n),console.log(E(`\u2713 Removed "${t}".`)),console.log(m(" Run /clear to drop it from the current session immediately."))}q();import{readFileSync as zp}from"node:fs";import{join as Kp}from"node:path";import{select as Xp}from"@inquirer/prompts";import{computeSyncStatus as Lo,planPartitions as Qp,relatedArticlePaths as Jp,resolveModelForOperation as Zp,runPartitioned as eh,loadProfileMap as th,resolveActiveProfile as nh,resolveCrossLinks as oh,applyStructureOrder as vl,orderSyncLine as Cl,applyRelatedArticles as Rl,relatedSyncLine as Sl}from"document360-engine";import Z from"picocolors";import kl from"wrap-ansi";import cs from"string-width";q();import it from"picocolors";import rs from"wrap-ansi";import ss from"string-width";var nn=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|setup|list] [id|path|--all]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots; setup: data-staging checklist; list: status",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"roadmap",usage:"/roadmap [done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (publish), take portal (pull), or skip \u2014 for each. Bare: walk them all",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],cl={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"work the screenshot pipeline (author specs, take shots)","/doctor":"run a health check"};function dl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(cl[n])return cl[n];let o=nn.find(r=>r.name===t);return o?o.desc:""}function ul(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return nn.filter(n=>n.name.startsWith(t))}function pl(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Np=new RegExp(`^\\s*/(?:${nn.map(e=>e.name).join("|")})(?:\\s|$)`),hl=e=>Np.test(e),fl=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),ml=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),gl=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Ip(e){let t=e.replace(/\r/g,"").split(`
|
|
286
|
+
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${L(n)} ${m("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?m(` [headers: ${r.join(", ")}]`):"";console.log(` ${L(n)} ${m(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function jp(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(v("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(v(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=os(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let a={};for(let u=1;u<o.length;u++)if(o[u]==="-H"||o[u]==="--header"){let g=o[++u],b=g?.match(/^([^:=]+)[:=](.+)$/);if(!b){console.log(v(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}a[b[1].trim()]=b[2].trim()}else{console.log(v(`Unexpected argument: ${o[u]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(a).length>0?a:void 0}}r.servers[t]=s,ll(r),console.log(""),console.log(E(`\u2713 Registered "${t}" (${n})`)),console.log(M(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(m(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Ep(e){let t=e[0];if(!t){console.log(v("Usage: /mcp remove <name>"));return}let n=os();if(!n.servers[t]){console.log(v(`No server named "${t}".`));return}delete n.servers[t],ll(n),console.log(E(`\u2713 Removed "${t}".`)),console.log(m(" Run /clear to drop it from the current session immediately."))}q();import{readFileSync as zp}from"node:fs";import{join as Kp}from"node:path";import{select as Xp}from"@inquirer/prompts";import{computeSyncStatus as Lo,planPartitions as Qp,relatedArticlePaths as Jp,resolveModelForOperation as Zp,runPartitioned as eh,loadProfileMap as th,resolveActiveProfile as nh,resolveCrossLinks as oh,applyStructureOrder as vl,orderSyncLine as Cl,applyRelatedArticles as Rl,relatedSyncLine as Sl}from"document360-engine";import Z from"picocolors";import kl from"wrap-ansi";import cs from"string-width";q();import it from"picocolors";import rs from"wrap-ansi";import ss from"string-width";var nn=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|checklist|list] [id|path|--all]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots; checklist: what to stage + dev test-id requests; list: status",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"roadmap",usage:"/roadmap [done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (publish), take portal (pull), or skip \u2014 for each. Bare: walk them all",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],cl={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"work the screenshot pipeline (author specs, take shots)","/doctor":"run a health check"};function dl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(cl[n])return cl[n];let o=nn.find(r=>r.name===t);return o?o.desc:""}function ul(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return nn.filter(n=>n.name.startsWith(t))}function pl(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Np=new RegExp(`^\\s*/(?:${nn.map(e=>e.name).join("|")})(?:\\s|$)`),hl=e=>Np.test(e),fl=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),ml=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),gl=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Ip(e){let t=e.replace(/\r/g,"").split(`
|
|
287
287
|
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let u=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)u.push(t[o++]);o++,n.push({kind:"code",lines:u});continue}if(fl(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&ml(t[o+1])){let u=gl(r);o+=2;let g=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)g.push(gl(t[o++]));n.push({kind:"table",header:u,rows:g});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let u=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let g=t[o++];u.push({ordered:/^\s*\d+\.\s+/.test(g),text:g.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:u});continue}if(r.trim()===""){o++;continue}if(hl(r)){n.push({kind:"para",text:r.trim()}),o++;continue}let a=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!hl(t[o])&&!fl(t[o])&&!(t[o].includes("|")&&o+1<t.length&&ml(t[o+1]));)a.push(t[o++]);n.push({kind:"para",text:a.join(" ")})}return n}function is(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?it.bold(t.slice(2,-2)):t.startsWith("`")?L(t.slice(1,-1)):it.italic(t.slice(1,-1)))}var _p=(e,t)=>e+" ".repeat(Math.max(0,t-ss(e)));function Lp(e,t,n){let o=e.length,r=e.map((C,N)=>Math.max(ss(C),...t.map(D=>ss(D[N]??"")))),s=Math.max(24,n),a=3*o+1,u=[...r],g=()=>u.reduce((C,N)=>C+N,0)+a,b=0;for(;g()>s&&b++<1e4;){let C=-1,N=6;for(let D=0;D<o;D++)u[D]>N&&(N=u[D],C=D);if(C===-1)break;u[C]-=1}let y=(C,N,D)=>it.gray(C+u.map(W=>"\u2500".repeat(W+2)).join(N)+D),P=it.gray("\u2502"),x=(C,N)=>{let D=u.map((K,X)=>{let he=C[X]??"",Qe=N?it.bold(he):is(he);return rs(Qe,K,{hard:!0}).split(`
|
|
288
288
|
`)}),W=Math.max(...D.map(K=>K.length)),z=[];for(let K=0;K<W;K++)z.push(u.map((X,he)=>`${P} ${_p(D[he][K]??"",X)} `).join("")+P);return z.join(`
|
|
289
289
|
`)},_=[y("\u250C","\u252C","\u2510"),x(e,!0)];return _.push(t.length===0?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524")),t.forEach((C,N)=>{_.push(x(C,!1)),_.push(N===t.length-1?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524"))}),_.join(`
|
|
@@ -336,14 +336,14 @@ Articles:
|
|
|
336
336
|
`+e.paths.map(r=>`- ${r}`).join(`
|
|
337
337
|
`)}function Os(e,t,n){let o=e.reduce((a,u)=>a+u.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(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.paths.length===1?"":"s"}`),"",`Estimated cost: ${xe(r)}\u2013${xe(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Ms(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),a=e.reduce((C,N)=>C+o(N),0),u=r.reduce((C,N)=>C+o(N),0),g=e.reduce((C,N)=>C+N.costUsd,0),b=e.reduce((C,N)=>C+N.outputTokens,0),y=n==="api"?`${xe(g)} total`:at(b),P=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=C=>`${C} article${C===1?"":"s"}`,_=[];if(s.length===0)_.push(`Wrote ${x(a)} (${P}) successfully \xB7 ${y}.`),_.push("Next \u2014 push them to Document360:"),_.push("/publish --all"),_.push("Or add screenshots first with /screenshot author --all. Drafts are reviewable in the portal after publishing.");else{_.push(`Wrote ${u}/${x(a)} (${P}) \xB7 ${y}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)_.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return _}function Us(e,t,n){try{let o=Gh({cwd:e,paths:n.map(s=>`${t}/${s}`)});if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 /check --fix corrects them.`}catch{return null}}function Ws(e,t,n){let o=(zl(e)?.docsDir??Kh).replace(/\/+$/,""),r=t.map(u=>u.path);if(n.path){let u=nf(n.path,o);return r.includes(u)?{docsDir:o,targets:[u],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${u}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=of(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let a=Is(e,o,s);if(a.length===0){let u=n.scope?` under "${n.scope}"`:"",g=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${u} are already written. Use /write <path> to rewrite one, or /write${g} --rewrite to regenerate them all.`}}return{docsDir:o,targets:a,planCount:r.length}}async function Kl(e,t){if(!zl(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Vo(e)){for(let W of Bl(t.cwd,t.profileName))console.log(m(W));return{kind:"continue"}}if(lt("write",e)){let W=rn(t.cwd,"write",e,t.profileName);if(W.length>0){for(let z of W)console.log(m(z));return{kind:"continue"}}}let n=zh(t.cwd);if(n.length===0)return console.log(v("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:a,rewrite:u}=Ns(e),{docsDir:g,targets:b,reason:y,rewriting:P}=Ws(t.cwd,n,{scope:o,path:r,rewrite:u});if(b.length===0)return console.log(y?M(y):M("Nothing to write.")),{kind:"continue"};P&&console.log(M(`--rewrite: regenerating ${b.length} already-written article${b.length===1?"":"s"} (overwrites them; git has your baseline).`));let x=Yh(b),_=Es(a),{model:C,forced:N}=Xh(t.cwd,"standard"),D=!!r;if(s&&!D){let W=Vh({files:_s(t.cwd,n,b),op:"write",model:C});o&&console.log(m(`Scope: ${o} (${b.length} pending).`));for(let z of Os(x,W,_))console.log(z);return console.log(m(`Model: ${C}${N?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(m(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Writing ${b.length} article${b.length===1?"":"s"} across ${x.length} partition${x.length===1?"":"s"} (\u2264${_} agents at once) on ${C}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let W of Qh({cwd:t.cwd,partitions:x,promptFor:z=>Ls(z,g,{rewrite:P||D}),concurrency:_,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(W.type==="partition_status")W.status==="running"?console.log(m(` \u25B8 ${W.label} \u2014 writing\u2026`)):W.status==="done"?console.log(E(` \u2713 ${W.label}`)):console.log(v(` \u2717 ${W.label}`));else if(W.type==="run_done"){console.log("");let z=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let X of Ms(W.results,x,z))console.log(W.ok?E(X):M(X));if(W.ok)try{Jh(t.cwd,b.map(X=>`${g}/${X}`),{writtenCap:Zh})}catch{}let K=Us(t.cwd,g,b);K&&console.log(M(K))}}catch(W){console.log(v(`Write run failed: ${W.message}`))}return console.log(""),{kind:"continue"}}q();import{existsSync as rf,readdirSync as Xl,statSync as Ql}from"node:fs";import{join as Jl}from"node:path";import{inputDir as sf,readProjectConfig as af}from"document360-engine";var Zl=/\.(md|markdown|pdf|txt)$/i;function Fs(e){let t=sf(e);if(!rf(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Xl(t)){let s=Jl(t,r),a=!1;try{a=Ql(s).isDirectory()}catch{continue}if(a){if(r.startsWith("."))continue;let u=lf(s);u>0&&n.push({name:r,docCount:u})}else Zl.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function lf(e){let t=0;for(let n of Xl(e))try{Ql(Jl(e,n)).isFile()&&Zl.test(n)&&t++}catch{}return t}function qs(e,t){let n=t.trim().toLowerCase();return n?e.find(o=>o.name.toLowerCase()===n)?.name??e.find(o=>o.name.toLowerCase().startsWith(n))?.name??e.find(o=>o.name.toLowerCase().includes(n))?.name??null:null}function Go(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in .d360-writer/input/${e}/`:t?`the input docs in .d360-writer/input/ relevant to: "${t}"`:"the input docs in .d360-writer/input/"}.`,t&&!e?`Use "${t}" as the feature framing.`:"","","Follow the skill: (1) read those PRDs/specs as the primary source (intent, user-facing surface,","terminology, user stories, prerequisites); (2) locate and read the CODE that implements that surface","to pin exact UI strings/routes/states \u2014 never fabricate; flag anything the PRD claims that you","cannot find in source; (3) propose a tight feature-scoped article set (\u22483\u20135) and pin it to",".d360-writer/plan.json + AGENT-PLAN.md, with each article's `sources` listing BOTH the PRD file(s)","AND the grounding code files; (4) flag overlaps with existing articles (do not merge). Then stop and","offer /write. Do NOT write the articles in this turn."].filter(Boolean).join(`
|
|
338
338
|
`)}var Hs="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function ec(e,t){let n=t?.cwd??process.cwd();if(!af(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Fs(n);if(o.length===0&&r===0)return console.log(m(Hs)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(m("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let g of o)console.log(` ${g.name} ${m(`(${g.docCount} doc${g.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let u=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Go(u),display:u?`/draft ${u}`:"/draft"}}let a=qs(o,s);return{kind:"forward-to-agent",prompt:Go(a??"",a?void 0:s),display:`/draft ${s}`}}q();import{listOpenForDocs as cf,readProjectConfig as df}from"document360-engine";function Bs(e){try{return cf(e).filter(t=>t.kind==="request").length}catch{return 0}}function Vs(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Gs(e,t=!1){let n=["Run the document-handoff skill.",""];return e?n.push(`The builder hand-off (what was shipped this session): "${e}".`,"Treat this as the Stage 1 hand-off: ground it in the cited/changed code + the architecture brief,","then decide and APPLY the right doc action \u2014 a new section, a new article, an update to existing","article(s), or a retirement, or a mix. No fixed shape; pick the smallest set that keeps the docs correct."):n.push("No description was given \u2014 call d360_inbox and act on the OPEN `request` messages the builder left:","for each, run the document-handoff flow (ground \u2192 decide \u2192 apply) and mark the request `status: done`","with `resulting_articles` when finished."),n.push("","Draft only \u2014 do not publish. If you would create multiple new articles (a section), call","d360_estimate_cost and present the count + cost band first, then wait for the go-ahead."),t&&n.push("","After the drafts exist and the user confirms any bulk gate, publish the new/updated articles to","Document360 (the publish-to-d360 skill). On a production profile, respect the write-guard."),n.join(`
|
|
339
|
-
`)}var Ys="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function tc(e,t){let n=t?.cwd??process.cwd();if(!df(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Vs(e);if(!r&&Bs(n)===0)return console.log(m(Ys)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Gs(r,o),display:s}}q();import{search as uf}from"@inquirer/prompts";import{findByName as pf,getSession as hf,listSessions as ff,relativeTime as oc}from"document360-engine";async function rc(e,t){let n=ff(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(m("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=pf(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(v(`No session matches "${o}".`)),nc(n),{kind:"continue"})}if(!process.stdin.isTTY)return nc(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>uf({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let a=(s??"").toLowerCase();return n.filter(u=>!a||u.name.toLowerCase().includes(a)||u.firstPrompt.toLowerCase().includes(a)).map(u=>({name:`${u.name} ${oc(u.updatedAt)}`,value:u.uuid,description:u.firstPrompt.slice(0,100)}))}})),r=hf(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function nc(e){console.log("");for(let t of e.slice(0,15))console.log(` ${L(t.name)} ${m(oc(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}q();import{renameSession as mf}from"document360-engine";function zs(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 sc(e,t){let n=zs(e.join(" "));if(!n)return console.log(v("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(mf(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log(v("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(E(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as ic,readProjectConfig as gf,writeProjectConfig as wf}from"document360-engine";q();function Ks(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=gf(e);if(!o)return"No .d360-writer/config.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return ic().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},wf(o,e),null):`Unknown environment "${r}". Known: ${ic().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function ac(e,t){let n=e[0];if(!n)return So(t.cwd),{kind:"continue"};if(n==="add"){let o=Ks(t.cwd,e[1],e[2]);return o?(console.log(v(o)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${L(`/profile ${e[1]}`)} then ${L("/login")}`),{kind:"continue"})}return Po(t.cwd,n),To(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}q();import{select as yf}from"@inquirer/prompts";import{readProjectConfig as kf,readUserConfig as lc,resolveModelSetting as Xs,writeUserConfig as cc}from"document360-engine";var qe=[{value:null,label:"Auto",desc:"Sonnet (latest) \u2014 right-sized for docs work (recommended); heavier models only when you pin them"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus (latest) \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet (latest) \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku (latest) \xB7 fastest for quick answers"}];function Yo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=qe.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function bf(e){switch(e.source){case"project":return".d360-writer/config.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"auto":return"auto \u2014 the docs-right default (newest Sonnet); /model to pin another"}}function _n(e,t){let n=()=>Xs(e).model;if(t==="default"){let s=lc();return s.defaultModel?(delete s.defaultModel,cc(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Xs(e).model} (auto; applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}cc({...lc(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=kf(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer/config.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function dc(e,t){let n=e[0]?.trim();if(!n){let a=Xs(t.cwd);if(!process.stdin.isTTY)return console.log(`${$e("Model:")} ${L(a.model)}${a.source==="auto"?m(" (auto)"):""}`),console.log(m(` source: ${bf(a)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let u=Yo(a),g;try{g=await t.withPausedInput(()=>yf({message:`Select model (current: ${a.model}${a.source==="auto"?" \xB7 auto":""})`,default:qe[u].value,choices:qe.map((x,_)=>({name:`${x.label}${_===u?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:b,changed:y,effective:P}=_n(t.cwd,g??"default");for(let x of b)console.log(x.startsWith("\u26A0")?M(x):x.startsWith("\u2713")?E(x):m(x));return y&&await t.setModel(P),{kind:"continue"}}let{lines:o,changed:r,effective:s}=_n(t.cwd,n);for(let a of o)console.log(a.startsWith("\u26A0")?M(a):a.startsWith("\u2713")?E(a):m(a));return r&&await t.setModel(s),{kind:"continue"}}zo();async function gc(e,t){return await t.withPausedInput(()=>Xt(t.cwd)),{kind:"clear"}}async function wc(e,t){return await t.withPausedInput(()=>xo(t.cwd,t.profileName)),{kind:"clear"}}q();import{resolveActiveProfile as Mf}from"document360-engine";async function yc(e,t){let n=!1;try{n=Mf(t.cwd).production}catch{}return n?(console.log(M("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(m("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}q();var kc=async(e,t)=>{try{await t.withPausedInput(()=>Ro({}))}catch(n){console.log(v(`Login failed: ${n.message}`))}return{kind:"continue"}};q();import{resolveActiveProfile as Uf,clearTokens as Wf,clearProfileProject as Ff}from"document360-engine";async function bc(e,t){let n;try{n=Uf(t.cwd,t.profileName).name}catch(r){return console.log(v(r.message)),{kind:"continue"}}let o=Wf(n);return Ff(t.cwd,n),console.log(o?E(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):m(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(m("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as Zs}from"node:fs";import{isAbsolute as $c,join as xc,resolve as vc}from"node:path";import{readProjectConfig as Cc,screenshotPlaceholderIds as qf,DEFAULT_CAPTURE_DIR as Rc,DEFAULT_OUTPUT_DIR as Hf}from"document360-engine";var Js=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function On(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="setup")return{mode:"setup"};if(t==="list")return{mode:"list",scope:e[1]?Js(e[1]):void 0};t==="author"&&(e=e.slice(1));let n=!e.includes("--no-setup"),o=e.filter(s=>s!=="--no-setup");if(o[0]==="--list")return{mode:"list",scope:o[1]?Js(o[1]):void 0};let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:Js(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function Pt(e,t){let n=Cc(e),o=n?.captureDir??Rc,r=n?.outputDir??Hf,s=(a,u)=>$c(a)?xc(a,u):vc(e,a,u);return qf(e,{scope:t}).map(({id:a,file:u})=>{let g=Zs(s(r,`${a}.png`))?"captured":Zs(s(o,`${a}.spec.ts`))?"spec":"placeholder";return{id:a,file:u,state:g}})}function Sc(e,t){let n=Cc(e)?.captureDir??Rc;return Zs($c(n)?xc(n,`${t}.spec.ts`):vc(e,n,`${t}.spec.ts`))}var Bf={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Vf={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Ko(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 a of e.filter(u=>u.file===s))r.push(` ${Bf[a.state]} ${a.id.padEnd(34)} ${Vf[a.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Pc(e){let t=e.filter(s=>s.state==="placeholder"),n=e.filter(s=>s.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(s=>s.id),indent:!1});let r=new Map;for(let s of t){let a=r.get(s.file);a?a.push(s):r.set(s.file,[s])}for(let s of[...r.keys()].sort()){let a=r.get(s);if(a.length===1){o.push({kind:"shot",action:"author",label:a[0].id,ids:[a[0].id],indent:!1,note:` ${s}`});continue}o.push({kind:"article",action:"author",label:`${s} (${a.length})`,ids:a.map(u=>u.id),indent:!1});for(let u of a)o.push({kind:"shot",action:"author",label:u.id,ids:[u.id],indent:!0})}n.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${n.length} ready specs`,ids:n.map(s=>s.id),indent:!1});for(let s of n)o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],indent:n.length>1,note:" \u25D0 ready \u2014 enter captures"});return o}function Tc(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(`
|
|
339
|
+
`)}var Ys="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function tc(e,t){let n=t?.cwd??process.cwd();if(!df(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Vs(e);if(!r&&Bs(n)===0)return console.log(m(Ys)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Gs(r,o),display:s}}q();import{search as uf}from"@inquirer/prompts";import{findByName as pf,getSession as hf,listSessions as ff,relativeTime as oc}from"document360-engine";async function rc(e,t){let n=ff(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(m("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=pf(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(v(`No session matches "${o}".`)),nc(n),{kind:"continue"})}if(!process.stdin.isTTY)return nc(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>uf({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let a=(s??"").toLowerCase();return n.filter(u=>!a||u.name.toLowerCase().includes(a)||u.firstPrompt.toLowerCase().includes(a)).map(u=>({name:`${u.name} ${oc(u.updatedAt)}`,value:u.uuid,description:u.firstPrompt.slice(0,100)}))}})),r=hf(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function nc(e){console.log("");for(let t of e.slice(0,15))console.log(` ${L(t.name)} ${m(oc(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}q();import{renameSession as mf}from"document360-engine";function zs(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 sc(e,t){let n=zs(e.join(" "));if(!n)return console.log(v("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(mf(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log(v("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(E(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as ic,readProjectConfig as gf,writeProjectConfig as wf}from"document360-engine";q();function Ks(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=gf(e);if(!o)return"No .d360-writer/config.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return ic().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},wf(o,e),null):`Unknown environment "${r}". Known: ${ic().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function ac(e,t){let n=e[0];if(!n)return So(t.cwd),{kind:"continue"};if(n==="add"){let o=Ks(t.cwd,e[1],e[2]);return o?(console.log(v(o)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${L(`/profile ${e[1]}`)} then ${L("/login")}`),{kind:"continue"})}return Po(t.cwd,n),To(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}q();import{select as yf}from"@inquirer/prompts";import{readProjectConfig as kf,readUserConfig as lc,resolveModelSetting as Xs,writeUserConfig as cc}from"document360-engine";var qe=[{value:null,label:"Auto",desc:"Sonnet (latest) \u2014 right-sized for docs work (recommended); heavier models only when you pin them"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus (latest) \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet (latest) \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku (latest) \xB7 fastest for quick answers"}];function Yo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=qe.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function bf(e){switch(e.source){case"project":return".d360-writer/config.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"auto":return"auto \u2014 the docs-right default (newest Sonnet); /model to pin another"}}function _n(e,t){let n=()=>Xs(e).model;if(t==="default"){let s=lc();return s.defaultModel?(delete s.defaultModel,cc(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Xs(e).model} (auto; applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}cc({...lc(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=kf(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer/config.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function dc(e,t){let n=e[0]?.trim();if(!n){let a=Xs(t.cwd);if(!process.stdin.isTTY)return console.log(`${$e("Model:")} ${L(a.model)}${a.source==="auto"?m(" (auto)"):""}`),console.log(m(` source: ${bf(a)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let u=Yo(a),g;try{g=await t.withPausedInput(()=>yf({message:`Select model (current: ${a.model}${a.source==="auto"?" \xB7 auto":""})`,default:qe[u].value,choices:qe.map((x,_)=>({name:`${x.label}${_===u?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:b,changed:y,effective:P}=_n(t.cwd,g??"default");for(let x of b)console.log(x.startsWith("\u26A0")?M(x):x.startsWith("\u2713")?E(x):m(x));return y&&await t.setModel(P),{kind:"continue"}}let{lines:o,changed:r,effective:s}=_n(t.cwd,n);for(let a of o)console.log(a.startsWith("\u26A0")?M(a):a.startsWith("\u2713")?E(a):m(a));return r&&await t.setModel(s),{kind:"continue"}}zo();async function gc(e,t){return await t.withPausedInput(()=>Xt(t.cwd)),{kind:"clear"}}async function wc(e,t){return await t.withPausedInput(()=>xo(t.cwd,t.profileName)),{kind:"clear"}}q();import{resolveActiveProfile as Mf}from"document360-engine";async function yc(e,t){let n=!1;try{n=Mf(t.cwd).production}catch{}return n?(console.log(M("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(m("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}q();var kc=async(e,t)=>{try{await t.withPausedInput(()=>Ro({}))}catch(n){console.log(v(`Login failed: ${n.message}`))}return{kind:"continue"}};q();import{resolveActiveProfile as Uf,clearTokens as Wf,clearProfileProject as Ff}from"document360-engine";async function bc(e,t){let n;try{n=Uf(t.cwd,t.profileName).name}catch(r){return console.log(v(r.message)),{kind:"continue"}}let o=Wf(n);return Ff(t.cwd,n),console.log(o?E(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):m(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(m("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as Zs}from"node:fs";import{isAbsolute as $c,join as xc,resolve as vc}from"node:path";import{readProjectConfig as Cc,screenshotPlaceholderIds as qf,DEFAULT_CAPTURE_DIR as Rc,DEFAULT_OUTPUT_DIR as Hf}from"document360-engine";var Js=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function On(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="checklist"||t==="setup")return{mode:"checklist"};if(t==="list")return{mode:"list",scope:e[1]?Js(e[1]):void 0};t==="author"&&(e=e.slice(1));let n=!e.includes("--no-setup"),o=e.filter(s=>s!=="--no-setup");if(o[0]==="--list")return{mode:"list",scope:o[1]?Js(o[1]):void 0};let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:Js(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function Pt(e,t){let n=Cc(e),o=n?.captureDir??Rc,r=n?.outputDir??Hf,s=(a,u)=>$c(a)?xc(a,u):vc(e,a,u);return qf(e,{scope:t}).map(({id:a,file:u})=>{let g=Zs(s(r,`${a}.png`))?"captured":Zs(s(o,`${a}.spec.ts`))?"spec":"placeholder";return{id:a,file:u,state:g}})}function Sc(e,t){let n=Cc(e)?.captureDir??Rc;return Zs($c(n)?xc(n,`${t}.spec.ts`):vc(e,n,`${t}.spec.ts`))}var Bf={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Vf={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Ko(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 a of e.filter(u=>u.file===s))r.push(` ${Bf[a.state]} ${a.id.padEnd(34)} ${Vf[a.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Pc(e){let t=e.filter(s=>s.state==="placeholder"),n=e.filter(s=>s.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(s=>s.id),indent:!1});let r=new Map;for(let s of t){let a=r.get(s.file);a?a.push(s):r.set(s.file,[s])}for(let s of[...r.keys()].sort()){let a=r.get(s);if(a.length===1){o.push({kind:"shot",action:"author",label:a[0].id,ids:[a[0].id],indent:!1,note:` ${s}`});continue}o.push({kind:"article",action:"author",label:`${s} (${a.length})`,ids:a.map(u=>u.id),indent:!1});for(let u of a)o.push({kind:"shot",action:"author",label:u.id,ids:[u.id],indent:!0})}n.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${n.length} ready specs`,ids:n.map(s=>s.id),indent:!1});for(let s of n)o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],indent:n.length>1,note:" \u25D0 ready \u2014 enter captures"});return o}function Tc(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(`
|
|
340
340
|
`),"","For each: locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir); read the product source for","EXACT routes + stable data-testid selectors (never guess); enter the prepared context via","captureScope(); guard data prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts","(skip-with-TODO if a stable selector is missing). Do NOT run other skills. Report the specs you","wrote and any TODO data-testids."].join(`
|
|
341
341
|
`)}async function Xo(e,t){let n=On(e);if(n.mode==="list"){let a=t?.cwd??process.cwd(),u=Pt(a,n.scope);for(let b of Ko(u,n.scope))console.log(b);let g=u.filter(b=>b.state==="placeholder").length;return g>0&&(console.log(""),console.log(`Author specs: /screenshot author <id> (one shot) \xB7 /screenshot author <path> (a folder) \xB7 /screenshot author --all (all ${g} unauthored)`)),{kind:"continue"}}if(n.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${n.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${n.id}.spec.ts. Report per the skill's writer-facing format \u2014 spec path, data to`,"stage, dev requests only if any, and the capture command; no grounding narration."].join(`
|
|
342
|
-
`),display:`/screenshot ${n.id}`};if(n.mode==="capture"||n.mode==="
|
|
342
|
+
`),display:`/screenshot ${n.id}`};if(n.mode==="capture"||n.mode==="checklist")return{kind:"continue"};let r=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${n.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${n.scope}`:"every <!-- SCREENSHOT --> placeholder across the docs tree (the configured docsDir)"}.`,"Follow that skill exactly for each: read the SCREENSHOT block; read the product source for EXACT routes","and stable data-testid selectors (never guess); enter the prepared context via captureScope(); guard data",`prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts.${n.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`].join(`
|
|
343
343
|
`),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{spawn as Gf}from"node:child_process";import{existsSync as Dc,statSync as Yf}from"node:fs";import{isAbsolute as zf,join as Ac,resolve as Kf}from"node:path";import{readProjectConfig as Xf,DEFAULT_OUTPUT_DIR as Qf}from"document360-engine";var Jf=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function ei(e){let t=e.find(n=>!n.startsWith("--"));return e.includes("--all")?{mode:"all"}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:Jf(t)}:{mode:"single",id:t}:{mode:"picker"}}function ti(e,t){let n=Pt(e,t);return{ready:n.filter(o=>o.state==="spec").map(o=>o.id),captured:n.filter(o=>o.state==="captured").map(o=>o.id)}}function jc(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"),o=[];t.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${t.length} ready specs`,ids:t.map(s=>s.id),indent:!1});let r=new Map;for(let s of t){let a=r.get(s.file);a?a.push(s):r.set(s.file,[s])}for(let s of[...r.keys()].sort()){let a=r.get(s);if(a.length===1){o.push({kind:"shot",action:"capture",label:a[0].id,ids:[a[0].id],indent:!1,note:` ${s}`});continue}o.push({kind:"article",action:"capture",label:`${s} (${a.length})`,ids:a.map(u=>u.id),indent:!1});for(let u of a)o.push({kind:"shot",action:"capture",label:u.id,ids:[u.id],indent:!0})}for(let s of[...n].sort((a,u)=>a.id.localeCompare(u.id)))o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],indent:!1,note:" \u25CF captured \u2014 re-capture"});return o}function Zf(e,t){let n=Xf(e)?.outputDir??Qf;return zf(n)?Ac(n,`${t}.png`):Kf(e,n,`${t}.png`)}function ni(e,t,n,o){let r=Zf(e,t);return Dc(r)&&Yf(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function Ec(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}function Nc(e,t=4){let n=/captured\s+·|^▶ Annotating|^✓ \d+ captured|^\s*[⊘✗]\s+\S+\s*$|^▶ Running \d+ spec/;return e.split(/\r?\n/).map(r=>r.trimEnd()).filter(r=>r.trim().length>0&&!n.test(r.trim())).slice(-t).join(`
|
|
344
344
|
`)}var em=/^[A-Za-z0-9._-]+$/;function oi(e){return new Promise((t,n)=>{if(!em.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=Gf(`d360-capture capture ${e.id}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";e.stdio==="pipe"&&(o.stdout?.on("data",a=>{r+=a.toString()}),o.stderr?.on("data",a=>{r+=a.toString()}));let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",a=>{e.signal?.removeEventListener("abort",s),n(a)}),o.on("close",a=>{e.signal?.removeEventListener("abort",s),t({exitCode:a??1,output:r})})})}function Ic(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function Qo(e){return Dc(Ac(e,".d360-writer","capture.json"))}function ri(){return["Screenshot capture is not configured in this repo yet (no `.d360-writer/capture.json`). Set it up","conversationally \u2014 never tell the user to run `d360-capture init`:","","1. Find the live app URL yourself first: `.d360-writer/config.json` `appUrl`, the product brief, the"," architecture brief, the repo (README, deploy config). Present what you found for confirmation \u2014 or"," ask for it if unknown. In the SAME message also ask: (a) is that URL the production environment?"," (b) which prepared demo context should screenshots enter \u2014 the capture scope (read the product"," source to know what this product scopes by: project / workspace / org; a single-context product"," needs none). One short numbered message, then END YOUR TURN and wait for the answers.","2. On the answers, write `.d360-writer/capture.json` in exactly this shape (fill the values):","```json","{",' "projectId": "<projectId from .d360-writer/config.json>",',' "profiles": {',' "<production or staging, matching their answer>": {',' "connection": { "startUrl": "<the app URL>" },',' "production": <true when they said production>,',' "scope": { "<scopeKey>": "<their demo context>" }'," }"," },",' "defaultProfile": "<the same profile name>"',"}","```"," Omit `scope` for a single-context product. Do not add captureDir/outputDir (defaults apply).","3. Also record the app URL as `appUrl` in `.d360-writer/config.json` \u2014 add/update just that key,",' preserving everything else. It is the canonical "where the product lives" fact (you may use it to'," deep-link stable app screens from articles).","4. Close with the ONE remaining external step, then the retry:"," `d360-capture auth` (run in this repo's terminal; first time also `npm i -g document360-capture`)"," then `/screenshot capture`."].join(`
|
|
345
|
-
`)}function _c(e,t){let n=new Map(Pt(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function si(e,t){let n=t?.cwd??process.cwd(),o=ei(e);if(!Qo(n))return console.log("Screenshot capture is not set up in this repo yet. Run: d360-capture init"),{kind:"continue"};let{ready:r,captured:s}=ti(n,o.mode==="scope"?o.scope:void 0),a=o.mode==="single"?[o.id]:o.mode==="picker"?r:[...r,...s];if(a.length===0)return console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};let u=Date.now(),g=[];for(let y of a){console.log(`\u25B6 ${y}`);try{let{exitCode:P}=await oi({cwd:n,id:y,stdio:"inherit"});g.push({id:y,outcome:ni(n,y,P,u)})}catch(P){if(P.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};g.push({id:y,outcome:"failed",detail:P.message})}}let b=y=>g.filter(P=>P.outcome===y).length;return console.log(`\u2713 ${b("captured")} captured \xB7 \u2298 ${b("skipped")} skipped \xB7 \u2717 ${b("failed")} failed`),{kind:"continue"}}import{existsSync as tm,readFileSync as nm}from"node:fs";import{isAbsolute as om,join as rm,resolve as sm}from"node:path";import{readProjectConfig as im,DEFAULT_CAPTURE_DIR as am}from"document360-engine";async function sn(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-
|
|
346
|
-
`),display:"/
|
|
345
|
+
`)}function _c(e,t){let n=new Map(Pt(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function si(e,t){let n=t?.cwd??process.cwd(),o=ei(e);if(!Qo(n))return console.log("Screenshot capture is not set up in this repo yet. Run: d360-capture init"),{kind:"continue"};let{ready:r,captured:s}=ti(n,o.mode==="scope"?o.scope:void 0),a=o.mode==="single"?[o.id]:o.mode==="picker"?r:[...r,...s];if(a.length===0)return console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};let u=Date.now(),g=[];for(let y of a){console.log(`\u25B6 ${y}`);try{let{exitCode:P}=await oi({cwd:n,id:y,stdio:"inherit"});g.push({id:y,outcome:ni(n,y,P,u)})}catch(P){if(P.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};g.push({id:y,outcome:"failed",detail:P.message})}}let b=y=>g.filter(P=>P.outcome===y).length;return console.log(`\u2713 ${b("captured")} captured \xB7 \u2298 ${b("skipped")} skipped \xB7 \u2717 ${b("failed")} failed`),{kind:"continue"}}import{existsSync as tm,readFileSync as nm}from"node:fs";import{isAbsolute as om,join as rm,resolve as sm}from"node:path";import{readProjectConfig as im,DEFAULT_CAPTURE_DIR as am}from"document360-engine";async function sn(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-writer/capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-CHECKLIST.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
|
|
346
|
+
`),display:"/screenshot checklist"}}var Lc="-".repeat(64);function ii(e){let t=am;try{let y=im(e);y?.captureDir&&(t=y.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=om(t)?rm(t,"CAPTURE-TESTID-REQUESTS.json"):sm(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!tm(n))return null;let o;try{let y=JSON.parse(nm(n,"utf8").replace(/^/,""));o=Array.isArray(y?.requests)?y.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(y=>y.file).filter(Boolean)).size,s=o.length,a=`${s} data-testid attribute${s===1?"":"s"}`,u=`${r} source file${r===1?"":"s"}`,g=`${t}/CAPTURE-TESTID-REQUESTS.md`,b=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${a} requested across ${u}.`,"\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.","",Lc,`Read ${g} and ${b}. They list ${a} 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.",Lc]}st();q();import{listOpenForDocs as lm,readProjectConfig as cm}from"document360-engine";function ai(e){try{return lm(e).length}catch{return 0}}function li(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape.",' \u2022 answer to a [discovery]-tagged question (subject starts "[discovery] ") \u2192 this is product-discovery,'," not an article edit: fold the fact into `.d360-writer/product-brief.md` (updating the cited grounding,"," clearing the matching OPEN marker), then RE-RUN the discover-product readiness assessment \u2014 set the"," brief's frontmatter status to `confident` and offer propose-structure if every rubric dimension now"," passes, else ask the next focused batch via d360_ask_builder. Do not touch articles for these.",' \u2022 answer to a [depth]-tagged question (subject starts "[depth] ") \u2192 this is per-feature depth-mining,'," not the brief and not an article edit: fold it into the DOCS PLAN per propose-structure's"," depth-reconcile \u2014 adjust that feature's article palette in plan.json/AGENT-PLAN.md (add rows citing"," the answer's .d360-writer/messages/ file in `sources`, never renumber existing rows), decrement"," open_depth_questions in AGENT-PLAN.md's frontmatter, and flip status to `pinned` at zero."," \u2022 answer (a reply to any other question you asked; `re` = your question id) \u2192 fold the fact into the"," affected article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only \u2014 do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
|
|
347
347
|
`)}async function Oc(e,t){let n=t?.cwd??process.cwd();return cm(n)?ai(n)===0?(console.log(m("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:li(),display:"/inbox"}:(console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}q();import{listOpenHints as dm,listOpenForDocs as um,listOpenDirectives as pm,readProjectConfig as hm,computeSyncStatus as fm,planPull as mm,applyPull as gm,planImport as wm,applyImport as ym}from"document360-engine";function Mn(e){let t=0,n=0,o=0,r=0;try{t=dm(e).length}catch{}try{let s=um(e);n=s.filter(a=>a.kind==="request").length,o=s.filter(a=>a.kind==="answer").length}catch{}try{r=pm(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function Un(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),t.length?t.join(", "):null}function di(e){return{publish:e.includes("--publish")}}function ui({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page" \u2014 .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and \u2014 if it already exists \u2014 RE-ASSERTS and VERIFIES that the category is hidden). If the result has `hiddenConfirmed: false` or a `warning`, SURFACE that warning to the user PROMINENTLY at the end of your summary (\u26A0 the internal feedback control zone may be public on their KB \u2014 they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY \u2014 triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","4. Decide the right doc actions across ALL of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief \u2014 EXCEPT an answer to a [discovery]-tagged question (subject starts \"[discovery] \"), which is product discovery: fold it into `.d360-writer/product-brief.md`, then re-run the discover-product readiness assessment (flip the brief to `confident` if every rubric dimension now passes and offer propose-structure, else leave a follow-up [discovery] question), and EXCEPT an answer to a [depth]-tagged question (subject starts \"[depth] \"), which is per-feature depth-mining: fold it into the DOCS PLAN per propose-structure's depth-reconcile (adjust that feature's article palette in plan.json/AGENT-PLAN.md, cite the answer's messages/ file in new rows' `sources`, never renumber existing rows, decrement AGENT-PLAN.md's open_depth_questions and flip status to `pinned` at zero) \u2014 address each feedback item (improve the doc it points at \u2014 as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts \u2014 following the active doc-type playbook).","5. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the loop:"," \u2022 stamp consumed hints, and mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done) \u2014 including a step whose work you can verify an EARLIER session already completed but left unstamped \u2014 and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed \u2014 never delete existing steps;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article \u2014 `**d360-writer response:** \u2713 actioned in <article> \u2014 <date>` (or `declined \u2014 <reason>`) \u2014 NEVER overwriting the person's own text \u2014 then call d360_feedback_done(article_id, resulting_articles);"," \u2022 EXCEPT the Creator-notes item (is_creator_notes:true): do NOT reply in it \u2014 instead fold its content into `.d360-writer/architecture/CREATOR-NOTES.md` as an appended, dated `## From portal Creator notes (<date>)` section (preserve every existing note + human edit), then call d360_feedback_done for it.","8. Push the drafts to Document360.","9. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs \u2014 only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)"];return t.push(e?"10. Then publish the new/updated articles live (publish-to-d360 skill), respecting the production write-guard.":"Leave everything as DRAFTS for review \u2014 do not publish live (run /publish when you want them live)."),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (plus the d360_ask_builder question you left for it)."),t.join(`
|
|
348
348
|
`)}var km={status:fm,plan:mm,apply:gm,planImport:wm,applyImport:ym};async function pi(e,t=km){let n={pulled:[],imported:[],conflicts:[],failed:[]},o;try{o=await t.status({cwd:e.cwd,profileName:e.profileName})}catch(r){return n.error=r.message,n}for(let r of o.entries)if(r.status==="conflict"&&r.path)n.conflicts.push(r.path);else if(r.status==="untracked-remote"&&r.articleId)try{let s=await t.planImport({cwd:e.cwd,profileName:e.profileName,articleId:r.articleId});t.applyImport({cwd:e.cwd,profileName:e.profileName},s),n.imported.push(s.path)}catch(s){n.failed.push({path:r.title??r.articleId,error:s.message})}else if(r.status==="remote-ahead"&&r.path)try{let s=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},s),n.pulled.push(r.path)}catch(s){n.failed.push({path:r.path,error:s.message})}return n}var ci=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Jo=e=>e===1?"":"s";function hi(e){if(e.error)return[`\u26A0 Couldn't check Document360 for portal changes (${e.error.slice(0,100)}) \u2014 proceeding; the agent will re-check.`];let t=[];return e.pulled.length&&t.push(`\u2713 Pulled ${e.pulled.length} portal edit${Jo(e.pulled.length)} into local: ${ci(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Jo(e.imported.length)} into local drafts: ${ci(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Jo(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${ci(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${Jo(e.failed.length)} failed \u2014 left for /pull.`),t}async function Mc(e,t){let n=t?.cwd??process.cwd();if(!hm(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=_e(n,t?.profileName);if(!o.ok)return console.log(v(o.reason)),{kind:"continue"};let{publish:r}=di(e);console.log(m("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await pi({cwd:n,profileName:t?.profileName});for(let u of hi(s))console.log(u.startsWith("\u2713")?E(u):u.startsWith("\u2139")?m(u):M(u));let a=Un(Mn(n));return console.log(m(a?`Catching up on ${a}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:ui({publish:r}),display:`/catch-up${r?" --publish":""}`}}q();import{spawn as bm}from"node:child_process";var Tt="document360-writer",Zo=`npm i -g ${Tt}@latest`;async function er(){let e=process.platform==="win32";return new Promise(t=>{try{let n=bm(`npm i -g ${Tt}@latest`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});n.on("error",o=>t({ok:!1,output:String(o)})),n.on("close",o=>t({ok:o===0,output:""})),e||n.unref()}catch(n){t({ok:!1,output:String(n)})}})}async function Uc(){return console.log(m(`Updating ${Tt}\u2026`)),(await er()).ok?console.log(E("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(v(`Update failed \u2014 run manually: ${Zo}`)),{kind:"continue"}}q();st();import{existsSync as fi,rmSync as $m}from"node:fs";import{basename as Wc,resolve as mi}from"node:path";import{execFileSync as xm}from"node:child_process";import{input as vm}from"@inquirer/prompts";import{readProjectConfig as Cm,devHintsGuidePath as Rm}from"document360-engine";var Sm=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Pm=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),tr=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Fc=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function qc(e){let t=tr(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Fc(t)?!0:Pm.has(t)}function gi(e){let t=null;try{t=Cm(e)}catch{t=null}let n=new Set(Sm);for(let o of[tr(t?.docsDir),tr(t?.captureDir),tr(t?.outputDir)])o&&Fc(o)&&n.add(o);return[...n].filter(o=>qc(o)&&fi(mi(e,o)))}function wi(e,t){let n=[],o=[];for(let r of t){if(!qc(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{$m(mi(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Hc(e,t){try{return xm("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
349
349
|
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Tm(e){return Hc(e,".d360-writer/hints")}function Dm(e){return Hc(e,".d360-writer/messages")}function yi(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Tm(e),o=Dm(e),r=fi(mi(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(s=>` \u2022 ${s}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o>0?[`\u26A0 ${o} message(s) under .d360-writer/messages/ are not committed \u2014 commit them first or they're gone.`]:[],...r?["Note: a repo-root user-docs/ is NOT touched (only .d360-writer/ is removed)."]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${Wc(e)}`]}async function Bc(e,t){let n=gi(t.cwd);for(let g of yi(t.cwd,n))console.log(n.length===0?m(g):g);if(n.length===0)return{kind:"continue"};let o=Wc(t.cwd);if((await t.withPausedInput(()=>vm({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(M("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=fi(Rm(t.cwd)),{removed:a,failed:u}=wi(t.cwd,n);console.log(E(`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`));for(let g of u)console.log(v(` \u2717 ${g.path}: ${g.error}`));if(s){for(let g of Eo())console.log(g);console.log(m("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(m("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}q();import{lintDocs as Am}from"document360-engine";function nr(e){if(e.length===0)return["\u2713 No issues found \u2014 no leaked internals, unknown commands, stale version facts, or AI-tells in the docs."];let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}let n=[`\u26A0 ${e.length} doc issue${e.length===1?"":"s"} in ${t.size} article${t.size===1?"":"s"} (leaked internals / unknown commands / stale facts / AI-tells):`];for(let[o,r]of t){n.push(` ${o}`);for(let s of r)n.push(` L${s.line}: "${s.term}" \u2014 ${s.message}`)}return n}function ki(e){let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}return["The documentation quality check found issues in already-written articles. FIX each one by EDITING the","article in place \u2014 do not rewrite whole articles, just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","How to fix, by issue type:","- internal-leak (an agent codename, an internal skill name, or a d360_* tool name): this is the"," documentation engine's own machinery and must NOT appear in user docs. Reword the sentence to describe"," the behavior in plain user terms, or delete the internal aside. Do NOT swap it for another internal term.","- unknown-command: the named /command or --flag does not exist in the product source. Find the correct"," command/flag in the source and use it; if there is no real equivalent, remove the claim.","- stale-fact: the version contradicts the product's package.json engines \u2014 correct it to the real value.","- ai-tell: a machine-sounding buzzword (e.g. delve, leverage, furthermore, robust). Rewrite the phrase in"," plain, direct developer language; preserve the meaning; do NOT swap one buzzword for another.","- stray-file: a junk *.publish.md file (a publish transform wrongly written to disk). DELETE the file \u2014",' do not edit it, do not publish it; the real article is its sibling without ".publish". Nothing else changes.',"","Rules: edit ONLY the listed articles; do not touch others; do not publish; introduce no new internal","nouns, invented commands, or wrong facts. When done, every listed issue should be gone.","","Issues:",[...t.entries()].map(([o,r])=>[o,...r.map(s=>` - L${s.line} [${s.kind}]: "${s.term}" \u2014 ${s.message}`)].join(`
|
|
@@ -357,7 +357,7 @@ ${a.map(b=>` \u25CB ${b.title}`).join(`
|
|
|
357
357
|
${n.map(b=>` \u25CB ${b.title}`).join(`
|
|
358
358
|
`)}`};let u=a[0].title;Gm(e,u,{doneAt:new Date().toISOString()});let g=ed(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${u}${g?` \u2014 next up: ${g.title}${g.run?` (${g.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function td(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?rr(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function nd(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=rr(e).find(r=>r.status==="open"&&r.title.trim().toLowerCase()===n);return o?[`Execute this open docs-roadmap step: "${o.title}".`,o.run?`Its run command: ${o.run}`:"",o.body?`Step detail:
|
|
359
359
|
${o.body}`:"","",`Close the loop IN THE SAME TURN the step's goal state is reached: call d360_roadmap_done with exactly the title "${o.title}", then tell the user it is marked done. This INCLUDES discovering the goal already holds \u2014 "no action needed" completes the STEP, not just the turn, so stamp it done then too. Leave it open ONLY if the work is genuinely incomplete (blocked, or background results not yet applied) \u2014 then say exactly what remains before it can be closed.`].filter(Boolean).join(`
|
|
360
|
-
`):null}async function od(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=sr(n,e.slice(1).join(" ").trim());return console.log(r.ok?E(r.line):M(r.line)),{kind:"continue"}}let o=vi(n);console.log(L(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?m(r):r);return{kind:"continue"}}var rd={help:Xr,"?":Xr,clear:Ua,exit:Qr,quit:Qr,init:ns,mcp:_o,publish:Tl,audit:Nn,discover:Dl,scope:jl,pull:ql,resolve:Ul,convert:Hl,write:Kl,draft:ec,document:tc,resume:rc,rename:sc,profile:ac,model:dc,doctor:Ln,workspace:gc,project:wc,"allow-prod":yc,login:kc,logout:bc,screenshot:async(e,t)=>{let n=On(e);return n.mode==="capture"?si(n.rest,t):n.mode==="
|
|
360
|
+
`):null}async function od(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=sr(n,e.slice(1).join(" ").trim());return console.log(r.ok?E(r.line):M(r.line)),{kind:"continue"}}let o=vi(n);console.log(L(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?m(r):r);return{kind:"continue"}}var rd={help:Xr,"?":Xr,clear:Ua,exit:Qr,quit:Qr,init:ns,mcp:_o,publish:Tl,audit:Nn,discover:Dl,scope:jl,pull:ql,resolve:Ul,convert:Hl,write:Kl,draft:ec,document:tc,resume:rc,rename:sc,profile:ac,model:dc,doctor:Ln,workspace:gc,project:wc,"allow-prod":yc,login:kc,logout:bc,screenshot:async(e,t)=>{let n=On(e);return n.mode==="capture"?si(n.rest,t):n.mode==="checklist"?sn():Xo(e,t)},capture:si,"capture-setup":sn,devhints:Xa,inbox:Oc,"catch-up":Mc,update:Uc,reset:Bc,check:Vc,review:Kc,reorder:Xc,structure:zc,genre:or,roadmap:od};function sd(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),o=(n[0]??"").toLowerCase();return o?{name:o,args:n.slice(1)}:null}st();var Ym="Or just tell me what to write or update.",zm='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function ue(e){return e===1?"":"s"}function ir(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Fn(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var Km={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",options:[{cmd:"/genre web",desc:"web app / SaaS UI"},{cmd:"/genre cli",desc:"command-line tool"},{cmd:"/genre service",desc:"API / backend service"},{cmd:"/genre library",desc:"SDK / library"}]};function Xm(e){let t=[];if(e.devhints!=="current"&&e.builderStarted){let n=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",o=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";t.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${n}${o} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${n}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&t.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:Km,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.discovery&&e.discovery.status!=="confident"){let n=e.discovery.openQuestions;t.push(e.discovery.status==="pending"?{key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/publish steps)."}:n>0?{key:"discovery",bullet:`product discovery is waiting on ${n} answer${ue(n)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}:{key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.directives>0||e.pendingText){let n=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",o=[];e.directives>0&&o.push(`${e.directives} owner directive${ue(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
|
|
361
361
|
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${ue(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${ue(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ue(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${ue(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${ue(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${ue(n)} changed both here and on Document360 (conflicts) \u2014 /publish skips these`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each conflict \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${n} conflict${ue(n)} (keep yours / take the portal's / skip).`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${ue(n.total)} done \u2014 next: ${o.title}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${ue(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${ue(n)}.`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${ue(n)} under .d360-writer/ \u2014 a commit request is standing in your builder's mailbox (the sync bookkeeping in there protects against duplicate publishes)`,lead:null,picker:null,follow:null})}return t}function id(e){return e.find(t=>t.lead||t.picker)??null}function Ci(e,t){let n=t.filter(a=>a.bullet).map(a=>` \u2022 ${a.bullet}`),o=id(t),r=[];o?.lead?r.push(Fn(o.lead)):o?.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let a of t.filter(u=>u!==o).slice(0,2))a.follow&&r.push(a.follow);let s=[[e,...n].join(`
|
|
362
362
|
`)];return r.length&&s.push(r.join(" ")),s.push(Ym),s.join(`
|
|
363
363
|
|
|
@@ -388,7 +388,7 @@ ${su}`}),Q(f?"/doctor":"/init");return}f&&Q("/doctor");try{let p=De(e,s),w=At(p.
|
|
|
388
388
|
`)})}catch{}let O=i("ready-decision",()=>vt(!0));O.kind==="autoAudit"?(d({kind:"note",tone:"info",text:O.note}),Nn().then(p=>{p.kind==="forward-to-agent"&&p.prompt&&te(p.prompt,{display:p.display,quietUser:!0})})):O.kind==="recommend"&&oo(O.rec);let h=Math.round(performance.now()-c);h>=800&&qw({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${h}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${l.length?l.join(`
|
|
389
389
|
`):"no single phase \u226580ms"}
|
|
390
390
|
cwd: ${e}`}),Lr()},[]),Ae(()=>{let c=setInterval(()=>{Lr()},ny);return()=>clearInterval(c)},[Lr]),Ae(()=>{if(N||he||Pr||Yn.current||me!==null||He.length>0||P!==""||yn!==null||ce.current.length>0||Zn.current||Er)return;let c=vt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&oo(c.rec,{silent:!0})},[N,he,me,He,P,yn,Er,K,vt,Pr]),Ae(()=>{let c=null,l=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let f=`${Me.columns??80}x${Me.rows??24}`;f!==la.current&&(la.current=f,xu(R=>R+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+bl(_t.current,et())+"\x1B[?2026l")},80))},400)};return Me.on("resize",i),()=>{c&&clearTimeout(c),l&&clearTimeout(l),Me.off("resize",i)}},[Me,et]);let Ee=Math.max(20,(Me.columns??80)-1),da=Ui(()=>zw(e,s),[e,s,K]),Mr=(()=>{if(yu)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Tr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Tr?` v${Tr}`:""}\u2026`,isSetup:!0};if(so)return{text:"\u{1F6E0} press c to copy the d360-writer feedback \u2014 then send it to the team (Teams / Slack / email)\u2026",isSetup:!0};if(yn)return vu?{text:"\u2713 copied \u2014 paste it into your coding agent \xB7 I\u2019ll pick up automatically when it finishes\u2026",isSetup:!0}:{text:"\u2328 press c to copy the prompt above \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(ce.current.length>0)return ce.current[0].mode==="conflict"?{text:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let c=re(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let l=Wi(e,(c.docsDir??cu).replace(/\/+$/,"")),i=(()=>{try{return ln(l)&&iw(l).length>0}catch{return!1}})();try{let f=De(e,s),R=At(f.name);if(!(!!R&&!(dt(R)&&!R.refreshToken)))return{text:`Sign in with /login (profile "${f.name}")\u2026`,isSetup:!0};if(!f.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!f.project.workspaceId&&!i)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return i?{text:Kw,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),$n=ul(P),ua=$n.length>0&&!N,Ur=u!==null?Fd(u,8,Ee):null,ao=Re?Re.paths.filter(c=>!Re.query||c.toLowerCase().includes(Re.query.toLowerCase())).slice(0,8):[],lo=Se?Se.sessions.filter(c=>{let l=Se.query.toLowerCase();return!l||c.name.toLowerCase().includes(l)||c.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],Pe=G((c,l)=>{je.current?.close(),je.current=Bd({cwd:e,resume:c,profileName:l??s,allowProdWrites:Lt.current}),c||(Be.current={uuid:null,firstPrompt:null,titleFired:!1},ft(null)),Ht(0),Bt(0)},[e,s]),pa=G((c,l,i)=>{if(Xw.test(c))try{let f=De(e,s),R=typeof l.project_id=="string"&&l.project_id||f.project.projectId,O=pr(l,i),h=[],p=hr(i);c.endsWith("publish_article")&&p&&h.push(`Live: ${p}`);let w=fr(i);w?h.push(`Preview: ${w}`):O&&R&&h.push(`Preview: ${ur(f.connection.portalUrl,R,O,f.project.languageCode??"en")}`),h.length>0&&d({kind:"link",lines:h})}catch{}},[e,s,d]),te=G(async(c,l)=>{Kn(!0),Yn.current=!1,Ue(),pt([]),hn(null),Ir(null);let i=zn.current;l?.quietUser||d({kind:"user",text:l?.echoDisplay&&l.display?l.display:c});let f=Be.current;f.firstPrompt||(f.firstPrompt=l?.display??c),ht.current=Date.now(),Et(0),D(!0),Jn.current.clear();let R="",O=!1,h=!1,p="",w={num:0,closed:!1,cueSeen:!1},k=null,$=()=>{k||(k=setTimeout(()=>{k=null,g(p.length>0?p:null)},60))},S=()=>{k&&clearTimeout(k),k=null,g(null)},U=(T=!1)=>{let{head:B,keep:I}=qd(p,T);B.trim()&&d({kind:"assistant",text:_i(B.trimEnd(),w)}),p=I,S()};try{for await(let T of je.current.send(c))if(T.type==="session"){if(!f.uuid){f.uuid=T.sessionId;let B=new Date().toISOString(),I=Ar.current,F=I??yw(f.firstPrompt??"session");kw({uuid:T.sessionId,name:F,renamed:!!I,titled:!1,cwd:e,firstPrompt:f.firstPrompt??"",createdAt:B,updatedAt:B}),ft(F),Ar.current=null}}else if(T.type==="text"){p+=T.delta,R+=T.delta;let B=Hd(p);if(B>0){let I=p.slice(0,B).trimEnd();I&&d({kind:"assistant",text:_i(I,w)}),p=p.slice(B)}$(),Et(I=>I+T.delta.length)}else if(T.type==="tool"){O=!0;let B=cr(T.name,T.input);B&&(U(),d({kind:"tool",title:B.title,sep:B.sep,arg:B.arg}),Jn.current.set(T.id,{name:T.name,input:T.input}))}else if(T.type==="article_diff"){let B=Xe(T.oldContent,T.newContent,et());B&&(U(),d({kind:"diff",added:B.added,removed:B.removed,lines:B.lines,hidden:B.hidden}))}else if(T.type==="tool_result"){T.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(T.output)&&(to.current=!0);let B=Jn.current.get(T.id);if(B){Jn.current.delete(T.id),U();let I=dr(T.output,4,T.isError?void 0:B.name,B.input);d({kind:"tool-result",lines:I.lines,hidden:I.hidden,isError:T.isError}),T.isError||pa(B.name,B.input,T.output)}}else if(T.type==="result"){U(!0),Ht(I=>I+T.outputTokens),Bt(I=>I+T.costUsd);let B=T.inputTokens+T.cacheReadTokens+T.cacheCreationTokens;if(d({kind:"done",seconds:Math.round((Date.now()-ht.current)/1e3),tokens:T.outputTokens,costUsd:T.costUsd,ok:T.ok,...B>0?{inTokens:B,cachedPct:Math.round(T.cacheReadTokens/B*100)}:{}}),!h&&!O&&!R.trim()&&!fn.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),T.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(R))try{let I=Zd(e);if(ln(I)){let F=xr(I,"utf8").trim();F&&(Or(F),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(T.ok&&w.cueSeen)Qi(!0),pt([]);else{let I=T.ok?Td(R,nn.map(F=>F.name)):[];if(I.length>0)Q(I[0]);else if(T.ok&&R.trim()){let F=vt(!1);F.kind==="recommend"&&(F.rec.lead||F.rec.picker)||vw(c,R,e).then(ne=>{ne&&zn.current===i&&we(ne)}).catch(()=>{})}}if(f.uuid&&(Fi(f.uuid),!f.titleFired)){f.titleFired=!0;let I=f.uuid,F=f.firstPrompt;F&&Vd(F,e).then(ne=>{ne&&(ww(I,ne),ft(ne))}).catch(()=>{})}}else T.type==="error"&&(U(!0),h=!0,T.kind==="auth"&&(to.current=!0),d({kind:"note",text:`agent error: ${T.message}`,tone:"error"}))}finally{D(!1),S(),X(T=>T+1),Be.current.uuid&&Cd(e,Be.current.uuid,_t.current),to.current?(to.current=!1,mn.current=l?.display??c,we("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):mn.current=null,fn.current&&(fn.current=!1,$t.current.length>0&&(d({kind:"note",tone:"info",text:`(${$t.current.length} queued message(s) discarded)`}),$t.current=[],jr([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,pa,et,we,Q,Ue,vt]),Yt=G(async c=>{let l=Cr(e,"standard");ht.current=Date.now(),Et(0),D(!0);let i=new AbortController;ke.current=i;let f=async(R,O)=>{let h=Hi(R);oe({verb:"Publishing",total:h.length,done:0,active:[],rows:Bn(h),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:O?`Resolving cross-links in ${R.length} article${R.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${R.length} article${R.length===1?"":"s"} across ${h.length} partition${h.length===1?"":"s"} (\u2264${En} agents at once) on ${l.model}\u2026 (esc to stop)`});let p=!1;for await(let w of vr({cwd:e,partitions:h,promptFor:k=>Wo(k.paths),concurrency:En,profileName:s,allowProdWrites:Lt.current,model:l.model,signal:i.signal}))if(w.type==="partition_status")w.status==="running"?oe(k=>k&&{...k,active:[...k.active,w.label],rows:Le(k.rows,w.label,"active"),lastAt:Date.now()}):oe(k=>k&&{...k,active:k.active.filter($=>$!==w.label),done:k.done+1,rows:Le(k.rows,w.label,w.status==="done"?"done":"failed"),lastAt:Date.now()});else if(w.type==="partition_event")oe(k=>{if(!k)return k;let $={...k,lastAt:Date.now()};return w.event.type==="tool"?$.tools=k.tools+1:w.event.type==="text"&&($.chars=k.chars+w.event.delta.length),$});else if(w.type==="run_done"){p=w.aborted,Bt(U=>U+w.totalCostUsd),Ht(U=>U+w.results.reduce((T,B)=>T+B.outputTokens,0));let k=w.aborted?"Stopped. ":"",$=t.kind==="api"?"api":"subscription";d({kind:"note",tone:w.aborted?"warn":w.ok?"ok":"warn",text:k+ms(w.results,h,$).join(`
|
|
391
|
-
`)});let S=fs(e,s);if(S&&d({kind:"note",tone:"info",text:S}),!w.aborted){try{let U=await tu({cwd:e,profileName:s}),T=nu(U);T?d({kind:"note",tone:"info",text:T}):U.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${U.skipped}`})}catch(U){d({kind:"note",tone:"warn",text:`Order sync failed: ${U.message}`})}try{let U=ru(await ou({cwd:e,profileName:s}));U&&d({kind:"note",tone:"info",text:U})}catch(U){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${U.message}`})}}}return p};try{if(!await f(c,!1)){let O=await gs(e,s,c);O.length>0&&await f(O,!0)}}catch(R){d({kind:"note",tone:"error",text:`Publish run failed: ${R.message}`})}finally{ke.current=null,oe(null),D(!1),X(R=>R+1)}},[e,s,d,t]),Wr=G(async c=>{await te(ps(c),{display:`/publish ${c}`,quietUser:!0});try{let l=await Fo(e,s,c.replace(/\\/g,"/"));l.length>0&&(hn(`Related articles not yet published (${l.length}):`),pt([`/publish --related ${c}`,...l.map(i=>`/publish ${i}`)]))}catch{}},[e,s,te]),co=G(c=>{if(c)try{for(let l of Array.isArray(c)?c:[c]){let i=td(e,l);if(!i)continue;sr(e,i.title).ok&&d({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${i.title}`});return}}catch{}},[e,d]),ha=G(async(c,l)=>{let f=Ew(c,3),R=Cr(e,"standard");ht.current=Date.now(),Et(0),D(!0);let O=new AbortController;ke.current=O,oe({verb:"Authoring",unit:"spec",total:f.length,done:0,active:[],rows:Bn(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${c.length} screenshot spec${c.length===1?"":"s"} across ${f.length} partition${f.length===1?"":"s"} (\u22646 agents at once) on ${R.model}${R.forced?" (forced)":""}\u2026 (esc to stop)`});let h=!1;try{for await(let p of vr({cwd:e,partitions:f,promptFor:Tc,concurrency:6,profileName:s,allowProdWrites:Lt.current,model:R.model,signal:O.signal}))if(p.type==="partition_status")p.status==="running"?oe(w=>w&&{...w,active:[...w.active,p.label],rows:Le(w.rows,p.label,"active"),lastAt:Date.now()}):oe(w=>w&&{...w,active:w.active.filter(k=>k!==p.label),done:w.done+1,rows:Le(w.rows,p.label,p.status==="done"?"done":"failed"),lastAt:Date.now()});else if(p.type==="partition_event")oe(w=>{if(!w)return w;let k={...w,lastAt:Date.now()};return p.event.type==="tool"?k.tools=w.tools+1:p.event.type==="text"&&(k.chars=w.chars+p.event.delta.length),k});else if(p.type==="run_done"){Bt(S=>S+p.totalCostUsd),Ht(S=>S+p.results.reduce((U,T)=>U+T.outputTokens,0));let w=p.results.filter(S=>S.ok).length,k=p.aborted?"Stopped. ":"";h=!p.aborted&&l.setup;let $=p.aborted?"":h?" Refreshing the capture-setup checklist\u2026":" Next: /screenshot capture --all (or /screenshot
|
|
391
|
+
`)});let S=fs(e,s);if(S&&d({kind:"note",tone:"info",text:S}),!w.aborted){try{let U=await tu({cwd:e,profileName:s}),T=nu(U);T?d({kind:"note",tone:"info",text:T}):U.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${U.skipped}`})}catch(U){d({kind:"note",tone:"warn",text:`Order sync failed: ${U.message}`})}try{let U=ru(await ou({cwd:e,profileName:s}));U&&d({kind:"note",tone:"info",text:U})}catch(U){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${U.message}`})}}}return p};try{if(!await f(c,!1)){let O=await gs(e,s,c);O.length>0&&await f(O,!0)}}catch(R){d({kind:"note",tone:"error",text:`Publish run failed: ${R.message}`})}finally{ke.current=null,oe(null),D(!1),X(R=>R+1)}},[e,s,d,t]),Wr=G(async c=>{await te(ps(c),{display:`/publish ${c}`,quietUser:!0});try{let l=await Fo(e,s,c.replace(/\\/g,"/"));l.length>0&&(hn(`Related articles not yet published (${l.length}):`),pt([`/publish --related ${c}`,...l.map(i=>`/publish ${i}`)]))}catch{}},[e,s,te]),co=G(c=>{if(c)try{for(let l of Array.isArray(c)?c:[c]){let i=td(e,l);if(!i)continue;sr(e,i.title).ok&&d({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${i.title}`});return}}catch{}},[e,d]),ha=G(async(c,l)=>{let f=Ew(c,3),R=Cr(e,"standard");ht.current=Date.now(),Et(0),D(!0);let O=new AbortController;ke.current=O,oe({verb:"Authoring",unit:"spec",total:f.length,done:0,active:[],rows:Bn(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${c.length} screenshot spec${c.length===1?"":"s"} across ${f.length} partition${f.length===1?"":"s"} (\u22646 agents at once) on ${R.model}${R.forced?" (forced)":""}\u2026 (esc to stop)`});let h=!1;try{for await(let p of vr({cwd:e,partitions:f,promptFor:Tc,concurrency:6,profileName:s,allowProdWrites:Lt.current,model:R.model,signal:O.signal}))if(p.type==="partition_status")p.status==="running"?oe(w=>w&&{...w,active:[...w.active,p.label],rows:Le(w.rows,p.label,"active"),lastAt:Date.now()}):oe(w=>w&&{...w,active:w.active.filter(k=>k!==p.label),done:w.done+1,rows:Le(w.rows,p.label,p.status==="done"?"done":"failed"),lastAt:Date.now()});else if(p.type==="partition_event")oe(w=>{if(!w)return w;let k={...w,lastAt:Date.now()};return p.event.type==="tool"?k.tools=w.tools+1:p.event.type==="text"&&(k.chars=w.chars+p.event.delta.length),k});else if(p.type==="run_done"){Bt(S=>S+p.totalCostUsd),Ht(S=>S+p.results.reduce((U,T)=>U+T.outputTokens,0));let w=p.results.filter(S=>S.ok).length,k=p.aborted?"Stopped. ":"";h=!p.aborted&&l.setup;let $=p.aborted?"":h?" Refreshing the capture-setup checklist\u2026":" Next: /screenshot capture --all (or /screenshot checklist first for the staging checklist).";d({kind:"note",tone:p.aborted?"warn":p.ok?"ok":"warn",text:`${k}Authored specs \u2014 ${w}/${p.results.length} batches ok.${$}`}),!p.aborted&&p.ok&&co(l.runLine)}}catch(p){d({kind:"note",tone:"error",text:`Spec authoring failed: ${p.message}`})}finally{ke.current=null,oe(null),D(!1),X(p=>p+1)}if(h){let p=await sn();p.kind==="forward-to-agent"&&p.prompt&&await te(p.prompt,{display:p.display,quietUser:!0});let w=ii(e);w&&d({kind:"note",tone:"info",text:w.join(`
|
|
392
392
|
`)})}},[e,s,d,te,co]),fa=G(async c=>{let l=await Xo([c]);l.kind==="forward-to-agent"&&l.prompt&&await te(l.prompt,{display:l.display,quietUser:!0}),Sc(e,c)&&be(`Spec ready \u2014 /screenshot capture ${c} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${c}`,reason:""})},[e,te,be]),Fr=G(async(c,l)=>{if(!Qo(e)){await te(ri(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}D(!0);let i=new AbortController;ke.current=i;let f=c.map($=>({label:$,items:1,status:"pending"}));oe({verb:"Capturing",unit:"screenshot",total:c.length,done:0,active:[],rows:f,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Capturing ${c.length} screenshot${c.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`});let R=Date.now(),O=[];try{for(let $ of c){if(i.signal.aborted)break;oe(I=>I&&{...I,active:[$],rows:Le(I.rows,$,"active"),lastAt:Date.now()});let{exitCode:S,output:U}=await oi({cwd:e,id:$,signal:i.signal,stdio:"pipe"});if(Ic(S,U)){d({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."});return}let T=i.signal.aborted&&S!==0?"failed":ni(e,$,S,R),B=T==="captured"?void 0:T==="skipped"?Ec(U)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Nc(U);O.push({id:$,outcome:T,detail:B}),oe(I=>I&&{...I,active:[],done:I.done+1,rows:Le(I.rows,$,T==="captured"?"done":"failed"),lastAt:Date.now()})}}catch($){d({kind:"note",tone:"error",text:`Capture run failed: ${$.message}`})}finally{ke.current=null,oe(null),D(!1),X($=>$+1)}if(O.length===0)return;let h=O.filter($=>$.outcome==="captured"),p=O.filter($=>$.outcome==="skipped"),w=O.filter($=>$.outcome==="failed"),k=c.length-O.length;d({kind:"note",tone:w.length?"warn":h.length?"ok":"info",text:`\u2713 ${h.length} captured`+(p.length?` \xB7 \u2298 ${p.length} skipped`:"")+(w.length?` \xB7 \u2717 ${w.length} failed`:"")+(k?` \xB7 ${k} not run (stopped)`:"")});for(let $ of p)d({kind:"note",tone:"info",text:`\u2298 ${$.id} \u2014 ${$.detail}`});for(let $ of w)$.detail&&d({kind:"note",tone:"error",text:`\u2717 ${$.id}
|
|
393
393
|
${$.detail}`});if(h.length>0){let $=_c(e,h.map(U=>U.id)),S=$.length===1?`/publish ${$[0]}`:"/publish";be(`PNG${h.length===1?"":"s"} saved to the screenshots folder \u2014 publish to put ${h.length===1?"it":"them"} in the article${$.length===1?"":"s"}: ${S}`,{kind:"cmd",cmd:S,reason:""})}else if(p.length>0){let $=c.length===1?`/screenshot capture ${c[0]}`:"/screenshot capture";be(null,{kind:"cmd",cmd:$,reason:""})}O.length===c.length&&w.length===0&&p.length===0&&co(l?.runLine)},[e,d,be,te,co]),qr=G(c=>{let l=At(c);if(!l||dt(l)&&!l.refreshToken)return null;let i={...dn(l.idToken)??{},...dn(l.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),Hr=G((c,l)=>{if(l){let i=re(e);i&&(i.defaultProfile=c,Gd(i,e))}a(c),Pe(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${l?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),qr(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),Q("/login")),X(i=>i+1)},[e,d,Pe,qr,Q]),uo=G((c,l,i)=>{bo(e,c,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Pe(),Yd(e,c)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:en(Zt(e)).join(`
|
|
394
394
|
`)}),Vt(Ct()),kn.current=Ie(e).status==="current",Gt.current=Ke(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,Pe,Vt]),po=G(async c=>{let l;try{l=await Rn(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Q("/workspace");return}if(l.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=l.workspaces.filter(R=>(R.workspace_type??"").toLowerCase()!=="apidocumentation"),f=i.length>0?i:l.workspaces;if(f.length===1){let R=f[0],O=l.workspaces.length-f.length;d({kind:"note",tone:"ok",text:`Selected the "${R.name??R.id}" workspace${O>0?" (skipped the API-documentation workspace)":""}.`}),uo(l.profile,l.projectId,R);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${f.length} available).`}),Q("/workspace")},[e,d,uo,Q]),ho=G((c,l)=>{$o(e,c,l.id,l.name),d({kind:"note",tone:"ok",text:`Project set to "${l.name??l.id}" (agent restarted).`}),Pe(),po(c)},[e,d,Pe,po]),ma=G(async c=>{let l;try{l=De(e,c)}catch{return}if(!l.project.workspaceId){if(l.project.projectId){if(!l.project.projectName)try{let{projects:i}=await ot(e,l.name),f=i.find(R=>R.id===l.project.projectId);f?.name&&Fw(e,l.name,{projectName:f.name})}catch{}await po(l.name);return}try{let{projects:i}=await ot(e,l.name);if(i.length===1){let f=i[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${f.name??f.id}".`}),ho(l.name,{id:f.id,name:f.name});return}if(i.length>1){let f=i.map(R=>({id:R.id,name:R.name??R.id,sub:R.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),wt({cursor:0,current:-1,rows:f,profile:l.name,environment:l.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Q("/project")}},[e,d,po,ho,Q]),zt=G(()=>{let c=ce.current[0];if(!c)return;Ue();let{plan:l,mode:i}=c;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let R of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${R}`});l.overwritesLocalChanges&&i==="pull"&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let f=Xe(l.oldContent,l.newContent,et());d(f?{kind:"diff",added:f.added,removed:f.removed,lines:f.lines,hidden:f.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),i==="conflict"?(d({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),d({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,et,Ue]),Br=G(()=>{if(ce.current.length>0){zt();return}let c=Ot.current;Ot.current=[],c.length>0?(d({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),Yt(c)):Q("/pull")},[zt,d,Yt,Q]),ga=G(c=>{if(ce.current.length===0)return!1;let l=c.trim().toLowerCase(),i=ce.current[0];if(i.mode==="conflict"){if(l==="l"||l==="local")ce.current.shift(),Ot.current.push(i.plan.path),d({kind:"note",tone:"info",text:`Keeping local ${i.plan.path} \u2014 will publish over the portal.`});else if(l==="p"||l==="portal"){ce.current.shift();try{zd({cwd:e,profileName:s},i.plan),d({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(f){d({kind:"note",tone:"error",text:`Take-portal failed: ${f.message}`})}}else if(l==="s"||l==="skip"||l==="n")ce.current.shift(),d({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let f=ce.current.length;return ce.current=[],Ot.current=[],d({kind:"note",tone:"info",text:`Resolve cancelled (${f} conflict${f===1?"":"s"} left untouched).`}),!0}return Br(),!0}if(l==="y"||l==="yes"){let f=ce.current.shift().plan;try{zd({cwd:e,profileName:s},f),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${f.path} (sync base advanced).`})}catch(R){d({kind:"note",tone:"error",text:`Pull failed: ${R.message}`})}}else if(l==="n"||l==="no"){let f=ce.current.shift().plan;d({kind:"note",tone:"info",text:`Skipped ${f.path}.`})}else{let f=ce.current.length;return ce.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${f} article(s) left untouched).`}),!0}return Br(),!0},[e,s,Br,d]),Vr=G(async c=>{d({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let l=await qi({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),f=l.entries.filter(O=>O.status==="conflict"&&O.path).map(O=>O.path);if(i){if(!f.includes(i)){d({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}f=[i]}if(f.length===0){d({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let R=[];for(let O of f)try{R.push({plan:await Xd({cwd:e,profileName:s,relPath:O}),mode:"conflict"})}catch(h){d({kind:"note",tone:"error",text:`Could not load ${O} from Document360: ${h.message}`})}if(R.length===0)return;d({kind:"note",tone:"info",text:`Resolving ${R.length} conflict${R.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),ce.current=R,Ot.current=[],zt()}catch(l){d({kind:"note",tone:"error",text:`Could not compute sync status: ${l.message}`})}},[e,s,d,zt]),wa=G(c=>{let l=Zn.current;if(!l)return!1;if(Zn.current=null,Ue(),c.trim()!==l.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:f}=wi(e,l.targets);d({kind:"note",tone:f.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 R of f)d({kind:"note",tone:"error",text:` \u2717 ${R.path}: ${R.error}`});return l.hadDevhints&&(d({kind:"note",tone:"warn",text:Eo().join(`
|
|
@@ -413,7 +413,7 @@ ${S.skipped.map(T=>` - ${T.path} (${T.reason})`).join(`
|
|
|
413
413
|
`)}),be($.length===0?`Deterministic issues fixed. Next: /review${p} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${p} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${p} --fix`,reason:""});return}d({kind:"note",tone:w.length===0?"ok":"warn",text:nr(w).join(`
|
|
414
414
|
`)}),w.length>0&&be(`Found ${w.length} doc issue${w.length===1?"":"s"} above. /check${p} --fix has the agent fix them in place (or /review${p} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${p} --fix`,reason:""});return}case"structure":{let h=Wn(e,s);if(h.length===0){d({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}d({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...h].join(`
|
|
415
415
|
`)});return}case"reorder":{let h=$i(e,f);if(!h){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await te(h.prompt,{display:h.display,quietUser:!0}),be("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let h=bi(e,f);if(!h){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=f.includes("--fix"),w=f.find($=>!$.startsWith("--")),k=p?eu(e,w):[];if(await te(h.prompt,{display:h.display,quietUser:!0}),p)try{Bi(e,k,{reviewedCap:Vi})}catch{}if(p)be("\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let $=f.filter(S=>S!=="--fix").join(" ");be(`The review listed issues above. /review${$?` ${$}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${$?` ${$}`:""} --fix`,reason:""})}return}case"capture-setup":{await O();return}case"devhints":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:en(Zt(e)).join(`
|
|
416
|
-
`)}),Vt(Ct()),kn.current=Ie(e).status==="current",Gt.current=Ke(e);return}case"discover":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await te(ws(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(ai(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await te(li(),{display:"/inbox",quietUser:!0});return}case"feedback":{let h=Zd(e),p="";try{p=ln(h)?xr(h,"utf8"):""}catch{p=""}if(!/^## /m.test(p)){d({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let w=await Ii(p.trim());d({kind:"note",tone:w?"ok":"warn",text:w?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${h} and copy it manually.`}),w&&Or(null);return}case"document":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:h,what:p}=Vs(f);if(!p&&Bs(e)===0){d({kind:"note",tone:"info",text:Ys});return}let w=`/document${p?` ${p}`:""}${h?" --publish":""}`;await te(Gs(p,h),{display:w,quietUser:!0});return}case"catch-up":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!ro(c.trim()))return;let{publish:h}=di(f);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let p=await pi({cwd:e,profileName:s});for(let k of hi(p))d({kind:"note",tone:k.startsWith("\u2713")?"ok":k.startsWith("\u2139")?"info":"warn",text:k});let w=Un(Mn(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await te(ui({publish:h}),{display:`/catch-up${h?" --publish":""}`,quietUser:!0});return}case"update":{_r.current=!0,d({kind:"note",tone:"info",text:`Updating ${Tt}\u2026 (don\u2019t close this window)`}),Xn(!0),(await er().finally(()=>Xn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),Q("/exit"),Ji("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Zo}`});return}case"screenshot":{let h=On(f);if(h.mode==="capture"){await R(h.rest);return}if(h.mode==="
|
|
416
|
+
`)}),Vt(Ct()),kn.current=Ie(e).status==="current",Gt.current=Ke(e);return}case"discover":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await te(ws(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(ai(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await te(li(),{display:"/inbox",quietUser:!0});return}case"feedback":{let h=Zd(e),p="";try{p=ln(h)?xr(h,"utf8"):""}catch{p=""}if(!/^## /m.test(p)){d({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let w=await Ii(p.trim());d({kind:"note",tone:w?"ok":"warn",text:w?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${h} and copy it manually.`}),w&&Or(null);return}case"document":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:h,what:p}=Vs(f);if(!p&&Bs(e)===0){d({kind:"note",tone:"info",text:Ys});return}let w=`/document${p?` ${p}`:""}${h?" --publish":""}`;await te(Gs(p,h),{display:w,quietUser:!0});return}case"catch-up":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!ro(c.trim()))return;let{publish:h}=di(f);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let p=await pi({cwd:e,profileName:s});for(let k of hi(p))d({kind:"note",tone:k.startsWith("\u2713")?"ok":k.startsWith("\u2139")?"info":"warn",text:k});let w=Un(Mn(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await te(ui({publish:h}),{display:`/catch-up${h?" --publish":""}`,quietUser:!0});return}case"update":{_r.current=!0,d({kind:"note",tone:"info",text:`Updating ${Tt}\u2026 (don\u2019t close this window)`}),Xn(!0),(await er().finally(()=>Xn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),Q("/exit"),Ji("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Zo}`});return}case"screenshot":{let h=On(f);if(h.mode==="capture"){await R(h.rest);return}if(h.mode==="checklist"){await O();return}if(h.mode==="list"){if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=Pt(e,h.scope);if(h.picker){if(k.length===0){d({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let S=Pc(k);if(S.length===0){d({kind:"note",tone:"info",text:Ko(k,h.scope).join(`
|
|
417
417
|
`)}),be(`\u2713 All ${k.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}yt({cursor:0,rows:S,title:"Screenshots \u2014 pick what to author or capture:"});return}d({kind:"note",tone:"info",text:Ko(k,h.scope).join(`
|
|
418
418
|
`)});let $=k.filter(S=>S.state==="placeholder").length;if($>0){let S=h.scope?`/screenshot author ${h.scope}`:"/screenshot author --all";be(`${$} of ${k.length} still need${$===1?"s":""} a spec \u2014 /screenshot author <id> authors one, ${S} authors them all in parallel.`,{kind:"cmd",cmd:S,reason:""})}return}if(h.mode==="single"){await fa(h.id);return}if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=h.mode==="scope"?h.scope:void 0,w=Nw(e,{scope:p}).map(k=>k.id);if(w.length===0){d({kind:"note",tone:"info",text:p?`No screenshot placeholders under ${p}.`:"No screenshot placeholders found in the docs."});return}await ha(w,{setup:h.setup,runLine:h.mode==="scope"?[`/screenshot author ${h.scope}`,`/screenshot ${h.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await R(f);return}case"reset":{let h=gi(e);if(h.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Zn.current={repoName:Vn(e),targets:h,hadDevhints:ln(Jd(e))},d({kind:"note",tone:"warn",text:yi(e,h).join(`
|
|
419
419
|
`)}),we(Vn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,zt,Vr,d,Pe,te,Yt,Wr,ma]),fo=G(c=>{let l=(c??P).trim();if(x(""),Qn(null),Nt(0),l.startsWith("/")&&(Yn.current=!1,Ue(),hn(null),pt(f=>Nd(f,l))),!l||(Qi(!1),wa(l))||ga(l))return;Dr.current.push(l);let i=Od(l,Zi.current);if(l.startsWith("/"))d({kind:"user",text:l}),Qe(!0),xn(i).finally(()=>Qe(!1));else if(Hw(i)){d({kind:"user",text:l});let f=Bw(i);if(!f)te(i,{display:l,quietUser:!0});else{try{Vw(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}te(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${f}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${f}" and the article path(s) you wrote.`,{display:l,quietUser:!0})}}else{let f=nd(e,i);te(f??i,{display:l})}},[P,wa,ga,xn,te]),ya=G(c=>{if(c.length>1){if(c.includes("\x1B"))return;let l=Id(c);if(_d(l)){let i=Ld(++bu.current,l);Zi.current.set(i,l),_(i)}else _(l);return}_(c)},[_]),Kt=Math.max(10,Ee-6),ka=Ui(()=>br(b.text,Kt),[b.text,Kt]),Gr=G(c=>y(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+c))})),[]),mo=G(c=>y(l=>({...l,pos:Ud(br(l.text,Kt),l.pos,c)})),[Kt]),vn=G(c=>y(l=>({...l,pos:Wd(br(l.text,Kt),l.pos,c)})),[Kt]),Cu=["\x1B[H","\x1B[1~","\x1BOH"],Ru=["\x1B[F","\x1B[4~","\x1BOF"],ba=G((c,l)=>l.leftArrow?(Gr(-1),!0):l.rightArrow?(Gr(1),!0):c&&Cu.includes(c)?(vn("start"),!0):c&&Ru.includes(c)?(vn("end"),!0):l.ctrl&&c==="a"?(vn("start"),!0):l.ctrl&&c==="e"?(vn("end"),!0):!1,[Gr,vn]);return rw((c,l)=>{if(l.ctrl&&c==="c"){je.current?.close(),r();return}if(!W){if(N){if(l.escape){if(ke.current){if(!ke.current.signal.aborted){let i=(eo?.verb??"work").toLowerCase(),f=eo?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${f}s)\u2026`}),ke.current.abort()}return}fn.current||(fn.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),je.current?.interrupt());return}if(l.return){let i=P.trim();if(!i)return;$t.current.push(i),jr([...$t.current]),x("");return}if(ba(c,l))return;if(l.upArrow){mo(-1);return}if(l.downArrow){mo(1);return}if(l.backspace||l.delete){C();return}c&&!l.ctrl&&!l.meta&&ya(c);return}if(mt){if(l.upArrow){gt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){gt(i=>i&&{...i,cursor:Math.min(qe.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=qe.length){gt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=qe[mt.cursor];gt(null);let{lines:f,changed:R,effective:O}=_n(e,i.value??"default");for(let h of f)d({kind:"note",tone:h.startsWith("\u26A0")?"warn":h.startsWith("\u2713")?"ok":"info",text:h});R&&(aa(h=>h+1),je.current?.setModel(O));return}if(c==="s"){let i=qe[mt.cursor];gt(null),je.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(l.escape){gt(null);return}return}if(Ve){if(l.upArrow){Mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Mt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ve.rows.length){Mt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return||c==="s"){let i=Ve.rows[Ve.cursor];Mt(null),Hr(i.name,l.return===!0);return}if(l.escape){Mt(null);return}return}if(no){if(l.escape){wn(null);return}if(l.leftArrow||l.tab&&l.shift){wn(i=>i&&{tab:(i.tab-1+Ne.length)%Ne.length});return}if(l.rightArrow||l.tab){wn(i=>i&&{tab:(i.tab+1)%Ne.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ne.length){wn({tab:Number(c)-1});return}return}if(Ge){if(l.upArrow){Ut(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ut(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ge.rows.length){Ut(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ge.rows[Ge.cursor].name;if(Ut(null),!ts(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let R=!1;try{let O=At(i);R=!!O&&!(dt(O)&&!O.refreshToken)}catch{R=!1}d({kind:"note",tone:"info",text:R?`Next: sign in to ${i} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${i}) and pick your project.`}),Q("/login"),X(O=>O+1);return}if(l.escape){Ut(null);return}return}if(ge){if(l.upArrow){Wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Wt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ge.rows.length){Wt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=ge.rows[ge.cursor],{profile:f,projectId:R}=ge;Wt(null),uo(f,R,i);return}if(l.escape){Wt(null);return}return}if(Ce){if(l.upArrow){wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){wt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ce.rows.length){wt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ce.rows[Ce.cursor],{profile:f}=Ce;wt(null),ho(f,i);return}if(l.escape){wt(null);return}return}if(ye){if(l.upArrow){qt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){qt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){qt(i=>i&&{...i,rows:i.rows.map((f,R)=>R===i.cursor?{...f,checked:!f.checked}:f)});return}if(l.return){let i=ye.rows.filter(f=>f.checked).map(f=>f.path);if(qt(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}ys(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of i)d({kind:"note",tone:"info",text:` ${f}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){qt(null);return}return}if(Ye){if(l.upArrow){kt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){kt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ye.rows.length){kt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ye.rows[Ye.cursor],f=Ye.run;kt(null),f(i.token);return}if(l.escape){kt(null);return}return}if(Je){if(l.upArrow){Ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ft(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Je.rows.length){Ft(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Je.rows[Je.cursor];Ft(null),i.conflict?Vr(i.paths[0]):i.kind==="article"?Wr(i.paths[0]):Yt(i.paths);return}if(l.escape){Ft(null);return}return}if(Ze){if(l.upArrow){yt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){yt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ze.rows.length){yt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ze.rows[Ze.cursor];yt(null),i.action==="capture"?Fr(i.ids,{runLine:i.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):i.kind==="shot"?fa(i.ids[0]):ha(i.ids,{setup:!0,runLine:i.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(l.escape){yt(null);return}return}if(Re){if(l.escape){bt(null);return}if(l.upArrow){bt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){bt(i=>i&&{...i,cursor:Math.min(Math.max(0,ao.length-1),i.cursor+1)});return}if(l.return){let i=ao[Re.cursor];if(i){bt(null);try{d({kind:"preview",name:Vn(i),text:au(xr(Wi(e,i),"utf8"))})}catch(f){d({kind:"note",tone:"error",text:`Could not read ${i}: ${f.message}`})}}return}if(l.backspace||l.delete){bt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){bt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(Se){if(l.escape){xt(null);return}if(l.upArrow){xt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){xt(i=>i&&{...i,cursor:Math.min(Math.max(0,lo.length-1),i.cursor+1)});return}if(l.return){let i=lo[Se.cursor];if(i){xt(null),Pe(i.uuid),Be.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},ft(i.name),Fi(i.uuid),_t.current=[];let f=Li(e,i.uuid);for(let R of f)d(R);d({kind:"note",tone:"ok",text:f.length?`Resumed "${i.name}" \u2014 restored ${f.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(l.backspace||l.delete){xt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){xt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(l.tab&&!P&&me){x(me),Ue();return}if(!P&&He.length>0&&!Pr&&c&&/^[1-9]$/.test(c)){let i=He[Number(c)-1];if(i){x(Dt(i));return}}if(!P&&(so||yn)&&c==="c"&&!l.ctrl&&!l.meta&&!l.return&&!l.tab){let i=so!=null;Ii(so??yn).then(R=>{d({kind:"note",tone:R?"ok":"warn",text:R?i?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":i?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),R&&i&&Or(null),R&&!i&&ca(!0)});return}if(!ba(c,l)){if(ua){if(l.upArrow){Nt(i=>Math.max(0,i-1));return}if(l.downArrow){Nt(i=>Math.min($n.length-1,i+1));return}if(l.tab){x("/"+($n[pn]?.name??"")+" "),Nt(0);return}if(l.return){let i=$n[pn];if(i){let f=P.trim().slice(1).split(/\s+/).slice(1).join(" ");if(pl(i.usage)&&!f){x("/"+i.name+" "),Nt(0);return}fo("/"+i.name+(f?" "+f:""));return}}}else{if(l.upArrow){if(P!==""&&It===null){mo(-1);return}let i=Dr.current;if(!i.length)return;let f=It===null?i.length-1:Math.max(0,It-1);Qn(f),x(i[f]??"");return}if(l.downArrow){if(P!==""&&It===null){mo(1);return}let i=Dr.current;if(It===null)return;let f=It+1;f>=i.length?(Qn(null),x("")):(Qn(f),x(i[f]??""));return}}if(l.return){fo();return}if(l.backspace||l.delete){C();return}if(l.escape){x(""),Nt(0),Ue(),pt([]),hn(null),Yn.current=!0;return}c&&!l.ctrl&&!l.meta&&ya(c)}}}),Ae(()=>{if(N||W)return;let c=$t.current.shift();c!==void 0&&(jr([...$t.current]),fo(c))},[N,W,fo]),Y(se,{flexDirection:"column",width:Ee,children:[Ur!==null&&Y(se,{marginTop:1,flexDirection:"column",children:[Ur.truncated&&j(A,{dimColor:!0,children:"\u2026"}),j(A,{children:Ur.text})]}),N&&(eo?j(ty,{p:eo}):j(Jw,{startTime:ht.current,chars:ku})),!N&&oa?j(Zw,{text:oa}):null,j(se,{borderStyle:"round",borderColor:da.prod?"yellow":V,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:P?ka.map((c,l)=>{let i=b.text.slice(c.start,c.end),f=l===$r(ka,b.pos),R=Math.min(b.pos,c.end)-c.start;return Y(A,{children:[j(A,{color:V,children:l===0?"> ":" "}),f?Y(Gn,{children:[i.slice(0,R),j(cn,{ch:i[R]??" "}),i.slice(R+1)]}):i||" "]},`${l}-${c.start}`)}):Y(A,{children:[j(A,{color:V,children:"> "}),Er?j(cn,{ch:" "}):me&&!N&&ve?Y(Gn,{children:[j(cn,{ch:ve[0],dim:!0}),j(A,{color:"gray",children:ve.slice(1)})]}):me&&!N?Y(Gn,{children:[j(cn,{ch:me[0],dim:!0}),j(A,{color:"gray",children:me.slice(1)}),j(A,{dimColor:!0,children:" (tab)"})]}):(Mr.isSetup||!wu)&&!N?Y(Gn,{children:[j(cn,{ch:Mr.text[0],dim:!0}),j(A,{color:"gray",children:Mr.text.slice(1)})]}):j(cn,{ch:" "})]})}),na.length>0&&j(se,{flexDirection:"column",paddingX:1,children:na.map((c,l)=>j(A,{color:"gray",children:`\u29D7 queued: ${c}`},`${l}-${c.slice(0,24)}`))}),no?j(Pd,{tab:no.tab,width:Ee,version:o,engineVersion:lu}):mt?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Select model"}),j(A,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),qe.map((c,l)=>Y(A,{color:l===mt.cursor?V:void 0,children:[l===mt.cursor?"\u276F ":" ",`${l+1}. ${c.label}${l===mt.current?" \u2714":""}`.padEnd(16),j(A,{color:"gray",children:c.desc})]},c.label)),j(A,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Ve?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Switch connection profile"}),Ve.rows.map((c,l)=>Y(A,{color:l===Ve.cursor?V:void 0,children:[l===Ve.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Ve.current?" \u2714":""}`.padEnd(20),j(A,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?j(A,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),j(A,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ge?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Pick your Document360 environment"}),Ge.rows.map((c,l)=>Y(A,{color:l===Ge.cursor?V:void 0,children:[l===Ge.cursor?"\u276F ":" ",`${l+1}. ${c.name}`.padEnd(16),j(A,{color:"gray",children:c.apiUrl})]},c.name)),j(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ge?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Switch workspace"}),j(A,{dimColor:!0,children:`environment ${ge.environment} \xB7 project ${ge.projectName??`${ge.projectId.slice(0,8)}\u2026`}`}),ge.rows.map((c,l)=>Y(A,{color:l===ge.cursor?V:void 0,children:[l===ge.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===ge.current?" \u2714":""}`.padEnd(30),j(A,{color:"gray",children:c.type??""})]},c.id)),j(A,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):Ce?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Choose project"}),j(A,{dimColor:!0,children:`environment ${Ce.environment}`}),Ce.rows.map((c,l)=>Y(A,{color:l===Ce.cursor?V:void 0,children:[l===Ce.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Ce.current?" \u2714":""}`.padEnd(30),j(A,{color:"gray",children:c.sub??""})]},c.id)),j(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ye?(()=>{let l=Math.min(Math.max(0,ye.cursor-Math.floor(7)),Math.max(0,ye.rows.length-14)),i=ye.rows.slice(l,l+14),f=ye.rows.filter(R=>R.checked).length;return Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:`Which folders back the user docs? (${f} selected of ${ye.rows.length})`}),l>0?j(A,{dimColor:!0,children:` \u2191 ${l} more`}):null,i.map((R,O)=>{let h=l+O;return Y(A,{color:h===ye.cursor?V:void 0,children:[h===ye.cursor?"\u276F ":" ",R.checked?"\u25C9 ":"\u25CB ",R.path.padEnd(Math.min(48,Ee-34)),j(A,{color:"gray",children:qo(R)})]},R.path)}),l+14<ye.rows.length?j(A,{dimColor:!0,children:` \u2193 ${ye.rows.length-l-14} more`}):null,j(A,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Ye?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Which category? (pick one to scope to)"}),Ye.rows.map((c,l)=>{let i=l===Ye.cursor,f=`${l+1}.`.padEnd(3);return Y(A,{color:i?V:void 0,children:[i?"\u276F ":" ",`${f} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Ee-24))),j(A,{color:"gray",children:` ${c.token}`})]},c.token)}),j(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Je?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Je.rows.map((c,l)=>{let i=l===Je.cursor,f=c.indent?" ":" ",R=`${l+1}.`.padEnd(3);return Y(A,{color:i?V:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${f}${R} ${c.label}`.padEnd(Math.min(56,Ee-24)),c.note?j(A,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),j(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):Ze?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:Ze.title}),(()=>{let{rows:l,cursor:i}=Ze,f=Math.max(0,Math.min(i-Math.floor(12/2),l.length-12)),R=l.slice(f,f+12);return Y(Gn,{children:[f>0?j(A,{color:"gray",children:` \u2026 ${f} more above`}):null,R.map((O,h)=>{let p=f+h,w=p===i,k=O.indent?" ":" ",$=p<9?`${p+1}.`.padEnd(3):" ";return Y(A,{color:w?V:void 0,bold:O.kind!=="shot"&&!w,children:[w?"\u276F ":" ",`${k}${$} ${O.label}`.padEnd(Math.min(56,Ee-24)),O.note?j(A,{color:"gray",children:O.note}):null]},`${O.kind}:${O.ids.join(",")}`)}),f+12<l.length?j(A,{color:"gray",children:` \u2026 ${l.length-f-12} more below`}):null]})})(),j(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):Re?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:`Preview article${Re.query?` \u2014 filter: ${Re.query}`:" (type to filter)"}`}),ao.length===0?j(A,{color:"gray",children:"no articles match"}):ao.map((c,l)=>Y(A,{color:l===Re.cursor?V:void 0,children:[l===Re.cursor?"\u276F ":" ",c]},c)),j(A,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Se?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:`Resume session${Se.query?` \u2014 filter: ${Se.query}`:" (type to filter)"}`}),lo.length===0?j(A,{color:"gray",children:"no sessions match"}):lo.map((c,l)=>Y(A,{color:l===Se.cursor?V:void 0,children:[l===Se.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),j(A,{color:l===Se.cursor?V:"gray",children:c.firstPrompt.slice(0,Math.max(10,Ee-40))})]},c.uuid)),j(A,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):ua?Y(se,{flexDirection:"column",children:[$n.map((c,l)=>Y(A,{color:l===pn?V:void 0,children:[l===pn?"\u276F ":" ",c.usage.padEnd(22)," ",j(A,{color:l===pn?V:"gray",children:c.name==="model"&&Nr?`${c.desc} (currently ${Nr})`:c.desc})]},c.name)),j(A,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!P&&He.length>0?Y(se,{flexDirection:"column",paddingX:1,children:[ta?j(A,{color:V,children:ta}):null,He.map((c,l)=>{let i=Dt(c),f=i.slice(0,Math.max(20,Ee-5)),R=Ee-f.length-7,O=R>=12?(Ed(c)??dl(i)).slice(0,R):"";return Y(A,{children:[j(A,{color:V,children:l+1})," ",f,O?j(A,{dimColor:!0,children:` \u2014 ${O}`}):null]},i)}),j(A,{dimColor:!0,children:`press 1-${He.length} to fill \xB7 esc cancel`})]}):j(se,{paddingX:1,children:Y(A,{color:"gray",children:[da.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Nr??"model n/a"}${t.kind==="api"?ia>0?` \xB7 ${xe(ia)}`:"":sa>0?` \xB7 ${at(sa)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}q();import{jsx as sy}from"react/jsx-runtime";async function uu(e=process.cwd(),t="auto",n,o="0.0.0"){let r=ry(t);r.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=oy(sy(du,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "document360-writer",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.134",
|
|
4
4
|
"description": "Standalone documentation agent CLI. Reads your code, writes your docs. Specialized for Document360 publishing.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"@inquirer/prompts": "^8.4.3",
|
|
35
35
|
"commander": "^14.0.3",
|
|
36
36
|
"diff": "^8.0.4",
|
|
37
|
-
"document360-engine": "^0.2.
|
|
37
|
+
"document360-engine": "^0.2.138",
|
|
38
38
|
"ink": "^5.2.1",
|
|
39
39
|
"picocolors": "^1.1.1",
|
|
40
40
|
"react": "^18.3.1",
|