document360-writer 0.5.55 → 0.5.56
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 +59 -59
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var dc=Object.defineProperty;var En=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var oi=(e,t)=>{for(var n in t)dc(e,n,{get:t[n],enumerable:!0})};import Be from"picocolors";var F,pc,fc,mc,ri,Kt,f,$,
|
|
2
|
+
var dc=Object.defineProperty;var En=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var oi=(e,t)=>{for(var n in t)dc(e,n,{get:t[n],enumerable:!0})};import Be from"picocolors";var F,pc,fc,mc,ri,Kt,f,$,L,j,_,se,Pe,W=En(()=>{"use strict";F="#7f56d9",[pc,fc,mc]=[127,86,217],ri=e=>Be.isColorSupported?`\x1B[38;2;${pc};${fc};${mc}m${e}\x1B[39m`:e,Kt=e=>Be.bold(ri(e)),f=e=>Be.dim(e),$=e=>Be.red(e),L=e=>Be.yellow(e),j=e=>Be.green(e),_=ri,se=e=>Be.gray(e),Pe=e=>Be.bold(e)});import{existsSync as qn,writeFileSync as Zt,readFileSync as Jc,readdirSync as Zc}from"node:fs";import{join as eu}from"node:path";import{devHintsGuidePath as Bn,hintsDir as $i,architectureDir as Pi,messagesDir as rr,creatorNotesPath as vi,devhintsStatePath as Ri,ensureDir as Hn,writeMessage as tu,listOpenForDev as nu}from"document360-engine";function Ti(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
4
|
<!-- devhints script v${re} \xB7 maintained by document360-writer (/devhints). -->
|
|
5
5
|
|
|
@@ -174,29 +174,29 @@ Anything only a human knows that would help document this product. For example:
|
|
|
174
174
|
|
|
175
175
|
(Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
|
|
176
176
|
`}function Nt(e){Hn($i(e)),Hn(Pi(e)),Hn(rr(e));for(let n of[$i(e),rr(e)]){let o=eu(n,".gitkeep");qn(o)||Zt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
177
|
-
`)}qn(vi(e))||Zt(vi(e),ou()),Zt(Bn(e),Ti());let t=
|
|
177
|
+
`)}qn(vi(e))||Zt(vi(e),ou()),Zt(Bn(e),Ti());let t=Le(e);return Di(e,new Date().toISOString()),t}async function Si(e,t){for(let n of _t(Nt(t.cwd)))console.log(n);return{kind:"continue"}}function lt(){return[`This is document360-writer's dev hand-off setup (v${re}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20134). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current; AND each session, check"," `.d360-writer/messages/` for open questions from the docs agent and answer them \u2014 all per"," `.d360-writer/DEV-HINTS-GUIDE.md`. If that section is already there, leave it (refine in place only if"," wrong) \u2014 do NOT add a duplicate. Then commit `.d360-writer/` and the memory-file change ONLY if"," something actually changed.","4. Two-way messages (Part 3): check `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each \u2014 fold durable facts into the architecture brief and/or drop"," a reply (`from: dev`, `kind: answer`, `re: <id>`) \u2014 then set the question's frontmatter `status: done`."," If there are none, continue.","5. Then STOP and ask me for tribal knowledge \u2014 present it as a clearly-marked, standalone prompt on its"," own line (NOT buried in prose) and WAIT for my reply before doing anything else. Use this shape:",' "\u23F8 YOUR INPUT NEEDED \u2014 Any tribal knowledge that would help document this product? (folder map,',` terminology, what to prioritize or skip, gotchas.) Type it below, or reply 'none' / 'carry on' to skip."`," If I give you anything, phrase it clearly and append it to `.d360-writer/architecture/CREATOR-NOTES.md`"," (keep the existing header comment and every note already there; only add). If I say 'none'/'carry on', continue.",`6. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${re},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","7. When everything is done, print the completion line, THEN the next command as its own copy-paste"," block so it is unmistakable. Pick the matching first line:",' \u2022 first-time setup: "\u2705 Setup complete. Now switch to the document360-writer terminal and paste this:"',' \u2022 a refresh (brief/notes already existed): "\u2705 Hand-off refreshed. Back in the document360-writer terminal, paste this:"'," Then, on its OWN line, fenced as a code block so it copies cleanly:"," ```"," write the docs for this repo"," ```"].join(`
|
|
178
178
|
`)}function sr(e){try{let t=Jc(Ri(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Di(e,t){let o={...sr(e)??{},emittedVersion:re,emittedAt:t};Zt(Ri(e),`${JSON.stringify(o,null,2)}
|
|
179
|
-
`)}function en(e){try{return Zc(Pi(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function
|
|
180
|
-
`)}),n.notifiedBuilder=!0))}catch{}return n}function Yn(e){if(!qn(Bn(e)))return[];let t=
|
|
181
|
-
`)}function Vn(){return['\u{1F9F9} One leftover: your builder still has the "Documentation hand-off" rule in its CLAUDE.md / AGENTS.md'," (reset only clears d360-writer's own .d360-writer/ folder \u2014 never your repo's files)."," To restore it, paste this prompt into your repo's coding agent (Claude Code / Codex / Cursor):",It,ir(),It]}function _t(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${re}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",It,lt(),It,"","That one run writes the architecture brief, adds the ongoing rule to your agent memory (CLAUDE.md / AGENTS.md)","and commits it so teammates inherit it, answers any open questions the writer left, and asks you for tribal","knowledge \u2014 no manual file edits. It also sets up the two-way channel: the writer can ask you questions","(`/inbox` on its side), and you can ask it to document a session on demand (Part 4 of the guide).","","When it finishes, come back to THIS terminal and run:"," write the docs for this repo"]}var It,re,Ci,ct=En(()=>{"use strict";It="-".repeat(64),re=5;Ci="Re-run dev\u2194docs onboarding (protocol v"});var Ui={};oi(Ui,{initCommand:()=>lr,scaffoldInit:()=>ar});import{input as tn,confirm as ru}from"@inquirer/prompts";import{basename as ji,join as zn}from"node:path";import{existsSync as
|
|
182
|
-
`),"utf8")}async function lr(){let e=process.cwd(),t=Ei(e);if(Mt(t)&&!await ru({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Li(e)??ji(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:Ni}),s=await tn({message:"Screenshot output directory:",default:_i}),c=await tn({message:"Default connection profile name:",default:"berlin"}),p=await tn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:Ii,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Oi(e)},k=lu(e);k?.terminologyGlossary&&(g.terminologyGlossary=k.terminologyGlossary),Ai(g,e),Mi(e);let x=Nt(e);console.log(""),console.log(j(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of _t(x))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Li(e){let t=zn(e,"package.json");if(!Mt(t))return null;try{return JSON.parse(su(t,"utf8")).name??null}catch{return null}}function Oi(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Mt(zn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=zn(e,n);Mt(o)&&!uu(o)&&t.push(n)}return t}function uu(e){try{return iu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Xn=En(()=>{"use strict";W();ct()});var Aa={};oi(Aa,{doctorCommand:()=>cn,renderDoctorChecks:()=>ja,runDoctorChecks:()=>Da});import{existsSync as Ud}from"node:fs";import{d360GetAll as Wd,getAccessToken as Fd,isExpired as Zr,loadProfileMap as Hd,loadTokens as qd,packageSkillsDir as Ta,projectConfigPath as Bd,readProjectConfig as Gd,DEFAULT_DOCS_DIR as Yd,fetchManifestSummary as Vd,resolveActiveProfile as zd,classifyClaudeAuth as Xd,CLAUDE_CODE_SETUP_HINT as Sa,resolveModelSetting as Kd,probeModel as Qd,D360AuthError as Jd}from"document360-engine";async function Da(e){let t=[],n=Number(process.versions.node.split(".")[0]);t.push(n>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let o=Xd();o.state==="ready"?t.push({level:"ok",label:`Claude auth: ${o.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):o.state==="maybe"?t.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${Sa}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Sa});let r=Kd(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let b=await Qd(e,r.model??void 0);b.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(b.latencyMs/1e3).toFixed(1)}s`}):b.timedOut?t.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):t.push({level:"fail",label:`Model call failed \u2014 ${b.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 s=Gd(e);if(!s)return t.push({level:"fail",label:`No ${Bd(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??Yd).replace(/\/+$/,"");t.push(s.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let g;try{g=zd(e),t.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(b){return t.push({level:"fail",label:`Profile config: ${b.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=qd(g.name);k?Zr(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Zr(k)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(k.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${g.name})`}),t.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let x=Hd(e,g.name);x?x.projectId&&g.project.projectId&&x.projectId!==g.project.projectId?t.push({level:"fail",label:`Category map projectId (${x.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(x.articles).length} articles, ${Object.keys(x.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),t.push(Ud(Ta())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Ta()}`,fix:"Reinstall document360-writer (broken install)"});let D=Me(e);if(D.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${re})`}):D.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${D.completedVersion}, current is v${re}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!Zr(k)||k.refreshToken)){let b={profile:g.name,connection:g.connection};try{await Fd(b);let C=await Wd(b,"/v3/projects");t.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${C.length} project(s) visible`})}catch(C){t.push({level:"fail",label:`API call failed: ${C.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let P=x?.projectId??g.project.projectId;if(P&&g.project.workspaceId)try{let C=await Vd(b,P,g.project.workspaceId);if(C){let N=(C.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${g.connection.name} (${C.languages?.length??0} language${(C.languages?.length??0)===1?"":"s"}) \xB7 hash ${N||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${g.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(C){C instanceof Jd||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(C.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??P})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):t.push({level:"warn",label:`Workspace sync manifest: probe failed (${C.message.slice(0,80)})`})}}return t}function ja(e){let t=[""];for(let r of e){let s=r.level==="ok"?j("\u2713"):r.level==="warn"?M("\u26A0"):$("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${_(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?j(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function cn(e,t){console.log(f("Running checks\u2026"));for(let n of ja(await Da(t.cwd)))console.log(n);return{kind:"continue"}}var so=En(()=>{"use strict";ct();W()});import{Command as Nm}from"commander";import{createRequire as _m}from"node:module";import{AUTH_MODES as Mm}from"document360-engine";import{input as Sc}from"@inquirer/prompts";import{loginPkce as Dc,refreshTokens as jc,toStoredTokens as ui,clearTokens as Ac,decodeJwtClaims as ci,isExpired as Ec,loadTokens as Ic,saveTokens as di,resolveActiveProfile as Mn,setProfileProject as Nc,readProjectConfig as _c}from"document360-engine";W();import{select as hc}from"@inquirer/prompts";import{resolveActiveProfile as gc,setProfileProject as wc,resolveProjectId as yc,listWorkspaces as kc}from"document360-engine";async function Qt(e,t){let n=gc(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??yc(o);return{workspaces:await kc(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var si=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Zo(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 In(e,t,n,o,r){wc(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ii(e,t,n){let o;try{o=await Qt(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=Zo(o.workspaces,t);return r?(In(e,o.profile,o.projectId,r.id,r.name),console.log(j(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Et(e,t){let n;try{n=await Qt(e,t)}catch(k){console.log($(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===c?_("\u25CF"):" "} ${si(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await hc({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${si(k)}${k.id===c?" (current)":""}`,value:k.id}))}),g=o.find(k=>k.id===p);In(e,s,r,p,g?.name),console.log(j(`\u2713 Workspace set to "${g?.name??p}" for profile "${s}".`))}W();import{select as bc}from"@inquirer/prompts";import{resolveActiveProfile as xc,setProfileProject as $c,listProjects as vc}from"document360-engine";async function Ge(e,t){let n=xc(e,t),o={profile:n.name,connection:n.connection};return{projects:await vc(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ai=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function er(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 Nn(e,t,n,o){$c(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function li(e,t,n){let o;try{o=await Ge(e,n)}catch(s){return console.log($(`Could not list projects: ${s.message}`)),1}let r=er(o.projects,t);return r?(Nn(e,o.profile,r.id,r.name),console.log(j(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log($(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function _n(e,t){let n;try{n=await Ge(e,t)}catch(g){console.log($(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===s?_("\u25CF"):" "} ${ai(g)} ${f(g.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await bc({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${ai(g)}${g.id===s?" (current)":""}`,value:g.id}))}),p=o.find(g=>g.id===c);Nn(e,r,c,p?.name),console.log(j(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import Cc from"picocolors";function Pc(e=process.env){return e.FORCE_HYPERLINK==="0"||!Cc.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 Rc(e,t=e,n){return Pc(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Tc=/https?:\/\/[^\s\x1b]+/g;function Jt(e,t){return e.replace(Tc,n=>Rc(n,n,t))}function pi(e){return{...ci(e.idToken)??{},...ci(e.accessToken)??{}}}function Ln(e){let t=pi(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 On(e){let t=Mn(process.cwd(),e.profile),n=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Dc(n,{manual:e.manual,promptForRedirect:s=>Sc({message:s})},s=>console.log(Jt(s))),r=ui(t.name,o);if(di(r),await tr(r,t.name,s=>console.log(f(s))),console.log(""),console.log(j(`\u2713 Logged in to "${t.name}" as ${Ln(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{_c(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Et(process.cwd(),t.name))}catch{}}async function tr(e,t,n){let r=pi(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Mn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await Ge(process.cwd(),t);c=p.find(g=>g.id===r)?.name}catch{}Nc(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function fi(e){let t=Mn(process.cwd(),e.profile),n=t.connection,o=Ic(t.name);if(!o){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${_(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Ln(o)}`),Ec(o))if(o.refreshToken)try{let r=ui(t.name,await jc(n,o.refreshToken));di(r),console.log(j(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(M(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(M("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function mi(e){let t=Mn(process.cwd(),e.profile);Ac(t.name)?console.log(j(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as hi,writeProjectConfig as Mc,resolveActiveProfile as Lc,loadTokens as Oc,isExpired as Uc}from"document360-engine";function Un(e){let t=hi(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?_("\u25CF "):" ",s=o.production?M(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Oc(n),g=p?Uc(p)&&!p.refreshToken?M("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${c}${s} [${g}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Wn(e,t){let n=hi(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log($(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Mc(n,e);let o=n.profiles[t].production?M(" \u26A0 PRODUCTION"):"";console.log(j(`\u2713 Default profile is now "${t}"${o}`))}function Fn(e,t){try{let n=Lc(e,t);console.log(""),console.log(`Profile ${_(n.name)}${n.production?M(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}W();import{existsSync as Wc,readdirSync as Fc,statSync as gi}from"node:fs";import{join as wi}from"node:path";import{apiLogDir as Hc}from"document360-engine";function yi(){let e=Hc();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Wc(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Fc(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(gi(wi(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(gi(wi(e,r)).size/1024).toFixed(1);console.log(` ${$(r)} ${f(`${s} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as qc,resolveAuth as Bc,findByName as Gc,slugify as Yc,touchSession as Vc,upsertSession as zc,resolveActiveProfile as Xc}from"document360-engine";async function ki(e,t,n,o,r,s){let c=Bc(n);c.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Xc(e,r)}catch(b){console.error($(`Document360 profile error: ${b.message}`)),process.exit(2)}p.production&&(console.error(M(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let g;if(o){let b=Gc(e,o);b||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),g=b.uuid,console.error(f(`Resuming "${b.name}"`))}let k=qc({cwd:e,resume:g,profileName:r,allowProdWrites:s===!0}),x=g??null,D=1;for await(let b of k.send(t))switch(b.type){case"session":if(!x){x=b.sessionId;let P=new Date().toISOString();zc({uuid:x,name:Yc(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(b.delta);break;case"tool":console.error(se(` \u2699 ${b.name}`));break;case"result":D=b.ok?0:1,console.error(f(`(${b.inputTokens}\u2192${b.outputTokens} tokens`+(b.costUsd>0?`, $${b.costUsd<.01?b.costUsd.toFixed(4):b.costUsd.toFixed(2)}`:"")+")")),b.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${b.message}`)),process.exit(1)}x&&Vc(x),process.stdout.write(`
|
|
183
|
-
`),process.exit(D)}import{createInterface as
|
|
179
|
+
`)}function en(e){try{return Zc(Pi(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Le(e){let n=sr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<re?"stale":"current",completedVersion:n}}function Gn(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:re};try{if(!qn(Bn(e)))return n;let o=sr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;re>r&&(Hn(rr(e)),Zt(Bn(e),Ti()),Di(e,t),n.guideRefreshed=!0),re>s&&(nu(e).some(p=>p.kind==="request"&&p.subject.startsWith(Ci))||(tu(e,{id:`onb${re}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Ci}${re})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${re}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",lt()].join(`
|
|
180
|
+
`)}),n.notifiedBuilder=!0))}catch{}return n}function Yn(e){if(!qn(Bn(e)))return[];let t=Le(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${re}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,It,lt(),It,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function ir(){return['document360-writer (its "docs agent") has been removed from this repository. Please undo its dev\u2192docs',"hand-off setup and restore this repo to how it was before \u2014 in order:","","1. In this repo's agent-memory file (CLAUDE.md, or AGENTS.md \u2014 whichever it edited), REMOVE the",' "Documentation hand-off" section that was added (the rule about dropping hint files in'," `.d360-writer/hints/`, keeping `.d360-writer/architecture/` current, and checking"," `.d360-writer/messages/`). Leave everything else in that file untouched.","2. The `.d360-writer/` folder is already deleted on disk. If it was committed, remove it from version"," control too \u2014 `git rm -r --cached .d360-writer` (if it still resolves) \u2014 and commit the deletions.","3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
|
|
181
|
+
`)}function Vn(){return['\u{1F9F9} One leftover: your builder still has the "Documentation hand-off" rule in its CLAUDE.md / AGENTS.md'," (reset only clears d360-writer's own .d360-writer/ folder \u2014 never your repo's files)."," To restore it, paste this prompt into your repo's coding agent (Claude Code / Codex / Cursor):",It,ir(),It]}function _t(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${re}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",It,lt(),It,"","That one run writes the architecture brief, adds the ongoing rule to your agent memory (CLAUDE.md / AGENTS.md)","and commits it so teammates inherit it, answers any open questions the writer left, and asks you for tribal","knowledge \u2014 no manual file edits. It also sets up the two-way channel: the writer can ask you questions","(`/inbox` on its side), and you can ask it to document a session on demand (Part 4 of the guide).","","When it finishes, come back to THIS terminal and run:"," write the docs for this repo"]}var It,re,Ci,ct=En(()=>{"use strict";It="-".repeat(64),re=5;Ci="Re-run dev\u2194docs onboarding (protocol v"});var Ui={};oi(Ui,{initCommand:()=>lr,scaffoldInit:()=>ar});import{input as tn,confirm as ru}from"@inquirer/prompts";import{basename as ji,join as zn}from"node:path";import{existsSync as Lt,readFileSync as su,readdirSync as iu,writeFileSync as au}from"node:fs";import{writeProjectConfig as Ai,readProjectConfig as lu,projectConfigPath as Ei,writerDir as cu,DEFAULT_DOCS_DIR as Ii,DEFAULT_CAPTURE_DIR as Ni,DEFAULT_OUTPUT_DIR as _i}from"document360-engine";function ar(e,t="berlin"){let n=Ei(e);if(Lt(n))return{created:!1,path:n,profileName:""};let o={projectId:Mi(e)??ji(e),docsDir:Ii,captureDir:Ni,outputDir:_i,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Oi(e)};return Ai(o,e),Li(e),{created:!0,path:n,profileName:t}}function Li(e){let t=zn(cu(e),".gitignore");Lt(t)||au(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
182
|
+
`),"utf8")}async function lr(){let e=process.cwd(),t=Ei(e);if(Lt(t)&&!await ru({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Mi(e)??ji(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:Ni}),s=await tn({message:"Screenshot output directory:",default:_i}),c=await tn({message:"Default connection profile name:",default:"berlin"}),p=await tn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:Ii,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Oi(e)},k=lu(e);k?.terminologyGlossary&&(g.terminologyGlossary=k.terminologyGlossary),Ai(g,e),Li(e);let x=Nt(e);console.log(""),console.log(j(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of _t(x))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Mi(e){let t=zn(e,"package.json");if(!Lt(t))return null;try{return JSON.parse(su(t,"utf8")).name??null}catch{return null}}function Oi(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Lt(zn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=zn(e,n);Lt(o)&&!uu(o)&&t.push(n)}return t}function uu(e){try{return iu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Xn=En(()=>{"use strict";W();ct()});var Aa={};oi(Aa,{doctorCommand:()=>cn,renderDoctorChecks:()=>ja,runDoctorChecks:()=>Da});import{existsSync as Fd}from"node:fs";import{d360GetAll as Hd,getAccessToken as qd,isExpired as Zr,loadProfileMap as Bd,loadTokens as Gd,packageSkillsDir as Ta,projectConfigPath as Yd,readProjectConfig as Vd,DEFAULT_DOCS_DIR as zd,fetchManifestSummary as Xd,resolveActiveProfile as Kd,classifyClaudeAuth as Qd,CLAUDE_CODE_SETUP_HINT as Sa,resolveModelSetting as Jd,probeModel as Zd,D360AuthError as ep}from"document360-engine";async function Da(e){let t=[],n=Number(process.versions.node.split(".")[0]);t.push(n>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let o=Qd();o.state==="ready"?t.push({level:"ok",label:`Claude auth: ${o.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):o.state==="maybe"?t.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${Sa}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Sa});let r=Jd(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let b=await Zd(e,r.model??void 0);b.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(b.latencyMs/1e3).toFixed(1)}s`}):b.timedOut?t.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):t.push({level:"fail",label:`Model call failed \u2014 ${b.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 s=Vd(e);if(!s)return t.push({level:"fail",label:`No ${Yd(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??zd).replace(/\/+$/,"");t.push(s.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let g;try{g=Kd(e),t.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(b){return t.push({level:"fail",label:`Profile config: ${b.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=Gd(g.name);k?Zr(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Zr(k)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(k.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${g.name})`}),t.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let x=Bd(e,g.name);x?x.projectId&&g.project.projectId&&x.projectId!==g.project.projectId?t.push({level:"fail",label:`Category map projectId (${x.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(x.articles).length} articles, ${Object.keys(x.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),t.push(Fd(Ta())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Ta()}`,fix:"Reinstall document360-writer (broken install)"});let D=Le(e);if(D.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${re})`}):D.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${D.completedVersion}, current is v${re}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!Zr(k)||k.refreshToken)){let b={profile:g.name,connection:g.connection};try{await qd(b);let C=await Hd(b,"/v3/projects");t.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${C.length} project(s) visible`})}catch(C){t.push({level:"fail",label:`API call failed: ${C.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let R=x?.projectId??g.project.projectId;if(R&&g.project.workspaceId)try{let C=await Xd(b,R,g.project.workspaceId);if(C){let N=(C.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${g.connection.name} (${C.languages?.length??0} language${(C.languages?.length??0)===1?"":"s"}) \xB7 hash ${N||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${g.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(C){C instanceof ep||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(C.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??R})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):t.push({level:"warn",label:`Workspace sync manifest: probe failed (${C.message.slice(0,80)})`})}}return t}function ja(e){let t=[""];for(let r of e){let s=r.level==="ok"?j("\u2713"):r.level==="warn"?L("\u26A0"):$("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${_(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?j(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function cn(e,t){console.log(f("Running checks\u2026"));for(let n of ja(await Da(t.cwd)))console.log(n);return{kind:"continue"}}var so=En(()=>{"use strict";ct();W()});import{Command as Om}from"commander";import{createRequire as Um}from"node:module";import{AUTH_MODES as Wm}from"document360-engine";import{input as Sc}from"@inquirer/prompts";import{loginPkce as Dc,refreshTokens as jc,toStoredTokens as ui,clearTokens as Ac,decodeJwtClaims as ci,isExpired as Ec,loadTokens as Ic,saveTokens as di,resolveActiveProfile as Ln,setProfileProject as Nc,readProjectConfig as _c}from"document360-engine";W();import{select as hc}from"@inquirer/prompts";import{resolveActiveProfile as gc,setProfileProject as wc,resolveProjectId as yc,listWorkspaces as kc}from"document360-engine";async function Qt(e,t){let n=gc(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??yc(o);return{workspaces:await kc(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var si=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Zo(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 In(e,t,n,o,r){wc(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ii(e,t,n){let o;try{o=await Qt(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=Zo(o.workspaces,t);return r?(In(e,o.profile,o.projectId,r.id,r.name),console.log(j(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Et(e,t){let n;try{n=await Qt(e,t)}catch(k){console.log($(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===c?_("\u25CF"):" "} ${si(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await hc({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${si(k)}${k.id===c?" (current)":""}`,value:k.id}))}),g=o.find(k=>k.id===p);In(e,s,r,p,g?.name),console.log(j(`\u2713 Workspace set to "${g?.name??p}" for profile "${s}".`))}W();import{select as bc}from"@inquirer/prompts";import{resolveActiveProfile as xc,setProfileProject as $c,listProjects as vc}from"document360-engine";async function Ge(e,t){let n=xc(e,t),o={profile:n.name,connection:n.connection};return{projects:await vc(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ai=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function er(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 Nn(e,t,n,o){$c(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function li(e,t,n){let o;try{o=await Ge(e,n)}catch(s){return console.log($(`Could not list projects: ${s.message}`)),1}let r=er(o.projects,t);return r?(Nn(e,o.profile,r.id,r.name),console.log(j(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log($(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function _n(e,t){let n;try{n=await Ge(e,t)}catch(g){console.log($(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===s?_("\u25CF"):" "} ${ai(g)} ${f(g.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await bc({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${ai(g)}${g.id===s?" (current)":""}`,value:g.id}))}),p=o.find(g=>g.id===c);Nn(e,r,c,p?.name),console.log(j(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import Cc from"picocolors";function Pc(e=process.env){return e.FORCE_HYPERLINK==="0"||!Cc.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 Rc(e,t=e,n){return Pc(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Tc=/https?:\/\/[^\s\x1b]+/g;function Jt(e,t){return e.replace(Tc,n=>Rc(n,n,t))}function pi(e){return{...ci(e.idToken)??{},...ci(e.accessToken)??{}}}function Mn(e){let t=pi(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 On(e){let t=Ln(process.cwd(),e.profile),n=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Dc(n,{manual:e.manual,promptForRedirect:s=>Sc({message:s})},s=>console.log(Jt(s))),r=ui(t.name,o);if(di(r),await tr(r,t.name,s=>console.log(f(s))),console.log(""),console.log(j(`\u2713 Logged in to "${t.name}" as ${Mn(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{_c(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Et(process.cwd(),t.name))}catch{}}async function tr(e,t,n){let r=pi(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Ln(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await Ge(process.cwd(),t);c=p.find(g=>g.id===r)?.name}catch{}Nc(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function fi(e){let t=Ln(process.cwd(),e.profile),n=t.connection,o=Ic(t.name);if(!o){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${_(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Mn(o)}`),Ec(o))if(o.refreshToken)try{let r=ui(t.name,await jc(n,o.refreshToken));di(r),console.log(j(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(L("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function mi(e){let t=Ln(process.cwd(),e.profile);Ac(t.name)?console.log(j(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as hi,writeProjectConfig as Lc,resolveActiveProfile as Mc,loadTokens as Oc,isExpired as Uc}from"document360-engine";function Un(e){let t=hi(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?_("\u25CF "):" ",s=o.production?L(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Oc(n),g=p?Uc(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${c}${s} [${g}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Wn(e,t){let n=hi(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log($(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Lc(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(j(`\u2713 Default profile is now "${t}"${o}`))}function Fn(e,t){try{let n=Mc(e,t);console.log(""),console.log(`Profile ${_(n.name)}${n.production?L(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}W();import{existsSync as Wc,readdirSync as Fc,statSync as gi}from"node:fs";import{join as wi}from"node:path";import{apiLogDir as Hc}from"document360-engine";function yi(){let e=Hc();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Wc(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Fc(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(gi(wi(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(gi(wi(e,r)).size/1024).toFixed(1);console.log(` ${$(r)} ${f(`${s} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as qc,resolveAuth as Bc,findByName as Gc,slugify as Yc,touchSession as Vc,upsertSession as zc,resolveActiveProfile as Xc}from"document360-engine";async function ki(e,t,n,o,r,s){let c=Bc(n);c.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Xc(e,r)}catch(b){console.error($(`Document360 profile error: ${b.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let g;if(o){let b=Gc(e,o);b||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),g=b.uuid,console.error(f(`Resuming "${b.name}"`))}let k=qc({cwd:e,resume:g,profileName:r,allowProdWrites:s===!0}),x=g??null,D=1;for await(let b of k.send(t))switch(b.type){case"session":if(!x){x=b.sessionId;let R=new Date().toISOString();zc({uuid:x,name:Yc(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:R,updatedAt:R})}break;case"text":process.stdout.write(b.delta);break;case"tool":console.error(se(` \u2699 ${b.name}`));break;case"result":D=b.ok?0:1,console.error(f(`(${b.inputTokens}\u2192${b.outputTokens} tokens`+(b.costUsd>0?`, $${b.costUsd<.01?b.costUsd.toFixed(4):b.costUsd.toFixed(2)}`:"")+")")),b.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${b.message}`)),process.exit(1)}x&&Vc(x),process.stdout.write(`
|
|
183
|
+
`),process.exit(D)}import{createInterface as Zp}from"node:readline/promises";import{createSession as bs,resolveAuth as ef,getSession as tf,setTitle as nf,slugify as of,touchSession as rl,upsertSession as rf,generateTitle as sf,resolveActiveProfile as sl,resolveModelSetting as af,readProjectConfig as lf,decodeJwtClaims as nl,isExpired as cf,loadTokens as uf}from"document360-engine";var Re=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --all to author capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then run d360-capture in your app's repo \u2014 it signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot --list",s:"See capture status \u2014 which specs exist and which are done."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"d360-capture is a separate Playwright CLI \u2014 run it in the app's repo (needs its URL + a login)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"Author capture specs (--all / --list)."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/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:"Reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function Kc(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 bi(){let e=["document360-writer \u2014 help",""];for(let t of Re){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push(Kc(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function nr(){console.log("");for(let e of bi())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}W();import{getSession as Qc}from"document360-engine";async function xi(e,t){let n=t.currentUuid(),o=n?Qc(n):void 0;return console.log(o?f(`
|
|
184
184
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
185
185
|
`):f(`
|
|
186
186
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
187
187
|
`)),{kind:"clear"}}async function or(){return{kind:"exit"}}Xn();W();import{readMcpConfig as cr,writeMcpConfig as Wi}from"document360-engine";async function Kn(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(du(),{kind:"continue"}):t==="add"?(pu(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(fu(e.slice(1)),{kind:"continue"}):(console.log($(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function du(){let e=cr(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
|
|
188
188
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
189
|
-
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${_(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${_(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function pu(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log($("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log($(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=cr(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let g=o[++p],k=g?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log($(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}c[k[1].trim()]=k[2].trim()}else{console.log($(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(c).length>0?c:void 0}}r.servers[t]=s,Wi(r),console.log(""),console.log(j(`\u2713 Registered "${t}" (${n})`)),console.log(
|
|
189
|
+
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${_(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${_(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function pu(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log($("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log($(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=cr(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let g=o[++p],k=g?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log($(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}c[k[1].trim()]=k[2].trim()}else{console.log($(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(c).length>0?c:void 0}}r.servers[t]=s,Wi(r),console.log(""),console.log(j(`\u2713 Registered "${t}" (${n})`)),console.log(L(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function fu(e){let t=e[0];if(!t){console.log($("Usage: /mcp remove <name>"));return}let n=cr();if(!n.servers[t]){console.log($(`No server named "${t}".`));return}delete n.servers[t],Wi(n),console.log(j(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as Su}from"node:fs";import{join as Du}from"node:path";import{select as ju}from"@inquirer/prompts";import{computeSyncStatus as yr,planPartitions as Au,relatedArticlePaths as Eu,resolveModelForOperation as Iu,runPartitioned as Nu,loadProfileMap as _u,resolveActiveProfile as Lu,resolveCrossLinks as Mu,applyStructureOrder as Ou,orderSyncLine as Uu}from"document360-engine";import z from"picocolors";import Yi from"wrap-ansi";import hr from"string-width";W();import Ye from"picocolors";import ur from"wrap-ansi";import dr from"string-width";var Fi=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Hi=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),qi=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function mu(e){let t=e.replace(/\r/g,"").split(`
|
|
190
190
|
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(Fi(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Hi(t[o+1])){let p=qi(r);o+=2;let g=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)g.push(qi(t[o++]));n.push({kind:"table",header:p,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 p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);)p.push(t[o++].replace(/^\s*([-*]|\d+\.)\s+/,""));n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Fi(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Hi(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function pr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ye.bold(t.slice(2,-2)):t.startsWith("`")?_(t.slice(1,-1)):Ye.italic(t.slice(1,-1)))}var hu=(e,t)=>e+" ".repeat(Math.max(0,t-dr(e)));function gu(e,t,n){let o=e.length,r=e.map((C,N)=>Math.max(dr(C),...t.map(I=>dr(I[N]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],g=()=>p.reduce((C,N)=>C+N,0)+c,k=0;for(;g()>s&&k++<1e4;){let C=-1,N=6;for(let I=0;I<o;I++)p[I]>N&&(N=p[I],C=I);if(C===-1)break;p[C]-=1}let x=(C,N,I)=>Ye.gray(C+p.map(O=>"\u2500".repeat(O+2)).join(N)+I),D=Ye.gray("\u2502"),b=(C,N)=>{let I=p.map((pe,ne)=>{let De=C[ne]??"",ue=N?Ye.bold(De):pr(De);return ur(ue,pe,{hard:!0}).split(`
|
|
191
191
|
`)}),O=Math.max(...I.map(pe=>pe.length)),J=[];for(let pe=0;pe<O;pe++)J.push(p.map((ne,De)=>`${D} ${hu(I[De][pe]??"",ne)} `).join("")+D);return J.join(`
|
|
192
|
-
`)},
|
|
192
|
+
`)},R=[x("\u250C","\u252C","\u2510"),b(e,!0)];return R.push(t.length===0?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524")),t.forEach((C,N)=>{R.push(b(C,!1)),R.push(N===t.length-1?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524"))}),R.join(`
|
|
193
193
|
`)}function wu(e,t){switch(e.kind){case"heading":return Ye.bold(e.text);case"hr":return Ye.gray("\u2500".repeat(t));case"para":return ur(pr(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=ur(pr(n),Math.max(10,t-4)).split(`
|
|
194
194
|
`);return" \u2022 "+o+r.map(s=>`
|
|
195
195
|
`+s).join("")}).join(`
|
|
196
196
|
`);case"code":return e.lines.map(n=>Ye.gray(" "+n)).join(`
|
|
197
197
|
`);case"table":return gu(e.header,e.rows,t)}}function fr(e,t){let n=Math.max(20,t);return mu(e).map(o=>wu(o,n)).join(`
|
|
198
198
|
|
|
199
|
-
`)}W();import yu from"picocolors";var ku=[127,86,217],bu=[22,38,43],Bi={T:ku,E:bu},nn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],mr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,xu=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Gi(){if(!yu.isColorSupported)return[];let e=nn[0].length,t=[];for(let n=0;n<nn.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Bi[nn[n][r]],c=n+1<nn.length?Bi[nn[n+1][r]]:void 0;s&&c?o+=`${mr(s)}${xu(c)}\u2580\x1B[49m\x1B[39m`:s?o+=`${mr(s)}\u2580\x1B[39m`:c?o+=`${mr(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function on(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function me(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Ve(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var
|
|
199
|
+
`)}W();import yu from"picocolors";var ku=[127,86,217],bu=[22,38,43],Bi={T:ku,E:bu},nn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],mr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,xu=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Gi(){if(!yu.isColorSupported)return[];let e=nn[0].length,t=[];for(let n=0;n<nn.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Bi[nn[n][r]],c=n+1<nn.length?Bi[nn[n+1][r]]:void 0;s&&c?o+=`${mr(s)}${xu(c)}\u2580\x1B[49m\x1B[39m`:s?o+=`${mr(s)}\u2580\x1B[39m`:c?o+=`${mr(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function on(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function me(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Ve(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Mt=(e,t)=>` ${e.padEnd(13)}${t}`;function $u(e,t){let n=[Kt("\u270E document360-writer")+z.gray(` v${e.version}`),z.gray(" Reads your code, writes your docs."),"",Mt("Claude:",`${e.claude}${z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Mt("Document360:",e.configured?e.loggedOut?z.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?z.gray(` (${e.sessionHint})`):""}`:z.yellow("not set up \u2014 run /init")),Mt("Profile:",e.configured?`${e.profile}${z.gray(` (${e.apiUrl})`)}${e.prod?z.bold(z.yellow(" \u26A0 PRODUCTION")):""}`:z.gray("\u2014 (run /init)")),Mt("Project:",e.project),Mt("Mode:",z.gray(e.mode)),Mt("cwd:",z.gray(e.cwd))],o=Gi();if(o.length===0)return n.join(`
|
|
200
200
|
`);let r=2,s=3,c=hr(o[0]);if(!(t>=r+c+s+Math.max(...n.map(x=>hr(x)))))return[...o.map(x=>" "+x),...n].join(`
|
|
201
201
|
`);let g=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let x=0;x<Math.max(o.length+g,n.length);x++){let D=o[x-g]??" ".repeat(c);k.push((" ".repeat(r)+D+" ".repeat(s)+(n[x]??"")).trimEnd())}return k.join(`
|
|
202
202
|
`)}var vu={error:z.red,warn:z.yellow,ok:z.green,info:z.gray};function gr(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return $u(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),c=50,p=e.text.split(`
|
|
@@ -214,19 +214,19 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
|
214
214
|
`+fr(e.text,n);case"note":return`
|
|
215
215
|
`+vu[e.tone](Jt(e.text));case"done":return`
|
|
216
216
|
`+(e.ok?z.magenta("\u2736 "):z.red("\u2736 "))+z.gray(`Cooked for ${on(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${me(e.costUsd)}`:""))}}function Vi(e,t){return e.map(n=>gr(n,t)).join(`
|
|
217
|
-
`)}import{resolveActiveProfile as Cu,loadTokens as Pu,isExpired as Ru,decodeJwtClaims as zi}from"document360-engine";function Tu(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function
|
|
218
|
-
`)}var Xi={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function sn(e){return e.filter(t=>t.path!==null&&t.status in Xi&&!t.link).map(t=>({path:t.path,label:Xi[t.status]}))}function Qn(e){return e.filter(t=>t.link).length}function br(e,t){try{let n=_u(e,
|
|
219
|
-
`)}function xr(e,t,n){let o=b=>t[b.index]?.paths.length??0,r=e.filter(b=>b.ok),s=e.filter(b=>!b.ok),c=e.reduce((b,
|
|
220
|
-
`),display:"/audit"}}W();import{checkbox as
|
|
221
|
-
`);return
|
|
222
|
-
`)||
|
|
223
|
-
`},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=
|
|
217
|
+
`)}import{resolveActiveProfile as Cu,loadTokens as Pu,isExpired as Ru,decodeJwtClaims as zi}from"document360-engine";function Tu(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Me(e,t){try{let n=Cu(e,t),o=Pu(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Ru(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let c={...zi(o.idToken)??{},...zi(o.accessToken)??{}}.doc360_project_id;if(typeof c=="string"&&c&&c!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${Tu(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var rn=3;function kr(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, strip every <!-- SCREENSHOT ... --> block while keeping the visible [Screenshot: ...] line, normalize cross-article links).","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself \u2014 do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
|
|
218
|
+
`)}var Xi={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function sn(e){return e.filter(t=>t.path!==null&&t.status in Xi&&!t.link).map(t=>({path:t.path,label:Xi[t.status]}))}function Qn(e){return e.filter(t=>t.link).length}function br(e,t){try{let n=_u(e,Lu(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Mu(Su(Du(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages not published yet \u2014 they show as plain text for now and turn into live links once those pages are published.`}catch{return null}}function Wu(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=t.replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}function Ki(e){let t=[];e.length>1&&t.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(o=>o.path),indent:!1});let n=new Map;for(let o of e){let r=o.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),s=n.get(r);s?s.push(o):n.set(r,[o])}for(let o of[...n.keys()].sort()){let r=n.get(o).sort((s,c)=>s.path.localeCompare(c.path));t.push({kind:"category",label:`${Wu(o)} (${r.length})`,paths:r.map(s=>s.path),indent:!1});for(let s of r){let c=s.path.replace(/\\/g,"/").split("/").pop()??s.path;t.push({kind:"article",label:c,paths:[s.path],indent:!0,note:s.label})}}return t}function Jn(e){return[`Run the publish-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures) and remind me drafts need review in the portal."].join(`
|
|
219
|
+
`)}function xr(e,t,n){let o=b=>t[b.index]?.paths.length??0,r=e.filter(b=>b.ok),s=e.filter(b=>!b.ok),c=e.reduce((b,R)=>b+o(R),0),p=r.reduce((b,R)=>b+o(R),0),g=n==="api"?`${me(e.reduce((b,R)=>b+R.costUsd,0))} total`:Ve(e.reduce((b,R)=>b+R.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,x=b=>`${b} article${b===1?"":"s"}`,D=[];if(s.length===0)D.push(`Published ${x(c)} (${k}) successfully \xB7 ${g}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${x(c)} (${k}) \xB7 ${g}.`),D.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let b of s)D.push(` \u2717 ${b.label}${b.error?` \u2014 ${b.error}`:""}`)}return D}async function wr(e,t){let n=Au(t),{model:o}=Iu(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${rn} agents at once) on ${o}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let r of Nu({cwd:e.cwd,partitions:n,promptFor:s=>Jn(s.paths),concurrency:rn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:o}))if(r.type==="partition_status")r.status==="running"?console.log(f(` \u25B8 ${r.label} \u2014 publishing\u2026`)):r.status==="done"?console.log(j(` \u2713 ${r.label}`)):console.log($(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let s=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of xr(r.results,n,s))console.log(r.ok?j(p):L(p));let c=br(e.cwd,e.profileName);c&&console.log(f(c));try{let p=Uu(await Ou({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}}}catch(r){console.log($(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Zn(e,t,n){let o=Eu(e,n);if(o.length===0)return[];let r=new Set(sn((await yr({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Qi(e,t){let n=Me(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Zn(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(j("\u2713 All related articles are already published.")),{kind:"continue"}):await wr(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await yr({cwd:t?.cwd??process.cwd()}),s=sn(r.entries),c=Qn(r.entries);return c>0&&console.log(L(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),s.length===0?(console.log(j(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):t?await wr(t,s.map(p=>p.path)):{kind:"forward-to-agent",prompt:Jn(s.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log($(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let s=await yr({cwd:t?.cwd??process.cwd()});r=sn(s.entries);let c=Qn(s.entries);c>0&&console.log(L(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`))}catch(s){return console.log($(`Could not compute sync status: ${s.message}`)),console.log(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(j("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(f(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${f(`(${s.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>ju({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await wr(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:kr(o),display:`/publish ${o}`}}async function an(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
|
|
220
|
+
`),display:"/audit"}}W();import{checkbox as Fu}from"@inquirer/prompts";import{inventoryRepo as Hu,readProjectConfig as Ji,writeProjectConfig as qu}from"document360-engine";function $r(e,t){let n=Ji(e);n&&(n.authoritativeSourceFiles=t,qu(n,e))}function eo(e){let t=[`${e.fileCount}${e.fileCount>=5e3?"+":""} files`];return e.stacks.length&&t.push(e.stacks.join("+")),t.push(e.reason),t.join(" \xB7 ")}async function Zi(e,t){let n=t?.cwd??process.cwd();if(!Ji(n))return console.log($("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Hu(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(_("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(eo(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Fu({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${eo(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(f("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};$r(n,r),console.log(j(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as Xu}from"@inquirer/prompts";import{applyPull as Cr,computeSyncStatus as ra,compareRemoteSources as Ku,planPull as sa,planImport as Qu,applyImport as Ju,establishBaselines as Zu,rebaselineServerMeta as ed,D360AuthError as td}from"document360-engine";W();var ea=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:$,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:L,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:_,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:$,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:$,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:se,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:f,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:f,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:se,mark:"\xB7"}];function Bu(e){return e.path?e.path:`${e.title??"(untitled)"} ${se(`[${e.articleId}]`)}`}function Gu(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60);return`${n}m ${Math.round(t-n*60)}s`}function to(e,t){let n=[],o=e.entries.filter(x=>x.link);if(o.length>0){n.push(""),n.push(Pe("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let x of o)n.push(` ${L("~")} ${L(x.path??"")} ${se(`\u2192 "${x.link.title}"`)}`)}for(let x of ea){let D=e.entries.filter(b=>b.status===x.status&&!(x.status==="untracked-local"&&b.link));if(D.length!==0){n.push(""),n.push(Pe(x.header));for(let b of D)n.push(` ${x.paint(x.mark)} ${x.paint(Bu(b))}${b.detail?se(` (${b.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let c={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},p=o.length,g=s===r?j("\u2713 everything up to date"):[r>0?j(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...ea.map(x=>{let D=(e.counts[x.status]??0)-(x.status==="untracked-local"?p:0);return D>0?`${D} ${c[x.status]}`:null})].filter(Boolean).join(se(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${Gu(t)}`:"";return n.push(g+se(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as Yu}from"diff";import ta from"picocolors";var na=80,Vu="\x1B[48;2;74;28;28m",zu="\x1B[48;2;24;66;24m",oa="\x1B[49m",vr=e=>String(e).padStart(5);function ut(e,t,n){let o=b=>{let R=b.replace(/\r\n/g,`
|
|
221
|
+
`);return R.endsWith(`
|
|
222
|
+
`)||R===""?R:R+`
|
|
223
|
+
`},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=Yu("a","b",r,s,"","",{context:3}),g=0,k=0,x=[];p.hunks.forEach((b,R)=>{R>0&&x.push(ta.gray(" \u2026"));let C=b.oldStart,N=b.newStart;for(let I of b.lines){let O=I[0],J=I.slice(1).slice(0,c);O==="-"?(k++,x.push(`${Vu}${vr(C++)} - ${J}${oa}`)):O==="+"?(g++,x.push(`${zu}${vr(N++)} + ${J}${oa}`)):(x.push(ta.gray(vr(N))+" "+J),C++,N++)}});let D=x.slice(0,na);return{added:g,removed:k,lines:D,hidden:Math.max(0,x.length-na)}}async function ia(e,t){let n=Me(t.cwd,t.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await nd(t),{kind:"continue"};if(o==="--baseline")return await od(t,e.filter(c=>c!=="--baseline")),{kind:"continue"};if(o==="--compare")return await rd(t),{kind:"continue"};if(o)return console.log($(`Unknown option: ${o}`)),console.log(f("Usage: /pull pull portal edits + import new portal articles")),console.log(f(" /pull <path> pull one article (or resolve a conflict)")),console.log(f(" /pull --status drift report only (no writes)")),console.log(f(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await sd(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await Pr({cwd:t.cwd,profileName:t.profileName});for(let c of Rr(s))console.log(c.tone==="ok"?j(c.text):c.tone==="warn"?L(c.text):f(c.text));console.log("")}catch(r){r instanceof td?console.log($(r.message)):console.log($(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Pr(e){let t=await ra({cwd:e.cwd,profileName:e.profileName}),n={pulled:[],imported:[],conflicts:[],toPublish:0,failed:[]};for(let o of t.entries)if(o.status==="remote-ahead"&&o.path)try{let r=await sa({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Cr({cwd:e.cwd,profileName:e.profileName},r),n.pulled.push(o.path)}catch(r){n.failed.push({ref:o.path,error:r.message})}else if(o.status==="untracked-remote"&&o.articleId)try{let r=await Qu({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Ju({cwd:e.cwd,profileName:e.profileName},r),n.imported.push({title:r.title,path:r.path})}catch(r){n.failed.push({ref:o.title??o.articleId,error:r.message})}else o.status==="conflict"&&o.path?n.conflicts.push(o.path):(o.status==="local-ahead"||o.status==="untracked-local"&&!o.link)&&o.path&&n.toPublish++;return n}var no=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,dt=e=>e===1?"":"s";function Rr(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${dt(e.pulled.length)} into local: ${no(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${dt(e.imported.length)}: ${no(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${dt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${dt(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Take the portal copy: /pull <path> \xB7 keep yours: /publish <path>. (${no(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${dt(e.failed.length)} failed: ${no(e.failed.map(n=>n.ref))}`}),t.length===0&&t.push({tone:"ok",text:"\u2713 Already in sync with Document360 \u2014 nothing to pull."}),t}async function nd(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await ra({cwd:e.cwd,profileName:e.profileName});for(let o of to(n,Date.now()-t))console.log(o);console.log("")}async function od(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(f(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Zu({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await ed({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(j("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(j(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(j(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(L(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(f(` - ${s.path} (${s.reason})`))}}async function rd(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Ku({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Pe(String(t.legacyCount))} \xB7 Manifest: ${Pe(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(j("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log($(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(L(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(L(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(f(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function sd(e,t){let n=t.replace(/\\/g,"/"),o=await sa({cwd:e.cwd,profileName:e.profileName,relPath:n});console.log(""),console.log(`${_("\u25CF")} ${Pe(o.title)} ${se(`(${o.path})`)}`);for(let c of o.notes)console.log(L(` \u26A0 ${c}`));o.overwritesLocalChanges&&console.log(L(" \u26A0 This OVERWRITES local edits made since the last sync."));let r=ut(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(f(" Local file already matches the remote content \u2014 advancing the sync base only.")),Cr({cwd:e.cwd,profileName:e.profileName},o);return}console.log(se(` \u23BF Added ${r.added} line${dt(r.added)}, removed ${r.removed} line${dt(r.removed)}`));for(let c of r.lines)console.log(c);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Xu({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}Cr({cwd:e.cwd,profileName:e.profileName},o),console.log(j(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as id}from"node:fs";import{resolve as ad}from"node:path";import{estimateBulkCost as ld,planPartitions as cd,readProjectConfig as ud,resolveModelForOperation as dd,runPartitioned as pd,trackedArticlePaths as fd}from"document360-engine";var Tr=3;function Sr(e){let t,n=!1;for(let r=0;r<e.length;r++){let s=e[r];s==="--run"||s==="--yes"?n=!0:s==="--scope"?t=e[++r]:s?.startsWith("--scope=")&&(t=s.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function Dr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function jr(e,t){return t.map(n=>{let o=0;try{o=id(ad(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Ar(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite \u2014 be efficient:
|
|
224
224
|
- Read ONLY the article files listed below. Do NOT read source code, other articles, or fetch the live portal \u2014 you already have everything you need.
|
|
225
225
|
- Convert in place: wrap callouts, FAQs, tabs, accordions, and media embeds per the d360-markdown skill. Preserve all wording, headings, and structure; change only GFM\u2192DFM syntax.
|
|
226
226
|
- Publish each as a draft with a single update call. Do NOT re-read, re-verify, or polish after converting, and skip articles already in DFM.
|
|
227
227
|
- Work only on these files:
|
|
228
228
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
229
|
-
`)}function Er(e,t,n){let o=e.reduce((p,g)=>p+g.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${me(r)}\u2013${me(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Ir(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,N)=>C+o(N),0),p=r.reduce((C,N)=>C+o(N),0),g=e.reduce((C,N)=>C+N.costUsd,0),k=e.reduce((C,N)=>C+N.outputTokens,0),x=n==="api"?`${me(g)} total`:Ve(k),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=C=>`${C} article${C===1?"":"s"}`,
|
|
229
|
+
`)}function Er(e,t,n){let o=e.reduce((p,g)=>p+g.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${me(r)}\u2013${me(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Ir(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,N)=>C+o(N),0),p=r.reduce((C,N)=>C+o(N),0),g=e.reduce((C,N)=>C+N.costUsd,0),k=e.reduce((C,N)=>C+N.outputTokens,0),x=n==="api"?`${me(g)} total`:Ve(k),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=C=>`${C} article${C===1?"":"s"}`,R=[];if(s.length===0)R.push(`Converted ${b(c)} (${D}) successfully \xB7 ${x}.`);else{R.push(`Converted ${p}/${b(c)} (${D}) \xB7 ${x}.`),R.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)R.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return R}async function aa(e,t){if(!ud(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Sr(e),r=fd(t.cwd,t.profileName);if(r.length===0)return console.log($("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Dr(r,n);if(s.length===0)return console.log($(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=cd(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:g,forced:k}=dd(t.cwd,"light");if(!o){let x=ld({files:jr(t.cwd,s),op:"convert",model:g});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let D of Er(c,x,Tr))console.log(D);return console.log(f(`Model: ${g}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${c.length} partitions (\u2264${Tr} agents at once) on ${g}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let x of pd({cwd:t.cwd,partitions:c,promptFor:Ar,concurrency:Tr,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:g}))if(x.type==="partition_status")x.status==="running"?console.log(f(` \u25B8 ${x.label} \u2014 converting\u2026`)):x.status==="done"?console.log(j(` \u2713 ${x.label}`)):console.log($(` \u2717 ${x.label}`));else if(x.type==="run_done"){console.log("");let D=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let b of Ir(x.results,c,D))console.log(x.ok?j(b):L(b))}}catch(x){console.log($(`Convert run failed: ${x.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as la}from"node:fs";import{resolve as ca}from"node:path";import{estimateBulkCost as md,lintDocs as hd,planPartitions as gd,readDocsPlan as wd,readProjectConfig as ua,DEFAULT_DOCS_DIR as yd,resolveModelForOperation as kd,runPartitioned as bd}from"document360-engine";var xd=3,$d=8;function Nr(e){return e===void 0||!Number.isFinite(e)?xd:Math.max(1,Math.min(Math.floor(e),$d))}function _r(e){let t,n,o=!1,r=!1,s,c=g=>{let k=Number(g);return g!==void 0&&Number.isFinite(k)?k:void 0};for(let g=0;g<e.length;g++){let k=e[g];if(k==="--preview"||k==="--dry-run")o=!0;else if(k==="--rewrite"||k==="--force")r=!0;else{if(k==="--run"||k==="--yes"||k==="--all")continue;k==="--scope"?t=e[++g]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?s=c(e[++g]):k?.startsWith("--concurrency=")?s=c(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=g=>g?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function vd(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Cd(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Lr(e,t,n){return n.filter(o=>{try{return la(ca(e,t,o)).size===0}catch{return!0}})}function Mr(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let c of o.get(r)?.sources??[])try{s+=la(ca(e,c)).size}catch{}return{path:r,bytes:s}})}function Or(e,t,n={}){let o=n.rewrite?`- Some or all of these articles ALREADY EXIST on disk \u2014 this is a re-author (rewrite/upgrade), NOT a first draft. For any that exist, do NOT preserve or lightly-edit the current file: RE-AUTHOR it from scratch against the plan + sources + the active doc-type playbook standard. The existing file is what you're replacing \u2014 its structure is NOT the target; match only the project's voice/terminology.
|
|
230
230
|
`:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
231
231
|
- It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose and the source files it draws from (AGENT-PLAN.md has the same table).
|
|
232
232
|
- Read ONLY those source files plus any shared context you genuinely need, and ground every statement in them. Never invent UI labels, routes, or behaviour \u2014 if the source does not say it, omit it.
|
|
@@ -235,72 +235,72 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
|
235
235
|
- Each article is independent. Do NOT write, edit, or publish any article not in this list, and do NOT publish to Document360 \u2014 these are local drafts.
|
|
236
236
|
Articles:
|
|
237
237
|
`+e.paths.map(r=>`- ${r}`).join(`
|
|
238
|
-
`)}function Ur(e,t,n){let o=e.reduce((c,p)=>c+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${me(r)}\u2013${me(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Wr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,N)=>C+o(N),0),p=r.reduce((C,N)=>C+o(N),0),g=e.reduce((C,N)=>C+N.costUsd,0),k=e.reduce((C,N)=>C+N.outputTokens,0),x=n==="api"?`${me(g)} total`:Ve(k),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=C=>`${C} article${C===1?"":"s"}`,
|
|
239
|
-
`)}var Gr="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function ga(e,t){let n=t?.cwd??process.cwd();if(!
|
|
240
|
-
`)}var Xr="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 wa(e,t){let n=t?.cwd??process.cwd();if(!
|
|
238
|
+
`)}function Ur(e,t,n){let o=e.reduce((c,p)=>c+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${me(r)}\u2013${me(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Wr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,N)=>C+o(N),0),p=r.reduce((C,N)=>C+o(N),0),g=e.reduce((C,N)=>C+N.costUsd,0),k=e.reduce((C,N)=>C+N.outputTokens,0),x=n==="api"?`${me(g)} total`:Ve(k),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=C=>`${C} article${C===1?"":"s"}`,R=[];if(s.length===0)R.push(`Wrote ${b(c)} (${D}) successfully \xB7 ${x}.`),R.push("Next \u2014 push them to Document360:"),R.push("/publish --all"),R.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{R.push(`Wrote ${p}/${b(c)} (${D}) \xB7 ${x}.`),R.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)R.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return R}function Fr(e,t,n){try{let o=hd({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 Hr(e,t,n){let o=(ua(e)?.docsDir??yd).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=vd(n.path,o);return r.includes(p)?{docsDir:o,targets:[p],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${p}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=Cd(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 c=Lr(e,o,s);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"",g=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${g} --rewrite to regenerate them all.`}}return{docsDir:o,targets:c,planCount:r.length}}async function da(e,t){if(!ua(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=wd(t.cwd);if(n.length===0)return console.log($("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:c,rewrite:p}=_r(e),{docsDir:g,targets:k,reason:x,rewriting:D}=Hr(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(x?L(x):L("Nothing to write.")),{kind:"continue"};D&&console.log(L(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let b=gd(k),R=Nr(c),{model:C,forced:N}=kd(t.cwd,"standard"),I=!!r;if(s&&!I){let O=md({files:Mr(t.cwd,n,k),op:"write",model:C});o&&console.log(f(`Scope: ${o} (${k.length} pending).`));for(let J of Ur(b,O,R))console.log(J);return console.log(f(`Model: ${C}${N?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${k.length} article${k.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${R} agents at once) on ${C}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let O of bd({cwd:t.cwd,partitions:b,promptFor:J=>Or(J,g,{rewrite:D||I}),concurrency:R,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(O.type==="partition_status")O.status==="running"?console.log(f(` \u25B8 ${O.label} \u2014 writing\u2026`)):O.status==="done"?console.log(j(` \u2713 ${O.label}`)):console.log($(` \u2717 ${O.label}`));else if(O.type==="run_done"){console.log("");let J=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let ne of Wr(O.results,b,J))console.log(O.ok?j(ne):L(ne));let pe=Fr(t.cwd,g,k);pe&&console.log(L(pe))}}catch(O){console.log($(`Write run failed: ${O.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as Pd,readdirSync as pa,statSync as fa}from"node:fs";import{join as ma}from"node:path";import{inputDir as Rd,readProjectConfig as Td}from"document360-engine";var ha=/\.(md|markdown|pdf|txt)$/i;function qr(e){let t=Rd(e);if(!Pd(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of pa(t)){let s=ma(t,r),c=!1;try{c=fa(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=Sd(s);p>0&&n.push({name:r,docCount:p})}else ha.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Sd(e){let t=0;for(let n of pa(e))try{fa(ma(e,n)).isFile()&&ha.test(n)&&t++}catch{}return t}function Br(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 oo(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(`
|
|
239
|
+
`)}var Gr="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function ga(e,t){let n=t?.cwd??process.cwd();if(!Td(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=qr(n);if(o.length===0&&r===0)return console.log(f(Gr)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let g of o)console.log(` ${g.name} ${f(`(${g.docCount} doc${g.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:oo(p),display:p?`/draft ${p}`:"/draft"}}let c=Br(o,s);return{kind:"forward-to-agent",prompt:oo(c??"",c?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as Dd,readProjectConfig as jd}from"document360-engine";function Yr(e){try{return Dd(e).filter(t=>t.kind==="request").length}catch{return 0}}function Vr(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function zr(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(`
|
|
240
|
+
`)}var Xr="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 wa(e,t){let n=t?.cwd??process.cwd();if(!jd(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Vr(e);if(!r&&Yr(n)===0)return console.log(f(Xr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:zr(r,o),display:s}}W();import{search as Ad}from"@inquirer/prompts";import{findByName as Ed,getSession as Id,listSessions as Nd,relativeTime as ka}from"document360-engine";async function ba(e,t){let n=Nd(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(f("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=Ed(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),ya(n),{kind:"continue"})}if(!process.stdin.isTTY)return ya(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Ad({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${ka(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Id(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function ya(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${f(ka(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as _d}from"document360-engine";function Kr(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 xa(e,t){let n=Kr(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(_d(o,n)?console.log(j(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(j(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as $a,readProjectConfig as Ld,writeProjectConfig as Md}from"document360-engine";W();function Qr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Ld(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 $a().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Md(o,e),null):`Unknown environment "${r}". Known: ${$a().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function va(e,t){let n=e[0];if(!n)return Un(t.cwd),{kind:"continue"};if(n==="add"){let o=Qr(t.cwd,e[1],e[2]);return o?(console.log($(o)),{kind:"continue"}):(console.log(j(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/login")}`),{kind:"continue"})}return Wn(t.cwd,n),Fn(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Od}from"@inquirer/prompts";import{readProjectConfig as Ud,readUserConfig as Ca,resolveModelSetting as Jr,writeUserConfig as Pa}from"document360-engine";var Ee=[{value:null,label:"Auto",desc:"Engine right-sizes per task \u2014 Sonnet for routine work, Opus for analysis (recommended)"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus 4.8 \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet 4.6 \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku 4.5 \xB7 fastest for quick answers"}];function ro(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=Ee.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Wd(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"claude-settings":return"Claude Code's own settings (~/.claude/settings.json)";case"claude-default":return"Claude Code default (no override configured)"}}function ln(e,t){let n=()=>{let s=Jr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Ca();return s.defaultModel?(delete s.defaultModel,Pa(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Jr(e).model??"Claude Code default"} (applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}Pa({...Ca(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Ud(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 Ra(e,t){let n=e[0]?.trim();if(!n){let c=Jr(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${_(c.model??"Claude Code default")}`),console.log(f(` source: ${Wd(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=ro(c),g;try{g=await t.withPausedInput(()=>Od({message:`Select model (current: ${c.model??"Claude Code default"})`,default:Ee[p].value,choices:Ee.map((b,R)=>({name:`${b.label}${R===p?" \u2714":""}`,value:b.value,description:b.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:x,effective:D}=ln(t.cwd,g??"default");for(let b of k)console.log(b.startsWith("\u26A0")?L(b):b.startsWith("\u2713")?j(b):f(b));return x&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:s}=ln(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?L(c):c.startsWith("\u2713")?j(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}so();async function Ea(e,t){return await t.withPausedInput(()=>Et(t.cwd)),{kind:"clear"}}async function Ia(e,t){return await t.withPausedInput(()=>_n(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as tp}from"document360-engine";async function Na(e,t){let n=!1;try{n=tp(t.cwd).production}catch{}return n?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var _a=async(e,t)=>{try{await t.withPausedInput(()=>On({}))}catch(n){console.log($(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as np,clearTokens as op,clearProfileProject as rp}from"document360-engine";async function La(e,t){let n;try{n=np(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let o=op(n);return rp(t.cwd,n),console.log(o?j(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):f(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(f("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as Ma}from"node:fs";import{isAbsolute as sp,join as ip,resolve as ap}from"node:path";import{readProjectConfig as lp,screenshotPlaceholderIds as cp,DEFAULT_CAPTURE_DIR as up,DEFAULT_OUTPUT_DIR as dp}from"document360-engine";var Oa=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function es(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Oa(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Oa(o),setup:t}:{mode:"single",id:o}}function ts(e,t){let n=lp(e),o=n?.captureDir??up,r=n?.outputDir??dp,s=(c,p)=>sp(c)?ip(c,p):ap(e,c,p);return cp(e,{scope:t}).map(({id:c,file:p})=>{let g=Ma(s(r,`${c}.png`))?"captured":Ma(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:g}})}var pp={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},fp={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function ns(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(s=>s.file))].sort(),o=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of n){r.push(s);for(let c of e.filter(p=>p.file===s))r.push(` ${pp[c.state]} ${c.id.padEnd(34)} ${fp[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Ua(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(`
|
|
241
241
|
`),"","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(`
|
|
242
242
|
`)}async function io(e,t){let n=es(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of ns(ts(c,n.scope),n.scope))console.log(p);return{kind:"continue"}}if(n.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${n.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${n.id}.spec.ts. Report the spec path and any TODO data-testids or data to stage.`].join(`
|
|
243
243
|
`),display:`/screenshot ${n.id}`};let r=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${n.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${n.scope}`:"every <!-- SCREENSHOT --> placeholder across the docs tree (the configured docsDir)"}.`,"Follow that skill exactly for each: read the SCREENSHOT block; read the product source for EXACT routes","and stable data-testid selectors (never guess); enter the prepared context via captureScope(); guard data",`prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts.${n.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`].join(`
|
|
244
|
-
`),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as
|
|
245
|
-
`),display:"/capture-setup"}}var Wa="-".repeat(64);function os(e){let t=
|
|
246
|
-
`)}async function Fa(e,t){let n=t?.cwd??process.cwd();return
|
|
247
|
-
`)}var
|
|
248
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
244
|
+
`),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as mp,readFileSync as hp}from"node:fs";import{isAbsolute as gp,join as wp,resolve as yp}from"node:path";import{readProjectConfig as kp,DEFAULT_CAPTURE_DIR as bp}from"document360-engine";async function un(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-SETUP.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
|
|
245
|
+
`),display:"/capture-setup"}}var Wa="-".repeat(64);function os(e){let t=bp;try{let x=kp(e);x?.captureDir&&(t=x.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=gp(t)?wp(t,"CAPTURE-TESTID-REQUESTS.json"):yp(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!mp(n))return null;let o;try{let x=JSON.parse(hp(n,"utf8").replace(/^/,""));o=Array.isArray(x?.requests)?x.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(x=>x.file).filter(Boolean)).size,s=o.length,c=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,g=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${c} requested across ${p}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",Wa,`Read ${g} and ${k}. They list ${c} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",Wa]}ct();W();import{listOpenForDocs as xp,readProjectConfig as $p}from"document360-engine";function rs(e){try{return xp(e).length}catch{return 0}}function ss(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape."," \u2022 answer (a reply to a question you asked; `re` = your question id) \u2192 fold the fact into the affected"," article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only \u2014 do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
|
|
246
|
+
`)}async function Fa(e,t){let n=t?.cwd??process.cwd();return $p(n)?rs(n)===0?(console.log(f("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:ss(),display:"/inbox"}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as vp,listOpenForDocs as Cp,readProjectConfig as Pp,computeSyncStatus as Rp,planPull as Tp,applyPull as Sp}from"document360-engine";function Ot(e){let t=0,n=0,o=0;try{t=vp(e).length}catch{}try{let r=Cp(e);n=r.filter(s=>s.kind==="request").length,o=r.filter(s=>s.kind==="answer").length}catch{}return{hints:t,requests:n,answers:o}}function Ut(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"}`),t.length?t.join(", "):null}function as(e){return{publish:e.includes("--publish")}}function ls({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 reconciled before this run: clean portal edits were pulled into local, and any conflicts / new-portal-articles were surfaced to the user. Do NOT re-pull. 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) AND d360_inbox (open requests + answers).","3. 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), and fold any answers into the affected article(s) + the architecture brief.","4. 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.","5. Write/update the articles as drafts, grounded in the cited sources.","6. Close the loop: stamp consumed hints, and mark handled messages status: done with resulting_articles.","7. Push the drafts to Document360.","8. 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?"9. 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(`
|
|
247
|
+
`)}var Dp={status:Rp,plan:Tp,apply:Sp};async function cs(e,t=Dp){let n={pulled:[],conflicts:[],untrackedRemote:[],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")n.untrackedRemote.push(r.title??r.articleId??"(untitled)");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 is=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,ao=e=>e===1?"":"s";function us(e){if(e.error)return[`\u26A0 Couldn't check Document360 for portal changes (${e.error.slice(0,100)}) \u2014 proceeding; the agent will re-check.`];let t=[];return e.pulled.length&&t.push(`\u2713 Pulled ${e.pulled.length} portal edit${ao(e.pulled.length)} into local: ${is(e.pulled)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${ao(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${is(e.conflicts)}`),e.untrackedRemote.length&&t.push(`\u2139 ${e.untrackedRemote.length} new article${ao(e.untrackedRemote.length)} in the portal ${e.untrackedRemote.length===1?"isn't":"aren't"} local yet \u2014 run /pull to bring ${e.untrackedRemote.length===1?"it":"them"} in: ${is(e.untrackedRemote)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull${ao(e.failed.length)} failed \u2014 left for /pull.`),t}async function Ha(e,t){let n=t?.cwd??process.cwd();if(!Pp(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Me(n,t?.profileName);if(!o.ok)return console.log($(o.reason)),{kind:"continue"};let{publish:r}=as(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await cs({cwd:n,profileName:t?.profileName});for(let p of us(s))console.log(p.startsWith("\u2713")?j(p):p.startsWith("\u2139")?f(p):L(p));let c=Ut(Ot(n));return console.log(f(c?`Catching up on ${c}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:ls({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as jp}from"node:child_process";var pt="document360-writer",lo=`npm i -g ${pt}@latest`;async function co(){let e=process.platform==="win32";return new Promise(t=>{try{let n=jp(`npm i -g ${pt}@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 qa(){return console.log(f(`Updating ${pt}\u2026`)),(await co()).ok?console.log(j("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log($(`Update failed \u2014 run manually: ${lo}`)),{kind:"continue"}}W();ct();import{existsSync as ds,rmSync as Ap}from"node:fs";import{basename as Ba,resolve as ps}from"node:path";import{execFileSync as Ep}from"node:child_process";import{input as Ip}from"@inquirer/prompts";import{readProjectConfig as Np,devHintsGuidePath as _p}from"document360-engine";var Lp=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Mp=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),uo=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Ga=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Ya(e){let t=uo(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Ga(t)?!0:Mp.has(t)}function fs(e){let t=null;try{t=Np(e)}catch{t=null}let n=new Set(Lp);for(let o of[uo(t?.docsDir),uo(t?.captureDir),uo(t?.outputDir)])o&&Ga(o)&&n.add(o);return[...n].filter(o=>Ya(o)&&ds(ps(e,o)))}function ms(e,t){let n=[],o=[];for(let r of t){if(!Ya(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Ap(ps(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Va(e,t){try{return Ep("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
248
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Op(e){return Va(e,".d360-writer/hints")}function Up(e){return Va(e,".d360-writer/messages")}function hs(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Op(e),o=Up(e),r=ds(ps(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: ${Ba(e)}`]}async function za(e,t){let n=fs(t.cwd);for(let g of hs(t.cwd,n))console.log(n.length===0?f(g):g);if(n.length===0)return{kind:"continue"};let o=Ba(t.cwd);if((await t.withPausedInput(()=>Ip({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=ds(_p(t.cwd)),{removed:c,failed:p}=ms(t.cwd,n);console.log(j(`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`));for(let g of p)console.log($(` \u2717 ${g.path}: ${g.error}`));if(s){for(let g of Vn())console.log(g);console.log(f("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}W();import{lintDocs as Wp}from"document360-engine";function po(e){if(e.length===0)return["\u2713 No issues found \u2014 no leaked internals, unknown commands, or stale version facts 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):`];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 gs(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.","","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(`
|
|
249
249
|
`)).join(`
|
|
250
250
|
`)].join(`
|
|
251
|
-
`)}async function Xa(e,t){let n=e.includes("--fix"),o=e.find(c=>!c.startsWith("--")),r=o?` ${o}`:"",s=
|
|
252
|
-
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=
|
|
253
|
-
`);return{lines:s.slice(0,t).map(c=>ke(c,ks)),hidden:Math.max(0,s.length-t)}}function ho(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function go(e,t){if(typeof e.article_id=="string"&&e.article_id)return e.article_id;try{let n=JSON.parse(t),r=(Array.isArray(n)?n[0]:n)?.id;return typeof r=="string"&&r?r:null}catch{return null}}function wo(e){try{let t=JSON.parse(e),o=(Array.isArray(t)?t[0]:t)?.url;return typeof o=="string"&&/^https?:\/\//.test(o)?o:null}catch{return null}}var
|
|
254
|
-
|
|
255
|
-
`),console.log(`${j("\u25CF")} ${Pe(s.title)}${s.arg!==null?se(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=ut(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=p=>p===1?"":"s";console.log(se(` \u23BF Added ${s.added} line${c(s.added)}, removed ${s.removed} line${c(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(f(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let c=mo(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?$:se;c.lines.forEach((g,k)=>console.log(p((k===0?" \u23BF ":" ")+g))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||
|
|
256
|
-
`),console.log(f(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(rl(t.uuid),t.titleFired||
|
|
257
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){
|
|
258
|
-
`)}import{existsSync as
|
|
259
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var
|
|
260
|
-
`)){let c=s.trim().replace(
|
|
261
|
-
`)}function Rl(e){if(!e.ready)return{kind:"idle"};let t=!!e.pendingText;if(!e.hasDocs)return{kind:"noDocs",note:
|
|
251
|
+
`)}async function Xa(e,t){let n=e.includes("--fix"),o=e.find(c=>!c.startsWith("--")),r=o?` ${o}`:"",s=Wp({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(j("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:gs(s),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts)\u2026"));for(let c of po(s))console.log(s.length===0?j(c):L(c));return s.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}W();import{lintDocs as Fp,loadStyleGuide as Hp,buildReviewPrompt as qp,readProjectConfig as Bp,DEFAULT_DOCS_DIR as Gp}from"document360-engine";function ws(e,t){let n=Bp(e);if(!n)return null;let o=(n.docsDir??Gp).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(k=>!k.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),c=Fp({cwd:e}),p=s?c.filter(k=>k.path===`${o}/${s}`||k.path.startsWith(`${o}/${s}/`)):c;return{prompt:qp({docsRoot:o,scope:s,styleGuide:Hp(e),deterministicFindings:p,fix:r}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function Ka(e,t){let n=ws(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}var Qa={help:nr,"?":nr,clear:xi,exit:or,quit:or,init:lr,mcp:Kn,publish:Qi,audit:an,scope:Zi,pull:ia,convert:aa,write:da,draft:ga,document:wa,resume:ba,rename:xa,profile:va,model:Ra,doctor:cn,workspace:Ea,project:Ia,"allow-prod":Na,login:_a,logout:La,screenshot:io,"capture-setup":un,devhints:Si,inbox:Fa,"catch-up":Ha,update:qa,reset:za,check:Xa,review:Ka};function Ja(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}ct();W();var Yp={Bash:"command",PowerShell:"command",Read:"file_path",Write:"file_path",Edit:"file_path",NotebookEdit:"notebook_path",Glob:"pattern",Grep:"pattern",WebFetch:"url",WebSearch:"query",Agent:"description",Task:"description",Skill:"skill"},el=160,ks=200,tl=40;function ke(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Za(e){let t=Object.entries(e).filter(([,o])=>o!=null&&o!=="");if(t.length===0)return null;let n=t.slice(0,4).map(([o,r])=>`${o}: ${ke(typeof r=="string"?r:JSON.stringify(r),tl)}`);return t.length>4&&n.push("\u2026"),ke(n.join(", "),el)}var ze=e=>typeof e=="string"&&e?e:null,ys=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Vp(e){let t=ze(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function zp(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=ze(t.title);if(!o)return null;let r=Vp(t.local_path);return n("Create article",`"${ke(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=ze(t.title),r=ys(t.article_id);return n("Update article",o?`"${ke(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",ys(t.article_id)?`id ${ys(t.article_id)}\u2026`:null);case"d360_publish_article":{let o=t.version_number;return n("Publish article LIVE",typeof o=="number"?`v${o}`:null)}case"d360_unpublish_article":return n("Unpublish article",null);case"d360_create_category":return n("Create category",ze(t.name)?`"${ke(ze(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=ze(t.file_path);return n("Upload image",o?ke(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function fo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),c=s.join("__");if(r==="document360"){let k=zp(c,t);if(k)return k}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Za(t)}}let n=Yp[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:ke(o,el)}:{title:e,sep:"",arg:Za(t)}}function Xp(e){if(e===null||typeof e!="object")return typeof e=="string"?e:null;let t=e;for(let n of["name","title","slug","id"])if(typeof t[n]=="string"&&t[n])return t[n];return null}function Kp(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Xp).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>ke(r,ks))]}if(t!==null&&typeof t=="object"){let n=Object.entries(t).filter(([,o])=>o!==null&&(typeof o=="string"||typeof o=="number"||typeof o=="boolean")).slice(0,6).map(([o,r])=>`${o}: ${ke(String(r),tl)}`);return n.length>0?[ke(n.join(" \xB7 "),ks)]:null}return null}function Qp(e){let t=ze(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Jp(e,t,n){switch(e){case"d360_create_article":{let o=Qp(t?.local_path);return[`\u2713 draft created${o?` \xB7 ${o}`:""}`]}case"d360_update_article":return["\u2713 draft updated"];case"d360_fork_article":return["\u2713 forked to a new draft"];case"d360_publish_article":return["\u2713 PUBLISHED LIVE \u2014 visible to readers"];case"d360_unpublish_article":return["\u2713 reverted to draft (removed from readers)"];case"d360_create_category":{let o=ze(t?.name);return[`\u2713 category created${o?` \xB7 "${o}"`:""}`]}case"d360_upload_drive_file":{let o=n.match(/https?:\/\/\S+/);return[`\u2713 uploaded${o?` \xB7 ${ke(o[0],120)}`:""}`]}default:return null}}function mo(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
252
|
+
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=Jp(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let s=Kp(r)??r.split(`
|
|
253
|
+
`);return{lines:s.slice(0,t).map(c=>ke(c,ks)),hidden:Math.max(0,s.length-t)}}function ho(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function go(e,t){if(typeof e.article_id=="string"&&e.article_id)return e.article_id;try{let n=JSON.parse(t),r=(Array.isArray(n)?n[0]:n)?.id;return typeof r=="string"&&r?r:null}catch{return null}}function wo(e){try{let t=JSON.parse(e),o=(Array.isArray(t)?t[0]:t)?.url;return typeof o=="string"&&/^https?:\/\//.test(o)?o:null}catch{return null}}var df=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function pf(e,t,n,o){if(df.test(e))try{let r=sl(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=go(t,n),p=wo(n);e.endsWith("publish_article")&&p&&console.log(_(` \u2B95 Live: ${p}`)),c&&s&&console.log(_(` \u2B95 Preview: ${ho(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function il(e=process.cwd(),t="auto",n){let o=ef(t);o.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${_("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${_('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),ff(e,n),o.kind==="subscription"&&(o.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,s=bs({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=Zp({input:process.stdin,output:process.stdout}),g=[],k=null,x=!1;p.on("line",R=>{if(k){let C=k;k=null,C(R)}else g.push(R)}),p.on("close",()=>{if(x=!0,k){let R=k;k=null,R(null)}});function D(){return g.length>0?Promise.resolve(g.shift()):x?Promise.resolve(null):(process.stdout.write(_("> ")),new Promise(R=>{k=R}))}let b={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=bs({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setPendingName:R=>{c.pendingName=R},setModel:async R=>s.setModel(R),withPausedInput:async R=>{p.pause();try{return await R()}finally{p.resume()}}};try{for(;;){let R=await D();if(R===null)break;let C=R.trim();if(C){if(C.startsWith("/")){let N=Ja(C);if(!N)continue;let I=Qa[N.name];if(!I){console.log($(`Unknown command: /${N.name}`)),console.log(f("Type /help for the list."));continue}let O=await I(N.args,b);if(O.kind==="exit")break;if(O.kind==="clear"){b.restartAgent();continue}if(O.kind==="allow-prod"){r=!0,b.restartAgent(),console.log(j("\u2713 Production writes authorized for this session.")),console.log("");continue}if(O.kind==="resume"){s.close(),s=bs({cwd:e,resume:O.uuid,profileName:n,allowProdWrites:r});let J=tf(O.uuid);c={uuid:O.uuid,firstPrompt:J?.firstPrompt??null,titleFired:!0},rl(O.uuid),console.log(j(`\u2713 Resumed "${O.name}"`)),console.log("");continue}O.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=O.display??O.prompt),await ol(s,O.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=C),await ol(s,C,o,c,e)}}}finally{s.close(),p.close()}}function ff(e,t){console.log(""),console.log(Kt("document360-writer")),console.log(f(` cwd: ${e}`));let n=af(e);if(console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(mf(e,t)),!lf(e))console.log(L(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{try{Gn(e);for(let o of Yn(e))console.log(L(` ${o}`))}catch{}try{let o=Ut(Ot(e));o&&console.log(L(` \u{1F4CB} ${o} from the repo's coding agent \u2014 run /catch-up.`))}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function mf(e,t){try{let n=sl(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=uf(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...nl(r.idToken)??{},...nl(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return cf(r)&&!r.refreshToken?L(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function hf(){console.error(""),console.error(`Sign in with your Claude subscription: run ${_("claude")} once, then retry.`),console.error(` (No Claude Code? ${_("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${_("https://console.anthropic.com/settings/keys")}`)}function gf(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;rf({uuid:t,name:r??of(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function wf(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||sf(o,t).then(r=>{r&&nf(n,r)}).catch(()=>{})}async function ol(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))yf(c,o,r,n,s)}function yf(e,t,n,o,r){switch(e.type){case"session":t.uuid||gf(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=fo(e.name,e.input);s&&(process.stdout.write(`
|
|
254
|
+
|
|
255
|
+
`),console.log(`${j("\u25CF")} ${Pe(s.title)}${s.arg!==null?se(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=ut(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=p=>p===1?"":"s";console.log(se(` \u23BF Added ${s.added} line${c(s.added)}, removed ${s.removed} line${c(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(f(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let c=mo(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?$:se;c.lines.forEach((g,k)=>console.log(p((k===0?" \u23BF ":" ")+g))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||pf(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
|
|
256
|
+
`),console.log(f(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(rl(t.uuid),t.titleFired||wf(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&hf();break}}import{render as Nm}from"ink";import{resolveAuth as _m}from"document360-engine";import{useCallback as V,useEffect as Te,useMemo as Rs,useRef as Q,useState as H}from"react";import{Box as oe,Text as T,useApp as Lf,useInput as Mf,useStdout as Of}from"ink";import{existsSync as Xe,readFileSync as Ts,readdirSync as jo}from"node:fs";import{spawnSync as Uf}from"node:child_process";import{basename as pn,isAbsolute as Wf,join as mt}from"node:path";import{createSession as Ll,classifyClaudeAuth as As,CLAUDE_CODE_SETUP_HINT as Ff,loginPkce as Hf,toStoredTokens as qf,saveTokens as Bf,getAccessToken as Gf,resolveActiveProfile as de,resolveProjectId as Yf,getArticle as Vf,decodeJwtClaims as Ft,isExpired as We,loadTokens as Ke,clearTokens as zf,clearProfileProject as Xf,setTitle as Kf,slugify as Qf,touchSession as Ss,upsertSession as Jf,generateTitle as Ml,findByName as Zf,listSessions as em,renameSession as tm,suggestNextAction as nm,readProjectConfig as Z,writeProjectConfig as Ol,resolveModelSetting as Es,loadProfileMap as Do,applyPull as om,computeSyncStatus as Ul,countLocalAhead as rm,lintDocs as Wl,compareRemoteSources as sm,planPull as im,establishBaselines as am,rebaselineServerMeta as lm,inventoryRepo as cm,knownEnvironments as um,resolveEnvironment as dm,planPartitions as Ds,partitionEvenly as pm,screenshotPlaceholderIds as fm,trackedArticlePaths as mm,runPartitioned as Ro,estimateBulkCost as Fl,resolveModelForOperation as To,readDocsPlan as Hl,checkForUpdate as hm,detectInstallKind as gm,isSelfUpdatable as wm,devHintsGuidePath as Is,toolFeedbackPath as ym,reconcileToolFeedback as km,DEFAULT_DOCS_DIR as fn,setProfileProject as bm,writeCrashLog as xm,applyStructureOrder as $m,orderSyncLine as vm}from"document360-engine";ct();import{spawn as al}from"node:child_process";function kf(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function bf(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?al([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):al(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",c=>o(c===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function ll(e){for(let[t,n]of kf())if(await bf(t,n,e))return!0;return!1}var xf=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function xs(e,t){if(t.closed)return e;let n=e.split(`
|
|
257
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){xf.test(s)&&(t.cueSeen=!0);continue}let c=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);c?(n[r]=`${c[1]}${++t.num}. ${c[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
|
|
258
|
+
`)}import{existsSync as $f,mkdirSync as vf,readFileSync as Cf,writeFileSync as Pf}from"node:fs";import{join as cl}from"node:path";import{writerDir as Rf}from"document360-engine";function ul(e){return cl(Rf(e),".sessions")}function dl(e,t){return cl(ul(e),`${t}.json`)}function pl(e,t,n){try{vf(ul(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Pf(dl(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function $s(e,t){try{let n=dl(e,t);if(!$f(n))return[];let o=JSON.parse(Cf(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Tf=e=>`\x1B]0;${e}\x07`,Sf=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function fl(e){process.stdout.isTTY&&process.stdout.write(e)}function Wt(e){fl(Tf(e))}function yo(e){fl(Sf(e))}var ko=["\xB7 "," \xB7"],bo="\u{1F7E3}";so();Xn();var xo=[{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:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path>] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Reports issues; --fix applies the corrections in place",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],ml={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function hl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(ml[n])return ml[n];let o=xo.find(r=>r.name===t);return o?o.desc:""}function gl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return xo.filter(n=>n.name.startsWith(t))}function wl(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as yl,Text as ie}from"ink";import{jsx as le,jsxs as $o}from"react/jsx-runtime";function Df({row:e}){switch(e.t){case"head":return le(ie,{color:F,bold:!0,children:e.s});case"text":return le(ie,{children:e.s});case"dim":return le(ie,{dimColor:!0,children:e.s});case"sub":return le(ie,{bold:!0,dimColor:!0,children:e.s});case"good":return le(ie,{color:"green",children:e.s});case"step":return $o(ie,{children:[le(ie,{color:F,children:`${e.n}. `}),e.s]});case"cmd":return $o(ie,{children:[" ",le(ie,{color:F,children:e.name.padEnd(20)}),le(ie,{dimColor:!0,children:e.s})]});case"gap":return le(ie,{children:" "})}}function kl({tab:e,width:t}){let n=Re[e]??Re[0],o=6+Re.reduce((s,c)=>s+c.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return $o(yl,{flexDirection:"column",paddingX:1,children:[$o(ie,{children:[le(ie,{color:F,bold:!0,children:"Help "}),Re.map((s,c)=>c===e?le(ie,{color:"white",backgroundColor:F,bold:!0,children:` ${s.label} `},s.key):le(ie,{dimColor:!0,children:` ${s.label} `},s.key))]}),le(ie,{color:F,children:r}),le(yl,{flexDirection:"column",marginTop:1,children:n.rows.map((s,c)=>le(Df,{row:s},c))}),le(ie,{dimColor:!0,children:`
|
|
259
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var jf=/^(?:\d+[.)]|[-*•])\s+/;function bl(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
260
|
+
`)){let c=s.trim().replace(jf,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let g=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!g||!o.has(g[1].toLowerCase()))continue;let k=`/${g[1].toLowerCase()}${g[2]?` ${g[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}W();function dn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Oe(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function xl(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Af=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function $l(e,t,n){if(!Af.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(s=>{let c=s.replace(/\\/g,"/");return r===c||r.endsWith(`/${c}`)})??null}function vs(e){return e.replace(/^[\w.-]+\//,"")}var vo=16,vl={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function ft(e){return typeof e=="string"?e:e.cmd}function Cl(e){return typeof e=="string"?void 0:e.desc}function Cs(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Pl(e,t){let n=Cs(t);return e.some(r=>ft(r).trim()===t.trim()||!!n&&Cs(ft(r))===n)?e.filter(r=>ft(r).trim()!==t.trim()&&!(n&&Cs(ft(r))===n)):[]}var Ef='\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 If(e,t){switch(e){case"/write":return"finish the planned articles that aren\u2019t written yet";case"/catch-up":return"write up everything your builder flagged";case"/audit":return t?"also scan the code for other changes":"check the code for anything new or missing in the docs";case"/pull":return"pull edits + new articles from Document360";case"/publish":return"push your local changes up to Document360";default:return""}}function Ue(e){return e===1?"":"s"}function Nf(e){switch(e){case"/write":return"it finishes the articles already planned";case"/catch-up":return"it clears everything your builder queued";case"/audit":return"it shows what the latest code changes touch";case"/pull":return"it reconciles anything changed on Document360";case"/publish":return"it pushes your local edits up to Document360";default:return"it\u2019s the most useful next step"}}function Ps(e,t,n){let o=[];e.pendingWrites>0&&o.push(` \u2022 ${e.pendingWrites} planned article${Ue(e.pendingWrites)} still unwritten`),e.localAhead>0&&o.push(` \u2022 ${e.localAhead} article${Ue(e.localAhead)} changed locally \u2014 ready to publish`),e.pendingText&&o.push(` \u2022 your builder left ${e.pendingText}`),e.behind>0&&o.push(` \u2022 ${e.behind} code change${Ue(e.behind)} since your last docs check`);let r=o.length>0?["Welcome back \u2014 where your docs stand:",...o,`I\u2019d start with ${t[0]} \u2014 ${Nf(t[0])}.`]:[`Welcome back. Your ${e.tracked} tracked article${Ue(e.tracked)} are all in sync.`];return r.push("",...t.map((s,c)=>` ${c+1} ${s.padEnd(9)} ${If(s,n)}`),"Or just tell me what to write or update."),r.join(`
|
|
261
|
+
`)}function Rl(e){if(!e.ready)return{kind:"idle"};let t=!!e.pendingText;if(!e.hasDocs)return{kind:"noDocs",note:Ef,ghost:"write the docs for this repo",title:t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:null,options:t?["/catch-up","/audit"]:["/audit"]};if(e.pendingWrites>0){let r=t?["/write","/catch-up"]:["/write","/audit"],s=`\u{1F4DD} ${e.pendingWrites} planned article${Ue(e.pendingWrites)} not written yet \u2014 pick up where you left off:`;return{kind:"actions",note:Ps(e,r,t),title:s,options:r}}if(e.localAhead>0){let r=t?["/publish","/catch-up"]:["/publish","/audit"],s=`\u{1F4E4} ${e.localAhead} article${Ue(e.localAhead)} changed locally \u2014 ready to publish to Document360:`;return{kind:"actions",note:Ps(e,r,t),title:s,options:r}}if(!t&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${Ue(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`};let n=t?["/catch-up","/audit"]:["/audit","/pull"],o=t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:e.behind>0?`\u{1F4CB} ${e.behind} code change${Ue(e.behind)} since your last docs check \u2014 /audit to see what needs updating (or /audit --auto on to run it for you):`:`\u{1F4DA} ${e.tracked} article${Ue(e.tracked)} tracked for "${e.profileName}". What next?`;return{kind:"actions",note:Ps(e,n,t),title:o,options:n}}var _f=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Tl(e){return e.replace(/\r\n?/g,`
|
|
262
262
|
`)}function Sl(e){return e.includes(`
|
|
263
263
|
`)||e.length>200}function Dl(e,t){let n=t.split(`
|
|
264
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function jl(e,t){return e.replace(
|
|
264
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function jl(e,t){return e.replace(_f,n=>t.get(n)??n)}function Al(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Co(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
265
265
|
`)){if(s.length===0)o.push({start:r,end:r});else for(let c=0;c<s.length;c+=n)o.push({start:r+c,end:r+Math.min(c+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function Po(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function El(e,t,n){let o=Po(e,t),r=o+n;if(r<0||r>=e.length)return t;let s=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+s,e[r].end)}function Il(e,t,n){let o=e[Po(e,t)];return n==="start"?o.start:o.end}function Nl(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
266
266
|
`),s=0;for(let c=r.length-1;c>=0;c--){let p=r[c];if(s+=Math.max(1,Math.ceil(p.length/o)),s>=t){let g=s-t;return{text:[g>0?p.slice(g*o):p,...r.slice(c+1)].join(`
|
|
267
267
|
`),truncated:c>0||g>0}}}return{text:e,truncated:!1}}function _l(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
268
|
-
`)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as js,jsx as E,jsxs as G}from"react/jsx-runtime";var
|
|
268
|
+
`)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as js,jsx as E,jsxs as G}from"react/jsx-runtime";var Cm={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},ql=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
269
269
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
270
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
271
|
-
${
|
|
270
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Pm(e,t,n,o){let r=As(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",c=Es(e),p=Z(e),g=(p?.docsDir??fn).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${g}/ + config`,x={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:Cm[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:k};if(p===null)return x;try{let D=de(e,o);x.profile=D.name,x.apiUrl=D.connection.apiUrl,x.prod=D.production,x.project=D.project.projectName??D.project.projectId??"(chosen at login)";let b=Ke(D.name);if(b){let R={...Ft(b.idToken)??{},...Ft(b.accessToken)??{}},C=R.email??R.preferred_username??"signed in";We(b)?b.refreshToken&&(x.who=C,x.loggedOut=!1,x.sessionHint="session expired \u2014 refreshing\u2026"):(x.who=C,x.loggedOut=!1,x.sessionHint=`session valid until ${new Date(b.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return x}function Rm(e,t){try{let n=de(e,t),o=Ke(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Ft(o.idToken)??{},...Ft(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return We(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var Bl=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Ao=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Tm="Ask me to write or update an article\u2026";function So({ch:e,dim:t}){let[n,o]=H(!0);return Te(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),E(T,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Sm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Gl(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Dm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Yl(e){try{return jo(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Vl(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Yl(mt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Yl(mt(e,o)))}function zl(e,t){try{let n=Z(e);if(!n)return!1;let o=de(e,t),r=Do(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=mt(e,(n.docsDir??fn).replace(/\/+$/,""));return!!(Xe(s)&&jo(s).length>0||Xe(Is(e)))}catch{return!1}}function jm({startTime:e,chars:t}){let[n,o]=H(0);Te(()=>{let g=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(g)},[]);let r=Ao[n%Ao.length],s=Bl[Math.floor(n/16)%Bl.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return G(oe,{children:[E(T,{color:F,children:` ${r} ${s}\u2026 `}),E(T,{color:"gray",children:`(${on(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var Am=12e4;function Em({p:e}){let[t,n]=H(0);Te(()=>{let I=setInterval(()=>n(O=>O+1),150);return()=>clearInterval(I)},[]);let o=Ao[t%Ao.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),p=Date.now()-e.lastAt>=Am,g=e.verb??"Converting",k=e.unit??"article",x=e.rows.reduce((I,O)=>I+O.items,0),D=g.toLowerCase(),b=e.rows,R=0;if(b.length>vo){let I=b.findIndex(J=>J.status==="active"||J.status==="pending"),O=Math.max(0,Math.min(I-2,b.length-vo));R=b.slice(0,O).filter(J=>J.status==="done").length,b=b.slice(O,O+vo)}let C=Math.min(40,Math.max(...b.map(I=>vs(I.label).length),0)),N=I=>I==="failed"?"red":I==="active"?F:void 0;return G(oe,{flexDirection:"column",children:[G(oe,{children:[E(T,{color:F,children:` ${o} ${g} ${x} ${k}${x===1?"":"s"} `}),E(T,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${on(r)} \xB7 esc to stop`})]}),R>0&&E(T,{dimColor:!0,children:` \u2714 +${R} done`}),b.map(I=>G(T,{color:N(I.status),dimColor:I.status==="done"||I.status==="pending",children:[` ${vl[I.status]} ${vs(I.label).padEnd(C)}`,I.status==="active"&&I.itemsDone!==void 0?` (${I.itemsDone}/${I.items} ${k}${I.items===1?"":"s"})`:I.status!=="pending"?` (${I.items} ${k}${I.items===1?"":"s"})`:"",I.status==="active"?` \u2190 ${D}\u2026`:""]},I.label)),p&&E(T,{color:"yellow",children:` \u26A0 no activity for ${on(s)} \u2014 press esc to stop if it's wedged`})]})}var Im=10800*1e3;function Xl({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Lf(),[s,c]=H(n),[p,g]=H(null),[k,x]=H({text:"",pos:0}),D=k.text,b=V(l=>{x(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),R=V(l=>{x(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),C=V(()=>{x(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=Al(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[N,I]=H(!1),[O,J]=H(!1),[pe,ne]=H(0),[De,ue]=H(null),[Qe,q]=H([]),ht=Q(0),[oc,mn]=H(!1),[rc,hn]=H(!1),[Eo,Ms]=H(null),[sc,gt]=H(0),Je=Q(0),[Ht,wt]=H(0),[yt,gn]=H(null),Os=Q(new Map),ic=Q(0),kt=Q([]),be=Q(null);be.current===null&&(be.current=Ll({cwd:e,profileName:s,allowProdWrites:!1}));let Ie=Q({uuid:null,firstPrompt:null,titleFired:!1}),wn=Q(new Map),bt=Q(!1),Io=Q([]),Fe=Q([]),No=Q(null),[Us,Ze]=H(null),_o=Q(null),[et,tt]=H(null),[Ne,xt]=H(null),[He,$t]=H(null),[fe,vt]=H(null),[xe,nt]=H(null),[ot,Ct]=H(null),[Ws,he]=H(null),[$e,rt]=H(null),[ge,Pt]=H(null),[Fs,Lo]=H([]),st=Q([]),qt=Q(!1),ve=Q(null),[yn,ee]=H(null),kn=Q(!1),bn=Q(null),Bt=Q(null),[Ce,it]=H(null),[Mo,Gt]=H(null),[Hs,Rt]=H(0),[qs,Tt]=H(0),[ac,Bs]=H(0),Oo=Rs(()=>{try{return Es(e).model??"auto"}catch{return null}},[e,ac]),{stdout:je}=Of(),[,lc]=H(0),Gs=Q(`${je.columns??80}x${je.rows??24}`),qe=V(()=>Math.max(20,(je.columns??80)-1),[je]),d=V(l=>{kt.current.push(l),console.log(gr(l,qe()))},[qe]),[Uo,Wo]=H(null),St=V(l=>{Wo(l),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),Fo=Q(!1),Ho=V(async()=>{try{if(Fo.current||!wm(gm())||Z(e)?.mode==="engineer")return;let l=await hm({pkg:pt,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;Fo.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${pt} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),hn(!0),(await co().finally(()=>hn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),q(a=>a.includes("/exit")?a:[...a,"/exit"]),Ms(l.latest)):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${lo}`})}catch{}},[e,o,d]),qo=V(l=>{let i=Me(e,s);return i.ok?!0:(d({kind:"note",tone:"warn",text:i.reason}),Bt.current=l,q(["/login"]),!1)},[e,s,d]),[Bo,Go]=H(null),Yt=Q(!0),xn=Q(0),Vt=Q(0);Te(()=>{let l=setInterval(()=>{if(Yt.current){xn.current=0,Vt.current=0;return}if(!N)try{if(!Xe(Is(e)))return;if(Le(e).status==="current"){Yt.current=!0,xn.current=0,Vt.current=0,d({kind:"note",tone:"ok",text:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs."}),Wo(null),ue("write the docs for this repo");return}xn.current+=1;let i=xn.current;if((i===4||i%15===0)&&Vt.current<3){Vt.current+=1;let a=Vt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:en(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${a}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${a}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,N,d]),Te(()=>{let l=Us??pn(e);if(!N){yo(0),Wt(`${bo} ${l}`);return}yo(3);let i=0;Wt(`${ko[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%ko.length,Wt(`${ko[i]} ${l}`)},400);return()=>clearInterval(a)},[N,e,Us]),Te(()=>()=>yo(0),[]);let Yo=V(l=>{try{let i=Z(e);if(!i)return{kind:"idle"};let a=de(e,s),h=Ke(a.name),u=!!h&&(!We(h)||!!h.refreshToken),m=zl(e,s)||!Vl(e,i.authoritativeSourceFiles),w=As(t).state==="missing",y=Do(e,a.name),P=y?Object.keys(y.articles).length:0,S=mt(e,(i.docsDir??fn).replace(/\/+$/,"")),K=!1;try{K=Xe(S)&&jo(S).length>0}catch{}let B=0;if(y?.lastAnalyzedCommit)try{let U=Uf("git",["rev-list","--count",`${y.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});U.status===0&&(B=parseInt((U.stdout||"").trim(),10)||0)}catch{}let M=0;try{let U=Hl(e);if(U.length>0){let X=(i.docsDir??fn).replace(/\/+$/,"");M=Lr(e,X,U.map(ye=>ye.path)).length}}catch{}let v=rm(e,s),A={ready:u&&m&&!w,hasDocs:K,tracked:P,pendingText:Ut(Ot(e)),behind:B,pendingWrites:M,localAhead:v,autoAudit:!!i.autoAudit,profileName:a.name,allowAutoAudit:l};return Rl(A)}catch{return{kind:"idle"}}},[e,s,t]);Te(()=>{let l=performance.now(),i=[],a=(w,y)=>{let P=performance.now();try{return y()}finally{let S=Math.round(performance.now()-P);S>=80&&i.push(`${w}: ${S}ms`)}};d({kind:"banner",info:a("banner",()=>Pm(e,o,t,s))});let h=As(t).state==="missing";if(h&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
|
|
271
|
+
${Ff}
|
|
272
272
|
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!Z(e)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
273
|
-
${ql}`}),q(h?["/doctor","/init"]:["/init"]);return}h&&q(["/doctor"]);try{let w=de(e,s),y=Ke(w.name);y&&We(y)&&y.refreshToken?
|
|
274
|
-
`)}),St(lt()),Yt.current=!1)}}catch{}try{let w=a("reconcile-feedback",()=>
|
|
273
|
+
${ql}`}),q(h?["/doctor","/init"]:["/init"]);return}h&&q(["/doctor"]);try{let w=de(e,s),y=Ke(w.name);y&&We(y)&&y.refreshToken?Gf({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),ne(P=>P+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),q(["/login"])}):(!y||We(y))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),q(["/login"]))}catch{}try{let w=Z(e),y=de(e,s),P=Ke(y.name);w&&P&&!We(P)&&Vl(e,w.authoritativeSourceFiles)&&!zl(e,s)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),q(["/scope"]))}catch{}try{if(a("reconcile-devhints",()=>Gn(e)),Le(e).status!=="current")if(en(e))d({kind:"note",tone:"info",text:`\u{1F514} A newer dev\u2194docs protocol (v${re}) is available \u2014 your builder can re-run /devhints when convenient. Your docs aren't blocked.`});else{let w=Yn(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
|
|
274
|
+
`)}),St(lt()),Yt.current=!1)}}catch{}try{let w=a("reconcile-feedback",()=>km(e));w.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}let u=a("ready-decision",()=>Yo(!0));u.kind==="autoAudit"?(d({kind:"note",tone:"info",text:u.note}),an().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&ae(w.prompt,{display:w.display,quietUser:!0})})):u.kind==="noDocs"?(d({kind:"note",tone:"info",text:u.note}),ue(u.ghost),q(u.options),u.title&&he(u.title)):u.kind==="actions"&&(d({kind:"note",tone:"info",text:u.note}),q(u.options),he(u.title));let m=Math.round(performance.now()-l);m>=800&&xm({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${m}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${i.length?i.join(`
|
|
275
275
|
`):"no single phase \u226580ms"}
|
|
276
|
-
cwd: ${e}`}),Ho()},[]),Te(()=>{let l=setInterval(()=>{Ho()},
|
|
277
|
-
`)});let y=br(e,s);y&&d({kind:"note",tone:"info",text:y})}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{ve.current=null,ee(null),I(!1),ne(u=>u+1)}},[e,s,d,t]),Xo=V(async l=>{await ae(kr(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await Zn(e,s,l.replace(/\\/g,"/"));i.length>0&&(he(`Related articles not yet published (${i.length}):`),q([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ae]),Ko=V(l=>{let i=Ke(l);if(!i||We(i)&&!i.refreshToken)return null;let a={...Ft(i.idToken)??{},...Ft(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),Qo=V((l,i)=>{if(i){let a=Z(e);a&&(a.defaultProfile=l,Ol(a,e))}c(l),we(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Ko(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),q(["/login"])),ne(a=>a+1)},[e,d,we,Ko]),Pn=V((l,i,a)=>{In(e,l,i,a.id,a.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),we(),Do(e,l)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:_t(Nt(e)).join(`
|
|
278
|
-
`)}),St(lt()),Yt.current=
|
|
276
|
+
cwd: ${e}`}),Ho()},[]),Te(()=>{let l=setInterval(()=>{Ho()},Im);return()=>clearInterval(l)},[Ho]),Te(()=>{if(N||Qe.length>0)return;let l=Yo(!1);(l.kind==="actions"||l.kind==="noDocs")&&(q(l.options),he(l.title??null))},[N,Qe,pe,Yo]),Te(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let h=`${je.columns??80}x${je.rows??24}`;h!==Gs.current&&(Gs.current=h,lc(u=>u+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Vi(kt.current,qe())+"\x1B[?2026l")},80))},400)};return je.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),je.off("resize",a)}},[je,qe]);let _e=Math.max(20,(je.columns??80)-1),Ys=Rs(()=>Rm(e,s),[e,s,pe]),Vo=(()=>{if(rc)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Eo!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Eo?` v${Eo}`:""}\u2026`,isSetup:!0};let l=Z(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=mt(e,(l.docsDir??fn).replace(/\/+$/,"")),a=(()=>{try{return Xe(i)&&jo(i).length>0}catch{return!1}})();try{let h=de(e,s),u=Ke(h.name);if(!(!!u&&!(We(u)&&!u.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${h.name}")\u2026`,isSetup:!0};if(!h.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!h.project.workspaceId&&!a)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return a?{text:Tm,isSetup:!1}:Uo?{text:"Press c to copy the prompt above, run it in your coding agent \u2014 then ask me to write the docs",isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),zt=gl(D),Vs=zt.length>0&&!N,zo=p!==null?Nl(p,8,_e):null,$n=$e?$e.paths.filter(l=>!$e.query||l.toLowerCase().includes($e.query.toLowerCase())).slice(0,8):[],vn=Ce?Ce.sessions.filter(l=>{let i=Ce.query.toLowerCase();return!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],we=V((l,i)=>{be.current?.close(),be.current=Ll({cwd:e,resume:l,profileName:i??s,allowProdWrites:bt.current}),l||(Ie.current={uuid:null,firstPrompt:null,titleFired:!1},Ze(null)),Rt(0),Tt(0)},[e,s]),zs=V((l,i,a)=>{if(Sm.test(l))try{let h=de(e,s),u=typeof i.project_id=="string"&&i.project_id||h.project.projectId,m=go(i,a),w=[],y=wo(a);l.endsWith("publish_article")&&y&&w.push(`Live: ${y}`),m&&u&&w.push(`Preview: ${ho(h.connection.portalUrl,u,m,h.project.languageCode??"en")}`),w.length>0&&d({kind:"link",lines:w})}catch{}},[e,s,d]),ae=V(async(l,i)=>{mn(!0),ue(null),q([]),he(null),Wo(null),Go(null);let a=++ht.current;i?.quietUser||d({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let h=Ie.current;h.firstPrompt||(h.firstPrompt=i?.display??l),Je.current=Date.now(),gt(0),I(!0),wn.current.clear();let u="",m=!1,w=!1,y="",P={num:0,closed:!1,cueSeen:!1},S=null,K=()=>{S||(S=setTimeout(()=>{S=null,g(y.length>0?y:null)},60))},B=()=>{S&&clearTimeout(S),S=null,g(null)},M=()=>{if(y.trim()){let v=xs(y.trimEnd(),P);d({kind:"assistant",text:v})}y="",B()};try{for await(let v of be.current.send(l))if(v.type==="session"){if(!h.uuid){h.uuid=v.sessionId;let A=new Date().toISOString(),U=_o.current,X=U??Qf(h.firstPrompt??"session");Jf({uuid:v.sessionId,name:X,renamed:!!U,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:A,updatedAt:A}),Ze(X),_o.current=null}}else if(v.type==="text"){y+=v.delta,u+=v.delta;let A=_l(y);if(A>0){let U=y.slice(0,A).trimEnd();U&&d({kind:"assistant",text:xs(U,P)}),y=y.slice(A)}K(),gt(U=>U+v.delta.length)}else if(v.type==="tool"){m=!0;let A=fo(v.name,v.input);A&&(M(),d({kind:"tool",title:A.title,sep:A.sep,arg:A.arg}),wn.current.set(v.id,{name:v.name,input:v.input}))}else if(v.type==="article_diff"){let A=ut(v.oldContent,v.newContent,qe());A&&(M(),d({kind:"diff",added:A.added,removed:A.removed,lines:A.lines,hidden:A.hidden}))}else if(v.type==="tool_result"){v.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(v.output)&&(kn.current=!0);let A=wn.current.get(v.id);if(A){wn.current.delete(v.id),M();let U=mo(v.output,4,v.isError?void 0:A.name,A.input);d({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:v.isError}),v.isError||zs(A.name,A.input,v.output)}}else if(v.type==="result"){if(M(),Rt(U=>U+v.outputTokens),Tt(U=>U+v.costUsd),d({kind:"done",seconds:Math.round((Date.now()-Je.current)/1e3),tokens:v.outputTokens,costUsd:v.costUsd,ok:v.ok}),!w&&!m&&!u.trim()&&!qt.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)."}),v.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let U=ym(e);if(Xe(U)){let X=Ts(U,"utf8").trim();X&&(Go(X),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{}let A=v.ok?bl(u,xo.map(U=>U.name)):[];if(A.length>0?q(A):v.ok&&u.trim()&&nm(l,u,e).then(U=>{U&&ht.current===a&&ue(U)}).catch(()=>{}),h.uuid&&(Ss(h.uuid),!h.titleFired)){h.titleFired=!0;let U=h.uuid,X=h.firstPrompt;X&&Ml(X,e).then(ye=>{ye&&(Kf(U,ye),Ze(ye))}).catch(()=>{})}}else v.type==="error"&&(M(),w=!0,v.kind==="auth"&&(kn.current=!0),d({kind:"note",text:`agent error: ${v.message}`,tone:"error"}))}finally{I(!1),B(),ne(v=>v+1),Ie.current.uuid&&pl(e,Ie.current.uuid,kt.current),kn.current&&(kn.current=!1,bn.current=i?.display??l,q(["/login"])),qt.current&&(qt.current=!1,st.current.length>0&&(d({kind:"note",tone:"info",text:`(${st.current.length} queued message(s) discarded)`}),st.current=[],Lo([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,zs,qe]),Cn=V(async l=>{let i=Ds(l),a=To(e,"standard");Je.current=Date.now(),gt(0),I(!0);let h=new AbortController;ve.current=h,ee({verb:"Publishing",total:i.length,done:0,active:[],rows:dn(i),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${rn} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let u of Ro({cwd:e,partitions:i,promptFor:m=>Jn(m.paths),concurrency:rn,profileName:s,allowProdWrites:bt.current,model:a.model,signal:h.signal}))if(u.type==="partition_status")u.status==="running"?ee(m=>m&&{...m,active:[...m.active,u.label],rows:Oe(m.rows,u.label,"active"),lastAt:Date.now()}):ee(m=>m&&{...m,active:m.active.filter(w=>w!==u.label),done:m.done+1,rows:Oe(m.rows,u.label,u.status==="done"?"done":"failed"),lastAt:Date.now()});else if(u.type==="partition_event")ee(m=>{if(!m)return m;let w={...m,lastAt:Date.now()};return u.event.type==="tool"?w.tools=m.tools+1:u.event.type==="text"&&(w.chars=m.chars+u.event.delta.length),w});else if(u.type==="run_done"){Tt(P=>P+u.totalCostUsd),Rt(P=>P+u.results.reduce((S,K)=>S+K.outputTokens,0));let m=u.aborted?"Stopped. ":"",w=t.kind==="api"?"api":"subscription";d({kind:"note",tone:u.aborted?"warn":u.ok?"ok":"warn",text:m+xr(u.results,i,w).join(`
|
|
277
|
+
`)});let y=br(e,s);if(y&&d({kind:"note",tone:"info",text:y}),!u.aborted)try{let P=vm(await $m({cwd:e,profileName:s}));P&&d({kind:"note",tone:"info",text:P})}catch{}}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{ve.current=null,ee(null),I(!1),ne(u=>u+1)}},[e,s,d,t]),Xo=V(async l=>{await ae(kr(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await Zn(e,s,l.replace(/\\/g,"/"));i.length>0&&(he(`Related articles not yet published (${i.length}):`),q([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ae]),Ko=V(l=>{let i=Ke(l);if(!i||We(i)&&!i.refreshToken)return null;let a={...Ft(i.idToken)??{},...Ft(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),Qo=V((l,i)=>{if(i){let a=Z(e);a&&(a.defaultProfile=l,Ol(a,e))}c(l),we(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Ko(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),q(["/login"])),ne(a=>a+1)},[e,d,we,Ko]),Pn=V((l,i,a)=>{In(e,l,i,a.id,a.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),we(),Do(e,l)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:_t(Nt(e)).join(`
|
|
278
|
+
`)}),St(lt()),Yt.current=Le(e).status==="current"||en(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,we,St]),Rn=V(async l=>{let i;try{i=await Qt(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),q(["/workspace"]);return}if(i.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),h=a.length>0?a:i.workspaces;if(h.length===1){let u=h[0],m=i.workspaces.length-h.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),Pn(i.profile,i.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),q(["/workspace"])},[e,d,Pn]),Tn=V((l,i)=>{Nn(e,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),we(),Rn(l)},[e,d,we,Rn]),Xs=V(async l=>{let i;try{i=de(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await Ge(e,i.name),h=a.find(u=>u.id===i.project.projectId);h?.name&&bm(e,i.name,{projectName:h.name})}catch{}await Rn(i.name);return}try{let{projects:a}=await Ge(e,i.name);if(a.length===1){let h=a[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${h.name??h.id}".`}),Tn(i.name,{id:h.id,name:h.name});return}if(a.length>1){let h=a.map(u=>({id:u.id,name:u.name??u.id,sub:u.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),nt({cursor:0,current:-1,rows:h,profile:i.name,environment:i.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),q(["/project"])}},[e,d,Rn,Tn]),Sn=V(()=>{let l=Fe.current[0];if(!l)return;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let a of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${a}`});l.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let i=ut(l.oldContent,l.newContent,qe());d(i?{kind:"diff",added:i.added,removed:i.removed,lines:i.lines,hidden:i.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,qe]),Ks=V(l=>{if(Fe.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Fe.current.shift();try{om({cwd:e,profileName:s},a),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Fe.current.length===0&&q(h=>h.length>0?h:["/pull"])}catch(h){d({kind:"note",tone:"error",text:`Pull failed: ${h.message}`})}}else if(i==="n"||i==="no"){let a=Fe.current.shift();d({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Fe.current.length;return Fe.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return Sn(),!0},[e,s,Sn,d]),Qs=V(l=>{let i=No.current;if(!i)return!1;if(No.current=null,ue(null),ht.current++,l.trim()!==i.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:h}=ms(e,i.targets);d({kind:"note",tone:h.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let u of h)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return i.hadDevhints&&(d({kind:"note",tone:"warn",text:Vn().join(`
|
|
279
279
|
`)}),St(ir())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
280
|
-
${ql}`}),q(["/init"]),mn(!1),!0},[e,d,St]),Js=V(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),h=i.slice(1);switch(mn(!0),a){case"help":Gt({tab:0});return;case"exit":case"quit":be.current?.close(),r();return;case"clear":we(),kt.current=[],mn(!1),ue(null),ht.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=de(e,s)}catch(m){d({kind:"note",tone:"error",text:m.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),J(!0);try{let m=await
|
|
280
|
+
${ql}`}),q(["/init"]),mn(!1),!0},[e,d,St]),Js=V(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),h=i.slice(1);switch(mn(!0),a){case"help":Gt({tab:0});return;case"exit":case"quit":be.current?.close(),r();return;case"clear":we(),kt.current=[],mn(!1),ue(null),ht.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=de(e,s)}catch(m){d({kind:"note",tone:"error",text:m.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),J(!0);try{let m=await Hf(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},y=>d({kind:"note",tone:"info",text:y})),w=qf(u.name,m);if(Bf(w),await tr(w,u.name,y=>d({kind:"note",tone:"info",text:y})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${Mn(w)}`}),await Xs(s),Bt.current){let y=Bt.current;Bt.current=null;let P=Me(e,s);P.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${y}.`}),q([y])):(d({kind:"note",tone:"warn",text:`${P.reason} (then ${y}.)`}),q(["/login"]),Bt.current=y)}else bn.current&&(ue(bn.current),bn.current=null,d({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(m){d({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{J(!1),ne(m=>m+1)}return}case"allow-prod":{let u=!1;try{u=de(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}bt.current=!0,we(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Kr(h.join(" ")),m=Ie.current.uuid;if(!m){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}_o.current=u,Ze(u),Wt(`${bo} ${u}`),d({kind:"note",tone:"ok",text:`Session will be named "${u}" once it starts.`});return}if(!u){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Ie.current.firstPrompt??"";Ml(w,e).then(y=>{y?(ue(`/rename ${y}`),d({kind:"note",tone:"info",text:`Suggestion: "${y}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}tm(m,u),Ze(u),Wt(`${bo} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=h[0],m=Z(e);if(!u){let w=Object.entries(m?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let y=w.map(([K,B])=>({name:K,env:B.connection?.environment??"custom",prod:B.production===!0,who:Ko(K)})),P=s??m?.defaultProfile,S=Math.max(0,y.findIndex(K=>K.name===P));xt({cursor:S,current:S,rows:y});return}if(u==="add"){let w=Qr(e,h[1],h[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),Qo(h[1],!1);return}if(!m?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}Qo(u,!0);return}case"doctor":await cn(h,{cwd:e});return;case"mcp":await Kn(h);return;case"init":{if(Z(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let u=um().map(m=>({name:m,apiUrl:dm(m).apiUrl}));$t({cursor:0,rows:u});return}case"resume":{let u=h.join(" ").trim(),m=em(e).filter(P=>P.uuid!==Ie.current.uuid);if(!u){if(!m.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}it({query:"",cursor:0,sessions:m});return}let w=Zf(e,u);if(!w){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}we(w.uuid),Ie.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},Ze(w.name),Ss(w.uuid),kt.current=[];let y=$s(e,w.uuid);for(let P of y)d(P);d({kind:"note",tone:"ok",text:y.length?`Resumed "${w.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=h.join(" ").trim(),m;try{m=await Qt(e,s)}catch(y){d({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!u){let y=m.workspaces.map(S=>({id:S.id,name:S.name??S.id,type:S.workspace_type}));if(y.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let P=Math.max(0,y.findIndex(S=>S.id===m.current));vt({cursor:P,current:P,rows:y,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let w=Zo(m.workspaces,u);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}Pn(m.profile,m.projectId,w);return}case"project":{let u=h.join(" ").trim(),m;try{m=await Ge(e,s)}catch(y){d({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!u){let y=m.projects.map(S=>({id:S.id,name:S.name??S.id,sub:S.sub_domain}));if(y.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let P=y.findIndex(S=>S.id===m.current);nt({cursor:Math.max(0,P),current:P,rows:y,profile:m.profile,environment:m.environment});return}let w=er(m.projects,u);if(!w){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${m.projects.map(y=>y.name??y.id).join(", ")}`});return}Tn(m.profile,w);return}case"logout":{let u;try{u=de(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let m=zf(u);Xf(e,u),we(),ne(w=>w+1),d({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${u}" and cleared its project/workspace selection.`:`Profile "${u}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),q(["/login"]);return}case"publish":{if(!qo(l.trim()))return;if(h[0]==="--related"&&h[1]){let m=await Zn(e,s,h[1].replace(/\\/g,"/"));if(m.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Cn(m);return}if(h[0]&&h[0]!=="--all"){await Xo(h[0]);return}let u=h[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Ul({cwd:e,profileName:s}),w=sn(m.entries),y=Qn(m.entries);if(y>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${y} article${y===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),w.length===0){d({kind:"note",tone:"ok",text:y>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let P=m.counts["unknown-base"]??0;P>0&&d({kind:"note",tone:"info",text:`(${P} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(u){await Cn(w.map(P=>P.path));return}Ct({cursor:0,rows:Ki(w)})}catch(m){d({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let u=h.join(" ").trim();if(!u){let w=[];try{w=Object.keys(Do(e,de(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}rt({query:"",cursor:0,paths:w});return}let m=Wf(u)?u:mt(e,u);if(Xe(m)){try{d({kind:"preview",name:pn(m),text:Gl(Ts(m,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${m}: ${w.message}`})}return}if(Dm.test(u)){try{let w=de(e,s),y={profile:w.name,connection:w.connection},P=w.project.projectId??Yf(y),S=await Vf(y,P,u);d({kind:"preview",name:S.title??u,text:S.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${u}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let u=h[0]?.trim();if(!u){let P=ro(Es(e));tt({cursor:P,current:P});return}let{lines:m,changed:w,effective:y}=ln(e,u);for(let P of m)d({kind:"note",tone:P.startsWith("\u26A0")?"warn":P.startsWith("\u2713")?"ok":"info",text:P});w&&(Bs(P=>P+1),be.current?.setModel(y));return}case"convert":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:m}=Sr(h),w=mm(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let y=Dr(w,u);if(y.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${w.length} are tracked overall.)`});return}let P=Ds(y),S=3,K=`/convert${u?` --scope ${u}`:""} --run`,B=To(e,"light");if(!m){let v=Fl({files:jr(e,y),op:"convert",model:B.model}),A=u?`Scope: ${u} (${y.length} of ${w.length} tracked)
|
|
281
281
|
`:"",U=`
|
|
282
|
-
Model: ${B.model}${B.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:A+Er(
|
|
283
|
-
`)+U}),q([K]);return}Je.current=Date.now(),gt(0),I(!0);let
|
|
284
|
-
`)})}}catch(v){d({kind:"note",tone:"error",text:`Convert run failed: ${v.message}`})}finally{ve.current=null,ee(null),I(!1),ne(v=>v+1)}return}case"write":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Hl(e);if(u.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:w,preview:y,concurrency:
|
|
282
|
+
Model: ${B.model}${B.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:A+Er(P,v,S).join(`
|
|
283
|
+
`)+U}),q([K]);return}Je.current=Date.now(),gt(0),I(!0);let M=new AbortController;ve.current=M,ee({verb:"Converting",total:P.length,done:0,active:[],rows:dn(P),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${y.length} articles across ${P.length} partitions (\u2264${S} agents at once) on ${B.model}\u2026 (esc to stop)`});try{for await(let v of Ro({cwd:e,partitions:P,promptFor:Ar,concurrency:S,profileName:s,allowProdWrites:bt.current,model:B.model,signal:M.signal}))if(v.type==="partition_status")v.status==="running"?ee(A=>A&&{...A,active:[...A.active,v.label],rows:Oe(A.rows,v.label,"active"),lastAt:Date.now()}):ee(A=>A&&{...A,active:A.active.filter(U=>U!==v.label),done:A.done+1,rows:Oe(A.rows,v.label,v.status==="done"?"done":"failed"),lastAt:Date.now()});else if(v.type==="partition_event")ee(A=>{if(!A)return A;let U={...A,lastAt:Date.now()};return v.event.type==="tool"?U.tools=A.tools+1:v.event.type==="text"&&(U.chars=A.chars+v.event.delta.length),U});else if(v.type==="run_done"){Tt(X=>X+v.totalCostUsd),Rt(X=>X+v.results.reduce((ye,jt)=>ye+jt.outputTokens,0));let A=v.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";d({kind:"note",tone:v.aborted?"warn":v.ok?"ok":"warn",text:A+Ir(v.results,P,U).join(`
|
|
284
|
+
`)})}}catch(v){d({kind:"note",tone:"error",text:`Convert run failed: ${v.message}`})}finally{ve.current=null,ee(null),I(!1),ne(v=>v+1)}return}case"write":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Hl(e);if(u.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:w,preview:y,concurrency:P,rewrite:S}=_r(h),{docsDir:K,targets:B,reason:M,rewriting:v}=Hr(e,u,{scope:m,path:w,rewrite:S});if(B.length===0){d({kind:"note",tone:"warn",text:M??"Nothing to write."});return}v&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${B.length} already-written article${B.length===1?"":"s"} (overwrites them; git has your baseline).`});let A=Ds(B),U=Nr(P),X=To(e,"standard"),ye=!!w;if(y&&!ye){let Y=Fl({files:Mr(e,u,B),op:"write",model:X.model}),te=m?`Scope: ${m} (${B.length} pending)
|
|
285
285
|
`:"",ce=`
|
|
286
286
|
Model: ${X.model}${X.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:te+Ur(A,Y,U).join(`
|
|
287
287
|
`)+ce}),q([`/write${m?` --scope ${m}`:""}`]);return}Je.current=Date.now(),gt(0),I(!0);let jt=new AbortController;ve.current=jt,ee({verb:"Writing",total:A.length,done:0,active:[],rows:dn(A),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${B.length} article${B.length===1?"":"s"} across ${A.length} partition${A.length===1?"":"s"} (\u2264${U} agents at once) on ${X.model}${X.forced?" (forced)":""}\u2026 (esc to stop)`});let ni=new Set;try{for await(let Y of Ro({cwd:e,partitions:A,promptFor:te=>Or(te,K,{rewrite:v||ye}),concurrency:U,profileName:s,allowProdWrites:bt.current,model:X.model,signal:jt.signal}))if(Y.type==="partition_status")Y.status==="running"?ee(te=>te&&{...te,active:[...te.active,Y.label],rows:Oe(te.rows,Y.label,"active"),lastAt:Date.now()}):ee(te=>te&&{...te,active:te.active.filter(ce=>ce!==Y.label),done:te.done+1,rows:Oe(te.rows,Y.label,Y.status==="done"?"done":"failed"),lastAt:Date.now()});else if(Y.type==="partition_event"){let te=null;if(Y.event.type==="tool"){let ce=$l(Y.event.name,Y.event.input,A[Y.index]?.paths??[]);ce&&!ni.has(ce)&&(ni.add(ce),te=Y.label)}ee(ce=>{if(!ce)return ce;let Ae={...ce,lastAt:Date.now()};return Y.event.type==="tool"?Ae.tools=ce.tools+1:Y.event.type==="text"&&(Ae.chars=ce.chars+Y.event.delta.length),te&&(Ae.rows=xl(Ae.rows,te)),Ae})}else if(Y.type==="run_done"){Tt(At=>At+Y.totalCostUsd),Rt(At=>At+Y.results.reduce((An,at)=>An+at.outputTokens,0));let te=Y.aborted?"Stopped. ":"",ce=t.kind==="api"?"api":"subscription";d({kind:"note",tone:Y.aborted?"warn":Y.ok?"ok":"warn",text:te+Wr(Y.results,A,ce).join(`
|
|
288
288
|
`)});let Ae=Y.aborted?null:Fr(e,K,B);if(Ae&&d({kind:"note",tone:"warn",text:Ae}),!Y.aborted&&Y.ok){let At=m??w??"",An=At?` ${At}`:"",at=[];Ae&&at.push({cmd:`/check${An} --fix`,desc:"fix the issues the checker just flagged"}),at.push({cmd:`/review${An} --fix`,desc:"editorial review + apply fixes (style, grammar, structure)"}),at.push({cmd:"/publish --all",desc:"publish the drafts to Document360"}),at.push({cmd:"/screenshot --all",desc:"add screenshots first (optional)"}),q(at),he(Ae?"Written \u2014 but the checker flagged issues. Fix, review, then publish:":"Written. Review for quality, then publish:")}}}catch(Y){d({kind:"note",tone:"error",text:`Write run failed: ${Y.message}`})}finally{ve.current=null,ee(null),I(!1),ne(Y=>Y+1)}return}case"draft":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:m}=qr(e);if(u.length===0&&m===0){d({kind:"note",tone:"info",text:Gr});return}let w=h.join(" ").trim();if(!w&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
289
289
|
${u.map(S=>` \u2022 ${S.name} (${S.docCount} doc${S.docCount===1?"":"s"})`).join(`
|
|
290
|
-
`)}`}),q(u.map(S=>`/draft ${S.name}`));return}let y="",
|
|
291
|
-
`)});return}if(u==="--baseline"){let y=h.find(B=>!B.startsWith("--")),
|
|
290
|
+
`)}`}),q(u.map(S=>`/draft ${S.name}`));return}let y="",P;if(w){let S=Br(u,w);S?y=S:P=w}else y=u[0]?.name??"";await ae(oo(y,P),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!qo(l.trim()))return;let u=h.find(m=>m.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let y=Date.now(),P=await Ul({cwd:e,profileName:s});d({kind:"note",tone:"info",text:to(P,Date.now()-y).join(`
|
|
291
|
+
`)});return}if(u==="--baseline"){let y=h.find(B=>!B.startsWith("--")),P=y?y.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:P?`Setting the sync baseline for ${P}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let S=await am({cwd:e,profileName:s,relPaths:P?[P]:void 0}),K=P?{rebaselined:[],skipped:[]}:await lm({cwd:e,profileName:s});if(S.baselined.length===0&&S.skipped.length===0&&K.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}S.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${S.baselined.length} article${S.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),K.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${K.rebaselined.length} article${K.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),S.skipped.length>0&&d({kind:"note",tone:"warn",text:`${S.skipped.length} skipped:
|
|
292
292
|
${S.skipped.map(B=>` - ${B.path} (${B.reason})`).join(`
|
|
293
|
-
`)}`}),ne(B=>B+1);return}if(u==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let y=await
|
|
294
|
-
`)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=h[0];if(m){let y=await
|
|
293
|
+
`)}`}),ne(B=>B+1);return}if(u==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let y=await sm({cwd:e,profileName:s}),P=y.onlyInLegacy.length===0&&y.onlyInManifest.length===0&&y.mappedMissingFromManifest.length===0,S=[`Legacy listing: ${y.legacyCount} \xB7 Manifest: ${y.manifestCount} \xB7 in both: ${y.inBoth}`];P?S.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(y.mappedMissingFromManifest.length&&S.push(`\u2717 ${y.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${y.mappedMissingFromManifest.slice(0,5).join(", ")}`),y.onlyInLegacy.length&&S.push(`\u26A0 ${y.onlyInLegacy.length} only in the legacy listing: ${y.onlyInLegacy.slice(0,5).join(", ")}`),y.onlyInManifest.length&&S.push(`\u26A0 ${y.onlyInManifest.length} only in the manifest: ${y.onlyInManifest.slice(0,5).join(", ")}`),S.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:P?"ok":"warn",text:S.join(`
|
|
294
|
+
`)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=h[0];if(m){let y=await im({cwd:e,profileName:s,relPath:m.replace(/\\/g,"/")});Fe.current=[y],Sn();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let w=await Pr({cwd:e,profileName:s});for(let y of Rr(w))d({kind:"note",tone:y.tone,text:y.text});ne(y=>y+1)}catch(m){d({kind:"note",tone:"error",text:`Pull failed: ${m.message}`})}return}case"scope":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=cm(e);if(u.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Pt({cursor:0,rows:u.map(m=>({...m,checked:m.recommended}))});return}case"audit":{if(h[0]==="--auto"){let m=Z(e);if(!m){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=h[1]!=="off";Ol({...m,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let u=await an();u.kind==="forward-to-agent"&&u.prompt&&await ae(u.prompt,{display:u.display,quietUser:!0});return}case"check":{let u=h.find(y=>!y.startsWith("--")),m=u?` ${u}`:"",w=Wl({cwd:e,scope:u});if(h.includes("--fix")){if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}d({kind:"note",tone:"info",text:`Fixing ${w.length} doc issue${w.length===1?"":"s"}\u2026`}),await ae(gs(w),{display:`/check${m} --fix`,quietUser:!0});let y=Wl({cwd:e,scope:u});d({kind:"note",tone:y.length===0?"ok":"warn",text:y.length===0?"\u2713 Doc-checker: all issues resolved.":po(y).join(`
|
|
295
295
|
`)}),q([{cmd:`/review${m} --fix`,desc:"editorial review + apply fixes (style, grammar, structure)"},{cmd:"/publish --all",desc:"publish the corrected docs to Document360"}]),he(y.length===0?"Deterministic issues fixed. Review for quality, then publish:":"Some issues remain \u2014 review, then publish:");return}d({kind:"note",tone:w.length===0?"ok":"warn",text:po(w).join(`
|
|
296
296
|
`)}),w.length>0&&(q([{cmd:`/check${m} --fix`,desc:"have the agent fix these in place"},{cmd:`/review${m} --fix`,desc:"also run the editorial review (style, grammar, structure)"},{cmd:"/publish --all",desc:"skip fixing \u2014 publish the docs as-is"}]),he(`Found ${w.length} doc issue${w.length===1?"":"s"} above \u2014 fix them, or publish as-is:`));return}case"review":{let u=ws(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=h.includes("--fix");if(await ae(u.prompt,{display:u.display,quietUser:!0}),m)q([{cmd:"/publish --all",desc:"publish the corrected docs to Document360"},{cmd:"/check",desc:"optional: instant re-scan for leaks/bad commands (no tokens)"}]),he("\u2713 Editor applied its fixes \u2014 your docs are corrected. Publish them, or re-scan first:");else{let w=h.filter(y=>y!=="--fix").join(" ");q([{cmd:`/review${w?` ${w}`:""} --fix`,desc:"let the editor apply all the fixes it listed above"},{cmd:"/check --fix",desc:"fix just the deterministic issues (leaks, bad commands)"},{cmd:"/publish --all",desc:"skip fixing \u2014 publish the docs as-is"}]),he("The review listed issues above. Apply the fixes, or publish as-is:")}return}case"capture-setup":{let u=await un();u.kind==="forward-to-agent"&&u.prompt&&await ae(u.prompt,{display:u.display,quietUser:!0});let m=os(e);m&&d({kind:"note",tone:"info",text:m.join(`
|
|
297
297
|
`)});return}case"devhints":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:_t(Nt(e)).join(`
|
|
298
|
-
`)}),St(lt()),Yt.current=
|
|
299
|
-
`)});return}if(u.mode==="single"){let
|
|
298
|
+
`)}),St(lt()),Yt.current=Le(e).status==="current"||en(e);return}case"inbox":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(rs(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 ae(ss(),{display:"/inbox",quietUser:!0});return}case"document":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:m}=Vr(h);if(!m&&Yr(e)===0){d({kind:"note",tone:"info",text:Xr});return}let w=`/document${m?` ${m}`:""}${u?" --publish":""}`;await ae(zr(m,u),{display:w,quietUser:!0});return}case"catch-up":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!qo(l.trim()))return;let{publish:u}=as(h);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let m=await cs({cwd:e,profileName:s});for(let y of us(m))d({kind:"note",tone:y.startsWith("\u2713")?"ok":y.startsWith("\u2139")?"info":"warn",text:y});let w=Ut(Ot(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ae(ls({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{Fo.current=!0,d({kind:"note",tone:"info",text:`Updating ${pt}\u2026 (don\u2019t close this window)`}),hn(!0),(await co().finally(()=>hn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),q(m=>m.includes("/exit")?m:[...m,"/exit"]),Ms("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${lo}`});return}case"screenshot":{let u=es(h);if(u.mode==="list"){if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:ns(ts(e,u.scope),u.scope).join(`
|
|
299
|
+
`)});return}if(u.mode==="single"){let M=await io(h);M.kind==="forward-to-agent"&&M.prompt&&await ae(M.prompt,{display:M.display,quietUser:!0});return}if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=u.mode==="scope"?u.scope:void 0,w=fm(e,{scope:m}).map(M=>M.id);if(w.length===0){d({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let y=6,P=pm(w,3),S=To(e,"standard");Je.current=Date.now(),gt(0),I(!0);let K=new AbortController;ve.current=K,ee({verb:"Authoring",unit:"spec",total:P.length,done:0,active:[],rows:dn(P),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${w.length} screenshot spec${w.length===1?"":"s"} across ${P.length} partition${P.length===1?"":"s"} (\u2264${y} agents at once) on ${S.model}${S.forced?" (forced)":""}\u2026 (esc to stop)`});let B=!1;try{for await(let M of Ro({cwd:e,partitions:P,promptFor:Ua,concurrency:y,profileName:s,allowProdWrites:bt.current,model:S.model,signal:K.signal}))if(M.type==="partition_status")M.status==="running"?ee(v=>v&&{...v,active:[...v.active,M.label],rows:Oe(v.rows,M.label,"active"),lastAt:Date.now()}):ee(v=>v&&{...v,active:v.active.filter(A=>A!==M.label),done:v.done+1,rows:Oe(v.rows,M.label,M.status==="done"?"done":"failed"),lastAt:Date.now()});else if(M.type==="partition_event")ee(v=>{if(!v)return v;let A={...v,lastAt:Date.now()};return M.event.type==="tool"?A.tools=v.tools+1:M.event.type==="text"&&(A.chars=v.chars+M.event.delta.length),A});else if(M.type==="run_done"){Tt(X=>X+M.totalCostUsd),Rt(X=>X+M.results.reduce((ye,jt)=>ye+jt.outputTokens,0));let v=M.results.filter(X=>X.ok).length,A=M.aborted?"Stopped. ":"";B=!M.aborted&&u.setup;let U=M.aborted?"":B?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:M.aborted?"warn":M.ok?"ok":"warn",text:`${A}Authored specs \u2014 ${v}/${M.results.length} batches ok.${U}`})}}catch(M){d({kind:"note",tone:"error",text:`Spec authoring failed: ${M.message}`})}finally{ve.current=null,ee(null),I(!1),ne(M=>M+1)}if(B){let M=await un();M.kind==="forward-to-agent"&&M.prompt&&await ae(M.prompt,{display:M.display,quietUser:!0});let v=os(e);v&&d({kind:"note",tone:"info",text:v.join(`
|
|
300
300
|
`)})}return}case"reset":{let u=fs(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}No.current={repoName:pn(e),targets:u,hadDevhints:Xe(Is(e))},d({kind:"note",tone:"warn",text:hs(e,u).join(`
|
|
301
|
-
`)}),ue(pn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,Sn,d,we,ae,Cn,Xo,Xs]),Dn=V(l=>{let i=(l??D).trim();if(b(""),gn(null),wt(0),i.startsWith("/")&&(ue(null),ht.current++,he(null),q(h=>Pl(h,i))),!i||Qs(i)||Ks(i))return;Io.current.push(i);let a=jl(i,Os.current);i.startsWith("/")?(d({kind:"user",text:i}),Js(a)):ae(a,{display:i})},[D,Qs,Ks,Js,ae]),Zs=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=Tl(l);if(Sl(i)){let a=Dl(++ic.current,i);Os.current.set(a,i),P(a)}else P(i);return}P(l)},[P]),Dt=Math.max(10,_e-6),ei=Rs(()=>Co(k.text,Dt),[k.text,Dt]),Jo=V(l=>x(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),jn=V(l=>x(i=>({...i,pos:El(Co(i.text,Dt),i.pos,l)})),[Dt]),Xt=V(l=>x(i=>({...i,pos:Il(Co(i.text,Dt),i.pos,l)})),[Dt]),cc=["\x1B[H","\x1B[1~","\x1BOH"],uc=["\x1B[F","\x1B[4~","\x1BOF"],ti=V((l,i)=>i.leftArrow?(Jo(-1),!0):i.rightArrow?(Jo(1),!0):l&&cc.includes(l)?(Xt("start"),!0):l&&uc.includes(l)?(Xt("end"),!0):i.ctrl&&l==="a"?(Xt("start"),!0):i.ctrl&&l==="e"?(Xt("end"),!0):!1,[Jo,Xt]);return _f((l,i)=>{if(i.ctrl&&l==="c"){be.current?.close(),r();return}if(!O){if(N){if(i.escape){if(ve.current){if(!ve.current.signal.aborted){let a=(yn?.verb??"work").toLowerCase(),h=yn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${h}s)\u2026`}),ve.current.abort()}return}qt.current||(qt.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),be.current?.interrupt());return}if(i.return){let a=D.trim();if(!a)return;st.current.push(a),Mo([...st.current]),b("");return}if(ti(l,i))return;if(i.upArrow){jn(-1);return}if(i.downArrow){jn(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&Zs(l);return}if(et){if(i.upArrow){tt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){tt(a=>a&&{...a,cursor:Math.min(Ee.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ee.length){tt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Ee[et.cursor];tt(null);let{lines:h,changed:u,effective:m}=ln(e,a.value??"default");for(let w of h)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});u&&(Bs(w=>w+1),be.current?.setModel(m));return}if(l==="s"){let a=Ee[et.cursor];tt(null),be.current?.setModel(a.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){tt(null);return}return}if(Ne){if(i.upArrow){xt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){xt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ne.rows.length){xt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=Ne.rows[Ne.cursor];xt(null),Qo(a.name,i.return===!0);return}if(i.escape){xt(null);return}return}if(Lo){if(i.escape){Gt(null);return}if(i.leftArrow||i.tab&&i.shift){Gt(a=>a&&{tab:(a.tab-1+Re.length)%Re.length});return}if(i.rightArrow||i.tab){Gt(a=>a&&{tab:(a.tab+1)%Re.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.length){Gt({tab:Number(l)-1});return}return}if(He){if(i.upArrow){$t(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){$t(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=He.rows.length){$t(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=He.rows[He.cursor].name;if($t(null),!ar(e,a).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 "${a}").`});let u=!1;try{let m=Ke(a);u=!!m&&!(We(m)&&!m.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),q(["/login"]),ne(m=>m+1);return}if(i.escape){$t(null);return}return}if(fe){if(i.upArrow){vt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){vt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=fe.rows.length){vt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=fe.rows[fe.cursor],{profile:h,projectId:u}=fe;vt(null),Pn(h,u,a);return}if(i.escape){vt(null);return}return}if(xe){if(i.upArrow){nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){nt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=xe.rows.length){nt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=xe.rows[xe.cursor],{profile:h}=xe;nt(null),Tn(h,a);return}if(i.escape){nt(null);return}return}if(ge){if(i.upArrow){Pt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Pt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){Pt(a=>a&&{...a,rows:a.rows.map((h,u)=>u===a.cursor?{...h,checked:!h.checked}:h)});return}if(i.return){let a=ge.rows.filter(h=>h.checked).map(h=>h.path);if(Pt(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}$r(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of a)d({kind:"note",tone:"info",text:` ${h}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){Pt(null);return}return}if(ot){if(i.upArrow){Ct(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ct(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ot.rows.length){Ct(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ot.rows[ot.cursor];Ct(null),a.kind==="article"?Xo(a.paths[0]):Cn(a.paths);return}if(i.escape){Ct(null);return}return}if($e){if(i.escape){rt(null);return}if(i.upArrow){rt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){rt(a=>a&&{...a,cursor:Math.min(Math.max(0,$n.length-1),a.cursor+1)});return}if(i.return){let a=$n[$e.cursor];if(a){rt(null);try{d({kind:"preview",name:pn(a),text:Gl(Ts(mt(e,a),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${a}: ${h.message}`})}}return}if(i.backspace||i.delete){rt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){rt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(Ce){if(i.escape){it(null);return}if(i.upArrow){it(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){it(a=>a&&{...a,cursor:Math.min(Math.max(0,vn.length-1),a.cursor+1)});return}if(i.return){let a=vn[Ce.cursor];if(a){it(null),we(a.uuid),Ie.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Ze(a.name),Ss(a.uuid),kt.current=[];let h=$s(e,a.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${a.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){it(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){it(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!D&&De){b(De),ue(null),ht.current++;return}if(!D&&Qe.length>0&&l&&/^[1-9]$/.test(l)){let a=Qe[Number(l)-1];if(a){b(ft(a));return}}if(!D&&(Bo||Uo)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=Bo!=null;ll(Bo??Uo).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?a?"\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.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&a&&Go(null)});return}if(!ti(l,i)){if(Vs){if(i.upArrow){wt(a=>Math.max(0,a-1));return}if(i.downArrow){wt(a=>Math.min(zt.length-1,a+1));return}if(i.tab){b("/"+(zt[Ht]?.name??"")+" "),wt(0);return}if(i.return){let a=zt[Ht];if(a){let h=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(wl(a.usage)&&!h){b("/"+a.name+" "),wt(0);return}Dn("/"+a.name+(h?" "+h:""));return}}}else{if(i.upArrow){if(D!==""&&yt===null){jn(-1);return}let a=Io.current;if(!a.length)return;let h=yt===null?a.length-1:Math.max(0,yt-1);gn(h),b(a[h]??"");return}if(i.downArrow){if(D!==""&&yt===null){jn(1);return}let a=Io.current;if(yt===null)return;let h=yt+1;h>=a.length?(gn(null),b("")):(gn(h),b(a[h]??""));return}}if(i.return){Dn();return}if(i.backspace||i.delete){C();return}if(i.escape){b(""),wt(0),ue(null),q([]),he(null);return}l&&!i.ctrl&&!i.meta&&Zs(l)}}}),Te(()=>{if(N||O)return;let l=st.current.shift();l!==void 0&&(Mo([...st.current]),Dn(l))},[N,O,Dn]),G(oe,{flexDirection:"column",width:_e,children:[zo!==null&&G(oe,{marginTop:1,flexDirection:"column",children:[zo.truncated&&E(T,{dimColor:!0,children:"\u2026"}),E(T,{children:zo.text})]}),N&&(yn?E(Sm,{p:yn}):E(Rm,{startTime:Je.current,chars:sc})),E(oe,{borderStyle:"round",borderColor:Ys.prod?"yellow":F,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?ei.map((l,i)=>{let a=k.text.slice(l.start,l.end),h=i===Po(ei,k.pos),u=Math.min(k.pos,l.end)-l.start;return G(T,{children:[E(T,{color:F,children:i===0?"> ":" "}),h?G(js,{children:[a.slice(0,u),E(So,{ch:a[u]??" "}),a.slice(u+1)]}):a||" "]},`${i}-${l.start}`)}):G(T,{children:[E(T,{color:F,children:"> "}),De&&!N?G(js,{children:[E(So,{ch:De[0],dim:!0}),E(T,{color:"gray",children:De.slice(1)}),E(T,{dimColor:!0,children:" (tab)"})]}):(Vo.isSetup||!oc)&&!N?G(js,{children:[E(So,{ch:Vo.text[0],dim:!0}),E(T,{color:"gray",children:Vo.text.slice(1)})]}):E(So,{ch:" "})]})}),Fs.length>0&&E(oe,{flexDirection:"column",paddingX:1,children:Fs.map((l,i)=>E(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Lo?E(kl,{tab:Lo.tab,width:_e}):et?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Select model"}),E(T,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ee.map((l,i)=>G(T,{color:i===et.cursor?F:void 0,children:[i===et.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===et.current?" \u2714":""}`.padEnd(16),E(T,{color:"gray",children:l.desc})]},l.label)),E(T,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Ne?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Switch connection profile"}),Ne.rows.map((l,i)=>G(T,{color:i===Ne.cursor?F:void 0,children:[i===Ne.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===Ne.current?" \u2714":""}`.padEnd(20),E(T,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?E(T,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),E(T,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):He?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Pick your Document360 environment"}),He.rows.map((l,i)=>G(T,{color:i===He.cursor?F:void 0,children:[i===He.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),E(T,{color:"gray",children:l.apiUrl})]},l.name)),E(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Switch workspace"}),E(T,{dimColor:!0,children:`environment ${fe.environment} \xB7 project ${fe.projectName??`${fe.projectId.slice(0,8)}\u2026`}`}),fe.rows.map((l,i)=>G(T,{color:i===fe.cursor?F:void 0,children:[i===fe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===fe.current?" \u2714":""}`.padEnd(30),E(T,{color:"gray",children:l.type??""})]},l.id)),E(T,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):xe?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Choose project"}),E(T,{dimColor:!0,children:`environment ${xe.environment}`}),xe.rows.map((l,i)=>G(T,{color:i===xe.cursor?F:void 0,children:[i===xe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===xe.current?" \u2714":""}`.padEnd(30),E(T,{color:"gray",children:l.sub??""})]},l.id)),E(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ge?(()=>{let i=Math.min(Math.max(0,ge.cursor-Math.floor(7)),Math.max(0,ge.rows.length-14)),a=ge.rows.slice(i,i+14),h=ge.rows.filter(u=>u.checked).length;return G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Which folders back the user docs? (${h} selected of ${ge.rows.length})`}),i>0?E(T,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((u,m)=>{let w=i+m;return G(T,{color:w===ge.cursor?F:void 0,children:[w===ge.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,_e-34)),E(T,{color:"gray",children:eo(u)})]},u.path)}),i+14<ge.rows.length?E(T,{dimColor:!0,children:` \u2193 ${ge.rows.length-i-14} more`}):null,E(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():ot?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),ot.rows.map((l,i)=>{let a=i===ot.cursor,h=l.indent?" ":" ",u=`${i+1}.`.padEnd(3);return G(T,{color:a?F:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${h}${u} ${l.label}`.padEnd(Math.min(56,_e-24)),l.note?E(T,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),E(T,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):$e?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Preview article${$e.query?` \u2014 filter: ${$e.query}`:" (type to filter)"}`}),$n.length===0?E(T,{color:"gray",children:"no articles match"}):$n.map((l,i)=>G(T,{color:i===$e.cursor?F:void 0,children:[i===$e.cursor?"\u276F ":" ",l]},l)),E(T,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ce?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Resume session${Ce.query?` \u2014 filter: ${Ce.query}`:" (type to filter)"}`}),vn.length===0?E(T,{color:"gray",children:"no sessions match"}):vn.map((l,i)=>G(T,{color:i===Ce.cursor?F:void 0,children:[i===Ce.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),E(T,{color:i===Ce.cursor?F:"gray",children:l.firstPrompt.slice(0,Math.max(10,_e-40))})]},l.uuid)),E(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Vs?G(oe,{flexDirection:"column",children:[zt.map((l,i)=>G(T,{color:i===Ht?F:void 0,children:[i===Ht?"\u276F ":" ",l.usage.padEnd(22)," ",E(T,{color:i===Ht?F:"gray",children:l.name==="model"&&Oo?`${l.desc} (currently ${Oo})`:l.desc})]},l.name)),E(T,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!D&&Qe.length>0?G(oe,{flexDirection:"column",paddingX:1,children:[Ws?E(T,{color:F,children:Ws}):null,Qe.map((l,i)=>{let a=ft(l),h=a.slice(0,Math.max(20,_e-5)),u=_e-h.length-7,m=u>=12?(Cl(l)??hl(a)).slice(0,u):"";return G(T,{children:[E(T,{color:F,children:i+1})," ",h,m?E(T,{dimColor:!0,children:` \u2014 ${m}`}):null]},a)}),E(T,{dimColor:!0,children:`press 1-${Qe.length} to fill the command \xB7 esc dismiss`})]}):E(oe,{paddingX:1,children:G(T,{color:"gray",children:[Ys.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Oo??"model n/a"}${t.kind==="api"?qs>0?` \xB7 ${me(qs)}`:"":Hs>0?` \xB7 ${Ve(Hs)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Em}from"react/jsx-runtime";async function Kl(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Am(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=jm(Em(Xl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
302
|
-
`),process.exit(0)}W();import{writeCrashLog as Ql,isBenignTransportError as
|
|
301
|
+
`)}),ue(pn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,Sn,d,we,ae,Cn,Xo,Xs]),Dn=V(l=>{let i=(l??D).trim();if(b(""),gn(null),wt(0),i.startsWith("/")&&(ue(null),ht.current++,he(null),q(h=>Pl(h,i))),!i||Qs(i)||Ks(i))return;Io.current.push(i);let a=jl(i,Os.current);i.startsWith("/")?(d({kind:"user",text:i}),Js(a)):ae(a,{display:i})},[D,Qs,Ks,Js,ae]),Zs=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=Tl(l);if(Sl(i)){let a=Dl(++ic.current,i);Os.current.set(a,i),R(a)}else R(i);return}R(l)},[R]),Dt=Math.max(10,_e-6),ei=Rs(()=>Co(k.text,Dt),[k.text,Dt]),Jo=V(l=>x(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),jn=V(l=>x(i=>({...i,pos:El(Co(i.text,Dt),i.pos,l)})),[Dt]),Xt=V(l=>x(i=>({...i,pos:Il(Co(i.text,Dt),i.pos,l)})),[Dt]),cc=["\x1B[H","\x1B[1~","\x1BOH"],uc=["\x1B[F","\x1B[4~","\x1BOF"],ti=V((l,i)=>i.leftArrow?(Jo(-1),!0):i.rightArrow?(Jo(1),!0):l&&cc.includes(l)?(Xt("start"),!0):l&&uc.includes(l)?(Xt("end"),!0):i.ctrl&&l==="a"?(Xt("start"),!0):i.ctrl&&l==="e"?(Xt("end"),!0):!1,[Jo,Xt]);return Mf((l,i)=>{if(i.ctrl&&l==="c"){be.current?.close(),r();return}if(!O){if(N){if(i.escape){if(ve.current){if(!ve.current.signal.aborted){let a=(yn?.verb??"work").toLowerCase(),h=yn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${h}s)\u2026`}),ve.current.abort()}return}qt.current||(qt.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),be.current?.interrupt());return}if(i.return){let a=D.trim();if(!a)return;st.current.push(a),Lo([...st.current]),b("");return}if(ti(l,i))return;if(i.upArrow){jn(-1);return}if(i.downArrow){jn(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&Zs(l);return}if(et){if(i.upArrow){tt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){tt(a=>a&&{...a,cursor:Math.min(Ee.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ee.length){tt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Ee[et.cursor];tt(null);let{lines:h,changed:u,effective:m}=ln(e,a.value??"default");for(let w of h)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});u&&(Bs(w=>w+1),be.current?.setModel(m));return}if(l==="s"){let a=Ee[et.cursor];tt(null),be.current?.setModel(a.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){tt(null);return}return}if(Ne){if(i.upArrow){xt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){xt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ne.rows.length){xt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=Ne.rows[Ne.cursor];xt(null),Qo(a.name,i.return===!0);return}if(i.escape){xt(null);return}return}if(Mo){if(i.escape){Gt(null);return}if(i.leftArrow||i.tab&&i.shift){Gt(a=>a&&{tab:(a.tab-1+Re.length)%Re.length});return}if(i.rightArrow||i.tab){Gt(a=>a&&{tab:(a.tab+1)%Re.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.length){Gt({tab:Number(l)-1});return}return}if(He){if(i.upArrow){$t(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){$t(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=He.rows.length){$t(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=He.rows[He.cursor].name;if($t(null),!ar(e,a).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 "${a}").`});let u=!1;try{let m=Ke(a);u=!!m&&!(We(m)&&!m.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),q(["/login"]),ne(m=>m+1);return}if(i.escape){$t(null);return}return}if(fe){if(i.upArrow){vt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){vt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=fe.rows.length){vt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=fe.rows[fe.cursor],{profile:h,projectId:u}=fe;vt(null),Pn(h,u,a);return}if(i.escape){vt(null);return}return}if(xe){if(i.upArrow){nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){nt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=xe.rows.length){nt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=xe.rows[xe.cursor],{profile:h}=xe;nt(null),Tn(h,a);return}if(i.escape){nt(null);return}return}if(ge){if(i.upArrow){Pt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Pt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){Pt(a=>a&&{...a,rows:a.rows.map((h,u)=>u===a.cursor?{...h,checked:!h.checked}:h)});return}if(i.return){let a=ge.rows.filter(h=>h.checked).map(h=>h.path);if(Pt(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}$r(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of a)d({kind:"note",tone:"info",text:` ${h}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){Pt(null);return}return}if(ot){if(i.upArrow){Ct(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ct(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ot.rows.length){Ct(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ot.rows[ot.cursor];Ct(null),a.kind==="article"?Xo(a.paths[0]):Cn(a.paths);return}if(i.escape){Ct(null);return}return}if($e){if(i.escape){rt(null);return}if(i.upArrow){rt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){rt(a=>a&&{...a,cursor:Math.min(Math.max(0,$n.length-1),a.cursor+1)});return}if(i.return){let a=$n[$e.cursor];if(a){rt(null);try{d({kind:"preview",name:pn(a),text:Gl(Ts(mt(e,a),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${a}: ${h.message}`})}}return}if(i.backspace||i.delete){rt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){rt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(Ce){if(i.escape){it(null);return}if(i.upArrow){it(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){it(a=>a&&{...a,cursor:Math.min(Math.max(0,vn.length-1),a.cursor+1)});return}if(i.return){let a=vn[Ce.cursor];if(a){it(null),we(a.uuid),Ie.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Ze(a.name),Ss(a.uuid),kt.current=[];let h=$s(e,a.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${a.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){it(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){it(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!D&&De){b(De),ue(null),ht.current++;return}if(!D&&Qe.length>0&&l&&/^[1-9]$/.test(l)){let a=Qe[Number(l)-1];if(a){b(ft(a));return}}if(!D&&(Bo||Uo)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=Bo!=null;ll(Bo??Uo).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?a?"\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.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&a&&Go(null)});return}if(!ti(l,i)){if(Vs){if(i.upArrow){wt(a=>Math.max(0,a-1));return}if(i.downArrow){wt(a=>Math.min(zt.length-1,a+1));return}if(i.tab){b("/"+(zt[Ht]?.name??"")+" "),wt(0);return}if(i.return){let a=zt[Ht];if(a){let h=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(wl(a.usage)&&!h){b("/"+a.name+" "),wt(0);return}Dn("/"+a.name+(h?" "+h:""));return}}}else{if(i.upArrow){if(D!==""&&yt===null){jn(-1);return}let a=Io.current;if(!a.length)return;let h=yt===null?a.length-1:Math.max(0,yt-1);gn(h),b(a[h]??"");return}if(i.downArrow){if(D!==""&&yt===null){jn(1);return}let a=Io.current;if(yt===null)return;let h=yt+1;h>=a.length?(gn(null),b("")):(gn(h),b(a[h]??""));return}}if(i.return){Dn();return}if(i.backspace||i.delete){C();return}if(i.escape){b(""),wt(0),ue(null),q([]),he(null);return}l&&!i.ctrl&&!i.meta&&Zs(l)}}}),Te(()=>{if(N||O)return;let l=st.current.shift();l!==void 0&&(Lo([...st.current]),Dn(l))},[N,O,Dn]),G(oe,{flexDirection:"column",width:_e,children:[zo!==null&&G(oe,{marginTop:1,flexDirection:"column",children:[zo.truncated&&E(T,{dimColor:!0,children:"\u2026"}),E(T,{children:zo.text})]}),N&&(yn?E(Em,{p:yn}):E(jm,{startTime:Je.current,chars:sc})),E(oe,{borderStyle:"round",borderColor:Ys.prod?"yellow":F,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?ei.map((l,i)=>{let a=k.text.slice(l.start,l.end),h=i===Po(ei,k.pos),u=Math.min(k.pos,l.end)-l.start;return G(T,{children:[E(T,{color:F,children:i===0?"> ":" "}),h?G(js,{children:[a.slice(0,u),E(So,{ch:a[u]??" "}),a.slice(u+1)]}):a||" "]},`${i}-${l.start}`)}):G(T,{children:[E(T,{color:F,children:"> "}),De&&!N?G(js,{children:[E(So,{ch:De[0],dim:!0}),E(T,{color:"gray",children:De.slice(1)}),E(T,{dimColor:!0,children:" (tab)"})]}):(Vo.isSetup||!oc)&&!N?G(js,{children:[E(So,{ch:Vo.text[0],dim:!0}),E(T,{color:"gray",children:Vo.text.slice(1)})]}):E(So,{ch:" "})]})}),Fs.length>0&&E(oe,{flexDirection:"column",paddingX:1,children:Fs.map((l,i)=>E(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Mo?E(kl,{tab:Mo.tab,width:_e}):et?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Select model"}),E(T,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ee.map((l,i)=>G(T,{color:i===et.cursor?F:void 0,children:[i===et.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===et.current?" \u2714":""}`.padEnd(16),E(T,{color:"gray",children:l.desc})]},l.label)),E(T,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Ne?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Switch connection profile"}),Ne.rows.map((l,i)=>G(T,{color:i===Ne.cursor?F:void 0,children:[i===Ne.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===Ne.current?" \u2714":""}`.padEnd(20),E(T,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?E(T,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),E(T,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):He?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Pick your Document360 environment"}),He.rows.map((l,i)=>G(T,{color:i===He.cursor?F:void 0,children:[i===He.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),E(T,{color:"gray",children:l.apiUrl})]},l.name)),E(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Switch workspace"}),E(T,{dimColor:!0,children:`environment ${fe.environment} \xB7 project ${fe.projectName??`${fe.projectId.slice(0,8)}\u2026`}`}),fe.rows.map((l,i)=>G(T,{color:i===fe.cursor?F:void 0,children:[i===fe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===fe.current?" \u2714":""}`.padEnd(30),E(T,{color:"gray",children:l.type??""})]},l.id)),E(T,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):xe?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Choose project"}),E(T,{dimColor:!0,children:`environment ${xe.environment}`}),xe.rows.map((l,i)=>G(T,{color:i===xe.cursor?F:void 0,children:[i===xe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===xe.current?" \u2714":""}`.padEnd(30),E(T,{color:"gray",children:l.sub??""})]},l.id)),E(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ge?(()=>{let i=Math.min(Math.max(0,ge.cursor-Math.floor(7)),Math.max(0,ge.rows.length-14)),a=ge.rows.slice(i,i+14),h=ge.rows.filter(u=>u.checked).length;return G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Which folders back the user docs? (${h} selected of ${ge.rows.length})`}),i>0?E(T,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((u,m)=>{let w=i+m;return G(T,{color:w===ge.cursor?F:void 0,children:[w===ge.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,_e-34)),E(T,{color:"gray",children:eo(u)})]},u.path)}),i+14<ge.rows.length?E(T,{dimColor:!0,children:` \u2193 ${ge.rows.length-i-14} more`}):null,E(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():ot?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),ot.rows.map((l,i)=>{let a=i===ot.cursor,h=l.indent?" ":" ",u=`${i+1}.`.padEnd(3);return G(T,{color:a?F:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${h}${u} ${l.label}`.padEnd(Math.min(56,_e-24)),l.note?E(T,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),E(T,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):$e?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Preview article${$e.query?` \u2014 filter: ${$e.query}`:" (type to filter)"}`}),$n.length===0?E(T,{color:"gray",children:"no articles match"}):$n.map((l,i)=>G(T,{color:i===$e.cursor?F:void 0,children:[i===$e.cursor?"\u276F ":" ",l]},l)),E(T,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ce?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Resume session${Ce.query?` \u2014 filter: ${Ce.query}`:" (type to filter)"}`}),vn.length===0?E(T,{color:"gray",children:"no sessions match"}):vn.map((l,i)=>G(T,{color:i===Ce.cursor?F:void 0,children:[i===Ce.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),E(T,{color:i===Ce.cursor?F:"gray",children:l.firstPrompt.slice(0,Math.max(10,_e-40))})]},l.uuid)),E(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Vs?G(oe,{flexDirection:"column",children:[zt.map((l,i)=>G(T,{color:i===Ht?F:void 0,children:[i===Ht?"\u276F ":" ",l.usage.padEnd(22)," ",E(T,{color:i===Ht?F:"gray",children:l.name==="model"&&Oo?`${l.desc} (currently ${Oo})`:l.desc})]},l.name)),E(T,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!D&&Qe.length>0?G(oe,{flexDirection:"column",paddingX:1,children:[Ws?E(T,{color:F,children:Ws}):null,Qe.map((l,i)=>{let a=ft(l),h=a.slice(0,Math.max(20,_e-5)),u=_e-h.length-7,m=u>=12?(Cl(l)??hl(a)).slice(0,u):"";return G(T,{children:[E(T,{color:F,children:i+1})," ",h,m?E(T,{dimColor:!0,children:` \u2014 ${m}`}):null]},a)}),E(T,{dimColor:!0,children:`press 1-${Qe.length} to fill the command \xB7 esc dismiss`})]}):E(oe,{paddingX:1,children:G(T,{color:"gray",children:[Ys.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Oo??"model n/a"}${t.kind==="api"?qs>0?` \xB7 ${me(qs)}`:"":Hs>0?` \xB7 ${Ve(Hs)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Lm}from"react/jsx-runtime";async function Kl(e=process.cwd(),t="auto",n,o="0.0.0"){let r=_m(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Nm(Lm(Xl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
302
|
+
`),process.exit(0)}W();import{writeCrashLog as Ql,isBenignTransportError as Mm}from"document360-engine";var Jl=!1;function Ns(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Zl(e){if(Jl)return;Jl=!0;let t=(n,o)=>{if(Mm(o)){Ql({kind:n,level:"transport",message:Ns(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=Ql({kind:n,level:"fatal",message:Ns(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
303
303
|
`+$(`\u2717 d360-writer crashed: ${Ns(o)}`)+`
|
|
304
304
|
`),r&&process.stderr.write(f(` Crash details: ${r}`)+`
|
|
305
305
|
`+f(" Run: d360-writer logs")+`
|
|
306
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var
|
|
306
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Fm=Um(import.meta.url),ec=Fm("../package.json");Zl("d360-writer");var Se=new Om;function _s(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Se.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{_s(e),await On({profile:e.profile,manual:e.manual})});Se.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{_s(e),await mi({profile:e.profile})});Se.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{_s(e),await fi({profile:e.profile})});var Ls=Se.command("profile").description("Manage connection profiles for the current repo");Ls.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Un(process.cwd()));Ls.command("use <name>").description("Set the default profile for this repo").action(e=>Wn(process.cwd(),e));Ls.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Fn(process.cwd(),e));var tc=Se.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");tc.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Et(process.cwd(),e.profile));tc.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await ii(process.cwd(),e,t.profile)});var nc=Se.command("project").description("Choose the Document360 project for this repo (active profile's identity)");nc.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>_n(process.cwd(),e.profile));nc.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await li(process.cwd(),e,t.profile)});Se.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Xn(),Ui));await e()});Se.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>yi());Se.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(so(),Aa)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Se.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(ec.version,"-v, --version").option("-p, --prompt <text>","One-shot prompt mode (non-interactive)").option("-r, --resume <name>","Resume a saved session (with --prompt; use /resume inside the REPL)").option("-C, --cwd <dir>","Working directory",process.cwd()).option("--auth <mode>","Auth mode: auto | api | subscription","auto").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--yes","Skip the production write confirmation (for one-shot/CI)").option("--classic","Use the plain readline REPL instead of the Ink TUI").action(async e=>{if(Wm.includes(e.auth)||(console.error(`\u2717 Invalid --auth mode: ${e.auth}`),console.error("Run: d360-writer --auth auto | api | subscription"),process.exit(2)),e.prompt){await ki(e.cwd,e.prompt,e.auth,e.resume,e.profile,e.yes);return}e.resume&&(console.error("\u2717 --resume requires --prompt. In the interactive REPL, use /resume instead."),process.exit(2)),e.classic||!process.stdin.isTTY?await il(e.cwd,e.auth,e.profile):await Kl(e.cwd,e.auth,e.profile,ec.version)});Se.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|