document360-writer 0.5.48 → 0.5.49
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 +53 -53
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var oc=Object.defineProperty;var Go=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var rc=(e,t)=>{for(var n in t)oc(e,n,{get:t[n],enumerable:!0})};import
|
|
2
|
+
var oc=Object.defineProperty;var Go=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var rc=(e,t)=>{for(var n in t)oc(e,n,{get:t[n],enumerable:!0})};import Be from"picocolors";var F,sc,ic,ac,zs,Vt,f,$,M,A,_,se,Pe,W=Go(()=>{"use strict";F="#7f56d9",[sc,ic,ac]=[127,86,217],zs=e=>Be.isColorSupported?`\x1B[38;2;${sc};${ic};${ac}m${e}\x1B[39m`:e,Vt=e=>Be.bold(zs(e)),f=e=>Be.dim(e),$=e=>Be.red(e),M=e=>Be.yellow(e),A=e=>Be.green(e),_=zs,se=e=>Be.gray(e),Pe=e=>Be.bold(e)});import{existsSync as Mn,writeFileSync as Kt,readFileSync as Gc,readdirSync as Yc}from"node:fs";import{join as Vc}from"node:path";import{devHintsGuidePath as Ln,hintsDir as fi,architectureDir as gi,messagesDir as Jo,creatorNotesPath as mi,devhintsStatePath as wi,ensureDir as _n,writeMessage as zc,listOpenForDev as Xc}from"document360-engine";function yi(){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,35 +174,35 @@ 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 At(e){_n(fi(e)),_n(gi(e)),_n(Jo(e));for(let n of[fi(e),Jo(e)]){let o=Vc(n,".gitkeep");Mn(o)||Kt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
177
|
-
`)}Mn(mi(e))||Kt(mi(e),Kc()),Kt(Ln(e),yi());let t=
|
|
177
|
+
`)}Mn(mi(e))||Kt(mi(e),Kc()),Kt(Ln(e),yi());let t=_e(e);return bi(e,new Date().toISOString()),t}async function ki(e,t){for(let n of Et(At(t.cwd)))console.log(n);return{kind:"continue"}}function at(){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 Qo(e){try{let t=Gc(wi(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function bi(e,t){let o={...Qo(e)??{},emittedVersion:re,emittedAt:t};Kt(wi(e),`${JSON.stringify(o,null,2)}
|
|
179
|
-
`)}function Jt(e){try{return Yc(gi(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function
|
|
180
|
-
`)}),n.notifiedBuilder=!0))}catch{}return n}function Un(e){if(!Mn(Ln(e)))return[];let t=
|
|
181
|
-
`)}function Wn(){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):",jt,Zo(),jt]}function Et(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):",jt,at(),jt,"","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 jt,re,hi,lt=Go(()=>{"use strict";jt="-".repeat(64),re=5;hi="Re-run dev\u2194docs onboarding (protocol v"});var va={};rc(va,{doctorCommand:()=>sn,renderDoctorChecks:()=>$a,runDoctorChecks:()=>xa});import{existsSync as Ed}from"node:fs";import{d360GetAll as Id,getAccessToken as Nd,isExpired as Br,loadProfileMap as _d,loadTokens as Md,packageSkillsDir as ka,projectConfigPath as Ld,readProjectConfig as Od,DEFAULT_DOCS_DIR as Ud,fetchManifestSummary as Wd,resolveActiveProfile as Fd,classifyClaudeAuth as Hd,CLAUDE_CODE_SETUP_HINT as ba,resolveModelSetting as qd,probeModel as Bd,D360AuthError as Gd}from"document360-engine";async function xa(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=Hd();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. ${ba}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ba});let r=qd(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let k=await Bd(e,r.model??void 0);k.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(k.latencyMs/1e3).toFixed(1)}s`}):k.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 ${k.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=Od(e);if(!s)return t.push({level:"fail",label:`No ${Ld(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let u=(s.docsDir??Ud).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 ${u}/ 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 h;try{h=Fd(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(k){return t.push({level:"fail",label:`Profile config: ${k.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let y=Md(h.name);y?Br(y)&&!y.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Br(y)?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(y.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${h.name})`}),t.push(h.project.workspaceId?{level:"ok",label:`Workspace: ${h.project.workspaceName??h.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let x=_d(e,h.name);x?x.projectId&&h.project.projectId&&x.projectId!==h.project.projectId?t.push({level:"fail",label:`Category map projectId (${x.projectId}) \u2260 profile projectId (${h.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(x.articles).length} articles, ${Object.keys(x.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${h.name}" (created on first /publish)`}),t.push(Ed(ka())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ka()}`,fix:"Reinstall document360-writer (broken install)"});let D=Ne(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)"}),y&&(!Br(y)||y.refreshToken)){let k={profile:h.name,connection:h.connection};try{await Nd(k);let C=await Id(k,"/v3/projects");t.push({level:"ok",label:`API reachable (${h.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??h.project.projectId;if(P&&h.project.workspaceId)try{let C=await Wd(k,P,h.project.workspaceId);if(C){let N=(C.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${h.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 ${h.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 Gd||/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 (${h.project.projectName??P})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):t.push({level:"warn",label:`Workspace sync manifest: probe failed (${C.message.slice(0,80)})`})}}return t}function $a(e){let t=[""];for(let r of e){let s=r.level==="ok"?A("\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?A(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function sn(e,t){console.log(f("Running checks\u2026"));for(let n of $a(await xa(t.cwd)))console.log(n);return{kind:"continue"}}var Jn=Go(()=>{"use strict";lt();W()});import{Command as Tm}from"commander";import{createRequire as Sm}from"node:module";import{AUTH_MODES as Dm}from"document360-engine";import{input as xc}from"@inquirer/prompts";import{loginPkce as $c,refreshTokens as vc,toStoredTokens as ti,clearTokens as Cc,decodeJwtClaims as ei,isExpired as Pc,loadTokens as Rc,saveTokens as ni,resolveActiveProfile as Dn,setProfileProject as Tc,readProjectConfig as Sc}from"document360-engine";W();import{select as lc}from"@inquirer/prompts";import{resolveActiveProfile as cc,setProfileProject as uc,resolveProjectId as dc,listWorkspaces as pc}from"document360-engine";async function zt(e,t){let n=cc(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??dc(o);return{workspaces:await pc(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Xs=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Yo(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 Sn(e,t,n,o,r){uc(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Ks(e,t,n){let o;try{o=await zt(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=Yo(o.workspaces,t);return r?(Sn(e,o.profile,o.projectId,r.id,r.name),console.log(A(`\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 Dt(e,t){let n;try{n=await zt(e,t)}catch(y){console.log($(`Could not list workspaces: ${y.message}`));return}let{workspaces:o,projectId:r,profile:s,current:u}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let y of o)console.log(` ${y.id===u?_("\u25CF"):" "} ${Xs(y)} ${f(y.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await lc({message:"Select the Document360 workspace for this repo:",choices:o.map(y=>({name:`${Xs(y)}${y.id===u?" (current)":""}`,value:y.id}))}),h=o.find(y=>y.id===p);Sn(e,s,r,p,h?.name),console.log(A(`\u2713 Workspace set to "${h?.name??p}" for profile "${s}".`))}W();import{select as fc}from"@inquirer/prompts";import{resolveActiveProfile as mc,setProfileProject as hc,listProjects as gc}from"document360-engine";async function it(e,t){let n=mc(e,t),o={profile:n.name,connection:n.connection};return{projects:await gc(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Js=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Qs(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 Vo(e,t,n,o){hc(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Zs(e,t){let n;try{n=await it(e,t)}catch(h){console.log($(`Could not list projects: ${h.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 h of o)console.log(` ${h.id===s?_("\u25CF"):" "} ${Js(h)} ${f(h.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let u=await fc({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${Js(h)}${h.id===s?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===u);Vo(e,r,u,p?.name),console.log(A(`\u2713 Project set to "${p?.name??u}" for profile "${r}". Next: pick a workspace.`))}W();import wc from"picocolors";function yc(e=process.env){return e.FORCE_HYPERLINK==="0"||!wc.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 kc(e,t=e,n){return yc(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var bc=/https?:\/\/[^\s\x1b]+/g;function Xt(e,t){return e.replace(bc,n=>kc(n,n,t))}function oi(e){return{...ei(e.idToken)??{},...ei(e.accessToken)??{}}}function jn(e){let t=oi(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 An(e){let t=Dn(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 $c(n,{manual:e.manual,promptForRedirect:s=>xc({message:s})},s=>console.log(Xt(s))),r=ti(t.name,o);if(ni(r),await zo(r,t.name,s=>console.log(f(s))),console.log(""),console.log(A(`\u2713 Logged in to "${t.name}" as ${jn(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{Sc(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Dt(process.cwd(),t.name))}catch{}}async function zo(e,t,n){let r=oi(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Dn(process.cwd(),t).project.projectId)return;let u;try{let{projects:p}=await it(process.cwd(),t);u=p.find(h=>h.id===r)?.name}catch{}Tc(process.cwd(),t,{projectId:r,projectName:u}),n(` Project "${u??r}" written to profile "${t}".`)}catch{}}async function ri(e){let t=Dn(process.cwd(),e.profile),n=t.connection,o=Rc(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":""}: ${jn(o)}`),Pc(o))if(o.refreshToken)try{let r=ti(t.name,await vc(n,o.refreshToken));ni(r),console.log(A(`\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 si(e){let t=Dn(process.cwd(),e.profile);Cc(t.name)?console.log(A(`\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 ii,writeProjectConfig as Dc,resolveActiveProfile as jc,loadTokens as Ac,isExpired as Ec}from"document360-engine";function En(e){let t=ii(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?_("\u25CF "):" ",s=o.production?M(" \u26A0 PRODUCTION"):"",u=o.connection.environment??"(inline)",p=Ac(n),h=p?Ec(p)&&!p.refreshToken?M("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${u}${s} [${h}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function In(e,t){let n=ii(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,Dc(n,e);let o=n.profiles[t].production?M(" \u26A0 PRODUCTION"):"";console.log(A(`\u2713 Default profile is now "${t}"${o}`))}function Nn(e,t){try{let n=jc(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 Ic,readdirSync as Nc,statSync as ai}from"node:fs";import{join as li}from"node:path";import{apiLogDir as _c}from"document360-engine";function ci(){let e=_c();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Ic(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Nc(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=(ai(li(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=(ai(li(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 Mc,resolveAuth as Lc,findByName as Oc,slugify as Uc,touchSession as Wc,upsertSession as Fc,resolveActiveProfile as Hc}from"document360-engine";async function ui(e,t,n,o,r,s){let u=Lc(n);u.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)),u.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Hc(e,r)}catch(k){console.error($(`Document360 profile error: ${k.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 h;if(o){let k=Oc(e,o);k||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),h=k.uuid,console.error(f(`Resuming "${k.name}"`))}let y=Mc({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),x=h??null,D=1;for await(let k of y.send(t))switch(k.type){case"session":if(!x){x=k.sessionId;let P=new Date().toISOString();Fc({uuid:x,name:Uc(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(k.delta);break;case"tool":console.error(se(` \u2699 ${k.name}`));break;case"result":D=k.ok?0:1,console.error(f(`(${k.inputTokens}\u2192${k.outputTokens} tokens`+(k.costUsd>0?`, $${k.costUsd<.01?k.costUsd.toFixed(4):k.costUsd.toFixed(2)}`:"")+")")),k.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${k.message}`)),process.exit(1)}x&&Wc(x),process.stdout.write(`
|
|
179
|
+
`)}function Jt(e){try{return Yc(gi(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function _e(e){let n=Qo(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<re?"stale":"current",completedVersion:n}}function On(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:re};try{if(!Mn(Ln(e)))return n;let o=Qo(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;re>r&&(_n(Jo(e)),Kt(Ln(e),yi()),bi(e,t),n.guideRefreshed=!0),re>s&&(Xc(e).some(p=>p.kind==="request"&&p.subject.startsWith(hi))||(zc(e,{id:`onb${re}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${hi}${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:","",at()].join(`
|
|
180
|
+
`)}),n.notifiedBuilder=!0))}catch{}return n}function Un(e){if(!Mn(Ln(e)))return[];let t=_e(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}`,jt,at(),jt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Zo(){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 Wn(){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):",jt,Zo(),jt]}function Et(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):",jt,at(),jt,"","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 jt,re,hi,lt=Go(()=>{"use strict";jt="-".repeat(64),re=5;hi="Re-run dev\u2194docs onboarding (protocol v"});var va={};rc(va,{doctorCommand:()=>sn,renderDoctorChecks:()=>$a,runDoctorChecks:()=>xa});import{existsSync as Ed}from"node:fs";import{d360GetAll as Id,getAccessToken as Nd,isExpired as Br,loadProfileMap as _d,loadTokens as Md,packageSkillsDir as ka,projectConfigPath as Ld,readProjectConfig as Od,DEFAULT_DOCS_DIR as Ud,fetchManifestSummary as Wd,resolveActiveProfile as Fd,classifyClaudeAuth as Hd,CLAUDE_CODE_SETUP_HINT as ba,resolveModelSetting as qd,probeModel as Bd,D360AuthError as Gd}from"document360-engine";async function xa(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=Hd();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. ${ba}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ba});let r=qd(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let b=await Bd(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=Od(e);if(!s)return t.push({level:"fail",label:`No ${Ld(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let u=(s.docsDir??Ud).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 ${u}/ 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 h;try{h=Fd(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.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=Md(h.name);k?Br(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Br(k)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(k.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${h.name})`}),t.push(h.project.workspaceId?{level:"ok",label:`Workspace: ${h.project.workspaceName??h.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let x=_d(e,h.name);x?x.projectId&&h.project.projectId&&x.projectId!==h.project.projectId?t.push({level:"fail",label:`Category map projectId (${x.projectId}) \u2260 profile projectId (${h.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(x.articles).length} articles, ${Object.keys(x.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${h.name}" (created on first /publish)`}),t.push(Ed(ka())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ka()}`,fix:"Reinstall document360-writer (broken install)"});let D=_e(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&&(!Br(k)||k.refreshToken)){let b={profile:h.name,connection:h.connection};try{await Nd(b);let C=await Id(b,"/v3/projects");t.push({level:"ok",label:`API reachable (${h.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??h.project.projectId;if(P&&h.project.workspaceId)try{let C=await Wd(b,P,h.project.workspaceId);if(C){let N=(C.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${h.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 ${h.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 Gd||/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 (${h.project.projectName??P})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):t.push({level:"warn",label:`Workspace sync manifest: probe failed (${C.message.slice(0,80)})`})}}return t}function $a(e){let t=[""];for(let r of e){let s=r.level==="ok"?A("\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?A(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function sn(e,t){console.log(f("Running checks\u2026"));for(let n of $a(await xa(t.cwd)))console.log(n);return{kind:"continue"}}var Jn=Go(()=>{"use strict";lt();W()});import{Command as Tm}from"commander";import{createRequire as Sm}from"node:module";import{AUTH_MODES as Dm}from"document360-engine";import{input as xc}from"@inquirer/prompts";import{loginPkce as $c,refreshTokens as vc,toStoredTokens as ti,clearTokens as Cc,decodeJwtClaims as ei,isExpired as Pc,loadTokens as Rc,saveTokens as ni,resolveActiveProfile as Dn,setProfileProject as Tc,readProjectConfig as Sc}from"document360-engine";W();import{select as lc}from"@inquirer/prompts";import{resolveActiveProfile as cc,setProfileProject as uc,resolveProjectId as dc,listWorkspaces as pc}from"document360-engine";async function zt(e,t){let n=cc(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??dc(o);return{workspaces:await pc(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Xs=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Yo(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 Sn(e,t,n,o,r){uc(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Ks(e,t,n){let o;try{o=await zt(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=Yo(o.workspaces,t);return r?(Sn(e,o.profile,o.projectId,r.id,r.name),console.log(A(`\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 Dt(e,t){let n;try{n=await zt(e,t)}catch(k){console.log($(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:u}=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===u?_("\u25CF"):" "} ${Xs(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await lc({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${Xs(k)}${k.id===u?" (current)":""}`,value:k.id}))}),h=o.find(k=>k.id===p);Sn(e,s,r,p,h?.name),console.log(A(`\u2713 Workspace set to "${h?.name??p}" for profile "${s}".`))}W();import{select as fc}from"@inquirer/prompts";import{resolveActiveProfile as mc,setProfileProject as hc,listProjects as gc}from"document360-engine";async function it(e,t){let n=mc(e,t),o={profile:n.name,connection:n.connection};return{projects:await gc(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Js=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Qs(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 Vo(e,t,n,o){hc(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Zs(e,t){let n;try{n=await it(e,t)}catch(h){console.log($(`Could not list projects: ${h.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 h of o)console.log(` ${h.id===s?_("\u25CF"):" "} ${Js(h)} ${f(h.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let u=await fc({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${Js(h)}${h.id===s?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===u);Vo(e,r,u,p?.name),console.log(A(`\u2713 Project set to "${p?.name??u}" for profile "${r}". Next: pick a workspace.`))}W();import wc from"picocolors";function yc(e=process.env){return e.FORCE_HYPERLINK==="0"||!wc.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 kc(e,t=e,n){return yc(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var bc=/https?:\/\/[^\s\x1b]+/g;function Xt(e,t){return e.replace(bc,n=>kc(n,n,t))}function oi(e){return{...ei(e.idToken)??{},...ei(e.accessToken)??{}}}function jn(e){let t=oi(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 An(e){let t=Dn(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 $c(n,{manual:e.manual,promptForRedirect:s=>xc({message:s})},s=>console.log(Xt(s))),r=ti(t.name,o);if(ni(r),await zo(r,t.name,s=>console.log(f(s))),console.log(""),console.log(A(`\u2713 Logged in to "${t.name}" as ${jn(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{Sc(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Dt(process.cwd(),t.name))}catch{}}async function zo(e,t,n){let r=oi(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Dn(process.cwd(),t).project.projectId)return;let u;try{let{projects:p}=await it(process.cwd(),t);u=p.find(h=>h.id===r)?.name}catch{}Tc(process.cwd(),t,{projectId:r,projectName:u}),n(` Project "${u??r}" written to profile "${t}".`)}catch{}}async function ri(e){let t=Dn(process.cwd(),e.profile),n=t.connection,o=Rc(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":""}: ${jn(o)}`),Pc(o))if(o.refreshToken)try{let r=ti(t.name,await vc(n,o.refreshToken));ni(r),console.log(A(`\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 si(e){let t=Dn(process.cwd(),e.profile);Cc(t.name)?console.log(A(`\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 ii,writeProjectConfig as Dc,resolveActiveProfile as jc,loadTokens as Ac,isExpired as Ec}from"document360-engine";function En(e){let t=ii(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?_("\u25CF "):" ",s=o.production?M(" \u26A0 PRODUCTION"):"",u=o.connection.environment??"(inline)",p=Ac(n),h=p?Ec(p)&&!p.refreshToken?M("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${u}${s} [${h}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function In(e,t){let n=ii(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,Dc(n,e);let o=n.profiles[t].production?M(" \u26A0 PRODUCTION"):"";console.log(A(`\u2713 Default profile is now "${t}"${o}`))}function Nn(e,t){try{let n=jc(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 Ic,readdirSync as Nc,statSync as ai}from"node:fs";import{join as li}from"node:path";import{apiLogDir as _c}from"document360-engine";function ci(){let e=_c();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Ic(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Nc(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=(ai(li(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=(ai(li(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 Mc,resolveAuth as Lc,findByName as Oc,slugify as Uc,touchSession as Wc,upsertSession as Fc,resolveActiveProfile as Hc}from"document360-engine";async function ui(e,t,n,o,r,s){let u=Lc(n);u.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)),u.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Hc(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 h;if(o){let b=Oc(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)),h=b.uuid,console.error(f(`Resuming "${b.name}"`))}let k=Mc({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),x=h??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();Fc({uuid:x,name:Uc(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&&Wc(x),process.stdout.write(`
|
|
182
182
|
`),process.exit(D)}import{createInterface as Bp}from"node:readline/promises";import{createSession as ds,resolveAuth as Gp,getSession as Yp,setTitle as Vp,slugify as zp,touchSession as Ka,upsertSession as Xp,generateTitle as Kp,resolveActiveProfile as Ja,resolveModelSetting as Jp,readProjectConfig as Qp,decodeJwtClaims as za,isExpired as Zp,loadTokens as ef}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 qc(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 di(){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(qc(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function Xo(){console.log("");for(let e of di())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 Bc}from"document360-engine";async function pi(e,t){let n=t.currentUuid(),o=n?Bc(n):void 0;return console.log(o?f(`
|
|
183
183
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
184
184
|
`):f(`
|
|
185
185
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
186
186
|
`)),{kind:"clear"}}async function Ko(){return{kind:"exit"}}W();lt();import{input as Qt,confirm as Jc}from"@inquirer/prompts";import{basename as xi,join as Fn}from"node:path";import{existsSync as It,readFileSync as Qc,readdirSync as Zc,writeFileSync as eu}from"node:fs";import{writeProjectConfig as $i,readProjectConfig as tu,projectConfigPath as vi,writerDir as nu,DEFAULT_DOCS_DIR as Ci,DEFAULT_CAPTURE_DIR as Pi,DEFAULT_OUTPUT_DIR as Ri}from"document360-engine";function Ti(e,t="berlin"){let n=vi(e);if(It(n))return{created:!1,path:n,profileName:""};let o={projectId:ji(e)??xi(e),docsDir:Ci,captureDir:Pi,outputDir:Ri,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Ai(e)};return $i(o,e),Si(e),{created:!0,path:n,profileName:t}}function Si(e){let t=Fn(nu(e),".gitignore");It(t)||eu(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
187
|
-
`),"utf8")}async function Di(){let e=process.cwd(),t=vi(e);if(It(t)&&!await Jc({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=ji(e)??xi(e),o=await Qt({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Qt({message:"Capture directory (where document360-capture .spec.ts files live):",default:Pi}),s=await Qt({message:"Screenshot output directory:",default:Ri}),u=await Qt({message:"Default connection profile name:",default:"berlin"}),p=await Qt({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),h={projectId:o,docsDir:Ci,captureDir:r,outputDir:s,profiles:{[u]:{connection:{environment:p},production:!1}},defaultProfile:u,authoritativeSourceFiles:Ai(e)},
|
|
187
|
+
`),"utf8")}async function Di(){let e=process.cwd(),t=vi(e);if(It(t)&&!await Jc({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=ji(e)??xi(e),o=await Qt({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Qt({message:"Capture directory (where document360-capture .spec.ts files live):",default:Pi}),s=await Qt({message:"Screenshot output directory:",default:Ri}),u=await Qt({message:"Default connection profile name:",default:"berlin"}),p=await Qt({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),h={projectId:o,docsDir:Ci,captureDir:r,outputDir:s,profiles:{[u]:{connection:{environment:p},production:!1}},defaultProfile:u,authoritativeSourceFiles:Ai(e)},k=tu(e);k?.terminologyGlossary&&(h.terminologyGlossary=k.terminologyGlossary),$i(h,e),Si(e);let x=At(e);console.log(""),console.log(A(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${u}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of Et(x))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function ji(e){let t=Fn(e,"package.json");if(!It(t))return null;try{return JSON.parse(Qc(t,"utf8")).name??null}catch{return null}}function Ai(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])It(Fn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Fn(e,n);It(o)&&!ou(o)&&t.push(n)}return t}function ou(e){try{return Zc(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}W();import{readMcpConfig as er,writeMcpConfig as Ei}from"document360-engine";async function Hn(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(ru(),{kind:"continue"}):t==="add"?(su(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(iu(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 ru(){let e=er(),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 su(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=er(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let u={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let h=o[++p],
|
|
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(Ii(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Ni(t[o+1])){let p=_i(r);o+=2;let h=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)h.push(_i(t[o++]));n.push({kind:"table",header:p,rows:h});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 u=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Ii(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Ni(t[o+1]));)u.push(t[o++]);n.push({kind:"para",text:u.join(" ")})}return n}function or(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?
|
|
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 su(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=er(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let u={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let h=o[++p],k=h?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log($(`-H expects key:value (no spaces). Got: ${h??"(nothing)"}`));return}u[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(u).length>0?u:void 0}}r.servers[t]=s,Ei(r),console.log(""),console.log(A(`\u2713 Registered "${t}" (${n})`)),console.log(M(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function iu(e){let t=e[0];if(!t){console.log($("Usage: /mcp remove <name>"));return}let n=er();if(!n.servers[t]){console.log($(`No server named "${t}".`));return}delete n.servers[t],Ei(n),console.log(A(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as xu}from"node:fs";import{join as $u}from"node:path";import{select as vu}from"@inquirer/prompts";import{computeSyncStatus as cr,planPartitions as Cu,relatedArticlePaths as Pu,resolveModelForOperation as Ru,runPartitioned as Tu,loadProfileMap as Su,resolveActiveProfile as Du,resolveCrossLinks as ju}from"document360-engine";import z from"picocolors";import Oi from"wrap-ansi";import ir from"string-width";W();import Ge from"picocolors";import tr from"wrap-ansi";import nr from"string-width";var Ii=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Ni=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),_i=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function au(e){let t=e.replace(/\r/g,"").split(`
|
|
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(Ii(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Ni(t[o+1])){let p=_i(r);o+=2;let h=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)h.push(_i(t[o++]));n.push({kind:"table",header:p,rows:h});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 u=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Ii(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Ni(t[o+1]));)u.push(t[o++]);n.push({kind:"para",text:u.join(" ")})}return n}function or(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ge.bold(t.slice(2,-2)):t.startsWith("`")?_(t.slice(1,-1)):Ge.italic(t.slice(1,-1)))}var lu=(e,t)=>e+" ".repeat(Math.max(0,t-nr(e)));function cu(e,t,n){let o=e.length,r=e.map((C,N)=>Math.max(nr(C),...t.map(I=>nr(I[N]??"")))),s=Math.max(24,n),u=3*o+1,p=[...r],h=()=>p.reduce((C,N)=>C+N,0)+u,k=0;for(;h()>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)=>Ge.gray(C+p.map(O=>"\u2500".repeat(O+2)).join(N)+I),D=Ge.gray("\u2502"),b=(C,N)=>{let I=p.map((pe,ne)=>{let Se=C[ne]??"",ue=N?Ge.bold(Se):or(Se);return tr(ue,pe,{hard:!0}).split(`
|
|
191
191
|
`)}),O=Math.max(...I.map(pe=>pe.length)),Q=[];for(let pe=0;pe<O;pe++)Q.push(p.map((ne,Se)=>`${D} ${lu(I[Se][pe]??"",ne)} `).join("")+D);return Q.join(`
|
|
192
|
-
`)},P=[x("\u250C","\u252C","\u2510"),
|
|
193
|
-
`)}function uu(e,t){switch(e.kind){case"heading":return
|
|
192
|
+
`)},P=[x("\u250C","\u252C","\u2510"),b(e,!0)];return P.push(t.length===0?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524")),t.forEach((C,N)=>{P.push(b(C,!1)),P.push(N===t.length-1?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524"))}),P.join(`
|
|
193
|
+
`)}function uu(e,t){switch(e.kind){case"heading":return Ge.bold(e.text);case"hr":return Ge.gray("\u2500".repeat(t));case"para":return tr(or(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=tr(or(n),Math.max(10,t-4)).split(`
|
|
194
194
|
`);return" \u2022 "+o+r.map(s=>`
|
|
195
195
|
`+s).join("")}).join(`
|
|
196
|
-
`);case"code":return e.lines.map(n=>
|
|
196
|
+
`);case"code":return e.lines.map(n=>Ge.gray(" "+n)).join(`
|
|
197
197
|
`);case"table":return cu(e.header,e.rows,t)}}function rr(e,t){let n=Math.max(20,t);return au(e).map(o=>uu(o,n)).join(`
|
|
198
198
|
|
|
199
|
-
`)}W();import du from"picocolors";var pu=[127,86,217],fu=[22,38,43],Mi={T:pu,E:fu},Zt=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],sr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,mu=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Li(){if(!du.isColorSupported)return[];let e=Zt[0].length,t=[];for(let n=0;n<Zt.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Mi[Zt[n][r]],u=n+1<Zt.length?Mi[Zt[n+1][r]]:void 0;s&&u?o+=`${sr(s)}${mu(u)}\u2580\x1B[49m\x1B[39m`:s?o+=`${sr(s)}\u2580\x1B[39m`:u?o+=`${sr(u)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function en(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
|
|
199
|
+
`)}W();import du from"picocolors";var pu=[127,86,217],fu=[22,38,43],Mi={T:pu,E:fu},Zt=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],sr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,mu=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Li(){if(!du.isColorSupported)return[];let e=Zt[0].length,t=[];for(let n=0;n<Zt.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Mi[Zt[n][r]],u=n+1<Zt.length?Mi[Zt[n+1][r]]:void 0;s&&u?o+=`${sr(s)}${mu(u)}\u2580\x1B[49m\x1B[39m`:s?o+=`${sr(s)}\u2580\x1B[39m`:u?o+=`${sr(u)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function en(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 Ye(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Nt=(e,t)=>` ${e.padEnd(13)}${t}`;function hu(e,t){let n=[Vt("\u270E document360-writer")+z.gray(` v${e.version}`),z.gray(" Reads your code, writes your docs."),"",Nt("Claude:",`${e.claude}${z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Nt("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")),Nt("Profile:",e.configured?`${e.profile}${z.gray(` (${e.apiUrl})`)}${e.prod?z.bold(z.yellow(" \u26A0 PRODUCTION")):""}`:z.gray("\u2014 (run /init)")),Nt("Project:",e.project),Nt("Mode:",z.gray(e.mode)),Nt("cwd:",z.gray(e.cwd))],o=Li();if(o.length===0)return n.join(`
|
|
200
200
|
`);let r=2,s=3,u=ir(o[0]);if(!(t>=r+u+s+Math.max(...n.map(x=>ir(x)))))return[...o.map(x=>" "+x),...n].join(`
|
|
201
|
-
`);let h=Math.max(0,Math.floor((n.length-o.length)/2)),
|
|
201
|
+
`);let h=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let x=0;x<Math.max(o.length+h,n.length);x++){let D=o[x-h]??" ".repeat(u);k.push((" ".repeat(r)+D+" ".repeat(s)+(n[x]??"")).trimEnd())}return k.join(`
|
|
202
202
|
`)}var gu={error:z.red,warn:z.yellow,ok:z.green,info:z.gray};function ar(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return hu(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),u=50,p=e.text.split(`
|
|
203
|
-
`).flatMap(
|
|
203
|
+
`).flatMap(k=>Oi(k,s,{hard:!0}).split(`
|
|
204
204
|
`)),h=Math.max(0,p.length-u);return h>0&&(p=[...p.slice(0,u),z.dim(`\u2026 +${h} more lines`)]),`
|
|
205
|
-
`+p.map((
|
|
205
|
+
`+p.map((k,x)=>o+(x===0?_(" \u276F "):" ")+k+" ".repeat(Math.max(0,s-ir(k))+1)+r).join(`
|
|
206
206
|
`)}case"assistant":return`
|
|
207
207
|
`+rr(e.text,n);case"tool":{let o=e.arg!==null?z.gray(`${e.sep}(${e.arg})`):"";return`
|
|
208
208
|
`+Oi(z.green("\u25CF ")+z.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?z.red:z.gray,r=e.lines.map((s,u)=>o((u===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(z.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
@@ -214,19 +214,19 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
|
214
214
|
`+rr(e.text,n);case"note":return`
|
|
215
215
|
`+gu[e.tone](Xt(e.text));case"done":return`
|
|
216
216
|
`+(e.ok?z.magenta("\u2736 "):z.red("\u2736 "))+z.gray(`Cooked for ${en(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${me(e.costUsd)}`:""))}}function Ui(e,t){return e.map(n=>ar(n,t)).join(`
|
|
217
|
-
`)}import{resolveActiveProfile as wu,loadTokens as yu,isExpired as ku,decodeJwtClaims as Wi}from"document360-engine";function bu(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function
|
|
217
|
+
`)}import{resolveActiveProfile as wu,loadTokens as yu,isExpired as ku,decodeJwtClaims as Wi}from"document360-engine";function bu(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Me(e,t){try{let n=wu(e,t),o=yu(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(ku(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let u={...Wi(o.idToken)??{},...Wi(o.accessToken)??{}}.doc360_project_id;if(typeof u=="string"&&u&&u!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${bu(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var tn=3;function ur(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
218
|
`)}var Fi={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function nn(e){return e.filter(t=>t.path!==null&&t.status in Fi&&!t.link).map(t=>({path:t.path,label:Fi[t.status]}))}function qn(e){return e.filter(t=>t.link).length}function dr(e,t){try{let n=Su(e,Du(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=ju(xu($u(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 Au(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 Hi(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,u)=>s.path.localeCompare(u.path));t.push({kind:"category",label:`${Au(o)} (${r.length})`,paths:r.map(s=>s.path),indent:!1});for(let s of r){let u=s.path.replace(/\\/g,"/").split("/").pop()??s.path;t.push({kind:"article",label:u,paths:[s.path],indent:!0,note:s.label})}}return t}function Bn(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 pr(e,t,n){let o=
|
|
220
|
-
`),display:"/audit"}}W();import{checkbox as Eu}from"@inquirer/prompts";import{inventoryRepo as Iu,readProjectConfig as Bi,writeProjectConfig as Nu}from"document360-engine";function fr(e,t){let n=Bi(e);n&&(n.authoritativeSourceFiles=t,Nu(n,e))}function Yn(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 Gi(e,t){let n=t?.cwd??process.cwd();if(!Bi(n))return console.log($("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=Iu(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(_("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(Yn(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Eu({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Yn(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"};fr(n,r),console.log(A(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as Wu}from"@inquirer/prompts";import{applyPull as hr,computeSyncStatus as Ki,compareRemoteSources as Fu,planPull as Ji,planImport as Hu,applyImport as qu,establishBaselines as Bu,rebaselineServerMeta as Gu,D360AuthError as Yu}from"document360-engine";W();var Yi=[{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:M,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 _u(e){return e.path?e.path:`${e.title??"(untitled)"} ${se(`[${e.articleId}]`)}`}function Mu(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 Vn(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(` ${M("~")} ${M(x.path??"")} ${se(`\u2192 "${x.link.title}"`)}`)}for(let x of Yi){let D=e.entries.filter(
|
|
219
|
+
`)}function pr(e,t,n){let o=b=>t[b.index]?.paths.length??0,r=e.filter(b=>b.ok),s=e.filter(b=>!b.ok),u=e.reduce((b,P)=>b+o(P),0),p=r.reduce((b,P)=>b+o(P),0),h=n==="api"?`${me(e.reduce((b,P)=>b+P.costUsd,0))} total`:Ye(e.reduce((b,P)=>b+P.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(u)} (${k}) successfully \xB7 ${h}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${x(u)} (${k}) \xB7 ${h}.`),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 lr(e,t){let n=Cu(t),{model:o}=Ru(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${tn} 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 Tu({cwd:e.cwd,partitions:n,promptFor:s=>Bn(s.paths),concurrency:tn,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(A(` \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 pr(r.results,n,s))console.log(r.ok?A(p):M(p));let u=dr(e.cwd,e.profileName);u&&console.log(f(u))}}catch(r){console.log($(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Gn(e,t,n){let o=Pu(e,n);if(o.length===0)return[];let r=new Set(nn((await cr({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 Gn(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(A("\u2713 All related articles are already published.")),{kind:"continue"}):await lr(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await cr({cwd:t?.cwd??process.cwd()}),s=nn(r.entries),u=qn(r.entries);return u>0&&console.log(M(`\u26A0 ${u} 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(A(u>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):t?await lr(t,s.map(p=>p.path)):{kind:"forward-to-agent",prompt:Bn(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 cr({cwd:t?.cwd??process.cwd()});r=nn(s.entries);let u=qn(s.entries);u>0&&console.log(M(`\u26A0 ${u} 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(A("\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(()=>vu({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await lr(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:ur(o),display:`/publish ${o}`}}async function on(){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 Eu}from"@inquirer/prompts";import{inventoryRepo as Iu,readProjectConfig as Bi,writeProjectConfig as Nu}from"document360-engine";function fr(e,t){let n=Bi(e);n&&(n.authoritativeSourceFiles=t,Nu(n,e))}function Yn(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 Gi(e,t){let n=t?.cwd??process.cwd();if(!Bi(n))return console.log($("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=Iu(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(_("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(Yn(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Eu({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Yn(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"};fr(n,r),console.log(A(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as Wu}from"@inquirer/prompts";import{applyPull as hr,computeSyncStatus as Ki,compareRemoteSources as Fu,planPull as Ji,planImport as Hu,applyImport as qu,establishBaselines as Bu,rebaselineServerMeta as Gu,D360AuthError as Yu}from"document360-engine";W();var Yi=[{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:M,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 _u(e){return e.path?e.path:`${e.title??"(untitled)"} ${se(`[${e.articleId}]`)}`}function Mu(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 Vn(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(` ${M("~")} ${M(x.path??"")} ${se(`\u2192 "${x.link.title}"`)}`)}for(let x of Yi){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(_u(b))}${b.detail?se(` (${b.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let u={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},p=o.length,h=s===r?A("\u2713 everything up to date"):[r>0?A(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...Yi.map(x=>{let D=(e.counts[x.status]??0)-(x.status==="untracked-local"?p:0);return D>0?`${D} ${u[x.status]}`:null})].filter(Boolean).join(se(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${Mu(t)}`:"";return n.push(h+se(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as Lu}from"diff";import Vi from"picocolors";var zi=80,Ou="\x1B[48;2;74;28;28m",Uu="\x1B[48;2;24;66;24m",Xi="\x1B[49m",mr=e=>String(e).padStart(5);function ct(e,t,n){let o=b=>{let P=b.replace(/\r\n/g,`
|
|
221
221
|
`);return P.endsWith(`
|
|
222
222
|
`)||P===""?P:P+`
|
|
223
|
-
`},r=o(e),s=o(t);if(r===s)return null;let u=Math.max(20,n-10),p=Lu("a","b",r,s,"","",{context:3}),h=0,
|
|
223
|
+
`},r=o(e),s=o(t);if(r===s)return null;let u=Math.max(20,n-10),p=Lu("a","b",r,s,"","",{context:3}),h=0,k=0,x=[];p.hunks.forEach((b,P)=>{P>0&&x.push(Vi.gray(" \u2026"));let C=b.oldStart,N=b.newStart;for(let I of b.lines){let O=I[0],Q=I.slice(1).slice(0,u);O==="-"?(k++,x.push(`${Ou}${mr(C++)} - ${Q}${Xi}`)):O==="+"?(h++,x.push(`${Uu}${mr(N++)} + ${Q}${Xi}`)):(x.push(Vi.gray(mr(N))+" "+Q),C++,N++)}});let D=x.slice(0,zi);return{added:h,removed:k,lines:D,hidden:Math.max(0,x.length-zi)}}async function Qi(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 Vu(t),{kind:"continue"};if(o==="--baseline")return await zu(t,e.filter(u=>u!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Xu(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 Ku(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await gr({cwd:t.cwd,profileName:t.profileName});for(let u of wr(s))console.log(u.tone==="ok"?A(u.text):u.tone==="warn"?M(u.text):f(u.text));console.log("")}catch(r){r instanceof Yu?console.log($(r.message)):console.log($(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function gr(e){let t=await Ki({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 Ji({cwd:e.cwd,profileName:e.profileName,relPath:o.path});hr({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 Hu({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});qu({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 zn=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,ut=e=>e===1?"":"s";function wr(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${ut(e.pulled.length)} into local: ${zn(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${ut(e.imported.length)}: ${zn(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${ut(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${ut(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Take the portal copy: /pull <path> \xB7 keep yours: /publish <path>. (${zn(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${ut(e.failed.length)} failed: ${zn(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 Vu(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Ki({cwd:e.cwd,profileName:e.profileName});for(let o of Vn(n,Date.now()-t))console.log(o);console.log("")}async function zu(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 Bu({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Gu({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(A("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(A(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(A(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(M(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(f(` - ${s.path} (${s.reason})`))}}async function Xu(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Fu({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(A("\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(M(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(M(` ${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 Ku(e,t){let n=t.replace(/\\/g,"/"),o=await Ji({cwd:e.cwd,profileName:e.profileName,relPath:n});console.log(""),console.log(`${_("\u25CF")} ${Pe(o.title)} ${se(`(${o.path})`)}`);for(let u of o.notes)console.log(M(` \u26A0 ${u}`));o.overwritesLocalChanges&&console.log(M(" \u26A0 This OVERWRITES local edits made since the last sync."));let r=ct(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.")),hr({cwd:e.cwd,profileName:e.profileName},o);return}console.log(se(` \u23BF Added ${r.added} line${ut(r.added)}, removed ${r.removed} line${ut(r.removed)}`));for(let u of r.lines)console.log(u);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Wu({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}hr({cwd:e.cwd,profileName:e.profileName},o),console.log(A(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as Ju}from"node:fs";import{resolve as Qu}from"node:path";import{estimateBulkCost as Zu,planPartitions as ed,readProjectConfig as td,resolveModelForOperation as nd,runPartitioned as od,trackedArticlePaths as rd}from"document360-engine";var yr=3;function kr(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 br(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function xr(e,t){return t.map(n=>{let o=0;try{o=Ju(Qu(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function $r(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 vr(e,t,n){let o=e.reduce((p,h)=>p+h.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 Cr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),u=e.reduce((C,N)=>C+o(N),0),p=r.reduce((C,N)=>C+o(N),0),h=e.reduce((C,N)=>C+N.costUsd,0),
|
|
229
|
+
`)}function vr(e,t,n){let o=e.reduce((p,h)=>p+h.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 Cr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),u=e.reduce((C,N)=>C+o(N),0),p=r.reduce((C,N)=>C+o(N),0),h=e.reduce((C,N)=>C+N.costUsd,0),k=e.reduce((C,N)=>C+N.outputTokens,0),x=n==="api"?`${me(h)} total`:Ye(k),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Converted ${b(u)} (${D}) successfully \xB7 ${x}.`);else{P.push(`Converted ${p}/${b(u)} (${D}) \xB7 ${x}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}async function Zi(e,t){if(!td(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=kr(e),r=rd(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=br(r,n);if(s.length===0)return console.log($(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let u=ed(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:h,forced:k}=nd(t.cwd,"light");if(!o){let x=Zu({files:xr(t.cwd,s),op:"convert",model:h});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let D of vr(u,x,yr))console.log(D);return console.log(f(`Model: ${h}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${u.length} partitions (\u2264${yr} agents at once) on ${h}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let x of od({cwd:t.cwd,partitions:u,promptFor:$r,concurrency:yr,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:h}))if(x.type==="partition_status")x.status==="running"?console.log(f(` \u25B8 ${x.label} \u2014 converting\u2026`)):x.status==="done"?console.log(A(` \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 Cr(x.results,u,D))console.log(x.ok?A(b):M(b))}}catch(x){console.log($(`Convert run failed: ${x.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as ea}from"node:fs";import{resolve as ta}from"node:path";import{estimateBulkCost as sd,lintDocs as id,planPartitions as ad,readDocsPlan as ld,readProjectConfig as na,DEFAULT_DOCS_DIR as cd,resolveModelForOperation as ud,runPartitioned as dd}from"document360-engine";var pd=3,fd=8;function Pr(e){return e===void 0||!Number.isFinite(e)?pd:Math.max(1,Math.min(Math.floor(e),fd))}function Rr(e){let t,n,o=!1,r=!1,s,u=h=>{let k=Number(h);return h!==void 0&&Number.isFinite(k)?k:void 0};for(let h=0;h<e.length;h++){let k=e[h];if(k==="--preview"||k==="--dry-run")o=!0;else if(k==="--rewrite"||k==="--force")r=!0;else{if(k==="--run"||k==="--yes"||k==="--all")continue;k==="--scope"?t=e[++h]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?s=u(e[++h]):k?.startsWith("--concurrency=")?s=u(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=h=>h?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function md(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function hd(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Tr(e,t,n){return n.filter(o=>{try{return ea(ta(e,t,o)).size===0}catch{return!0}})}function Sr(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let u of o.get(r)?.sources??[])try{s+=ea(ta(e,u)).size}catch{}return{path:r,bytes:s}})}function Dr(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 jr(e,t,n){let o=e.reduce((u,p)=>u+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(u=>` \u2022 ${u.label} \u2014 ${u.paths.length} article${u.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 Ar(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),u=e.reduce((C,N)=>C+o(N),0),p=r.reduce((C,N)=>C+o(N),0),h=e.reduce((C,N)=>C+N.costUsd,0),
|
|
238
|
+
`)}function jr(e,t,n){let o=e.reduce((u,p)=>u+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(u=>` \u2022 ${u.label} \u2014 ${u.paths.length} article${u.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 Ar(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),u=e.reduce((C,N)=>C+o(N),0),p=r.reduce((C,N)=>C+o(N),0),h=e.reduce((C,N)=>C+N.costUsd,0),k=e.reduce((C,N)=>C+N.outputTokens,0),x=n==="api"?`${me(h)} total`:Ye(k),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Wrote ${b(u)} (${D}) successfully \xB7 ${x}.`),P.push("Next \u2014 push them to Document360:"),P.push("/publish --all"),P.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{P.push(`Wrote ${p}/${b(u)} (${D}) \xB7 ${x}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}function Er(e,t,n){try{let o=id({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 run /check to see + fix.`}catch{return null}}function Ir(e,t,n){let o=(na(e)?.docsDir??cd).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=md(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=hd(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 u=Tr(e,o,s);if(u.length===0){let p=n.scope?` under "${n.scope}"`:"",h=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${h} --rewrite to regenerate them all.`}}return{docsDir:o,targets:u,planCount:r.length}}async function oa(e,t){if(!na(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=ld(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:u,rewrite:p}=Rr(e),{docsDir:h,targets:k,reason:x,rewriting:D}=Ir(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(x?M(x):M("Nothing to write.")),{kind:"continue"};D&&console.log(M(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let b=ad(k),P=Pr(u),{model:C,forced:N}=ud(t.cwd,"standard"),I=!!r;if(s&&!I){let O=sd({files:Sr(t.cwd,n,k),op:"write",model:C});o&&console.log(f(`Scope: ${o} (${k.length} pending).`));for(let Q of jr(b,O,P))console.log(Q);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${P} 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 dd({cwd:t.cwd,partitions:b,promptFor:Q=>Dr(Q,h,{rewrite:D||I}),concurrency:P,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(A(` \u2713 ${O.label}`)):console.log($(` \u2717 ${O.label}`));else if(O.type==="run_done"){console.log("");let Q=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let ne of Ar(O.results,b,Q))console.log(O.ok?A(ne):M(ne));let pe=Er(t.cwd,h,k);pe&&console.log(M(pe))}}catch(O){console.log($(`Write run failed: ${O.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as gd,readdirSync as ra,statSync as sa}from"node:fs";import{join as ia}from"node:path";import{inputDir as wd,readProjectConfig as yd}from"document360-engine";var aa=/\.(md|markdown|pdf|txt)$/i;function Nr(e){let t=wd(e);if(!gd(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of ra(t)){let s=ia(t,r),u=!1;try{u=sa(s).isDirectory()}catch{continue}if(u){if(r.startsWith("."))continue;let p=kd(s);p>0&&n.push({name:r,docCount:p})}else aa.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function kd(e){let t=0;for(let n of ra(e))try{sa(ia(e,n)).isFile()&&aa.test(n)&&t++}catch{}return t}function _r(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 Xn(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
239
|
`)}var Mr="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function la(e,t){let n=t?.cwd??process.cwd();if(!yd(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Nr(n);if(o.length===0&&r===0)return console.log(f(Mr)),{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 h of o)console.log(` ${h.name} ${f(`(${h.docCount} doc${h.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Xn(p),display:p?`/draft ${p}`:"/draft"}}let u=_r(o,s);return{kind:"forward-to-agent",prompt:Xn(u??"",u?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as bd,readProjectConfig as xd}from"document360-engine";function Lr(e){try{return bd(e).filter(t=>t.kind==="request").length}catch{return 0}}function Or(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Ur(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 Wr="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 ca(e,t){let n=t?.cwd??process.cwd();if(!xd(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Or(e);if(!r&&Lr(n)===0)return console.log(f(Wr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Ur(r,o),display:s}}W();import{search as $d}from"@inquirer/prompts";import{findByName as vd,getSession as Cd,listSessions as Pd,relativeTime as da}from"document360-engine";async function pa(e,t){let n=Pd(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=vd(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),ua(n),{kind:"continue"})}if(!process.stdin.isTTY)return ua(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>$d({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let u=(s??"").toLowerCase();return n.filter(p=>!u||p.name.toLowerCase().includes(u)||p.firstPrompt.toLowerCase().includes(u)).map(p=>({name:`${p.name} ${da(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Cd(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function ua(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${f(da(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Rd}from"document360-engine";function Fr(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 fa(e,t){let n=Fr(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Rd(o,n)?console.log(A(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(A(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as ma,readProjectConfig as Td,writeProjectConfig as Sd}from"document360-engine";W();function Hr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Td(e);if(!o)return"No .d360-writer.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return ma().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Sd(o,e),null):`Unknown environment "${r}". Known: ${ma().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function ha(e,t){let n=e[0];if(!n)return En(t.cwd),{kind:"continue"};if(n==="add"){let o=Hr(t.cwd,e[1],e[2]);return o?(console.log($(o)),{kind:"continue"}):(console.log(A(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/login")}`),{kind:"continue"})}return In(t.cwd,n),Nn(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Dd}from"@inquirer/prompts";import{readProjectConfig as jd,readUserConfig as ga,resolveModelSetting as qr,writeUserConfig as wa}from"document360-engine";var
|
|
240
|
+
`)}var Wr="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 ca(e,t){let n=t?.cwd??process.cwd();if(!xd(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Or(e);if(!r&&Lr(n)===0)return console.log(f(Wr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Ur(r,o),display:s}}W();import{search as $d}from"@inquirer/prompts";import{findByName as vd,getSession as Cd,listSessions as Pd,relativeTime as da}from"document360-engine";async function pa(e,t){let n=Pd(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=vd(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),ua(n),{kind:"continue"})}if(!process.stdin.isTTY)return ua(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>$d({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let u=(s??"").toLowerCase();return n.filter(p=>!u||p.name.toLowerCase().includes(u)||p.firstPrompt.toLowerCase().includes(u)).map(p=>({name:`${p.name} ${da(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Cd(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function ua(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${f(da(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Rd}from"document360-engine";function Fr(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 fa(e,t){let n=Fr(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Rd(o,n)?console.log(A(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(A(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as ma,readProjectConfig as Td,writeProjectConfig as Sd}from"document360-engine";W();function Hr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Td(e);if(!o)return"No .d360-writer.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return ma().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Sd(o,e),null):`Unknown environment "${r}". Known: ${ma().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function ha(e,t){let n=e[0];if(!n)return En(t.cwd),{kind:"continue"};if(n==="add"){let o=Hr(t.cwd,e[1],e[2]);return o?(console.log($(o)),{kind:"continue"}):(console.log(A(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/login")}`),{kind:"continue"})}return In(t.cwd,n),Nn(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Dd}from"@inquirer/prompts";import{readProjectConfig as jd,readUserConfig as ga,resolveModelSetting as qr,writeUserConfig as wa}from"document360-engine";var Ae=[{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 Kn(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=Ae.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Ad(e){switch(e.source){case"project":return".d360-writer.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"claude-settings":return"Claude Code's own settings (~/.claude/settings.json)";case"claude-default":return"Claude Code default (no override configured)"}}function rn(e,t){let n=()=>{let s=qr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=ga();return s.defaultModel?(delete s.defaultModel,wa(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${qr(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}}wa({...ga(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=jd(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function ya(e,t){let n=e[0]?.trim();if(!n){let u=qr(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${_(u.model??"Claude Code default")}`),console.log(f(` source: ${Ad(u)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Kn(u),h;try{h=await t.withPausedInput(()=>Dd({message:`Select model (current: ${u.model??"Claude Code default"})`,default:Ae[p].value,choices:Ae.map((b,P)=>({name:`${b.label}${P===p?" \u2714":""}`,value:b.value,description:b.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:x,effective:D}=rn(t.cwd,h??"default");for(let b of k)console.log(b.startsWith("\u26A0")?M(b):b.startsWith("\u2713")?A(b):f(b));return x&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:s}=rn(t.cwd,n);for(let u of o)console.log(u.startsWith("\u26A0")?M(u):u.startsWith("\u2713")?A(u):f(u));return r&&await t.setModel(s),{kind:"continue"}}Jn();async function Ca(e,t){return await t.withPausedInput(()=>Dt(t.cwd)),{kind:"clear"}}async function Pa(e,t){return await t.withPausedInput(()=>Zs(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as Yd}from"document360-engine";async function Ra(e,t){let n=!1;try{n=Yd(t.cwd).production}catch{}return n?(console.log(M("\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 Ta=async(e,t)=>{try{await t.withPausedInput(()=>An({}))}catch(n){console.log($(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as Vd,clearTokens as zd,clearProfileProject as Xd}from"document360-engine";async function Sa(e,t){let n;try{n=Vd(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let o=zd(n);return Xd(t.cwd,n),console.log(o?A(`\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 Da}from"node:fs";import{isAbsolute as Kd,join as Jd,resolve as Qd}from"node:path";import{readProjectConfig as Zd,screenshotPlaceholderIds as ep,DEFAULT_CAPTURE_DIR as tp,DEFAULT_OUTPUT_DIR as np}from"document360-engine";var ja=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Gr(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?ja(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:ja(o),setup:t}:{mode:"single",id:o}}function Yr(e,t){let n=Zd(e),o=n?.captureDir??tp,r=n?.outputDir??np,s=(u,p)=>Kd(u)?Jd(u,p):Qd(e,u,p);return ep(e,{scope:t}).map(({id:u,file:p})=>{let h=Da(s(r,`${u}.png`))?"captured":Da(s(o,`${u}.spec.ts`))?"spec":"placeholder";return{id:u,file:p,state:h}})}var op={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},rp={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Vr(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 u of e.filter(p=>p.file===s))r.push(` ${op[u.state]} ${u.id.padEnd(34)} ${rp[u.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Aa(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 Qn(e,t){let n=Gr(e);if(n.mode==="list"){let u=t?.cwd??process.cwd();for(let p of Vr(Yr(u,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
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 sp,readFileSync as ip}from"node:fs";import{isAbsolute as ap,join as lp,resolve as cp}from"node:path";import{readProjectConfig as up,DEFAULT_CAPTURE_DIR as dp}from"document360-engine";async function an(){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 Ea="-".repeat(64);function zr(e){let t=dp;try{let x=up(e);x?.captureDir&&(t=x.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=ap(t)?lp(t,"CAPTURE-TESTID-REQUESTS.json"):cp(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!sp(n))return null;let o;try{let x=JSON.parse(ip(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,u=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,h=`${t}/CAPTURE-TESTID-REQUESTS.md`,
|
|
245
|
+
`),display:"/capture-setup"}}var Ea="-".repeat(64);function zr(e){let t=dp;try{let x=up(e);x?.captureDir&&(t=x.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=ap(t)?lp(t,"CAPTURE-TESTID-REQUESTS.json"):cp(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!sp(n))return null;let o;try{let x=JSON.parse(ip(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,u=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,h=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${u} 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.","",Ea,`Read ${h} and ${k}. They list ${u} 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.",Ea]}lt();W();import{listOpenForDocs as pp,readProjectConfig as fp}from"document360-engine";function Xr(e){try{return pp(e).length}catch{return 0}}function Kr(){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
246
|
`)}async function Ia(e,t){let n=t?.cwd??process.cwd();return fp(n)?Xr(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:Kr(),display:"/inbox"}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as mp,listOpenForDocs as hp,readProjectConfig as gp,computeSyncStatus as wp,planPull as yp,applyPull as kp}from"document360-engine";function _t(e){let t=0,n=0,o=0;try{t=mp(e).length}catch{}try{let r=hp(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 Mt(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 Qr(e){return{publish:e.includes("--publish")}}function Zr({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 bp={status:wp,plan:yp,apply:kp};async function es(e,t=bp){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 Jr=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Zn=e=>e===1?"":"s";function ts(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${Zn(e.pulled.length)} into local: ${Jr(e.pulled)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Zn(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Jr(e.conflicts)}`),e.untrackedRemote.length&&t.push(`\u2139 ${e.untrackedRemote.length} new article${Zn(e.untrackedRemote.length)} in the portal aren't local yet \u2014 run /pull to bring them in: ${Jr(e.untrackedRemote)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull${Zn(e.failed.length)} failed \u2014 left for /pull.`),t}async function Na(e,t){let n=t?.cwd??process.cwd();if(!gp(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=
|
|
247
|
+
`)}var bp={status:wp,plan:yp,apply:kp};async function es(e,t=bp){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 Jr=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Zn=e=>e===1?"":"s";function ts(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${Zn(e.pulled.length)} into local: ${Jr(e.pulled)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Zn(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Jr(e.conflicts)}`),e.untrackedRemote.length&&t.push(`\u2139 ${e.untrackedRemote.length} new article${Zn(e.untrackedRemote.length)} in the portal aren't local yet \u2014 run /pull to bring them in: ${Jr(e.untrackedRemote)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull${Zn(e.failed.length)} failed \u2014 left for /pull.`),t}async function Na(e,t){let n=t?.cwd??process.cwd();if(!gp(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}=Qr(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await es({cwd:n,profileName:t?.profileName});for(let p of ts(s))console.log(p.startsWith("\u2713")?A(p):p.startsWith("\u2139")?f(p):M(p));let u=Mt(_t(n));return console.log(f(u?`Catching up on ${u}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Zr({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as xp}from"node:child_process";var dt="document360-writer",eo=`npm i -g ${dt}@latest`;async function to(){let e=process.platform==="win32";return new Promise(t=>{try{let n=xp(`npm i -g ${dt}@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 _a(){return console.log(f(`Updating ${dt}\u2026`)),(await to()).ok?console.log(A("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log($(`Update failed \u2014 run manually: ${eo}`)),{kind:"continue"}}W();lt();import{existsSync as ns,rmSync as $p}from"node:fs";import{basename as Ma,resolve as os}from"node:path";import{execFileSync as vp}from"node:child_process";import{input as Cp}from"@inquirer/prompts";import{readProjectConfig as Pp,devHintsGuidePath as Rp}from"document360-engine";var Tp=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Sp=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),no=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),La=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Oa(e){let t=no(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:La(t)?!0:Sp.has(t)}function rs(e){let t=null;try{t=Pp(e)}catch{t=null}let n=new Set(Tp);for(let o of[no(t?.docsDir),no(t?.captureDir),no(t?.outputDir)])o&&La(o)&&n.add(o);return[...n].filter(o=>Oa(o)&&ns(os(e,o)))}function ss(e,t){let n=[],o=[];for(let r of t){if(!Oa(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{$p(os(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Ua(e,t){try{return vp("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
248
248
|
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Dp(e){return Ua(e,".d360-writer/hints")}function jp(e){return Ua(e,".d360-writer/messages")}function is(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Dp(e),o=jp(e),r=ns(os(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: ${Ma(e)}`]}async function Wa(e,t){let n=rs(t.cwd);for(let h of is(t.cwd,n))console.log(n.length===0?f(h):h);if(n.length===0)return{kind:"continue"};let o=Ma(t.cwd);if((await t.withPausedInput(()=>Cp({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(M("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=ns(Rp(t.cwd)),{removed:u,failed:p}=ss(t.cwd,n);console.log(A(`\u2713 Reset complete \u2014 removed ${u.length} item${u.length===1?"":"s"}. The repo is back to its original state.`));for(let h of p)console.log($(` \u2717 ${h.path}: ${h.error}`));if(s){for(let h of Wn())console.log(h);console.log(f("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}W();import{lintDocs as Ap}from"document360-engine";function oo(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 as(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 Fa(e,t){let n=e.includes("--fix"),o=Ap({cwd:t.cwd});if(n)return o.length===0?(console.log(A("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${o.length} doc issue${o.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:as(o),display:"/check --fix"});console.log(f("Linting the docs (engine internals, unknown commands, stale facts)\u2026"));for(let r of oo(o))console.log(o.length===0?A(r):M(r));return o.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}W();import{lintDocs as Ep,loadStyleGuide as Ip,buildReviewPrompt as Np,readProjectConfig as _p,DEFAULT_DOCS_DIR as Mp}from"document360-engine";function ls(e,t){let n=_p(e);if(!n)return null;let o=(n.docsDir??Mp).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(
|
|
251
|
+
`)}async function Fa(e,t){let n=e.includes("--fix"),o=Ap({cwd:t.cwd});if(n)return o.length===0?(console.log(A("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${o.length} doc issue${o.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:as(o),display:"/check --fix"});console.log(f("Linting the docs (engine internals, unknown commands, stale facts)\u2026"));for(let r of oo(o))console.log(o.length===0?A(r):M(r));return o.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}W();import{lintDocs as Ep,loadStyleGuide as Ip,buildReviewPrompt as Np,readProjectConfig as _p,DEFAULT_DOCS_DIR as Mp}from"document360-engine";function ls(e,t){let n=_p(e);if(!n)return null;let o=(n.docsDir??Mp).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(k=>!k.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),u=Ep({cwd:e}),p=s?u.filter(k=>k.path===`${o}/${s}`||k.path.startsWith(`${o}/${s}/`)):u;return{prompt:Np({docsRoot:o,scope:s,styleGuide:Ip(e),deterministicFindings:p,fix:r}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function Ha(e,t){let n=ls(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:Xo,"?":Xo,clear:pi,exit:Ko,quit:Ko,init:Di,mcp:Hn,publish:qi,audit:on,scope:Gi,pull:Qi,convert:Zi,write:oa,draft:la,document:ca,resume:pa,rename:fa,profile:ha,model:ya,doctor:sn,workspace:Ca,project:Pa,"allow-prod":Ra,login:Ta,logout:Sa,screenshot:Qn,"capture-setup":an,devhints:ki,inbox:Ia,"catch-up":Na,update:_a,reset:Wa,check:Fa,review:Ha};function Ba(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}lt();W();var Lp={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"},Ya=160,us=200,Va=40;function ke(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Ga(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),Va)}`);return t.length>4&&n.push("\u2026"),ke(n.join(", "),Ya)}var Ve=e=>typeof e=="string"&&e?e:null,cs=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Op(e){let t=Ve(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 Up(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Ve(t.title);if(!o)return null;let r=Op(t.local_path);return n("Create article",`"${ke(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Ve(t.title),r=cs(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)",cs(t.article_id)?`id ${cs(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",Ve(t.name)?`"${ke(Ve(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Ve(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 ro(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),u=s.join("__");if(r==="document360"){let k=Up(u,t);if(k)return k}let p=u.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Ga(t)}}let n=Lp[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:ke(o,Ya)}:{title:e,sep:"",arg:Ga(t)}}function Wp(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 Fp(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Wp).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>ke(r,us))]}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),Va)}`);return n.length>0?[ke(n.join(" \xB7 "),us)]:null}return null}function Hp(e){let t=Ve(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function qp(e,t,n){switch(e){case"d360_create_article":{let o=Hp(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=Ve(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 so(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
252
252
|
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let u=qp(n.slice(18),o,r);if(u)return{lines:u,hidden:0}}let s=Fp(r)??r.split(`
|
|
253
|
-
`);return{lines:s.slice(0,t).map(u=>ke(u,us)),hidden:Math.max(0,s.length-t)}}function io(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function ao(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 lo(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 tf=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function nf(e,t,n,o){if(tf.test(e))try{let r=Ja(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,u=ao(t,n),p=lo(n);e.endsWith("publish_article")&&p&&console.log(_(` \u2B95 Live: ${p}`)),u&&s&&console.log(_(` \u2B95 Preview: ${io(r.connection.portalUrl,s,u,r.project.languageCode??"en")}`))}catch{}}async function Qa(e=process.cwd(),t="auto",n){let o=Gp(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)),of(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=ds({cwd:e,profileName:n,allowProdWrites:r}),u={uuid:null,firstPrompt:null,titleFired:!1},p=Bp({input:process.stdin,output:process.stdout}),h=[],
|
|
253
|
+
`);return{lines:s.slice(0,t).map(u=>ke(u,us)),hidden:Math.max(0,s.length-t)}}function io(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function ao(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 lo(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 tf=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function nf(e,t,n,o){if(tf.test(e))try{let r=Ja(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,u=ao(t,n),p=lo(n);e.endsWith("publish_article")&&p&&console.log(_(` \u2B95 Live: ${p}`)),u&&s&&console.log(_(` \u2B95 Preview: ${io(r.connection.portalUrl,s,u,r.project.languageCode??"en")}`))}catch{}}async function Qa(e=process.cwd(),t="auto",n){let o=Gp(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)),of(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=ds({cwd:e,profileName:n,allowProdWrites:r}),u={uuid:null,firstPrompt:null,titleFired:!1},p=Bp({input:process.stdin,output:process.stdout}),h=[],k=null,x=!1;p.on("line",P=>{if(k){let C=k;k=null,C(P)}else h.push(P)}),p.on("close",()=>{if(x=!0,k){let P=k;k=null,P(null)}});function D(){return h.length>0?Promise.resolve(h.shift()):x?Promise.resolve(null):(process.stdout.write(_("> ")),new Promise(P=>{k=P}))}let b={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=ds({cwd:e,profileName:n,allowProdWrites:r}),u={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>u.uuid,setPendingName:P=>{u.pendingName=P},setModel:async P=>s.setModel(P),withPausedInput:async P=>{p.pause();try{return await P()}finally{p.resume()}}};try{for(;;){let P=await D();if(P===null)break;let C=P.trim();if(C){if(C.startsWith("/")){let N=Ba(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(A("\u2713 Production writes authorized for this session.")),console.log("");continue}if(O.kind==="resume"){s.close(),s=ds({cwd:e,resume:O.uuid,profileName:n,allowProdWrites:r});let Q=Yp(O.uuid);u={uuid:O.uuid,firstPrompt:Q?.firstPrompt??null,titleFired:!0},Ka(O.uuid),console.log(A(`\u2713 Resumed "${O.name}"`)),console.log("");continue}O.kind==="forward-to-agent"&&(u.firstPrompt||(u.firstPrompt=O.display??O.prompt),await Xa(s,O.prompt,o,u,e));continue}u.firstPrompt||(u.firstPrompt=C),await Xa(s,C,o,u,e)}}}finally{s.close(),p.close()}}function of(e,t){console.log(""),console.log(Vt("document360-writer")),console.log(f(` cwd: ${e}`));let n=Jp(e);if(console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(rf(e,t)),!Qp(e))console.log(M(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{try{On(e);for(let o of Un(e))console.log(M(` ${o}`))}catch{}try{let o=Mt(_t(e));o&&console.log(M(` \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 rf(e,t){try{let n=Ja(e,t),o=n.production?M(" \u26A0 PRODUCTION"):"",r=ef(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...za(r.idToken)??{},...za(r.accessToken)??{}},u=s.email??s.preferred_username??"signed in";return Zp(r)&&!r.refreshToken?M(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${u} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function sf(){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 af(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Xp({uuid:t,name:r??zp(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function lf(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Kp(o,t).then(r=>{r&&Vp(n,r)}).catch(()=>{})}async function Xa(e,t,n,o,r){let s=new Map;for await(let u of e.send(t))cf(u,o,r,n,s)}function cf(e,t,n,o,r){switch(e.type){case"session":t.uuid||af(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=ro(e.name,e.input);s&&(process.stdout.write(`
|
|
254
254
|
|
|
255
|
-
`),console.log(`${A("\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=ct(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let u=p=>p===1?"":"s";console.log(se(` \u23BF Added ${s.added} line${u(s.added)}, removed ${s.removed} line${u(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 u=so(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?$:se;u.lines.forEach((h,
|
|
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&&(Ka(t.uuid),t.titleFired||lf(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&sf();break}}import{render as vm}from"ink";import{resolveAuth as Cm}from"document360-engine";import{useCallback as V,useEffect as Te,useMemo as ws,useRef as J,useState as H}from"react";import{Box as oe,Text as T,useApp as Tf,useInput as Sf,useStdout as Df}from"ink";import{existsSync as
|
|
255
|
+
`),console.log(`${A("\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=ct(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let u=p=>p===1?"":"s";console.log(se(` \u23BF Added ${s.added} line${u(s.added)}, removed ${s.removed} line${u(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 u=so(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?$:se;u.lines.forEach((h,k)=>console.log(p((k===0?" \u23BF ":" ")+h))),u.hidden>0&&console.log(f(` \u2026 +${u.hidden} lines`)),e.isError||nf(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&&(Ka(t.uuid),t.titleFired||lf(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&sf();break}}import{render as vm}from"ink";import{resolveAuth as Cm}from"document360-engine";import{useCallback as V,useEffect as Te,useMemo as ws,useRef as J,useState as H}from"react";import{Box as oe,Text as T,useApp as Tf,useInput as Sf,useStdout as Df}from"ink";import{existsSync as ze,readFileSync as ys,readdirSync as $o}from"node:fs";import{spawnSync as jf}from"node:child_process";import{basename as cn,isAbsolute as Af,join as pt}from"node:path";import{createSession as Tl,classifyClaudeAuth as $s,CLAUDE_CODE_SETUP_HINT as Ef,loginPkce as If,toStoredTokens as Nf,saveTokens as _f,getAccessToken as Mf,resolveActiveProfile as de,resolveProjectId as Lf,getArticle as Of,decodeJwtClaims as Ot,isExpired as Ue,loadTokens as Xe,clearTokens as Uf,clearProfileProject as Wf,setTitle as Ff,slugify as Hf,touchSession as ks,upsertSession as qf,generateTitle as Sl,findByName as Bf,listSessions as Gf,renameSession as Yf,suggestNextAction as Vf,readProjectConfig as Z,writeProjectConfig as Dl,resolveModelSetting as vs,loadProfileMap as xo,applyPull as zf,computeSyncStatus as jl,countLocalAhead as Xf,lintDocs as Al,compareRemoteSources as Kf,planPull as Jf,establishBaselines as Qf,rebaselineServerMeta as Zf,inventoryRepo as em,knownEnvironments as tm,resolveEnvironment as nm,planPartitions as bs,partitionEvenly as om,screenshotPlaceholderIds as rm,trackedArticlePaths as sm,runPartitioned as yo,estimateBulkCost as El,resolveModelForOperation as ko,readDocsPlan as Il,checkForUpdate as im,detectInstallKind as am,isSelfUpdatable as lm,devHintsGuidePath as Cs,toolFeedbackPath as cm,reconcileToolFeedback as um,DEFAULT_DOCS_DIR as un,setProfileProject as dm,writeCrashLog as pm}from"document360-engine";lt();import{spawn as Za}from"node:child_process";function uf(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function df(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?Za([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Za(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",u=>o(u===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 el(e){for(let[t,n]of uf())if(await df(t,n,e))return!0;return!1}var pf=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function ps(e,t){if(t.closed)return e;let n=e.split(`
|
|
257
257
|
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){pf.test(s)&&(t.cueSeen=!0);continue}let u=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);u?(n[r]=`${u[1]}${++t.num}. ${u[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
|
|
258
258
|
`)}import{existsSync as ff,mkdirSync as mf,readFileSync as hf,writeFileSync as gf}from"node:fs";import{join as tl}from"node:path";import{writerDir as wf}from"document360-engine";function nl(e){return tl(wf(e),".sessions")}function ol(e,t){return tl(nl(e),`${t}.json`)}function rl(e,t,n){try{mf(nl(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");gf(ol(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function fs(e,t){try{let n=ol(e,t);if(!ff(n))return[];let o=JSON.parse(hf(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var yf=e=>`\x1B]0;${e}\x07`,kf=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function sl(e){process.stdout.isTTY&&process.stdout.write(e)}function Lt(e){sl(yf(e))}function co(e){sl(kf(e))}var uo=["\xB7 "," \xB7"],po="\u{1F7E3}";Jn();var fo=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer.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 [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). --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"}],il={"/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 al(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(il[n])return il[n];let o=fo.find(r=>r.name===t);return o?o.desc:""}function ll(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return fo.filter(n=>n.name.startsWith(t))}function cl(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as ul,Text as ie}from"ink";import{jsx as le,jsxs as mo}from"react/jsx-runtime";function bf({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 mo(ie,{children:[le(ie,{color:F,children:`${e.n}. `}),e.s]});case"cmd":return mo(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 dl({tab:e,width:t}){let n=Re[e]??Re[0],o=6+Re.reduce((s,u)=>s+u.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return mo(ul,{flexDirection:"column",paddingX:1,children:[mo(ie,{children:[le(ie,{color:F,bold:!0,children:"Help "}),Re.map((s,u)=>u===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(ul,{flexDirection:"column",marginTop:1,children:n.rows.map((s,u)=>le(bf,{row:s},u))}),le(ie,{dimColor:!0,children:`
|
|
259
259
|
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var xf=/^(?:\d+[.)]|[-*•])\s+/;function pl(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
260
|
-
`)){let u=s.trim().replace(xf,""),p=u.match(/^`([^`]+)`$/);p&&(u=p[1].trim());let h=u.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!h||!o.has(h[1].toLowerCase()))continue;let
|
|
261
|
-
`)}function wl(e){if(!e.ready)return{kind:"idle"};let t=!!e.pendingText;if(!e.hasDocs)return{kind:"noDocs",note:vf,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${
|
|
260
|
+
`)){let u=s.trim().replace(xf,""),p=u.match(/^`([^`]+)`$/);p&&(u=p[1].trim());let h=u.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!h||!o.has(h[1].toLowerCase()))continue;let k=`/${h[1].toLowerCase()}${h[2]?` ${h[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}W();function ln(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Le(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function fl(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var $f=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function ml(e,t,n){if(!$f.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 u=s.replace(/\\/g,"/");return r===u||r.endsWith(`/${u}`)})??null}function ms(e){return e.replace(/^[\w.-]+\//,"")}var ho=16,hl={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function hs(e){return e.trim().split(/\s+/).slice(1).join(" ")}function gl(e,t){let n=hs(t);return e.some(r=>r.trim()===t.trim()||!!n&&hs(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&hs(r)===n)):[]}var vf='\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 Cf(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 Oe(e){return e===1?"":"s"}function Pf(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 gs(e,t,n){let o=[];e.pendingWrites>0&&o.push(` \u2022 ${e.pendingWrites} planned article${Oe(e.pendingWrites)} still unwritten`),e.localAhead>0&&o.push(` \u2022 ${e.localAhead} article${Oe(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${Oe(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 ${Pf(t[0])}.`]:[`Welcome back. Your ${e.tracked} tracked article${Oe(e.tracked)} are all in sync.`];return r.push("",...t.map((s,u)=>` ${u+1} ${s.padEnd(9)} ${Cf(s,n)}`),"Or just tell me what to write or update."),r.join(`
|
|
261
|
+
`)}function wl(e){if(!e.ready)return{kind:"idle"};let t=!!e.pendingText;if(!e.hasDocs)return{kind:"noDocs",note:vf,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${Oe(e.pendingWrites)} not written yet \u2014 pick up where you left off:`;return{kind:"actions",note:gs(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${Oe(e.localAhead)} changed locally \u2014 ready to publish to Document360:`;return{kind:"actions",note:gs(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${Oe(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${Oe(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${Oe(e.tracked)} tracked for "${e.profileName}". What next?`;return{kind:"actions",note:gs(e,n,t),title:o,options:n}}var Rf=/\[Pasted text #\d+ \+\d+ lines?\]/g;function yl(e){return e.replace(/\r\n?/g,`
|
|
262
262
|
`)}function kl(e){return e.includes(`
|
|
263
263
|
`)||e.length>200}function bl(e,t){let n=t.split(`
|
|
264
264
|
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function xl(e,t){return e.replace(Rf,n=>t.get(n)??n)}function $l(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function go(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 u=0;u<s.length;u+=n)o.push({start:r+u,end:r+Math.min(u+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function wo(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function vl(e,t,n){let o=wo(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 Cl(e,t,n){let o=e[wo(e,t)];return n==="start"?o.start:o.end}function Pl(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
266
266
|
`),s=0;for(let u=r.length-1;u>=0;u--){let p=r[u];if(s+=Math.max(1,Math.ceil(p.length/o)),s>=t){let h=s-t;return{text:[h>0?p.slice(h*o):p,...r.slice(u+1)].join(`
|
|
267
267
|
`),truncated:u>0||h>0}}}return{text:e,truncated:!1}}function Rl(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 xs,jsx as E,jsxs as
|
|
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 xs,jsx as E,jsxs as G}from"react/jsx-runtime";var fm={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},Nl=` 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 mm(e,t,n,o){let r=$s(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)",u=vs(e),p=Z(e),h=(p?.docsDir??un).replace(/\/+$/,""),
|
|
270
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function mm(e,t,n,o){let r=$s(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)",u=vs(e),p=Z(e),h=(p?.docsDir??un).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${h}/ + config`,x={version:t,claude:s,model:u.model??"Claude Code default model",modelSource:fm[u.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=Xe(D.name);if(b){let P={...Ot(b.idToken)??{},...Ot(b.accessToken)??{}},C=P.email??P.preferred_username??"signed in";Ue(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 hm(e,t){try{let n=de(e,t),o=Xe(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Ot(o.idToken)??{},...Ot(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return Ue(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 _l=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],vo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],gm="Ask me to write or update an article\u2026";function bo({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 wm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Ml(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var ym=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ll(e){try{return $o(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Ol(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Ll(pt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Ll(pt(e,o)))}function Ul(e,t){try{let n=Z(e);if(!n)return!1;let o=de(e,t),r=xo(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=pt(e,(n.docsDir??un).replace(/\/+$/,""));return!!(ze(s)&&$o(s).length>0||ze(Cs(e)))}catch{return!1}}function km({startTime:e,chars:t}){let[n,o]=H(0);Te(()=>{let h=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(h)},[]);let r=vo[n%vo.length],s=_l[Math.floor(n/16)%_l.length],u=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:`(${en(u)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var bm=12e4;function xm({p:e}){let[t,n]=H(0);Te(()=>{let I=setInterval(()=>n(O=>O+1),150);return()=>clearInterval(I)},[]);let o=vo[t%vo.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),u=Math.round(e.chars/4),p=Date.now()-e.lastAt>=bm,h=e.verb??"Converting",k=e.unit??"article",x=e.rows.reduce((I,O)=>I+O.items,0),D=h.toLowerCase(),b=e.rows,P=0;if(b.length>ho){let I=b.findIndex(Q=>Q.status==="active"||Q.status==="pending"),O=Math.max(0,Math.min(I-2,b.length-ho));P=b.slice(0,O).filter(Q=>Q.status==="done").length,b=b.slice(O,O+ho)}let C=Math.min(40,Math.max(...b.map(I=>ms(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} ${h} ${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 ~${u} tokens \xB7 ${en(r)} \xB7 esc to stop`})]}),P>0&&E(T,{dimColor:!0,children:` \u2714 +${P} done`}),b.map(I=>G(T,{color:N(I.status),dimColor:I.status==="done"||I.status==="pending",children:[` ${hl[I.status]} ${ms(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 ${en(s)} \u2014 press esc to stop if it's wedged`})]})}var $m=10800*1e3;function Wl({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Tf(),[s,u]=H(n),[p,h]=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}})},[]),P=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=$l(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[N,I]=H(!1),[O,Q]=H(!1),[pe,ne]=H(0),[Se,ue]=H(null),[Ke,B]=H([]),ft=J(0),[Vl,dn]=H(!1),[zl,pn]=H(!1),[Co,Ss]=H(null),[Xl,mt]=H(0),Je=J(0),[Ut,ht]=H(0),[gt,fn]=H(null),Ds=J(new Map),Kl=J(0),wt=J([]),be=J(null);be.current===null&&(be.current=Tl({cwd:e,profileName:s,allowProdWrites:!1}));let Ee=J({uuid:null,firstPrompt:null,titleFired:!1}),mn=J(new Map),yt=J(!1),Po=J([]),Fe=J([]),Ro=J(null),[js,Qe]=H(null),To=J(null),[Ze,et]=H(null),[Ie,kt]=H(null),[He,bt]=H(null),[fe,xt]=H(null),[xe,tt]=H(null),[nt,$t]=H(null),[As,De]=H(null),[$e,ot]=H(null),[he,vt]=H(null),[Es,So]=H([]),rt=J([]),Wt=J(!1),ve=J(null),[hn,ee]=H(null),gn=J(!1),wn=J(null),Ft=J(null),[Ce,st]=H(null),[Do,Ht]=H(null),[Is,Ct]=H(0),[Ns,Pt]=H(0),[Jl,_s]=H(0),jo=ws(()=>{try{return vs(e).model??"auto"}catch{return null}},[e,Jl]),{stdout:je}=Df(),[,Ql]=H(0),Ms=J(`${je.columns??80}x${je.rows??24}`),qe=V(()=>Math.max(20,(je.columns??80)-1),[je]),d=V(l=>{wt.current.push(l),console.log(ar(l,qe()))},[qe]),[Ao,Eo]=H(null),Rt=V(l=>{Eo(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]),Io=J(!1),No=V(async()=>{try{if(Io.current||!lm(am())||Z(e)?.mode==="engineer")return;let l=await im({pkg:dt,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;Io.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${dt} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),pn(!0),(await to().finally(()=>pn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),B(a=>a.includes("/exit")?a:[...a,"/exit"]),Ss(l.latest)):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${eo}`})}catch{}},[e,o,d]),_o=V(l=>{let i=Me(e,s);return i.ok?!0:(d({kind:"note",tone:"warn",text:i.reason}),Ft.current=l,B(["/login"]),!1)},[e,s,d]),[Mo,Lo]=H(null),qt=J(!0),yn=J(0),Bt=J(0);Te(()=>{let l=setInterval(()=>{if(qt.current){yn.current=0,Bt.current=0;return}if(!N)try{if(!ze(Cs(e)))return;if(_e(e).status==="current"){qt.current=!0,yn.current=0,Bt.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."}),Eo(null),ue("write the docs for this repo");return}yn.current+=1;let i=yn.current;if((i===4||i%15===0)&&Bt.current<3){Bt.current+=1;let a=Bt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Jt(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=js??cn(e);if(!N){co(0),Lt(`${po} ${l}`);return}co(3);let i=0;Lt(`${uo[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%uo.length,Lt(`${uo[i]} ${l}`)},400);return()=>clearInterval(a)},[N,e,js]),Te(()=>()=>co(0),[]);let Oo=V(l=>{try{let i=Z(e);if(!i)return{kind:"idle"};let a=de(e,s),g=Xe(a.name),c=!!g&&(!Ue(g)||!!g.refreshToken),m=Ul(e,s)||!Ol(e,i.authoritativeSourceFiles),w=$s(t).state==="missing",y=xo(e,a.name),R=y?Object.keys(y.articles).length:0,S=pt(e,(i.docsDir??un).replace(/\/+$/,"")),K=!1;try{K=ze(S)&&$o(S).length>0}catch{}let q=0;if(y?.lastAnalyzedCommit)try{let U=jf("git",["rev-list","--count",`${y.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});U.status===0&&(q=parseInt((U.stdout||"").trim(),10)||0)}catch{}let L=0;try{let U=Il(e);if(U.length>0){let X=(i.docsDir??un).replace(/\/+$/,"");L=Tr(e,X,U.map(we=>we.path)).length}}catch{}let v=Xf(e,s),j={ready:c&&m&&!w,hasDocs:K,tracked:R,pendingText:Mt(_t(e)),behind:q,pendingWrites:L,localAhead:v,autoAudit:!!i.autoAudit,profileName:a.name,allowAutoAudit:l};return wl(j)}catch{return{kind:"idle"}}},[e,s,t]);Te(()=>{let l=performance.now(),i=[],a=(w,y)=>{let R=performance.now();try{return y()}finally{let S=Math.round(performance.now()-R);S>=80&&i.push(`${w}: ${S}ms`)}};d({kind:"banner",info:a("banner",()=>mm(e,o,t,s))});let g=$s(t).state==="missing";if(g&&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
271
|
${Ef}
|
|
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
|
-
${Nl}`}),
|
|
274
|
-
`)}),Rt(at()),qt.current=!1)}}catch{}try{let w=a("reconcile-feedback",()=>um(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 c=a("ready-decision",()=>Oo(!0));c.kind==="autoAudit"?(d({kind:"note",tone:"info",text:c.note}),on().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&ae(w.prompt,{display:w.display,quietUser:!0})})):c.kind==="noDocs"?(d({kind:"note",tone:"info",text:c.note}),ue(c.ghost),
|
|
273
|
+
${Nl}`}),B(g?["/doctor","/init"]:["/init"]);return}g&&B(["/doctor"]);try{let w=de(e,s),y=Xe(w.name);y&&Ue(y)&&y.refreshToken?Mf({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),ne(R=>R+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),B(["/login"])}):(!y||Ue(y))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),B(["/login"]))}catch{}try{let w=Z(e),y=de(e,s),R=Xe(y.name);w&&R&&!Ue(R)&&Ol(e,w.authoritativeSourceFiles)&&!Ul(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."}),B(["/scope"]))}catch{}try{if(a("reconcile-devhints",()=>On(e)),_e(e).status!=="current")if(Jt(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=Un(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
|
|
274
|
+
`)}),Rt(at()),qt.current=!1)}}catch{}try{let w=a("reconcile-feedback",()=>um(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 c=a("ready-decision",()=>Oo(!0));c.kind==="autoAudit"?(d({kind:"note",tone:"info",text:c.note}),on().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&ae(w.prompt,{display:w.display,quietUser:!0})})):c.kind==="noDocs"?(d({kind:"note",tone:"info",text:c.note}),ue(c.ghost),B(c.options),c.title&&De(c.title)):c.kind==="actions"&&(d({kind:"note",tone:"info",text:c.note}),B(c.options),De(c.title));let m=Math.round(performance.now()-l);m>=800&&pm({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}`}),No()},[]),Te(()=>{let l=setInterval(()=>{No()},$m);return()=>clearInterval(l)},[No]),Te(()=>{if(N||
|
|
277
|
-
`)});let
|
|
278
|
-
`)}),Rt(at()),qt.current=
|
|
276
|
+
cwd: ${e}`}),No()},[]),Te(()=>{let l=setInterval(()=>{No()},$m);return()=>clearInterval(l)},[No]),Te(()=>{if(N||Ke.length>0)return;let l=Oo(!1);(l.kind==="actions"||l.kind==="noDocs")&&(B(l.options),De(l.title??null))},[N,Ke,pe,Oo]),Te(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${je.columns??80}x${je.rows??24}`;g!==Ms.current&&(Ms.current=g,Ql(c=>c+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Ui(wt.current,qe())+"\x1B[?2026l")},80))},400)};return je.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),je.off("resize",a)}},[je,qe]);let Ne=Math.max(20,(je.columns??80)-1),Ls=ws(()=>hm(e,s),[e,s,pe]),Uo=(()=>{if(zl)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Co!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Co?` v${Co}`:""}\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=pt(e,(l.docsDir??un).replace(/\/+$/,"")),a=(()=>{try{return ze(i)&&$o(i).length>0}catch{return!1}})();try{let g=de(e,s),c=Xe(g.name);if(!(!!c&&!(Ue(c)&&!c.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${g.name}")\u2026`,isSetup:!0};if(!g.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!g.project.workspaceId&&!a)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return a?{text:gm,isSetup:!1}:Ao?{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}})(),Gt=ll(D),Os=Gt.length>0&&!N,Wo=p!==null?Pl(p,8,Ne):null,kn=$e?$e.paths.filter(l=>!$e.query||l.toLowerCase().includes($e.query.toLowerCase())).slice(0,8):[],bn=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):[],ge=V((l,i)=>{be.current?.close(),be.current=Tl({cwd:e,resume:l,profileName:i??s,allowProdWrites:yt.current}),l||(Ee.current={uuid:null,firstPrompt:null,titleFired:!1},Qe(null)),Ct(0),Pt(0)},[e,s]),Us=V((l,i,a)=>{if(wm.test(l))try{let g=de(e,s),c=typeof i.project_id=="string"&&i.project_id||g.project.projectId,m=ao(i,a),w=[],y=lo(a);l.endsWith("publish_article")&&y&&w.push(`Live: ${y}`),m&&c&&w.push(`Preview: ${io(g.connection.portalUrl,c,m,g.project.languageCode??"en")}`),w.length>0&&d({kind:"link",lines:w})}catch{}},[e,s,d]),ae=V(async(l,i)=>{dn(!0),ue(null),B([]),De(null),Eo(null),Lo(null);let a=++ft.current;i?.quietUser||d({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let g=Ee.current;g.firstPrompt||(g.firstPrompt=i?.display??l),Je.current=Date.now(),mt(0),I(!0),mn.current.clear();let c="",m=!1,w=!1,y="",R={num:0,closed:!1,cueSeen:!1},S=null,K=()=>{S||(S=setTimeout(()=>{S=null,h(y.length>0?y:null)},60))},q=()=>{S&&clearTimeout(S),S=null,h(null)},L=()=>{if(y.trim()){let v=ps(y.trimEnd(),R);d({kind:"assistant",text:v})}y="",q()};try{for await(let v of be.current.send(l))if(v.type==="session"){if(!g.uuid){g.uuid=v.sessionId;let j=new Date().toISOString(),U=To.current,X=U??Hf(g.firstPrompt??"session");qf({uuid:v.sessionId,name:X,renamed:!!U,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:j,updatedAt:j}),Qe(X),To.current=null}}else if(v.type==="text"){y+=v.delta,c+=v.delta;let j=Rl(y);if(j>0){let U=y.slice(0,j).trimEnd();U&&d({kind:"assistant",text:ps(U,R)}),y=y.slice(j)}K(),mt(U=>U+v.delta.length)}else if(v.type==="tool"){m=!0;let j=ro(v.name,v.input);j&&(L(),d({kind:"tool",title:j.title,sep:j.sep,arg:j.arg}),mn.current.set(v.id,{name:v.name,input:v.input}))}else if(v.type==="article_diff"){let j=ct(v.oldContent,v.newContent,qe());j&&(L(),d({kind:"diff",added:j.added,removed:j.removed,lines:j.lines,hidden:j.hidden}))}else if(v.type==="tool_result"){v.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(v.output)&&(gn.current=!0);let j=mn.current.get(v.id);if(j){mn.current.delete(v.id),L();let U=so(v.output,4,v.isError?void 0:j.name,j.input);d({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:v.isError}),v.isError||Us(j.name,j.input,v.output)}}else if(v.type==="result"){if(L(),Ct(U=>U+v.outputTokens),Pt(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&&!c.trim()&&!Wt.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(c))try{let U=cm(e);if(ze(U)){let X=ys(U,"utf8").trim();X&&(Lo(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 j=v.ok?pl(c,fo.map(U=>U.name)):[];if(j.length>0?B(j):v.ok&&c.trim()&&Vf(l,c,e).then(U=>{U&&ft.current===a&&ue(U)}).catch(()=>{}),g.uuid&&(ks(g.uuid),!g.titleFired)){g.titleFired=!0;let U=g.uuid,X=g.firstPrompt;X&&Sl(X,e).then(we=>{we&&(Ff(U,we),Qe(we))}).catch(()=>{})}}else v.type==="error"&&(L(),w=!0,v.kind==="auth"&&(gn.current=!0),d({kind:"note",text:`agent error: ${v.message}`,tone:"error"}))}finally{I(!1),q(),ne(v=>v+1),Ee.current.uuid&&rl(e,Ee.current.uuid,wt.current),gn.current&&(gn.current=!1,wn.current=i?.display??l,B(["/login"])),Wt.current&&(Wt.current=!1,rt.current.length>0&&(d({kind:"note",tone:"info",text:`(${rt.current.length} queued message(s) discarded)`}),rt.current=[],So([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Us,qe]),xn=V(async l=>{let i=bs(l),a=ko(e,"standard");Je.current=Date.now(),mt(0),I(!0);let g=new AbortController;ve.current=g,ee({verb:"Publishing",total:i.length,done:0,active:[],rows:ln(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${tn} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let c of yo({cwd:e,partitions:i,promptFor:m=>Bn(m.paths),concurrency:tn,profileName:s,allowProdWrites:yt.current,model:a.model,signal:g.signal}))if(c.type==="partition_status")c.status==="running"?ee(m=>m&&{...m,active:[...m.active,c.label],rows:Le(m.rows,c.label,"active"),lastAt:Date.now()}):ee(m=>m&&{...m,active:m.active.filter(w=>w!==c.label),done:m.done+1,rows:Le(m.rows,c.label,c.status==="done"?"done":"failed"),lastAt:Date.now()});else if(c.type==="partition_event")ee(m=>{if(!m)return m;let w={...m,lastAt:Date.now()};return c.event.type==="tool"?w.tools=m.tools+1:c.event.type==="text"&&(w.chars=m.chars+c.event.delta.length),w});else if(c.type==="run_done"){Pt(R=>R+c.totalCostUsd),Ct(R=>R+c.results.reduce((S,K)=>S+K.outputTokens,0));let m=c.aborted?"Stopped. ":"",w=t.kind==="api"?"api":"subscription";d({kind:"note",tone:c.aborted?"warn":c.ok?"ok":"warn",text:m+pr(c.results,i,w).join(`
|
|
277
|
+
`)});let y=dr(e,s);y&&d({kind:"note",tone:"info",text:y})}}catch(c){d({kind:"note",tone:"error",text:`Publish run failed: ${c.message}`})}finally{ve.current=null,ee(null),I(!1),ne(c=>c+1)}},[e,s,d,t]),Fo=V(async l=>{await ae(ur(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await Gn(e,s,l.replace(/\\/g,"/"));i.length>0&&(De(`Related articles not yet published (${i.length}):`),B([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ae]),Ho=V(l=>{let i=Xe(l);if(!i||Ue(i)&&!i.refreshToken)return null;let a={...Ot(i.idToken)??{},...Ot(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),qo=V((l,i)=>{if(i){let a=Z(e);a&&(a.defaultProfile=l,Dl(a,e))}u(l),ge(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Ho(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),B(["/login"])),ne(a=>a+1)},[e,d,ge,Ho]),$n=V((l,i,a)=>{Sn(e,l,i,a.id,a.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),ge(),xo(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:Et(At(e)).join(`
|
|
278
|
+
`)}),Rt(at()),qt.current=_e(e).status==="current"||Jt(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,ge,Rt]),vn=V(async l=>{let i;try{i=await zt(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),B(["/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(c=>(c.workspace_type??"").toLowerCase()!=="apidocumentation"),g=a.length>0?a:i.workspaces;if(g.length===1){let c=g[0],m=i.workspaces.length-g.length;d({kind:"note",tone:"ok",text:`Selected the "${c.name??c.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),$n(i.profile,i.projectId,c);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),B(["/workspace"])},[e,d,$n]),Cn=V((l,i)=>{Vo(e,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),ge(),vn(l)},[e,d,ge,vn]),Ws=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 it(e,i.name),g=a.find(c=>c.id===i.project.projectId);g?.name&&dm(e,i.name,{projectName:g.name})}catch{}await vn(i.name);return}try{let{projects:a}=await it(e,i.name);if(a.length===1){let g=a[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),Cn(i.name,{id:g.id,name:g.name});return}if(a.length>1){let g=a.map(c=>({id:c.id,name:c.name??c.id,sub:c.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),tt({cursor:0,current:-1,rows:g,profile:i.name,environment:i.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),B(["/project"])}},[e,d,vn,Cn]),Pn=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=ct(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]),Fs=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{zf({cwd:e,profileName:s},a),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Fe.current.length===0&&B(g=>g.length>0?g:["/pull"])}catch(g){d({kind:"note",tone:"error",text:`Pull failed: ${g.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 Pn(),!0},[e,s,Pn,d]),Hs=V(l=>{let i=Ro.current;if(!i)return!1;if(Ro.current=null,ue(null),ft.current++,l.trim()!==i.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:g}=ss(e,i.targets);d({kind:"note",tone:g.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 c of g)d({kind:"note",tone:"error",text:` \u2717 ${c.path}: ${c.error}`});return i.hadDevhints&&(d({kind:"note",tone:"warn",text:Wn().join(`
|
|
279
279
|
`)}),Rt(Zo())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
280
|
-
${Nl}`}),
|
|
280
|
+
${Nl}`}),B(["/init"]),dn(!1),!0},[e,d,Rt]),qs=V(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),g=i.slice(1);switch(dn(!0),a){case"help":Ht({tab:0});return;case"exit":case"quit":be.current?.close(),r();return;case"clear":ge(),wt.current=[],dn(!1),ue(null),ft.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let c;try{c=de(e,s)}catch(m){d({kind:"note",tone:"error",text:m.message});return}d({kind:"note",tone:"info",text:`Profile "${c.name}" \u2192 ${c.connection.name} (${c.connection.apiUrl})${c.production?" \u26A0 PRODUCTION":""}`}),Q(!0);try{let m=await If(c.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=Nf(c.name,m);if(_f(w),await zo(w,c.name,y=>d({kind:"note",tone:"info",text:y})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${c.name}" as ${jn(w)}`}),await Ws(s),Ft.current){let y=Ft.current;Ft.current=null;let R=Me(e,s);R.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${y}.`}),B([y])):(d({kind:"note",tone:"warn",text:`${R.reason} (then ${y}.)`}),B(["/login"]),Ft.current=y)}else wn.current&&(ue(wn.current),wn.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{Q(!1),ne(m=>m+1)}return}case"allow-prod":{let c=!1;try{c=de(e,s).production}catch{}if(!c){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}yt.current=!0,ge(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let c=Fr(g.join(" ")),m=Ee.current.uuid;if(!m){if(!c){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}To.current=c,Qe(c),Lt(`${po} ${c}`),d({kind:"note",tone:"ok",text:`Session will be named "${c}" once it starts.`});return}if(!c){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Ee.current.firstPrompt??"";Sl(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}Yf(m,c),Qe(c),Lt(`${po} ${c}`),d({kind:"note",tone:"ok",text:`Session renamed to "${c}".`});return}case"profile":{let c=g[0],m=Z(e);if(!c){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,q])=>({name:K,env:q.connection?.environment??"custom",prod:q.production===!0,who:Ho(K)})),R=s??m?.defaultProfile,S=Math.max(0,y.findIndex(K=>K.name===R));kt({cursor:S,current:S,rows:y});return}if(c==="add"){let w=Hr(e,g[1],g[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),qo(g[1],!1);return}if(!m?.profiles?.[c]){d({kind:"note",tone:"error",text:`Unknown profile "${c}". Create it: /profile add ${c} <environment>`});return}qo(c,!0);return}case"doctor":await sn(g,{cwd:e});return;case"mcp":await Hn(g);return;case"init":{if(Z(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer.json directly (or d360-writer init for the CLI wizard)."});return}let c=tm().map(m=>({name:m,apiUrl:nm(m).apiUrl}));bt({cursor:0,rows:c});return}case"resume":{let c=g.join(" ").trim(),m=Gf(e).filter(R=>R.uuid!==Ee.current.uuid);if(!c){if(!m.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}st({query:"",cursor:0,sessions:m});return}let w=Bf(e,c);if(!w){d({kind:"note",tone:"error",text:`No session matches "${c}".`});return}ge(w.uuid),Ee.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},Qe(w.name),ks(w.uuid),wt.current=[];let y=fs(e,w.uuid);for(let R of y)d(R);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 c=g.join(" ").trim(),m;try{m=await zt(e,s)}catch(y){d({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!c){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 R=Math.max(0,y.findIndex(S=>S.id===m.current));xt({cursor:R,current:R,rows:y,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let w=Yo(m.workspaces,c);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${c}".`});return}$n(m.profile,m.projectId,w);return}case"project":{let c=g.join(" ").trim(),m;try{m=await it(e,s)}catch(y){d({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!c){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 R=y.findIndex(S=>S.id===m.current);tt({cursor:Math.max(0,R),current:R,rows:y,profile:m.profile,environment:m.environment});return}let w=Qs(m.projects,c);if(!w){d({kind:"note",tone:"error",text:`No project matches "${c}". Available: ${m.projects.map(y=>y.name??y.id).join(", ")}`});return}Cn(m.profile,w);return}case"logout":{let c;try{c=de(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let m=Uf(c);Wf(e,c),ge(),ne(w=>w+1),d({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${c}" and cleared its project/workspace selection.`:`Profile "${c}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),B(["/login"]);return}case"publish":{if(!_o(l.trim()))return;if(g[0]==="--related"&&g[1]){let m=await Gn(e,s,g[1].replace(/\\/g,"/"));if(m.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await xn(m);return}if(g[0]&&g[0]!=="--all"){await Fo(g[0]);return}let c=g[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await jl({cwd:e,profileName:s}),w=nn(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 R=m.counts["unknown-base"]??0;R>0&&d({kind:"note",tone:"info",text:`(${R} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(c){await xn(w.map(R=>R.path));return}$t({cursor:0,rows:Hi(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 c=g.join(" ").trim();if(!c){let w=[];try{w=Object.keys(xo(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}ot({query:"",cursor:0,paths:w});return}let m=Af(c)?c:pt(e,c);if(ze(m)){try{d({kind:"preview",name:cn(m),text:Ml(ys(m,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${m}: ${w.message}`})}return}if(ym.test(c)){try{let w=de(e,s),y={profile:w.name,connection:w.connection},R=w.project.projectId??Lf(y),S=await Of(y,R,c);d({kind:"preview",name:S.title??c,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:`"${c}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let c=g[0]?.trim();if(!c){let R=Kn(vs(e));et({cursor:R,current:R});return}let{lines:m,changed:w,effective:y}=rn(e,c);for(let R of m)d({kind:"note",tone:R.startsWith("\u26A0")?"warn":R.startsWith("\u2713")?"ok":"info",text:R});w&&(_s(R=>R+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:c,run:m}=kr(g),w=sm(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=br(w,c);if(y.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${c}". (${w.length} are tracked overall.)`});return}let R=bs(y),S=3,K=`/convert${c?` --scope ${c}`:""} --run`,q=ko(e,"light");if(!m){let v=El({files:xr(e,y),op:"convert",model:q.model}),j=c?`Scope: ${c} (${y.length} of ${w.length} tracked)
|
|
281
281
|
`:"",U=`
|
|
282
282
|
Model: ${q.model}${q.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:j+vr(R,v,S).join(`
|
|
283
|
-
`)+U}),
|
|
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 c=Il(e);if(c.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:
|
|
283
|
+
`)+U}),B([K]);return}Je.current=Date.now(),mt(0),I(!0);let L=new AbortController;ve.current=L,ee({verb:"Converting",total:R.length,done:0,active:[],rows:ln(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${y.length} articles across ${R.length} partitions (\u2264${S} agents at once) on ${q.model}\u2026 (esc to stop)`});try{for await(let v of yo({cwd:e,partitions:R,promptFor:$r,concurrency:S,profileName:s,allowProdWrites:yt.current,model:q.model,signal:L.signal}))if(v.type==="partition_status")v.status==="running"?ee(j=>j&&{...j,active:[...j.active,v.label],rows:Le(j.rows,v.label,"active"),lastAt:Date.now()}):ee(j=>j&&{...j,active:j.active.filter(U=>U!==v.label),done:j.done+1,rows:Le(j.rows,v.label,v.status==="done"?"done":"failed"),lastAt:Date.now()});else if(v.type==="partition_event")ee(j=>{if(!j)return j;let U={...j,lastAt:Date.now()};return v.event.type==="tool"?U.tools=j.tools+1:v.event.type==="text"&&(U.chars=j.chars+v.event.delta.length),U});else if(v.type==="run_done"){Pt(X=>X+v.totalCostUsd),Ct(X=>X+v.results.reduce((we,St)=>we+St.outputTokens,0));let j=v.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";d({kind:"note",tone:v.aborted?"warn":v.ok?"ok":"warn",text:j+Cr(v.results,R,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 c=Il(e);if(c.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:R,rewrite:S}=Rr(g),{docsDir:K,targets:q,reason:L,rewriting:v}=Ir(e,c,{scope:m,path:w,rewrite:S});if(q.length===0){d({kind:"note",tone:"warn",text:L??"Nothing to write."});return}v&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${q.length} already-written article${q.length===1?"":"s"} (overwrites them; git has your baseline).`});let j=bs(q),U=Pr(R),X=ko(e,"standard"),we=!!w;if(y&&!we){let Y=El({files:Sr(e,c,q),op:"write",model:X.model}),te=m?`Scope: ${m} (${q.length} pending)
|
|
285
285
|
`:"",ce=`
|
|
286
|
-
Model: ${X.model}${X.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:te+jr(j,
|
|
287
|
-
`)+ce}),
|
|
288
|
-
`)}),!
|
|
286
|
+
Model: ${X.model}${X.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:te+jr(j,Y,U).join(`
|
|
287
|
+
`)+ce}),B([`/write${m?` --scope ${m}`:""}`]);return}Je.current=Date.now(),mt(0),I(!0);let St=new AbortController;ve.current=St,ee({verb:"Writing",total:j.length,done:0,active:[],rows:ln(j),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${q.length} article${q.length===1?"":"s"} across ${j.length} partition${j.length===1?"":"s"} (\u2264${U} agents at once) on ${X.model}${X.forced?" (forced)":""}\u2026 (esc to stop)`});let Vs=new Set;try{for await(let Y of yo({cwd:e,partitions:j,promptFor:te=>Dr(te,K,{rewrite:v||we}),concurrency:U,profileName:s,allowProdWrites:yt.current,model:X.model,signal:St.signal}))if(Y.type==="partition_status")Y.status==="running"?ee(te=>te&&{...te,active:[...te.active,Y.label],rows:Le(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:Le(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=ml(Y.event.name,Y.event.input,j[Y.index]?.paths??[]);ce&&!Vs.has(ce)&&(Vs.add(ce),te=Y.label)}ee(ce=>{if(!ce)return ce;let ye={...ce,lastAt:Date.now()};return Y.event.type==="tool"?ye.tools=ce.tools+1:Y.event.type==="text"&&(ye.chars=ce.chars+Y.event.delta.length),te&&(ye.rows=fl(ye.rows,te)),ye})}else if(Y.type==="run_done"){Pt(ye=>ye+Y.totalCostUsd),Ct(ye=>ye+Y.results.reduce((tc,nc)=>tc+nc.outputTokens,0));let te=Y.aborted?"Stopped. ":"",ce=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:Y.aborted?"warn":Y.ok?"ok":"warn",text:te+Ar(Y.results,j,ce).join(`
|
|
288
|
+
`)}),!Y.aborted){let ye=Er(e,K,q);ye&&d({kind:"note",tone:"warn",text:ye})}!Y.aborted&&Y.ok&&B(["/publish --all","/screenshot --all"])}}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:c,looseDocs:m}=Nr(e);if(c.length===0&&m===0){d({kind:"note",tone:"info",text:Mr});return}let w=g.join(" ").trim();if(!w&&c.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
289
289
|
${c.map(S=>` \u2022 ${S.name} (${S.docCount} doc${S.docCount===1?"":"s"})`).join(`
|
|
290
|
-
`)}`}),
|
|
291
|
-
`)});return}if(c==="--baseline"){let
|
|
290
|
+
`)}`}),B(c.map(S=>`/draft ${S.name}`));return}let y="",R;if(w){let S=_r(c,w);S?y=S:R=w}else y=c[0]?.name??"";await ae(Xn(y,R),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!_o(l.trim()))return;let c=g.find(m=>m.startsWith("--"));try{if(c==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let y=Date.now(),R=await jl({cwd:e,profileName:s});d({kind:"note",tone:"info",text:Vn(R,Date.now()-y).join(`
|
|
291
|
+
`)});return}if(c==="--baseline"){let y=g.find(q=>!q.startsWith("--")),R=y?y.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:R?`Setting the sync baseline for ${R}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let S=await Qf({cwd:e,profileName:s,relPaths:R?[R]:void 0}),K=R?{rebaselined:[],skipped:[]}:await Zf({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(q=>` - ${q.path} (${q.reason})`).join(`
|
|
293
|
-
`)}`}),ne(q=>q+1);return}if(c==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let
|
|
294
|
-
`)});return}if(c){d({kind:"note",tone:"error",text:`Unknown option: ${c} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=g[0];if(m){let
|
|
293
|
+
`)}`}),ne(q=>q+1);return}if(c==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let y=await Kf({cwd:e,profileName:s}),R=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}`];R?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:R?"ok":"warn",text:S.join(`
|
|
294
|
+
`)});return}if(c){d({kind:"note",tone:"error",text:`Unknown option: ${c} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=g[0];if(m){let y=await Jf({cwd:e,profileName:s,relPath:m.replace(/\\/g,"/")});Fe.current=[y],Pn();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let w=await gr({cwd:e,profileName:s});for(let y of wr(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 c=em(e);if(c.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}vt({cursor:0,rows:c.map(m=>({...m,checked:m.recommended}))});return}case"audit":{if(g[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=g[1]!=="off";Dl({...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 c=await on();c.kind==="forward-to-agent"&&c.prompt&&await ae(c.prompt,{display:c.display,quietUser:!0});return}case"check":{let c=Al({cwd:e});if(g.includes("--fix")){if(c.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 ${c.length} doc issue${c.length===1?"":"s"}\u2026`}),await ae(as(c),{display:"/check --fix",quietUser:!0});let m=Al({cwd:e});d({kind:"note",tone:m.length===0?"ok":"warn",text:m.length===0?"\u2713 Doc-checker: all issues resolved.":oo(m).join(`
|
|
295
295
|
`)});return}d({kind:"note",tone:c.length===0?"ok":"warn",text:oo(c).join(`
|
|
296
|
-
`)});return}case"review":{let c=ls(e,g);if(!c){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ae(c.prompt,{display:c.display,quietUser:!0});return}case"capture-setup":{let c=await an();c.kind==="forward-to-agent"&&c.prompt&&await ae(c.prompt,{display:c.display,quietUser:!0});let m=zr(e);m&&d({kind:"note",tone:"info",text:m.join(`
|
|
296
|
+
`)}),c.length>0&&(B(["/check --fix","/review","/publish --all"]),De(`${c.length} doc issue${c.length===1?"":"s"} found \u2014 fix them:`));return}case"review":{let c=ls(e,g);if(!c){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=g.includes("--fix");if(await ae(c.prompt,{display:c.display,quietUser:!0}),m)B(["/check","/publish --all"]),De("Fixes applied \u2014 re-check, then publish:");else{let w=g.filter(y=>y!=="--fix").join(" ");B([`/review${w?` ${w}`:""} --fix`,"/check --fix","/publish --all"]),De("Apply the review's fixes (or publish as-is):")}return}case"capture-setup":{let c=await an();c.kind==="forward-to-agent"&&c.prompt&&await ae(c.prompt,{display:c.display,quietUser:!0});let m=zr(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:Et(At(e)).join(`
|
|
298
|
-
`)}),Rt(at()),qt.current=
|
|
299
|
-
`)});return}if(c.mode==="single"){let L=await Qn(g);L.kind==="forward-to-agent"&&L.prompt&&await ae(L.prompt,{display:L.display,quietUser:!0});return}if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=c.mode==="scope"?c.scope:void 0,w=rm(e,{scope:m}).map(L=>L.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
|
|
300
|
-
`)})}return}case"reset":{let c=rs(e);if(c.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Ro.current={repoName:cn(e),targets:c,hadDevhints:
|
|
301
|
-
`)}),ue(cn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,Pn,d,ge,ae,xn,Fo,Ws]),Rn=V(l=>{let i=(l??D).trim();if(k(""),fn(null),ht(0),i.startsWith("/")&&(ue(null),ft.current++,nt(null),Y(g=>gl(g,i))),!i||Hs(i)||Fs(i))return;Po.current.push(i);let a=xl(i,Ds.current);i.startsWith("/")?(d({kind:"user",text:i}),qs(a)):ae(a,{display:i})},[D,Hs,Fs,qs,ae]),Bs=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=yl(l);if(kl(i)){let a=bl(++Kl.current,i);Ds.current.set(a,i),P(a)}else P(i);return}P(l)},[P]),Tt=Math.max(10,Ie-6),Gs=ws(()=>go(y.text,Tt),[y.text,Tt]),Bo=V(l=>x(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),Tn=V(l=>x(i=>({...i,pos:vl(go(i.text,Tt),i.pos,l)})),[Tt]),Yt=V(l=>x(i=>({...i,pos:Cl(go(i.text,Tt),i.pos,l)})),[Tt]),Zl=["\x1B[H","\x1B[1~","\x1BOH"],ec=["\x1B[F","\x1B[4~","\x1BOF"],Ys=V((l,i)=>i.leftArrow?(Bo(-1),!0):i.rightArrow?(Bo(1),!0):l&&Zl.includes(l)?(Yt("start"),!0):l&&ec.includes(l)?(Yt("end"),!0):i.ctrl&&l==="a"?(Yt("start"),!0):i.ctrl&&l==="e"?(Yt("end"),!0):!1,[Bo,Yt]);return Sf((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=(hn?.verb??"work").toLowerCase(),g=hn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${g}s)\u2026`}),ve.current.abort()}return}Wt.current||(Wt.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;rt.current.push(a),So([...rt.current]),k("");return}if(Ys(l,i))return;if(i.upArrow){Tn(-1);return}if(i.downArrow){Tn(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&Bs(l);return}if(Qe){if(i.upArrow){Ze(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ze(a=>a&&{...a,cursor:Math.min(je.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=je.length){Ze(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=je[Qe.cursor];Ze(null);let{lines:g,changed:c,effective:m}=rn(e,a.value??"default");for(let w of g)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});c&&(_s(w=>w+1),be.current?.setModel(m));return}if(l==="s"){let a=je[Qe.cursor];Ze(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){Ze(null);return}return}if(Ee){if(i.upArrow){kt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){kt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ee.rows.length){kt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=Ee.rows[Ee.cursor];kt(null),qo(a.name,i.return===!0);return}if(i.escape){kt(null);return}return}if(Do){if(i.escape){Ht(null);return}if(i.leftArrow||i.tab&&i.shift){Ht(a=>a&&{tab:(a.tab-1+Re.length)%Re.length});return}if(i.rightArrow||i.tab){Ht(a=>a&&{tab:(a.tab+1)%Re.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.length){Ht({tab:Number(l)-1});return}return}if(Fe){if(i.upArrow){bt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){bt(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){bt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Fe.rows[Fe.cursor].name;if(bt(null),!Ti(e,a).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${a}").`});let c=!1;try{let m=ze(a);c=!!m&&!(Oe(m)&&!m.refreshToken)}catch{c=!1}d({kind:"note",tone:"info",text:c?`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)`}),Y(["/login"]),ne(m=>m+1);return}if(i.escape){bt(null);return}return}if(fe){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)<=fe.rows.length){xt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=fe.rows[fe.cursor],{profile:g,projectId:c}=fe;xt(null),$n(g,c,a);return}if(i.escape){xt(null);return}return}if(xe){if(i.upArrow){et(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){et(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){et(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=xe.rows[xe.cursor],{profile:g}=xe;et(null),Cn(g,a);return}if(i.escape){et(null);return}return}if(he){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===" "){vt(a=>a&&{...a,rows:a.rows.map((g,c)=>c===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=he.rows.filter(g=>g.checked).map(g=>g.path);if(vt(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}fr(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer.json`});for(let g of a)d({kind:"note",tone:"info",text:` ${g}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){vt(null);return}return}if(tt){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)<=tt.rows.length){$t(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=tt.rows[tt.cursor];$t(null),a.kind==="article"?Fo(a.paths[0]):xn(a.paths);return}if(i.escape){$t(null);return}return}if($e){if(i.escape){ot(null);return}if(i.upArrow){ot(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){ot(a=>a&&{...a,cursor:Math.min(Math.max(0,kn.length-1),a.cursor+1)});return}if(i.return){let a=kn[$e.cursor];if(a){ot(null);try{d({kind:"preview",name:cn(a),text:Ml(ys(pt(e,a),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){ot(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){ot(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(Ce){if(i.escape){st(null);return}if(i.upArrow){st(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){st(a=>a&&{...a,cursor:Math.min(Math.max(0,bn.length-1),a.cursor+1)});return}if(i.return){let a=bn[Ce.cursor];if(a){st(null),ge(a.uuid),Ae.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Je(a.name),ks(a.uuid),wt.current=[];let g=fs(e,a.uuid);for(let c of g)d(c);d({kind:"note",tone:"ok",text:g.length?`Resumed "${a.name}" \u2014 restored ${g.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){st(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){st(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!D&&Se){k(Se),ue(null),ft.current++;return}if(!D&&Xe.length>0&&l&&/^[1-9]$/.test(l)){let a=Xe[Number(l)-1];if(a){k(a);return}}if(!D&&(Mo||Ao)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=Mo!=null;el(Mo??Ao).then(c=>{d({kind:"note",tone:c?"ok":"warn",text:c?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."}),c&&a&&Lo(null)});return}if(!Ys(l,i)){if(Os){if(i.upArrow){ht(a=>Math.max(0,a-1));return}if(i.downArrow){ht(a=>Math.min(Gt.length-1,a+1));return}if(i.tab){k("/"+(Gt[Ut]?.name??"")+" "),ht(0);return}if(i.return){let a=Gt[Ut];if(a){let g=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(cl(a.usage)&&!g){k("/"+a.name+" "),ht(0);return}Rn("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(D!==""&>===null){Tn(-1);return}let a=Po.current;if(!a.length)return;let g=gt===null?a.length-1:Math.max(0,gt-1);fn(g),k(a[g]??"");return}if(i.downArrow){if(D!==""&>===null){Tn(1);return}let a=Po.current;if(gt===null)return;let g=gt+1;g>=a.length?(fn(null),k("")):(fn(g),k(a[g]??""));return}}if(i.return){Rn();return}if(i.backspace||i.delete){C();return}if(i.escape){k(""),ht(0),ue(null),Y([]),nt(null);return}l&&!i.ctrl&&!i.meta&&Bs(l)}}}),Te(()=>{if(N||O)return;let l=rt.current.shift();l!==void 0&&(So([...rt.current]),Rn(l))},[N,O,Rn]),B(oe,{flexDirection:"column",width:Ie,children:[Wo!==null&&B(oe,{marginTop:1,flexDirection:"column",children:[Wo.truncated&&E(T,{dimColor:!0,children:"\u2026"}),E(T,{children:Wo.text})]}),N&&(hn?E(xm,{p:hn}):E(km,{startTime:Ke.current,chars:Xl})),E(oe,{borderStyle:"round",borderColor:Ls.prod?"yellow":F,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?Gs.map((l,i)=>{let a=y.text.slice(l.start,l.end),g=i===wo(Gs,y.pos),c=Math.min(y.pos,l.end)-l.start;return B(T,{children:[E(T,{color:F,children:i===0?"> ":" "}),g?B(xs,{children:[a.slice(0,c),E(bo,{ch:a[c]??" "}),a.slice(c+1)]}):a||" "]},`${i}-${l.start}`)}):B(T,{children:[E(T,{color:F,children:"> "}),Se&&!N?B(xs,{children:[E(bo,{ch:Se[0],dim:!0}),E(T,{color:"gray",children:Se.slice(1)}),E(T,{dimColor:!0,children:" (tab)"})]}):(Uo.isSetup||!Vl)&&!N?B(xs,{children:[E(bo,{ch:Uo.text[0],dim:!0}),E(T,{color:"gray",children:Uo.text.slice(1)})]}):E(bo,{ch:" "})]})}),Es.length>0&&E(oe,{flexDirection:"column",paddingX:1,children:Es.map((l,i)=>E(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Do?E(dl,{tab:Do.tab,width:Ie}):Qe?B(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.json still wins)."}),je.map((l,i)=>B(T,{color:i===Qe.cursor?F:void 0,children:[i===Qe.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===Qe.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"})]}):Ee?B(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Switch connection profile"}),Ee.rows.map((l,i)=>B(T,{color:i===Ee.cursor?F:void 0,children:[i===Ee.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===Ee.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"})]}):Fe?B(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Pick your Document360 environment"}),Fe.rows.map((l,i)=>B(T,{color:i===Fe.cursor?F:void 0,children:[i===Fe.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?B(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)=>B(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?B(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)=>B(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"})]}):he?(()=>{let i=Math.min(Math.max(0,he.cursor-Math.floor(7)),Math.max(0,he.rows.length-14)),a=he.rows.slice(i,i+14),g=he.rows.filter(c=>c.checked).length;return B(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Which folders back the user docs? (${g} selected of ${he.rows.length})`}),i>0?E(T,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((c,m)=>{let w=i+m;return B(T,{color:w===he.cursor?F:void 0,children:[w===he.cursor?"\u276F ":" ",c.checked?"\u25C9 ":"\u25CB ",c.path.padEnd(Math.min(48,Ie-34)),E(T,{color:"gray",children:Yn(c)})]},c.path)}),i+14<he.rows.length?E(T,{dimColor:!0,children:` \u2193 ${he.rows.length-i-14} more`}):null,E(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():tt?B(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),tt.rows.map((l,i)=>{let a=i===tt.cursor,g=l.indent?" ":" ",c=`${i+1}.`.padEnd(3);return B(T,{color:a?F:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${c} ${l.label}`.padEnd(Math.min(56,Ie-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?B(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Preview article${$e.query?` \u2014 filter: ${$e.query}`:" (type to filter)"}`}),kn.length===0?E(T,{color:"gray",children:"no articles match"}):kn.map((l,i)=>B(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?B(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Resume session${Ce.query?` \u2014 filter: ${Ce.query}`:" (type to filter)"}`}),bn.length===0?E(T,{color:"gray",children:"no sessions match"}):bn.map((l,i)=>B(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,Ie-40))})]},l.uuid)),E(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Os?B(oe,{flexDirection:"column",children:[Gt.map((l,i)=>B(T,{color:i===Ut?F:void 0,children:[i===Ut?"\u276F ":" ",l.usage.padEnd(22)," ",E(T,{color:i===Ut?F:"gray",children:l.name==="model"&&jo?`${l.desc} (currently ${jo})`:l.desc})]},l.name)),E(T,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!D&&Xe.length>0?B(oe,{flexDirection:"column",paddingX:1,children:[As?E(T,{color:F,children:As}):null,Xe.map((l,i)=>{let a=l.slice(0,Math.max(20,Ie-5)),g=Ie-a.length-7,c=g>=12?al(l).slice(0,g):"";return B(T,{children:[E(T,{color:F,children:i+1})," ",a,c?E(T,{dimColor:!0,children:` \u2014 ${c}`}):null]},l)}),E(T,{dimColor:!0,children:`press 1-${Xe.length} to fill the command \xB7 esc dismiss`})]}):E(oe,{paddingX:1,children:B(T,{color:"gray",children:[Ls.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${jo??"model n/a"}${t.kind==="api"?Ns>0?` \xB7 ${me(Ns)}`:"":Is>0?` \xB7 ${Ge(Is)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Pm}from"react/jsx-runtime";async function Fl(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Cm(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}=vm(Pm(Wl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
298
|
+
`)}),Rt(at()),qt.current=_e(e).status==="current"||Jt(e);return}case"inbox":{if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Xr(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(Kr(),{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:c,what:m}=Or(g);if(!m&&Lr(e)===0){d({kind:"note",tone:"info",text:Wr});return}let w=`/document${m?` ${m}`:""}${c?" --publish":""}`;await ae(Ur(m,c),{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(!_o(l.trim()))return;let{publish:c}=Qr(g);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let m=await es({cwd:e,profileName:s});for(let y of ts(m))d({kind:"note",tone:y.startsWith("\u2713")?"ok":y.startsWith("\u2139")?"info":"warn",text:y});let w=Mt(_t(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(Zr({publish:c}),{display:`/catch-up${c?" --publish":""}`,quietUser:!0});return}case"update":{Io.current=!0,d({kind:"note",tone:"info",text:`Updating ${dt}\u2026 (don\u2019t close this window)`}),pn(!0),(await to().finally(()=>pn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),B(m=>m.includes("/exit")?m:[...m,"/exit"]),Ss("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${eo}`});return}case"screenshot":{let c=Gr(g);if(c.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:Vr(Yr(e,c.scope),c.scope).join(`
|
|
299
|
+
`)});return}if(c.mode==="single"){let L=await Qn(g);L.kind==="forward-to-agent"&&L.prompt&&await ae(L.prompt,{display:L.display,quietUser:!0});return}if(!Z(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=c.mode==="scope"?c.scope:void 0,w=rm(e,{scope:m}).map(L=>L.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,R=om(w,3),S=ko(e,"standard");Je.current=Date.now(),mt(0),I(!0);let K=new AbortController;ve.current=K,ee({verb:"Authoring",unit:"spec",total:R.length,done:0,active:[],rows:ln(R),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 ${R.length} partition${R.length===1?"":"s"} (\u2264${y} agents at once) on ${S.model}${S.forced?" (forced)":""}\u2026 (esc to stop)`});let q=!1;try{for await(let L of yo({cwd:e,partitions:R,promptFor:Aa,concurrency:y,profileName:s,allowProdWrites:yt.current,model:S.model,signal:K.signal}))if(L.type==="partition_status")L.status==="running"?ee(v=>v&&{...v,active:[...v.active,L.label],rows:Le(v.rows,L.label,"active"),lastAt:Date.now()}):ee(v=>v&&{...v,active:v.active.filter(j=>j!==L.label),done:v.done+1,rows:Le(v.rows,L.label,L.status==="done"?"done":"failed"),lastAt:Date.now()});else if(L.type==="partition_event")ee(v=>{if(!v)return v;let j={...v,lastAt:Date.now()};return L.event.type==="tool"?j.tools=v.tools+1:L.event.type==="text"&&(j.chars=v.chars+L.event.delta.length),j});else if(L.type==="run_done"){Pt(X=>X+L.totalCostUsd),Ct(X=>X+L.results.reduce((we,St)=>we+St.outputTokens,0));let v=L.results.filter(X=>X.ok).length,j=L.aborted?"Stopped. ":"";q=!L.aborted&&c.setup;let U=L.aborted?"":q?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:L.aborted?"warn":L.ok?"ok":"warn",text:`${j}Authored specs \u2014 ${v}/${L.results.length} batches ok.${U}`})}}catch(L){d({kind:"note",tone:"error",text:`Spec authoring failed: ${L.message}`})}finally{ve.current=null,ee(null),I(!1),ne(L=>L+1)}if(q){let L=await an();L.kind==="forward-to-agent"&&L.prompt&&await ae(L.prompt,{display:L.display,quietUser:!0});let v=zr(e);v&&d({kind:"note",tone:"info",text:v.join(`
|
|
300
|
+
`)})}return}case"reset":{let c=rs(e);if(c.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Ro.current={repoName:cn(e),targets:c,hadDevhints:ze(Cs(e))},d({kind:"note",tone:"warn",text:is(e,c).join(`
|
|
301
|
+
`)}),ue(cn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,Pn,d,ge,ae,xn,Fo,Ws]),Rn=V(l=>{let i=(l??D).trim();if(b(""),fn(null),ht(0),i.startsWith("/")&&(ue(null),ft.current++,De(null),B(g=>gl(g,i))),!i||Hs(i)||Fs(i))return;Po.current.push(i);let a=xl(i,Ds.current);i.startsWith("/")?(d({kind:"user",text:i}),qs(a)):ae(a,{display:i})},[D,Hs,Fs,qs,ae]),Bs=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=yl(l);if(kl(i)){let a=bl(++Kl.current,i);Ds.current.set(a,i),P(a)}else P(i);return}P(l)},[P]),Tt=Math.max(10,Ne-6),Gs=ws(()=>go(k.text,Tt),[k.text,Tt]),Bo=V(l=>x(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),Tn=V(l=>x(i=>({...i,pos:vl(go(i.text,Tt),i.pos,l)})),[Tt]),Yt=V(l=>x(i=>({...i,pos:Cl(go(i.text,Tt),i.pos,l)})),[Tt]),Zl=["\x1B[H","\x1B[1~","\x1BOH"],ec=["\x1B[F","\x1B[4~","\x1BOF"],Ys=V((l,i)=>i.leftArrow?(Bo(-1),!0):i.rightArrow?(Bo(1),!0):l&&Zl.includes(l)?(Yt("start"),!0):l&&ec.includes(l)?(Yt("end"),!0):i.ctrl&&l==="a"?(Yt("start"),!0):i.ctrl&&l==="e"?(Yt("end"),!0):!1,[Bo,Yt]);return Sf((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=(hn?.verb??"work").toLowerCase(),g=hn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${g}s)\u2026`}),ve.current.abort()}return}Wt.current||(Wt.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;rt.current.push(a),So([...rt.current]),b("");return}if(Ys(l,i))return;if(i.upArrow){Tn(-1);return}if(i.downArrow){Tn(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&Bs(l);return}if(Ze){if(i.upArrow){et(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){et(a=>a&&{...a,cursor:Math.min(Ae.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ae.length){et(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Ae[Ze.cursor];et(null);let{lines:g,changed:c,effective:m}=rn(e,a.value??"default");for(let w of g)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});c&&(_s(w=>w+1),be.current?.setModel(m));return}if(l==="s"){let a=Ae[Ze.cursor];et(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){et(null);return}return}if(Ie){if(i.upArrow){kt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){kt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ie.rows.length){kt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=Ie.rows[Ie.cursor];kt(null),qo(a.name,i.return===!0);return}if(i.escape){kt(null);return}return}if(Do){if(i.escape){Ht(null);return}if(i.leftArrow||i.tab&&i.shift){Ht(a=>a&&{tab:(a.tab-1+Re.length)%Re.length});return}if(i.rightArrow||i.tab){Ht(a=>a&&{tab:(a.tab+1)%Re.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.length){Ht({tab:Number(l)-1});return}return}if(He){if(i.upArrow){bt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){bt(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){bt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=He.rows[He.cursor].name;if(bt(null),!Ti(e,a).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${a}").`});let c=!1;try{let m=Xe(a);c=!!m&&!(Ue(m)&&!m.refreshToken)}catch{c=!1}d({kind:"note",tone:"info",text:c?`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)`}),B(["/login"]),ne(m=>m+1);return}if(i.escape){bt(null);return}return}if(fe){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)<=fe.rows.length){xt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=fe.rows[fe.cursor],{profile:g,projectId:c}=fe;xt(null),$n(g,c,a);return}if(i.escape){xt(null);return}return}if(xe){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(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=xe.rows.length){tt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=xe.rows[xe.cursor],{profile:g}=xe;tt(null),Cn(g,a);return}if(i.escape){tt(null);return}return}if(he){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===" "){vt(a=>a&&{...a,rows:a.rows.map((g,c)=>c===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=he.rows.filter(g=>g.checked).map(g=>g.path);if(vt(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}fr(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer.json`});for(let g of a)d({kind:"note",tone:"info",text:` ${g}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){vt(null);return}return}if(nt){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)<=nt.rows.length){$t(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=nt.rows[nt.cursor];$t(null),a.kind==="article"?Fo(a.paths[0]):xn(a.paths);return}if(i.escape){$t(null);return}return}if($e){if(i.escape){ot(null);return}if(i.upArrow){ot(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){ot(a=>a&&{...a,cursor:Math.min(Math.max(0,kn.length-1),a.cursor+1)});return}if(i.return){let a=kn[$e.cursor];if(a){ot(null);try{d({kind:"preview",name:cn(a),text:Ml(ys(pt(e,a),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){ot(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){ot(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(Ce){if(i.escape){st(null);return}if(i.upArrow){st(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){st(a=>a&&{...a,cursor:Math.min(Math.max(0,bn.length-1),a.cursor+1)});return}if(i.return){let a=bn[Ce.cursor];if(a){st(null),ge(a.uuid),Ee.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Qe(a.name),ks(a.uuid),wt.current=[];let g=fs(e,a.uuid);for(let c of g)d(c);d({kind:"note",tone:"ok",text:g.length?`Resumed "${a.name}" \u2014 restored ${g.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){st(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){st(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!D&&Se){b(Se),ue(null),ft.current++;return}if(!D&&Ke.length>0&&l&&/^[1-9]$/.test(l)){let a=Ke[Number(l)-1];if(a){b(a);return}}if(!D&&(Mo||Ao)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=Mo!=null;el(Mo??Ao).then(c=>{d({kind:"note",tone:c?"ok":"warn",text:c?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."}),c&&a&&Lo(null)});return}if(!Ys(l,i)){if(Os){if(i.upArrow){ht(a=>Math.max(0,a-1));return}if(i.downArrow){ht(a=>Math.min(Gt.length-1,a+1));return}if(i.tab){b("/"+(Gt[Ut]?.name??"")+" "),ht(0);return}if(i.return){let a=Gt[Ut];if(a){let g=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(cl(a.usage)&&!g){b("/"+a.name+" "),ht(0);return}Rn("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(D!==""&>===null){Tn(-1);return}let a=Po.current;if(!a.length)return;let g=gt===null?a.length-1:Math.max(0,gt-1);fn(g),b(a[g]??"");return}if(i.downArrow){if(D!==""&>===null){Tn(1);return}let a=Po.current;if(gt===null)return;let g=gt+1;g>=a.length?(fn(null),b("")):(fn(g),b(a[g]??""));return}}if(i.return){Rn();return}if(i.backspace||i.delete){C();return}if(i.escape){b(""),ht(0),ue(null),B([]),De(null);return}l&&!i.ctrl&&!i.meta&&Bs(l)}}}),Te(()=>{if(N||O)return;let l=rt.current.shift();l!==void 0&&(So([...rt.current]),Rn(l))},[N,O,Rn]),G(oe,{flexDirection:"column",width:Ne,children:[Wo!==null&&G(oe,{marginTop:1,flexDirection:"column",children:[Wo.truncated&&E(T,{dimColor:!0,children:"\u2026"}),E(T,{children:Wo.text})]}),N&&(hn?E(xm,{p:hn}):E(km,{startTime:Je.current,chars:Xl})),E(oe,{borderStyle:"round",borderColor:Ls.prod?"yellow":F,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?Gs.map((l,i)=>{let a=k.text.slice(l.start,l.end),g=i===wo(Gs,k.pos),c=Math.min(k.pos,l.end)-l.start;return G(T,{children:[E(T,{color:F,children:i===0?"> ":" "}),g?G(xs,{children:[a.slice(0,c),E(bo,{ch:a[c]??" "}),a.slice(c+1)]}):a||" "]},`${i}-${l.start}`)}):G(T,{children:[E(T,{color:F,children:"> "}),Se&&!N?G(xs,{children:[E(bo,{ch:Se[0],dim:!0}),E(T,{color:"gray",children:Se.slice(1)}),E(T,{dimColor:!0,children:" (tab)"})]}):(Uo.isSetup||!Vl)&&!N?G(xs,{children:[E(bo,{ch:Uo.text[0],dim:!0}),E(T,{color:"gray",children:Uo.text.slice(1)})]}):E(bo,{ch:" "})]})}),Es.length>0&&E(oe,{flexDirection:"column",paddingX:1,children:Es.map((l,i)=>E(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Do?E(dl,{tab:Do.tab,width:Ne}):Ze?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.json still wins)."}),Ae.map((l,i)=>G(T,{color:i===Ze.cursor?F:void 0,children:[i===Ze.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===Ze.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"})]}):Ie?G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Switch connection profile"}),Ie.rows.map((l,i)=>G(T,{color:i===Ie.cursor?F:void 0,children:[i===Ie.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===Ie.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"})]}):he?(()=>{let i=Math.min(Math.max(0,he.cursor-Math.floor(7)),Math.max(0,he.rows.length-14)),a=he.rows.slice(i,i+14),g=he.rows.filter(c=>c.checked).length;return G(oe,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Which folders back the user docs? (${g} selected of ${he.rows.length})`}),i>0?E(T,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((c,m)=>{let w=i+m;return G(T,{color:w===he.cursor?F:void 0,children:[w===he.cursor?"\u276F ":" ",c.checked?"\u25C9 ":"\u25CB ",c.path.padEnd(Math.min(48,Ne-34)),E(T,{color:"gray",children:Yn(c)})]},c.path)}),i+14<he.rows.length?E(T,{dimColor:!0,children:` \u2193 ${he.rows.length-i-14} more`}):null,E(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():nt?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:"}),nt.rows.map((l,i)=>{let a=i===nt.cursor,g=l.indent?" ":" ",c=`${i+1}.`.padEnd(3);return G(T,{color:a?F:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${c} ${l.label}`.padEnd(Math.min(56,Ne-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)"}`}),kn.length===0?E(T,{color:"gray",children:"no articles match"}):kn.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)"}`}),bn.length===0?E(T,{color:"gray",children:"no sessions match"}):bn.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,Ne-40))})]},l.uuid)),E(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Os?G(oe,{flexDirection:"column",children:[Gt.map((l,i)=>G(T,{color:i===Ut?F:void 0,children:[i===Ut?"\u276F ":" ",l.usage.padEnd(22)," ",E(T,{color:i===Ut?F:"gray",children:l.name==="model"&&jo?`${l.desc} (currently ${jo})`:l.desc})]},l.name)),E(T,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!D&&Ke.length>0?G(oe,{flexDirection:"column",paddingX:1,children:[As?E(T,{color:F,children:As}):null,Ke.map((l,i)=>{let a=l.slice(0,Math.max(20,Ne-5)),g=Ne-a.length-7,c=g>=12?al(l).slice(0,g):"";return G(T,{children:[E(T,{color:F,children:i+1})," ",a,c?E(T,{dimColor:!0,children:` \u2014 ${c}`}):null]},l)}),E(T,{dimColor:!0,children:`press 1-${Ke.length} to fill the command \xB7 esc dismiss`})]}):E(oe,{paddingX:1,children:G(T,{color:"gray",children:[Ls.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${jo??"model n/a"}${t.kind==="api"?Ns>0?` \xB7 ${me(Ns)}`:"":Is>0?` \xB7 ${Ye(Is)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Pm}from"react/jsx-runtime";async function Fl(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Cm(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}=vm(Pm(Wl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
302
302
|
`),process.exit(0)}W();import{writeCrashLog as Hl,isBenignTransportError as Rm}from"document360-engine";var ql=!1;function Ps(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Bl(e){if(ql)return;ql=!0;let t=(n,o)=>{if(Rm(o)){Hl({kind:n,level:"transport",message:Ps(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=Hl({kind:n,level:"fatal",message:Ps(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
303
303
|
`+$(`\u2717 d360-writer crashed: ${Ps(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 jm=Sm(import.meta.url),Gl=jm("../package.json");Bl("d360-writer");var
|
|
306
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var jm=Sm(import.meta.url),Gl=jm("../package.json");Bl("d360-writer");var We=new Tm;function Rs(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}We.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=>{Rs(e),await An({profile:e.profile,manual:e.manual})});We.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Rs(e),await si({profile:e.profile})});We.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Rs(e),await ri({profile:e.profile})});var Ts=We.command("profile").description("Manage connection profiles for the current repo");Ts.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>En(process.cwd()));Ts.command("use <name>").description("Set the default profile for this repo").action(e=>In(process.cwd(),e));Ts.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Nn(process.cwd(),e));var Yl=We.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Yl.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Dt(process.cwd(),e.profile));Yl.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Ks(process.cwd(),e,t.profile)});We.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>ci());We.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(()=>(Jn(),va)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});We.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Gl.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(Dm.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 ui(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 Qa(e.cwd,e.auth,e.profile):await Fl(e.cwd,e.auth,e.profile,Gl.version)});We.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|