document360-writer 0.5.37 → 0.5.38
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 +36 -35
- package/dist/commands/write.d.ts +7 -2
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Vl=Object.defineProperty;var qo=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var zl=(e,t)=>{for(var n in t)Vl(e,n,{get:t[n],enumerable:!0})};import He from"picocolors";var W,Kl,Xl,Jl,qs,Gt,f
|
|
2
|
+
var Vl=Object.defineProperty;var qo=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var zl=(e,t)=>{for(var n in t)Vl(e,n,{get:t[n],enumerable:!0})};import He from"picocolors";var W,Kl,Xl,Jl,qs,Gt,f,v,O,E,N,re,ve,F=qo(()=>{"use strict";W="#7f56d9",[Kl,Xl,Jl]=[127,86,217],qs=e=>He.isColorSupported?`\x1B[38;2;${Kl};${Xl};${Jl}m${e}\x1B[39m`:e,Gt=e=>He.bold(qs(e)),f=e=>He.dim(e),v=e=>He.red(e),O=e=>He.yellow(e),E=e=>He.green(e),N=qs,re=e=>He.gray(e),ve=e=>He.bold(e)});import{existsSync as Nn,writeFileSync as Kt,readFileSync as _c,readdirSync as Mc}from"node:fs";import{join as Oc}from"node:path";import{devHintsGuidePath as _n,hintsDir as li,architectureDir as di,messagesDir as Ko,creatorNotesPath as ci,devhintsStatePath as pi,ensureDir as In,writeMessage as Lc,listOpenForDev as Uc}from"document360-engine";function fi(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
4
|
<!-- devhints script v${oe} \xB7 maintained by document360-writer (/devhints). -->
|
|
5
5
|
|
|
@@ -178,17 +178,17 @@ Anything only a human knows that would help document this product. For example:
|
|
|
178
178
|
`)}function Xo(e){try{let t=_c(pi(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function hi(e,t){let o={...Xo(e)??{},emittedVersion:oe,emittedAt:t};Kt(pi(e),`${JSON.stringify(o,null,2)}
|
|
179
179
|
`)}function Xt(e){try{return Mc(di(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ie(e){let n=Xo(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<oe?"stale":"current",completedVersion:n}}function Mn(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:oe};try{if(!Nn(_n(e)))return n;let o=Xo(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;oe>r&&(In(Ko(e)),Kt(_n(e),fi()),hi(e,t),n.guideRefreshed=!0),oe>s&&(Uc(e).some(p=>p.kind==="request"&&p.subject.startsWith(ui))||(Lc(e,{id:`onb${oe}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${ui}${oe})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${oe}${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:","",it()].join(`
|
|
180
180
|
`)}),n.notifiedBuilder=!0))}catch{}return n}function On(e){if(!Nn(_n(e)))return[];let t=Ie(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${oe}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Dt,it(),Dt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Jo(){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 Ln(){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):",Dt,Jo(),Dt]}function At(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${oe}.`," 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):",Dt,it(),Dt,"","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 Dt,oe,ui,at=qo(()=>{"use strict";Dt="-".repeat(64),oe=5;ui="Re-run dev\u2194docs onboarding (protocol v"});var ya={};zl(ya,{doctorCommand:()=>rn,renderDoctorChecks:()=>wa,runDoctorChecks:()=>ga});import{existsSync as xd}from"node:fs";import{d360GetAll as $d,getAccessToken as vd,isExpired as Fr,loadProfileMap as Cd,loadTokens as Pd,packageSkillsDir as ma,projectConfigPath as Rd,readProjectConfig as Td,DEFAULT_DOCS_DIR as Sd,fetchManifestSummary as Dd,resolveActiveProfile as jd,classifyClaudeAuth as Ad,CLAUDE_CODE_SETUP_HINT as ha,resolveModelSetting as Ed,probeModel as Id,D360AuthError as Nd}from"document360-engine";async function ga(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=Ad();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. ${ha}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ha});let r=Ed(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let y=await Id(e,r.model??void 0);y.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(y.latencyMs/1e3).toFixed(1)}s`}):y.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 ${y.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=Td(e);if(!s)return t.push({level:"fail",label:`No ${Rd(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??Sd).replace(/\/+$/,"");t.push(s.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let h;try{h=jd(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(y){return t.push({level:"fail",label:`Profile config: ${y.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let b=Pd(h.name);b?Fr(b)&&!b.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Fr(b)?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(b.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=Cd(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(xd(ma())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ma()}`,fix:"Reinstall document360-writer (broken install)"});let D=Ie(e);if(D.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${oe})`}):D.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${D.completedVersion}, current is v${oe}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),b&&(!Fr(b)||b.refreshToken)){let y={profile:h.name,connection:h.connection};try{await vd(y);let C=await $d(y,"/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 Dd(y,P,h.project.workspaceId);if(C){let I=(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 ${I||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${h.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(C){C instanceof Nd||/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 wa(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?O("\u26A0"):$("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${N(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?E(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function rn(e,t){console.log(f("Running checks\u2026"));for(let n of wa(await ga(t.cwd)))console.log(n);return{kind:"continue"}}var Kn=qo(()=>{"use strict";at();F()});import{Command as cm}from"commander";import{createRequire as um}from"node:module";import{AUTH_MODES as dm}from"document360-engine";import{input as dc}from"@inquirer/prompts";import{loginPkce as pc,refreshTokens as fc,toStoredTokens as Xs,clearTokens as mc,decodeJwtClaims as Ks,isExpired as hc,loadTokens as gc,saveTokens as Js,resolveActiveProfile as Tn,setProfileProject as wc,readProjectConfig as yc}from"document360-engine";F();import{select as Ql}from"@inquirer/prompts";import{resolveActiveProfile as Zl,setProfileProject as ec,resolveProjectId as tc,listWorkspaces as nc}from"document360-engine";async function Vt(e,t){let n=Zl(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??tc(o);return{workspaces:await nc(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Bs=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Bo(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 Rn(e,t,n,o,r){ec(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Ys(e,t,n){let o;try{o=await Vt(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=Bo(o.workspaces,t);return r?(Rn(e,o.profile,o.projectId,r.id,r.name),console.log(E(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function St(e,t){let n;try{n=await Vt(e,t)}catch(b){console.log($(`Could not list workspaces: ${b.message}`));return}let{workspaces:o,projectId:r,profile:s,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let b of o)console.log(` ${b.id===c?N("\u25CF"):" "} ${Bs(b)} ${f(b.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Ql({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${Bs(b)}${b.id===c?" (current)":""}`,value:b.id}))}),h=o.find(b=>b.id===p);Rn(e,s,r,p,h?.name),console.log(E(`\u2713 Workspace set to "${h?.name??p}" for profile "${s}".`))}F();import{select as oc}from"@inquirer/prompts";import{resolveActiveProfile as rc,setProfileProject as sc,listProjects as ic}from"document360-engine";async function st(e,t){let n=rc(e,t),o={profile:n.name,connection:n.connection};return{projects:await ic(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Gs=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Vs(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 Yo(e,t,n,o){sc(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function zs(e,t){let n;try{n=await st(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?N("\u25CF"):" "} ${Gs(h)} ${f(h.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await oc({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${Gs(h)}${h.id===s?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===c);Yo(e,r,c,p?.name),console.log(E(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}F();import ac from"picocolors";function lc(e=process.env){return e.FORCE_HYPERLINK==="0"||!ac.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 cc(e,t=e,n){return lc(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var uc=/https?:\/\/[^\s\x1b]+/g;function zt(e,t){return e.replace(uc,n=>cc(n,n,t))}function Qs(e){return{...Ks(e.idToken)??{},...Ks(e.accessToken)??{}}}function Sn(e){let t=Qs(e),n=t.email??t.preferred_username??t.sub??"unknown",o=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${n}${o}`}async function Dn(e){let t=Tn(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 pc(n,{manual:e.manual,promptForRedirect:s=>dc({message:s})},s=>console.log(zt(s))),r=Xs(t.name,o);if(Js(r),await Go(r,t.name,s=>console.log(f(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${Sn(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{yc(process.cwd())?.profiles?.[t.name]&&(console.log(""),await St(process.cwd(),t.name))}catch{}}async function Go(e,t,n){let r=Qs(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Tn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await st(process.cwd(),t);c=p.find(h=>h.id===r)?.name}catch{}wc(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Zs(e){let t=Tn(process.cwd(),e.profile),n=t.connection,o=gc(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 ${N(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Sn(o)}`),hc(o))if(o.refreshToken)try{let r=Xs(t.name,await fc(n,o.refreshToken));Js(r),console.log(E(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(O(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(O("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function ei(e){let t=Tn(process.cwd(),e.profile);mc(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}F();import{readProjectConfig as ti,writeProjectConfig as kc,resolveActiveProfile as bc,loadTokens as xc,isExpired as $c}from"document360-engine";function jn(e){let t=ti(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?N("\u25CF "):" ",s=o.production?O(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=xc(n),h=p?$c(p)&&!p.refreshToken?O("expired"):f("logged in"):f("not logged in");console.log(`${r}${N(n)} \u2192 ${c}${s} [${h}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function An(e,t){let n=ti(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,kc(n,e);let o=n.profiles[t].production?O(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function En(e,t){try{let n=bc(e,t);console.log(""),console.log(`Profile ${N(n.name)}${n.production?O(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}F();import{existsSync as vc,readdirSync as Cc,statSync as ni}from"node:fs";import{join as oi}from"node:path";import{apiLogDir as Pc}from"document360-engine";function ri(){let e=Pc();if(console.log(""),console.log(`Document360 API logs: ${N(e)}`),!vc(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Cc(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=(ni(oi(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=(ni(oi(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("")}F();import{createSession as Rc,resolveAuth as Tc,findByName as Sc,slugify as Dc,touchSession as jc,upsertSession as Ac,resolveActiveProfile as Ec}from"document360-engine";async function si(e,t,n,o,r,s){let c=Tc(n);c.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${N("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${N("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Ec(e,r)}catch(y){console.error($(`Document360 profile error: ${y.message}`)),process.exit(2)}p.production&&(console.error(O(`\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 y=Sc(e,o);y||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),h=y.uuid,console.error(f(`Resuming "${y.name}"`))}let b=Rc({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),x=h??null,D=1;for await(let y of b.send(t))switch(y.type){case"session":if(!x){x=y.sessionId;let P=new Date().toISOString();Ac({uuid:x,name:Dc(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(y.delta);break;case"tool":console.error(re(` \u2699 ${y.name}`));break;case"result":D=y.ok?0:1,console.error(f(`(${y.inputTokens}\u2192${y.outputTokens} tokens`+(y.costUsd>0?`, $${y.costUsd<.01?y.costUsd.toFixed(4):y.costUsd.toFixed(2)}`:"")+")")),y.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${y.message}`)),process.exit(1)}x&&jc(x),process.stdout.write(`
|
|
182
|
-
`),process.exit(D)}import{createInterface as Tp}from"node:readline/promises";import{createSession as is,resolveAuth as Sp,getSession as Dp,setTitle as jp,slugify as Ap,touchSession as qa,upsertSession as Ep,generateTitle as Ip,resolveActiveProfile as Ba,resolveModelSetting as Np,readProjectConfig as _p,decodeJwtClaims as Fa,isExpired as Mp,loadTokens as Op}from"document360-engine";var
|
|
181
|
+
`)}function Ln(){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):",Dt,Jo(),Dt]}function At(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${oe}.`," 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):",Dt,it(),Dt,"","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 Dt,oe,ui,at=qo(()=>{"use strict";Dt="-".repeat(64),oe=5;ui="Re-run dev\u2194docs onboarding (protocol v"});var ya={};zl(ya,{doctorCommand:()=>rn,renderDoctorChecks:()=>wa,runDoctorChecks:()=>ga});import{existsSync as xd}from"node:fs";import{d360GetAll as $d,getAccessToken as vd,isExpired as Fr,loadProfileMap as Cd,loadTokens as Pd,packageSkillsDir as ma,projectConfigPath as Rd,readProjectConfig as Td,DEFAULT_DOCS_DIR as Sd,fetchManifestSummary as Dd,resolveActiveProfile as jd,classifyClaudeAuth as Ad,CLAUDE_CODE_SETUP_HINT as ha,resolveModelSetting as Ed,probeModel as Id,D360AuthError as Nd}from"document360-engine";async function ga(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=Ad();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. ${ha}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ha});let r=Ed(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let y=await Id(e,r.model??void 0);y.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(y.latencyMs/1e3).toFixed(1)}s`}):y.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 ${y.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=Td(e);if(!s)return t.push({level:"fail",label:`No ${Rd(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??Sd).replace(/\/+$/,"");t.push(s.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let h;try{h=jd(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(y){return t.push({level:"fail",label:`Profile config: ${y.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let b=Pd(h.name);b?Fr(b)&&!b.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Fr(b)?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(b.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=Cd(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(xd(ma())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ma()}`,fix:"Reinstall document360-writer (broken install)"});let D=Ie(e);if(D.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${oe})`}):D.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${D.completedVersion}, current is v${oe}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),b&&(!Fr(b)||b.refreshToken)){let y={profile:h.name,connection:h.connection};try{await vd(y);let C=await $d(y,"/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 Dd(y,P,h.project.workspaceId);if(C){let I=(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 ${I||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${h.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(C){C instanceof Nd||/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 wa(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?O("\u26A0"):v("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${N(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?E(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):v(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function rn(e,t){console.log(f("Running checks\u2026"));for(let n of wa(await ga(t.cwd)))console.log(n);return{kind:"continue"}}var Kn=qo(()=>{"use strict";at();F()});import{Command as cm}from"commander";import{createRequire as um}from"node:module";import{AUTH_MODES as dm}from"document360-engine";import{input as dc}from"@inquirer/prompts";import{loginPkce as pc,refreshTokens as fc,toStoredTokens as Xs,clearTokens as mc,decodeJwtClaims as Ks,isExpired as hc,loadTokens as gc,saveTokens as Js,resolveActiveProfile as Tn,setProfileProject as wc,readProjectConfig as yc}from"document360-engine";F();import{select as Ql}from"@inquirer/prompts";import{resolveActiveProfile as Zl,setProfileProject as ec,resolveProjectId as tc,listWorkspaces as nc}from"document360-engine";async function Vt(e,t){let n=Zl(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??tc(o);return{workspaces:await nc(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Bs=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Bo(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 Rn(e,t,n,o,r){ec(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Ys(e,t,n){let o;try{o=await Vt(e,n)}catch(s){return console.log(v(`Could not list workspaces: ${s.message}`)),1}let r=Bo(o.workspaces,t);return r?(Rn(e,o.profile,o.projectId,r.id,r.name),console.log(E(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(v(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function St(e,t){let n;try{n=await Vt(e,t)}catch(b){console.log(v(`Could not list workspaces: ${b.message}`));return}let{workspaces:o,projectId:r,profile:s,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let b of o)console.log(` ${b.id===c?N("\u25CF"):" "} ${Bs(b)} ${f(b.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Ql({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${Bs(b)}${b.id===c?" (current)":""}`,value:b.id}))}),h=o.find(b=>b.id===p);Rn(e,s,r,p,h?.name),console.log(E(`\u2713 Workspace set to "${h?.name??p}" for profile "${s}".`))}F();import{select as oc}from"@inquirer/prompts";import{resolveActiveProfile as rc,setProfileProject as sc,listProjects as ic}from"document360-engine";async function st(e,t){let n=rc(e,t),o={profile:n.name,connection:n.connection};return{projects:await ic(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Gs=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Vs(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 Yo(e,t,n,o){sc(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function zs(e,t){let n;try{n=await st(e,t)}catch(h){console.log(v(`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?N("\u25CF"):" "} ${Gs(h)} ${f(h.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await oc({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${Gs(h)}${h.id===s?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===c);Yo(e,r,c,p?.name),console.log(E(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}F();import ac from"picocolors";function lc(e=process.env){return e.FORCE_HYPERLINK==="0"||!ac.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 cc(e,t=e,n){return lc(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var uc=/https?:\/\/[^\s\x1b]+/g;function zt(e,t){return e.replace(uc,n=>cc(n,n,t))}function Qs(e){return{...Ks(e.idToken)??{},...Ks(e.accessToken)??{}}}function Sn(e){let t=Qs(e),n=t.email??t.preferred_username??t.sub??"unknown",o=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${n}${o}`}async function Dn(e){let t=Tn(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 pc(n,{manual:e.manual,promptForRedirect:s=>dc({message:s})},s=>console.log(zt(s))),r=Xs(t.name,o);if(Js(r),await Go(r,t.name,s=>console.log(f(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${Sn(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{yc(process.cwd())?.profiles?.[t.name]&&(console.log(""),await St(process.cwd(),t.name))}catch{}}async function Go(e,t,n){let r=Qs(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Tn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await st(process.cwd(),t);c=p.find(h=>h.id===r)?.name}catch{}wc(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Zs(e){let t=Tn(process.cwd(),e.profile),n=t.connection,o=gc(t.name);if(!o){console.log(v(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${N(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Sn(o)}`),hc(o))if(o.refreshToken)try{let r=Xs(t.name,await fc(n,o.refreshToken));Js(r),console.log(E(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(O(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(O("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function ei(e){let t=Tn(process.cwd(),e.profile);mc(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}F();import{readProjectConfig as ti,writeProjectConfig as kc,resolveActiveProfile as bc,loadTokens as xc,isExpired as $c}from"document360-engine";function jn(e){let t=ti(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(v("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?N("\u25CF "):" ",s=o.production?O(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=xc(n),h=p?$c(p)&&!p.refreshToken?O("expired"):f("logged in"):f("not logged in");console.log(`${r}${N(n)} \u2192 ${c}${s} [${h}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function An(e,t){let n=ti(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(v(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,kc(n,e);let o=n.profiles[t].production?O(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function En(e,t){try{let n=bc(e,t);console.log(""),console.log(`Profile ${N(n.name)}${n.production?O(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(v(n.message)),process.exitCode=1}}F();import{existsSync as vc,readdirSync as Cc,statSync as ni}from"node:fs";import{join as oi}from"node:path";import{apiLogDir as Pc}from"document360-engine";function ri(){let e=Pc();if(console.log(""),console.log(`Document360 API logs: ${N(e)}`),!vc(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Cc(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=(ni(oi(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=(ni(oi(e,r)).size/1024).toFixed(1);console.log(` ${v(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("")}F();import{createSession as Rc,resolveAuth as Tc,findByName as Sc,slugify as Dc,touchSession as jc,upsertSession as Ac,resolveActiveProfile as Ec}from"document360-engine";async function si(e,t,n,o,r,s){let c=Tc(n);c.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${N("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${N("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Ec(e,r)}catch(y){console.error(v(`Document360 profile error: ${y.message}`)),process.exit(2)}p.production&&(console.error(O(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(v("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let h;if(o){let y=Sc(e,o);y||(console.error(v(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),h=y.uuid,console.error(f(`Resuming "${y.name}"`))}let b=Rc({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),x=h??null,D=1;for await(let y of b.send(t))switch(y.type){case"session":if(!x){x=y.sessionId;let P=new Date().toISOString();Ac({uuid:x,name:Dc(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(y.delta);break;case"tool":console.error(re(` \u2699 ${y.name}`));break;case"result":D=y.ok?0:1,console.error(f(`(${y.inputTokens}\u2192${y.outputTokens} tokens`+(y.costUsd>0?`, $${y.costUsd<.01?y.costUsd.toFixed(4):y.costUsd.toFixed(2)}`:"")+")")),y.ok||console.error(v("agent finished with an error result"));break;case"error":console.error(""),console.error(v(`agent error: ${y.message}`)),process.exit(1)}x&&jc(x),process.stdout.write(`
|
|
182
|
+
`),process.exit(D)}import{createInterface as Tp}from"node:readline/promises";import{createSession as is,resolveAuth as Sp,getSession as Dp,setTitle as jp,slugify as Ap,touchSession as qa,upsertSession as Ep,generateTitle as Ip,resolveActiveProfile as Ba,resolveModelSetting as Np,readProjectConfig as _p,decodeJwtClaims as Fa,isExpired as Mp,loadTokens as Op}from"document360-engine";var Ce=[{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 Ic(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 ii(){let e=["document360-writer \u2014 help",""];for(let t of Ce){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push(Ic(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function Vo(){console.log("");for(let e of ii())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}F();import{getSession as Nc}from"document360-engine";async function ai(e,t){let n=t.currentUuid(),o=n?Nc(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 zo(){return{kind:"exit"}}F();at();import{input as Jt,confirm as Fc}from"@inquirer/prompts";import{basename as gi,join as Un}from"node:path";import{existsSync as Et,readFileSync as Hc,readdirSync as qc,writeFileSync as Bc}from"node:fs";import{writeProjectConfig as wi,readProjectConfig as Yc,projectConfigPath as yi,writerDir as Gc,DEFAULT_DOCS_DIR as ki,DEFAULT_CAPTURE_DIR as bi,DEFAULT_OUTPUT_DIR as xi}from"document360-engine";function $i(e,t="berlin"){let n=yi(e);if(Et(n))return{created:!1,path:n,profileName:""};let o={projectId:Pi(e)??gi(e),docsDir:ki,captureDir:bi,outputDir:xi,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Ri(e)};return wi(o,e),vi(e),{created:!0,path:n,profileName:t}}function vi(e){let t=Un(Gc(e),".gitignore");Et(t)||Bc(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
187
|
-
`),"utf8")}async function Ci(){let e=process.cwd(),t=yi(e);if(Et(t)&&!await Fc({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Pi(e)??gi(e),o=await Jt({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Jt({message:"Capture directory (where document360-capture .spec.ts files live):",default:bi}),s=await Jt({message:"Screenshot output directory:",default:xi}),c=await Jt({message:"Default connection profile name:",default:"berlin"}),p=await Jt({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),h={projectId:o,docsDir:ki,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Ri(e)},b=Yc(e);b?.terminologyGlossary&&(h.terminologyGlossary=b.terminologyGlossary),wi(h,e),vi(e);let x=jt(e);console.log(""),console.log(E(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${N(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of At(x))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${N('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Pi(e){let t=Un(e,"package.json");if(!Et(t))return null;try{return JSON.parse(Hc(t,"utf8")).name??null}catch{return null}}function Ri(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Et(Un(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Un(e,n);Et(o)&&!Vc(o)&&t.push(n)}return t}function Vc(e){try{return qc(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}F();import{readMcpConfig as Qo,writeMcpConfig as Ti}from"document360-engine";async function Wn(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(zc(),{kind:"continue"}):t==="add"?(Kc(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Xc(e.slice(1)),{kind:"continue"}):(console.log(
|
|
187
|
+
`),"utf8")}async function Ci(){let e=process.cwd(),t=yi(e);if(Et(t)&&!await Fc({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Pi(e)??gi(e),o=await Jt({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Jt({message:"Capture directory (where document360-capture .spec.ts files live):",default:bi}),s=await Jt({message:"Screenshot output directory:",default:xi}),c=await Jt({message:"Default connection profile name:",default:"berlin"}),p=await Jt({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),h={projectId:o,docsDir:ki,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Ri(e)},b=Yc(e);b?.terminologyGlossary&&(h.terminologyGlossary=b.terminologyGlossary),wi(h,e),vi(e);let x=jt(e);console.log(""),console.log(E(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${N(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of At(x))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${N('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Pi(e){let t=Un(e,"package.json");if(!Et(t))return null;try{return JSON.parse(Hc(t,"utf8")).name??null}catch{return null}}function Ri(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Et(Un(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Un(e,n);Et(o)&&!Vc(o)&&t.push(n)}return t}function Vc(e){try{return qc(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}F();import{readMcpConfig as Qo,writeMcpConfig as Ti}from"document360-engine";async function Wn(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(zc(),{kind:"continue"}):t==="add"?(Kc(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Xc(e.slice(1)),{kind:"continue"}):(console.log(v(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function zc(){let e=Qo(),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(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(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Kc(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(
|
|
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(Si(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Di(t[o+1])){let p=ji(r);o+=2;let h=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)h.push(ji(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 c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Si(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Di(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function tr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?qe.bold(t.slice(2,-2)):t.startsWith("`")?N(t.slice(1,-1)):qe.italic(t.slice(1,-1)))}var Qc=(e,t)=>e+" ".repeat(Math.max(0,t-er(e)));function Zc(e,t,n){let o=e.length,r=e.map((C,I)=>Math.max(er(C),...t.map(_=>er(_[I]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],h=()=>p.reduce((C,I)=>C+I,0)+c,b=0;for(;h()>s&&b++<1e4;){let C=-1,I=6;for(let _=0;_<o;_++)p[_]>I&&(I=p[_],C=_);if(C===-1)break;p[C]-=1}let x=(C,I,_)=>qe.gray(C+p.map(L=>"\u2500".repeat(L+2)).join(I)+_),D=qe.gray("\u2502"),y=(C,I)=>{let _=p.map((de,ie)=>{let
|
|
191
|
-
`)}),L=Math.max(..._.map(de=>de.length)),Q=[];for(let de=0;de<L;de++)Q.push(p.map((ie,
|
|
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(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(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Kc(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(v("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(v(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Qo(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let h=o[++p],b=h?.match(/^([^:=]+)[:=](.+)$/);if(!b){console.log(v(`-H expects key:value (no spaces). Got: ${h??"(nothing)"}`));return}c[b[1].trim()]=b[2].trim()}else{console.log(v(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(c).length>0?c:void 0}}r.servers[t]=s,Ti(r),console.log(""),console.log(E(`\u2713 Registered "${t}" (${n})`)),console.log(O(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Xc(e){let t=e[0];if(!t){console.log(v("Usage: /mcp remove <name>"));return}let n=Qo();if(!n.servers[t]){console.log(v(`No server named "${t}".`));return}delete n.servers[t],Ti(n),console.log(E(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}F();import{readFileSync as du}from"node:fs";import{join as pu}from"node:path";import{select as fu}from"@inquirer/prompts";import{computeSyncStatus as ar,planPartitions as mu,relatedArticlePaths as hu,resolveModelForOperation as gu,runPartitioned as wu,loadProfileMap as yu,resolveActiveProfile as ku,resolveCrossLinks as bu}from"document360-engine";import V from"picocolors";import Ii from"wrap-ansi";import rr from"string-width";F();import qe from"picocolors";import Zo from"wrap-ansi";import er from"string-width";var Si=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Di=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),ji=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Jc(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(Si(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Di(t[o+1])){let p=ji(r);o+=2;let h=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)h.push(ji(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 c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Si(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Di(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function tr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?qe.bold(t.slice(2,-2)):t.startsWith("`")?N(t.slice(1,-1)):qe.italic(t.slice(1,-1)))}var Qc=(e,t)=>e+" ".repeat(Math.max(0,t-er(e)));function Zc(e,t,n){let o=e.length,r=e.map((C,I)=>Math.max(er(C),...t.map(_=>er(_[I]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],h=()=>p.reduce((C,I)=>C+I,0)+c,b=0;for(;h()>s&&b++<1e4;){let C=-1,I=6;for(let _=0;_<o;_++)p[_]>I&&(I=p[_],C=_);if(C===-1)break;p[C]-=1}let x=(C,I,_)=>qe.gray(C+p.map(L=>"\u2500".repeat(L+2)).join(I)+_),D=qe.gray("\u2502"),y=(C,I)=>{let _=p.map((de,ie)=>{let Re=C[ie]??"",le=I?qe.bold(Re):tr(Re);return Zo(le,de,{hard:!0}).split(`
|
|
191
|
+
`)}),L=Math.max(..._.map(de=>de.length)),Q=[];for(let de=0;de<L;de++)Q.push(p.map((ie,Re)=>`${D} ${Qc(_[Re][de]??"",ie)} `).join("")+D);return Q.join(`
|
|
192
192
|
`)},P=[x("\u250C","\u252C","\u2510"),y(e,!0)];return P.push(t.length===0?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524")),t.forEach((C,I)=>{P.push(y(C,!1)),P.push(I===t.length-1?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524"))}),P.join(`
|
|
193
193
|
`)}function eu(e,t){switch(e.kind){case"heading":return qe.bold(e.text);case"hr":return qe.gray("\u2500".repeat(t));case"para":return Zo(tr(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=Zo(tr(n),Math.max(10,t-4)).split(`
|
|
194
194
|
`);return" \u2022 "+o+r.map(s=>`
|
|
@@ -216,42 +216,43 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
|
216
216
|
`+(e.ok?V.magenta("\u2736 "):V.red("\u2736 "))+V.gray(`Cooked for ${Zt(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${fe(e.costUsd)}`:""))}}function Ni(e,t){return e.map(n=>sr(n,t)).join(`
|
|
217
217
|
`)}import{resolveActiveProfile as au,loadTokens as lu,isExpired as cu,decodeJwtClaims as _i}from"document360-engine";function uu(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ne(e,t){try{let n=au(e,t),o=lu(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(cu(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let c={..._i(o.idToken)??{},..._i(o.accessToken)??{}}.doc360_project_id;if(typeof c=="string"&&c&&c!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${uu(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var en=3;function lr(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 Mi={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function tn(e){return e.filter(t=>t.path!==null&&t.status in Mi&&!t.link).map(t=>({path:t.path,label:Mi[t.status]}))}function Fn(e){return e.filter(t=>t.link).length}function cr(e,t){try{let n=yu(e,ku(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=bu(du(pu(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 xu(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 Oi(e){let t=[];e.length>1&&t.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(o=>o.path),indent:!1});let n=new Map;for(let o of e){let r=o.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),s=n.get(r);s?s.push(o):n.set(r,[o])}for(let o of[...n.keys()].sort()){let r=n.get(o).sort((s,c)=>s.path.localeCompare(c.path));t.push({kind:"category",label:`${xu(o)} (${r.length})`,paths:r.map(s=>s.path),indent:!1});for(let s of r){let c=s.path.replace(/\\/g,"/").split("/").pop()??s.path;t.push({kind:"article",label:c,paths:[s.path],indent:!0,note:s.label})}}return t}function Hn(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 ur(e,t,n){let o=y=>t[y.index]?.paths.length??0,r=e.filter(y=>y.ok),s=e.filter(y=>!y.ok),c=e.reduce((y,P)=>y+o(P),0),p=r.reduce((y,P)=>y+o(P),0),h=n==="api"?`${fe(e.reduce((y,P)=>y+P.costUsd,0))} total`:Be(e.reduce((y,P)=>y+P.outputTokens,0)),b=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,x=y=>`${y} article${y===1?"":"s"}`,D=[];if(s.length===0)D.push(`Published ${x(c)} (${b}) successfully \xB7 ${h}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${x(c)} (${b}) \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 y of s)D.push(` \u2717 ${y.label}${y.error?` \u2014 ${y.error}`:""}`)}return D}async function ir(e,t){let n=mu(t),{model:o}=gu(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${en} 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 wu({cwd:e.cwd,partitions:n,promptFor:s=>Hn(s.paths),concurrency:en,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(E(` \u2713 ${r.label}`)):console.log(
|
|
220
|
-
`),display:"/audit"}}F();import{checkbox as $u}from"@inquirer/prompts";import{inventoryRepo as vu,readProjectConfig as Ui,writeProjectConfig as Cu}from"document360-engine";function dr(e,t){let n=Ui(e);n&&(n.authoritativeSourceFiles=t,Cu(n,e))}function Bn(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 Wi(e,t){let n=t?.cwd??process.cwd();if(!Ui(n))return console.log(
|
|
219
|
+
`)}function ur(e,t,n){let o=y=>t[y.index]?.paths.length??0,r=e.filter(y=>y.ok),s=e.filter(y=>!y.ok),c=e.reduce((y,P)=>y+o(P),0),p=r.reduce((y,P)=>y+o(P),0),h=n==="api"?`${fe(e.reduce((y,P)=>y+P.costUsd,0))} total`:Be(e.reduce((y,P)=>y+P.outputTokens,0)),b=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,x=y=>`${y} article${y===1?"":"s"}`,D=[];if(s.length===0)D.push(`Published ${x(c)} (${b}) successfully \xB7 ${h}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${x(c)} (${b}) \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 y of s)D.push(` \u2717 ${y.label}${y.error?` \u2014 ${y.error}`:""}`)}return D}async function ir(e,t){let n=mu(t),{model:o}=gu(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${en} 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 wu({cwd:e.cwd,partitions:n,promptFor:s=>Hn(s.paths),concurrency:en,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(E(` \u2713 ${r.label}`)):console.log(v(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let s=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of ur(r.results,n,s))console.log(r.ok?E(p):O(p));let c=cr(e.cwd,e.profileName);c&&console.log(f(c))}}catch(r){console.log(v(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function qn(e,t,n){let o=hu(e,n);if(o.length===0)return[];let r=new Set(tn((await ar({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Li(e,t){let n=Ne(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await qn(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(E("\u2713 All related articles are already published.")),{kind:"continue"}):await ir(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await ar({cwd:t?.cwd??process.cwd()}),s=tn(r.entries),c=Fn(r.entries);return c>0&&console.log(O(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),s.length===0?(console.log(E(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):t?await ir(t,s.map(p=>p.path)):{kind:"forward-to-agent",prompt:Hn(s.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log(v(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let s=await ar({cwd:t?.cwd??process.cwd()});r=tn(s.entries);let c=Fn(s.entries);c>0&&console.log(O(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`))}catch(s){return console.log(v(`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(E("\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(()=>fu({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 ir(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:lr(o),display:`/publish ${o}`}}async function nn(){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"}}F();import{checkbox as $u}from"@inquirer/prompts";import{inventoryRepo as vu,readProjectConfig as Ui,writeProjectConfig as Cu}from"document360-engine";function dr(e,t){let n=Ui(e);n&&(n.authoritativeSourceFiles=t,Cu(n,e))}function Bn(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 Wi(e,t){let n=t?.cwd??process.cwd();if(!Ui(n))return console.log(v("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=vu(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(N("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(Bn(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>$u({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Bn(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"};dr(n,r),console.log(E(`\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"}}F();import{confirm as ju}from"@inquirer/prompts";import{applyPull as fr,computeSyncStatus as Yi,compareRemoteSources as Au,planPull as Gi,planImport as Eu,applyImport as Iu,establishBaselines as Nu,rebaselineServerMeta as _u,D360AuthError as Mu}from"document360-engine";F();var Fi=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:v,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:O,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:N,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:v,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:v,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:re,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:re,mark:"\xB7"}];function Pu(e){return e.path?e.path:`${e.title??"(untitled)"} ${re(`[${e.articleId}]`)}`}function Ru(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 Yn(e,t){let n=[],o=e.entries.filter(x=>x.link);if(o.length>0){n.push(""),n.push(ve("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let x of o)n.push(` ${O("~")} ${O(x.path??"")} ${re(`\u2192 "${x.link.title}"`)}`)}for(let x of Fi){let D=e.entries.filter(y=>y.status===x.status&&!(x.status==="untracked-local"&&y.link));if(D.length!==0){n.push(""),n.push(ve(x.header));for(let y of D)n.push(` ${x.paint(x.mark)} ${x.paint(Pu(y))}${y.detail?re(` (${y.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let c={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},p=o.length,h=s===r?E("\u2713 everything up to date"):[r>0?E(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...Fi.map(x=>{let D=(e.counts[x.status]??0)-(x.status==="untracked-local"?p:0);return D>0?`${D} ${c[x.status]}`:null})].filter(Boolean).join(re(" \xB7 ")),b=t!==void 0?` \xB7 synced in ${Ru(t)}`:"";return n.push(h+re(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${b}`)),n}import{structuredPatch as Tu}from"diff";import Hi from"picocolors";var qi=80,Su="\x1B[48;2;74;28;28m",Du="\x1B[48;2;24;66;24m",Bi="\x1B[49m",pr=e=>String(e).padStart(5);function lt(e,t,n){let o=y=>{let P=y.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 c=Math.max(20,n-10),p=Tu("a","b",r,s,"","",{context:3}),h=0,b=0,x=[];p.hunks.forEach((y,P)=>{P>0&&x.push(Hi.gray(" \u2026"));let C=y.oldStart,I=y.newStart;for(let _ of y.lines){let L=_[0],Q=_.slice(1).slice(0,c);L==="-"?(b++,x.push(`${Su}${pr(C++)} - ${Q}${Bi}`)):L==="+"?(h++,x.push(`${Du}${pr(I++)} + ${Q}${Bi}`)):(x.push(Hi.gray(pr(I))+" "+Q),C++,I++)}});let D=x.slice(0,qi);return{added:h,removed:b,lines:D,hidden:Math.max(0,x.length-qi)}}async function Vi(e,t){let n=Ne(t.cwd,t.profileName);if(!n.ok)return console.log(
|
|
223
|
+
`},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=Tu("a","b",r,s,"","",{context:3}),h=0,b=0,x=[];p.hunks.forEach((y,P)=>{P>0&&x.push(Hi.gray(" \u2026"));let C=y.oldStart,I=y.newStart;for(let _ of y.lines){let L=_[0],Q=_.slice(1).slice(0,c);L==="-"?(b++,x.push(`${Su}${pr(C++)} - ${Q}${Bi}`)):L==="+"?(h++,x.push(`${Du}${pr(I++)} + ${Q}${Bi}`)):(x.push(Hi.gray(pr(I))+" "+Q),C++,I++)}});let D=x.slice(0,qi);return{added:h,removed:b,lines:D,hidden:Math.max(0,x.length-qi)}}async function Vi(e,t){let n=Ne(t.cwd,t.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Ou(t),{kind:"continue"};if(o==="--baseline")return await Lu(t,e.filter(c=>c!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Uu(t),{kind:"continue"};if(o)return console.log(v(`Unknown option: ${o}`)),console.log(f("Usage: /pull pull portal edits + import new portal articles")),console.log(f(" /pull <path> pull one article (or resolve a conflict)")),console.log(f(" /pull --status drift report only (no writes)")),console.log(f(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Wu(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await mr({cwd:t.cwd,profileName:t.profileName});for(let c of hr(s))console.log(c.tone==="ok"?E(c.text):c.tone==="warn"?O(c.text):f(c.text));console.log("")}catch(r){r instanceof Mu?console.log(v(r.message)):console.log(v(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function mr(e){let t=await Yi({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 Gi({cwd:e.cwd,profileName:e.profileName,relPath:o.path});fr({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 Eu({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Iu({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 Gn=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,ct=e=>e===1?"":"s";function hr(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${ct(e.pulled.length)} into local: ${Gn(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${ct(e.imported.length)}: ${Gn(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${ct(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${ct(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Take the portal copy: /pull <path> \xB7 keep yours: /publish <path>. (${Gn(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${ct(e.failed.length)} failed: ${Gn(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 Ou(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Yi({cwd:e.cwd,profileName:e.profileName});for(let o of Yn(n,Date.now()-t))console.log(o);console.log("")}async function Lu(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 Nu({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await _u({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(E("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(E(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(E(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(O(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(f(` - ${s.path} (${s.reason})`))}}async function Uu(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Au({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${ve(String(t.legacyCount))} \xB7 Manifest: ${ve(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(E("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(v(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(O(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(O(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(f(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Wu(e,t){let n=t.replace(/\\/g,"/"),o=await Gi({cwd:e.cwd,profileName:e.profileName,relPath:n});console.log(""),console.log(`${N("\u25CF")} ${ve(o.title)} ${re(`(${o.path})`)}`);for(let c of o.notes)console.log(O(` \u26A0 ${c}`));o.overwritesLocalChanges&&console.log(O(" \u26A0 This OVERWRITES local edits made since the last sync."));let r=lt(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.")),fr({cwd:e.cwd,profileName:e.profileName},o);return}console.log(re(` \u23BF Added ${r.added} line${ct(r.added)}, removed ${r.removed} line${ct(r.removed)}`));for(let c of r.lines)console.log(c);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>ju({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}fr({cwd:e.cwd,profileName:e.profileName},o),console.log(E(` \u2713 Pulled ${o.path} (sync base advanced).`))}F();import{statSync as Fu}from"node:fs";import{resolve as Hu}from"node:path";import{estimateBulkCost as qu,planPartitions as Bu,readProjectConfig as Yu,resolveModelForOperation as Gu,runPartitioned as Vu,trackedArticlePaths as zu}from"document360-engine";var gr=3;function wr(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 yr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function kr(e,t){return t.map(n=>{let o=0;try{o=Fu(Hu(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function br(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 xr(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: ${fe(r)}\u2013${fe(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function $r(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,I)=>C+o(I),0),p=r.reduce((C,I)=>C+o(I),0),h=e.reduce((C,I)=>C+I.costUsd,0),b=e.reduce((C,I)=>C+I.outputTokens,0),x=n==="api"?`${fe(h)} total`:Be(b),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,y=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Converted ${y(c)} (${D}) successfully \xB7 ${x}.`);else{P.push(`Converted ${p}/${y(c)} (${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(!Yu(t.cwd))return console.log(
|
|
229
|
+
`)}function xr(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: ${fe(r)}\u2013${fe(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function $r(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,I)=>C+o(I),0),p=r.reduce((C,I)=>C+o(I),0),h=e.reduce((C,I)=>C+I.costUsd,0),b=e.reduce((C,I)=>C+I.outputTokens,0),x=n==="api"?`${fe(h)} total`:Be(b),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,y=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Converted ${y(c)} (${D}) successfully \xB7 ${x}.`);else{P.push(`Converted ${p}/${y(c)} (${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(!Yu(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=wr(e),r=zu(t.cwd,t.profileName);if(r.length===0)return console.log(v("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=yr(r,n);if(s.length===0)return console.log(v(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=Bu(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:h,forced:b}=Gu(t.cwd,"light");if(!o){let x=qu({files:kr(t.cwd,s),op:"convert",model:h});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let D of xr(c,x,gr))console.log(D);return console.log(f(`Model: ${h}${b?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${c.length} partitions (\u2264${gr} 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 Vu({cwd:t.cwd,partitions:c,promptFor:br,concurrency:gr,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(E(` \u2713 ${x.label}`)):console.log(v(` \u2717 ${x.label}`));else if(x.type==="run_done"){console.log("");let D=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let y of $r(x.results,c,D))console.log(x.ok?E(y):O(y))}}catch(x){console.log(v(`Convert run failed: ${x.message}`))}return console.log(""),{kind:"continue"}}F();import{statSync as Ki}from"node:fs";import{resolve as Xi}from"node:path";import{estimateBulkCost as Ku,planPartitions as Xu,readDocsPlan as Ju,readProjectConfig as Ji,DEFAULT_DOCS_DIR as Qu,resolveModelForOperation as Zu,runPartitioned as ed}from"document360-engine";var td=3,nd=8;function vr(e){return e===void 0||!Number.isFinite(e)?td:Math.max(1,Math.min(Math.floor(e),nd))}function Cr(e){let t,n,o=!1,r=!1,s,c=h=>{let b=Number(h);return h!==void 0&&Number.isFinite(b)?b:void 0};for(let h=0;h<e.length;h++){let b=e[h];if(b==="--preview"||b==="--dry-run")o=!0;else if(b==="--rewrite"||b==="--force")r=!0;else{if(b==="--run"||b==="--yes"||b==="--all")continue;b==="--scope"?t=e[++h]:b?.startsWith("--scope=")?t=b.slice(8):b==="--concurrency"?s=c(e[++h]):b?.startsWith("--concurrency=")?s=c(b.slice(14)):b&&!b.startsWith("--")&&(n=b)}}let p=h=>h?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function od(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function rd(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Pr(e,t,n){return n.filter(o=>{try{return Ki(Xi(e,t,o)).size===0}catch{return!0}})}function Rr(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let c of o.get(r)?.sources??[])try{s+=Ki(Xi(e,c)).size}catch{}return{path:r,bytes:s}})}function Tr(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
|
+
`:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
230
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).
|
|
231
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.
|
|
232
|
-
|
|
233
|
+
`+o+`- Write the finished article to ${t}/<path>, following the write-article structure and the project terminologyGlossary. Add the \`sources:\` frontmatter listing the files you actually read.
|
|
233
234
|
- Emit \`<!-- SCREENSHOT -->\` placeholders where a visual helps, but do NOT author capture specs now.
|
|
234
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.
|
|
235
236
|
Articles:
|
|
236
|
-
`+e.paths.map(
|
|
237
|
-
`)}function Sr(e,t,n){let o=e.reduce((c,p)=>c+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${fe(r)}\u2013${fe(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Dr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,I)=>C+o(I),0),p=r.reduce((C,I)=>C+o(I),0),h=e.reduce((C,I)=>C+I.costUsd,0),b=e.reduce((C,I)=>C+I.outputTokens,0),x=n==="api"?`${fe(h)} total`:Be(b),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,y=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Wrote ${y(c)} (${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}/${y(c)} (${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 jr(e,t,n){let o=(Ji(e)?.docsDir??Qu).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=od(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=rd(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let c=Pr(e,o,s);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"",h=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${h} --rewrite to regenerate them all.`}}return{docsDir:o,targets:c,planCount:r.length}}async function Qi(e,t){if(!Ji(t.cwd))return console.log(
|
|
238
|
-
`)}var Ir="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function oa(e,t){let n=t?.cwd??process.cwd();if(!ad(n))return console.log(
|
|
239
|
-
`)}var Or="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 ra(e,t){let n=t?.cwd??process.cwd();if(!ud(n))return console.log(
|
|
237
|
+
`+e.paths.map(r=>`- ${r}`).join(`
|
|
238
|
+
`)}function Sr(e,t,n){let o=e.reduce((c,p)=>c+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${fe(r)}\u2013${fe(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Dr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,I)=>C+o(I),0),p=r.reduce((C,I)=>C+o(I),0),h=e.reduce((C,I)=>C+I.costUsd,0),b=e.reduce((C,I)=>C+I.outputTokens,0),x=n==="api"?`${fe(h)} total`:Be(b),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,y=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Wrote ${y(c)} (${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}/${y(c)} (${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 jr(e,t,n){let o=(Ji(e)?.docsDir??Qu).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=od(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=rd(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let c=Pr(e,o,s);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"",h=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${h} --rewrite to regenerate them all.`}}return{docsDir:o,targets:c,planCount:r.length}}async function Qi(e,t){if(!Ji(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=Ju(t.cwd);if(n.length===0)return console.log(v("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:c,rewrite:p}=Cr(e),{docsDir:h,targets:b,reason:x,rewriting:D}=jr(t.cwd,n,{scope:o,path:r,rewrite:p});if(b.length===0)return console.log(x?O(x):O("Nothing to write.")),{kind:"continue"};D&&console.log(O(`--rewrite: regenerating ${b.length} already-written article${b.length===1?"":"s"} (overwrites them; git has your baseline).`));let y=Xu(b),P=vr(c),{model:C,forced:I}=Zu(t.cwd,"standard"),_=!!r;if(s&&!_){let L=Ku({files:Rr(t.cwd,n,b),op:"write",model:C});o&&console.log(f(`Scope: ${o} (${b.length} pending).`));for(let Q of Sr(y,L,P))console.log(Q);return console.log(f(`Model: ${C}${I?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${b.length} article${b.length===1?"":"s"} across ${y.length} partition${y.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 L of ed({cwd:t.cwd,partitions:y,promptFor:Q=>Tr(Q,h,{rewrite:D||_}),concurrency:P,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(L.type==="partition_status")L.status==="running"?console.log(f(` \u25B8 ${L.label} \u2014 writing\u2026`)):L.status==="done"?console.log(E(` \u2713 ${L.label}`)):console.log(v(` \u2717 ${L.label}`));else if(L.type==="run_done"){console.log("");let Q=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let de of Dr(L.results,y,Q))console.log(L.ok?E(de):O(de))}}catch(L){console.log(v(`Write run failed: ${L.message}`))}return console.log(""),{kind:"continue"}}F();import{existsSync as sd,readdirSync as Zi,statSync as ea}from"node:fs";import{join as ta}from"node:path";import{inputDir as id,readProjectConfig as ad}from"document360-engine";var na=/\.(md|markdown|pdf|txt)$/i;function Ar(e){let t=id(e);if(!sd(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Zi(t)){let s=ta(t,r),c=!1;try{c=ea(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=ld(s);p>0&&n.push({name:r,docCount:p})}else na.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function ld(e){let t=0;for(let n of Zi(e))try{ea(ta(e,n)).isFile()&&na.test(n)&&t++}catch{}return t}function Er(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 Vn(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in .d360-writer/input/${e}/`:t?`the input docs in .d360-writer/input/ relevant to: "${t}"`:"the input docs in .d360-writer/input/"}.`,t&&!e?`Use "${t}" as the feature framing.`:"","","Follow the skill: (1) read those PRDs/specs as the primary source (intent, user-facing surface,","terminology, user stories, prerequisites); (2) locate and read the CODE that implements that surface","to pin exact UI strings/routes/states \u2014 never fabricate; flag anything the PRD claims that you","cannot find in source; (3) propose a tight feature-scoped article set (\u22483\u20135) and pin it to",".d360-writer/plan.json + AGENT-PLAN.md, with each article's `sources` listing BOTH the PRD file(s)","AND the grounding code files; (4) flag overlaps with existing articles (do not merge). Then stop and","offer /write. Do NOT write the articles in this turn."].filter(Boolean).join(`
|
|
239
|
+
`)}var Ir="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function oa(e,t){let n=t?.cwd??process.cwd();if(!ad(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Ar(n);if(o.length===0&&r===0)return console.log(f(Ir)),{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:Vn(p),display:p?`/draft ${p}`:"/draft"}}let c=Er(o,s);return{kind:"forward-to-agent",prompt:Vn(c??"",c?void 0:s),display:`/draft ${s}`}}F();import{listOpenForDocs as cd,readProjectConfig as ud}from"document360-engine";function Nr(e){try{return cd(e).filter(t=>t.kind==="request").length}catch{return 0}}function _r(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Mr(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 Or="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 ra(e,t){let n=t?.cwd??process.cwd();if(!ud(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=_r(e);if(!r&&Nr(n)===0)return console.log(f(Or)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Mr(r,o),display:s}}F();import{search as dd}from"@inquirer/prompts";import{findByName as pd,getSession as fd,listSessions as md,relativeTime as ia}from"document360-engine";async function aa(e,t){let n=md(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=pd(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(v(`No session matches "${o}".`)),sa(n),{kind:"continue"})}if(!process.stdin.isTTY)return sa(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>dd({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${ia(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=fd(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function sa(e){console.log("");for(let t of e.slice(0,15))console.log(` ${N(t.name)} ${f(ia(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}F();import{renameSession as hd}from"document360-engine";function Lr(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 la(e,t){let n=Lr(e.join(" "));if(!n)return console.log(v("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(hd(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log(v("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(E(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as ca,readProjectConfig as gd,writeProjectConfig as wd}from"document360-engine";F();function Ur(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=gd(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 ca().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},wd(o,e),null):`Unknown environment "${r}". Known: ${ca().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function ua(e,t){let n=e[0];if(!n)return jn(t.cwd),{kind:"continue"};if(n==="add"){let o=Ur(t.cwd,e[1],e[2]);return o?(console.log(v(o)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${N(`/profile ${e[1]}`)} then ${N("/login")}`),{kind:"continue"})}return An(t.cwd,n),En(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}F();import{select as yd}from"@inquirer/prompts";import{readProjectConfig as kd,readUserConfig as da,resolveModelSetting as Wr,writeUserConfig as pa}from"document360-engine";var Se=[{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 zn(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=Se.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function bd(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 on(e,t){let n=()=>{let s=Wr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=da();return s.defaultModel?(delete s.defaultModel,pa(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Wr(e).model??"Claude Code default"} (applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}pa({...da(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=kd(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 fa(e,t){let n=e[0]?.trim();if(!n){let c=Wr(t.cwd);if(!process.stdin.isTTY)return console.log(`${ve("Model:")} ${N(c.model??"Claude Code default")}`),console.log(f(` source: ${bd(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=zn(c),h;try{h=await t.withPausedInput(()=>yd({message:`Select model (current: ${c.model??"Claude Code default"})`,default:Se[p].value,choices:Se.map((y,P)=>({name:`${y.label}${P===p?" \u2714":""}`,value:y.value,description:y.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:b,changed:x,effective:D}=on(t.cwd,h??"default");for(let y of b)console.log(y.startsWith("\u26A0")?O(y):y.startsWith("\u2713")?E(y):f(y));return x&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:s}=on(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?O(c):c.startsWith("\u2713")?E(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}Kn();async function ka(e,t){return await t.withPausedInput(()=>St(t.cwd)),{kind:"clear"}}async function ba(e,t){return await t.withPausedInput(()=>zs(t.cwd,t.profileName)),{kind:"clear"}}F();import{resolveActiveProfile as _d}from"document360-engine";async function xa(e,t){let n=!1;try{n=_d(t.cwd).production}catch{}return n?(console.log(O("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}F();var $a=async(e,t)=>{try{await t.withPausedInput(()=>Dn({}))}catch(n){console.log(v(`Login failed: ${n.message}`))}return{kind:"continue"}};F();import{resolveActiveProfile as Md,clearTokens as Od,clearProfileProject as Ld}from"document360-engine";async function va(e,t){let n;try{n=Md(t.cwd,t.profileName).name}catch(r){return console.log(v(r.message)),{kind:"continue"}}let o=Od(n);return Ld(t.cwd,n),console.log(o?E(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):f(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(f("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as Ca}from"node:fs";import{isAbsolute as Ud,join as Wd,resolve as Fd}from"node:path";import{readProjectConfig as Hd,screenshotPlaceholderIds as qd,DEFAULT_CAPTURE_DIR as Bd,DEFAULT_OUTPUT_DIR as Yd}from"document360-engine";var Pa=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Hr(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Pa(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Pa(o),setup:t}:{mode:"single",id:o}}function qr(e,t){let n=Hd(e),o=n?.captureDir??Bd,r=n?.outputDir??Yd,s=(c,p)=>Ud(c)?Wd(c,p):Fd(e,c,p);return qd(e,{scope:t}).map(({id:c,file:p})=>{let h=Ca(s(r,`${c}.png`))?"captured":Ca(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:h}})}var Gd={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Vd={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Br(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(s=>s.file))].sort(),o=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of n){r.push(s);for(let c of e.filter(p=>p.file===s))r.push(` ${Gd[c.state]} ${c.id.padEnd(34)} ${Vd[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Ra(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(`
|
|
240
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(`
|
|
241
242
|
`)}async function Xn(e,t){let n=Hr(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of Br(qr(c,n.scope),n.scope))console.log(p);return{kind:"continue"}}if(n.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${n.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${n.id}.spec.ts. Report the spec path and any TODO data-testids or data to stage.`].join(`
|
|
242
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(`
|
|
243
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 zd,readFileSync as Kd}from"node:fs";import{isAbsolute as Xd,join as Jd,resolve as Qd}from"node:path";import{readProjectConfig as Zd,DEFAULT_CAPTURE_DIR as ep}from"document360-engine";async function sn(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-SETUP.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
|
|
244
245
|
`),display:"/capture-setup"}}var Ta="-".repeat(64);function Yr(e){let t=ep;try{let x=Zd(e);x?.captureDir&&(t=x.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Xd(t)?Jd(t,"CAPTURE-TESTID-REQUESTS.json"):Qd(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!zd(n))return null;let o;try{let x=JSON.parse(Kd(n,"utf8").replace(/^/,""));o=Array.isArray(x?.requests)?x.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(x=>x.file).filter(Boolean)).size,s=o.length,c=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,h=`${t}/CAPTURE-TESTID-REQUESTS.md`,b=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${c} requested across ${p}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",Ta,`Read ${h} and ${b}. They list ${c} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",Ta]}at();F();import{listOpenForDocs as tp,readProjectConfig as np}from"document360-engine";function Gr(e){try{return tp(e).length}catch{return 0}}function Vr(){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(`
|
|
245
|
-
`)}async function Sa(e,t){let n=t?.cwd??process.cwd();return np(n)?Gr(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:Vr(),display:"/inbox"}:(console.log(
|
|
246
|
-
`)}var cp={status:ip,plan:ap,apply:lp};async function Jr(e,t=cp){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 zr=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Jn=e=>e===1?"":"s";function Qr(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${Jn(e.pulled.length)} into local: ${zr(e.pulled)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Jn(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${zr(e.conflicts)}`),e.untrackedRemote.length&&t.push(`\u2139 ${e.untrackedRemote.length} new article${Jn(e.untrackedRemote.length)} in the portal aren't local yet \u2014 run /pull to bring them in: ${zr(e.untrackedRemote)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull${Jn(e.failed.length)} failed \u2014 left for /pull.`),t}async function Da(e,t){let n=t?.cwd??process.cwd();if(!sp(n))return console.log(
|
|
247
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function yp(e){return Na(e,".d360-writer/hints")}function kp(e){return Na(e,".d360-writer/messages")}function os(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=yp(e),o=kp(e),r=Zr(es(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: ${Aa(e)}`]}async function _a(e,t){let n=ts(t.cwd);for(let h of os(t.cwd,n))console.log(n.length===0?f(h):h);if(n.length===0)return{kind:"continue"};let o=Aa(t.cwd);if((await t.withPausedInput(()=>fp({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(O("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Zr(hp(t.cwd)),{removed:c,failed:p}=ns(t.cwd,n);console.log(E(`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`));for(let h of p)console.log(
|
|
246
|
+
`)}async function Sa(e,t){let n=t?.cwd??process.cwd();return np(n)?Gr(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:Vr(),display:"/inbox"}:(console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}F();import{listOpenHints as op,listOpenForDocs as rp,readProjectConfig as sp,computeSyncStatus as ip,planPull as ap,applyPull as lp}from"document360-engine";function Nt(e){let t=0,n=0,o=0;try{t=op(e).length}catch{}try{let r=rp(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 _t(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 Kr(e){return{publish:e.includes("--publish")}}function Xr({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 cp={status:ip,plan:ap,apply:lp};async function Jr(e,t=cp){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 zr=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Jn=e=>e===1?"":"s";function Qr(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${Jn(e.pulled.length)} into local: ${zr(e.pulled)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Jn(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${zr(e.conflicts)}`),e.untrackedRemote.length&&t.push(`\u2139 ${e.untrackedRemote.length} new article${Jn(e.untrackedRemote.length)} in the portal aren't local yet \u2014 run /pull to bring them in: ${zr(e.untrackedRemote)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull${Jn(e.failed.length)} failed \u2014 left for /pull.`),t}async function Da(e,t){let n=t?.cwd??process.cwd();if(!sp(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ne(n,t?.profileName);if(!o.ok)return console.log(v(o.reason)),{kind:"continue"};let{publish:r}=Kr(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await Jr({cwd:n,profileName:t?.profileName});for(let p of Qr(s))console.log(p.startsWith("\u2713")?E(p):p.startsWith("\u2139")?f(p):O(p));let c=_t(Nt(n));return console.log(f(c?`Catching up on ${c}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Xr({publish:r}),display:`/catch-up${r?" --publish":""}`}}F();import{spawn as up}from"node:child_process";var ut="document360-writer",Qn=`npm i -g ${ut}@latest`;async function Zn(){let e=process.platform==="win32";return new Promise(t=>{try{let n=up(`npm i -g ${ut}@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 ja(){return console.log(f(`Updating ${ut}\u2026`)),(await Zn()).ok?console.log(E("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(v(`Update failed \u2014 run manually: ${Qn}`)),{kind:"continue"}}F();at();import{existsSync as Zr,rmSync as dp}from"node:fs";import{basename as Aa,resolve as es}from"node:path";import{execFileSync as pp}from"node:child_process";import{input as fp}from"@inquirer/prompts";import{readProjectConfig as mp,devHintsGuidePath as hp}from"document360-engine";var gp=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],wp=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),eo=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Ea=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Ia(e){let t=eo(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Ea(t)?!0:wp.has(t)}function ts(e){let t=null;try{t=mp(e)}catch{t=null}let n=new Set(gp);for(let o of[eo(t?.docsDir),eo(t?.captureDir),eo(t?.outputDir)])o&&Ea(o)&&n.add(o);return[...n].filter(o=>Ia(o)&&Zr(es(e,o)))}function ns(e,t){let n=[],o=[];for(let r of t){if(!Ia(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{dp(es(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Na(e,t){try{return pp("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
248
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function yp(e){return Na(e,".d360-writer/hints")}function kp(e){return Na(e,".d360-writer/messages")}function os(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=yp(e),o=kp(e),r=Zr(es(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: ${Aa(e)}`]}async function _a(e,t){let n=ts(t.cwd);for(let h of os(t.cwd,n))console.log(n.length===0?f(h):h);if(n.length===0)return{kind:"continue"};let o=Aa(t.cwd);if((await t.withPausedInput(()=>fp({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(O("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Zr(hp(t.cwd)),{removed:c,failed:p}=ns(t.cwd,n);console.log(E(`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`));for(let h of p)console.log(v(` \u2717 ${h.path}: ${h.error}`));if(s){for(let h of Ln())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"}}var Ma={help:Vo,"?":Vo,clear:ai,exit:zo,quit:zo,init:Ci,mcp:Wn,publish:Li,audit:nn,scope:Wi,pull:Vi,convert:zi,write:Qi,draft:oa,document:ra,resume:aa,rename:la,profile:ua,model:fa,doctor:rn,workspace:ka,project:ba,"allow-prod":xa,login:$a,logout:va,screenshot:Xn,"capture-setup":sn,devhints:mi,inbox:Sa,"catch-up":Da,update:ja,reset:_a};function Oa(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}at();F();var bp={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"},Ua=160,ss=200,Wa=40;function we(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function La(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}: ${we(typeof r=="string"?r:JSON.stringify(r),Wa)}`);return t.length>4&&n.push("\u2026"),we(n.join(", "),Ua)}var Ye=e=>typeof e=="string"&&e?e:null,rs=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function xp(e){let t=Ye(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 $p(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Ye(t.title);if(!o)return null;let r=xp(t.local_path);return n("Create article",`"${we(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Ye(t.title),r=rs(t.article_id);return n("Update article",o?`"${we(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",rs(t.article_id)?`id ${rs(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",Ye(t.name)?`"${we(Ye(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Ye(t.file_path);return n("Upload image",o?we(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function to(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),c=s.join("__");if(r==="document360"){let b=$p(c,t);if(b)return b}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:La(t)}}let n=bp[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:we(o,Ua)}:{title:e,sep:"",arg:La(t)}}function vp(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 Cp(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(vp).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>we(r,ss))]}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}: ${we(String(r),Wa)}`);return n.length>0?[we(n.join(" \xB7 "),ss)]:null}return null}function Pp(e){let t=Ye(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Rp(e,t,n){switch(e){case"d360_create_article":{let o=Pp(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=Ye(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 ${we(o[0],120)}`:""}`]}default:return null}}function no(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
248
249
|
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=Rp(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let s=Cp(r)??r.split(`
|
|
249
|
-
`);return{lines:s.slice(0,t).map(c=>
|
|
250
|
+
`);return{lines:s.slice(0,t).map(c=>we(c,ss)),hidden:Math.max(0,s.length-t)}}function oo(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function ro(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 so(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 Lp=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Up(e,t,n,o){if(Lp.test(e))try{let r=Ba(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=ro(t,n),p=so(n);e.endsWith("publish_article")&&p&&console.log(N(` \u2B95 Live: ${p}`)),c&&s&&console.log(N(` \u2B95 Preview: ${oo(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function Ya(e=process.cwd(),t="auto",n){let o=Sp(t);o.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${N("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${N('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${N("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${N("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Wp(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=is({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=Tp({input:process.stdin,output:process.stdout}),h=[],b=null,x=!1;p.on("line",P=>{if(b){let C=b;b=null,C(P)}else h.push(P)}),p.on("close",()=>{if(x=!0,b){let P=b;b=null,P(null)}});function D(){return h.length>0?Promise.resolve(h.shift()):x?Promise.resolve(null):(process.stdout.write(N("> ")),new Promise(P=>{b=P}))}let y={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=is({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setPendingName:P=>{c.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 I=Oa(C);if(!I)continue;let _=Ma[I.name];if(!_){console.log(v(`Unknown command: /${I.name}`)),console.log(f("Type /help for the list."));continue}let L=await _(I.args,y);if(L.kind==="exit")break;if(L.kind==="clear"){y.restartAgent();continue}if(L.kind==="allow-prod"){r=!0,y.restartAgent(),console.log(E("\u2713 Production writes authorized for this session.")),console.log("");continue}if(L.kind==="resume"){s.close(),s=is({cwd:e,resume:L.uuid,profileName:n,allowProdWrites:r});let Q=Dp(L.uuid);c={uuid:L.uuid,firstPrompt:Q?.firstPrompt??null,titleFired:!0},qa(L.uuid),console.log(E(`\u2713 Resumed "${L.name}"`)),console.log("");continue}L.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=L.display??L.prompt),await Ha(s,L.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=C),await Ha(s,C,o,c,e)}}}finally{s.close(),p.close()}}function Wp(e,t){console.log(""),console.log(Gt("document360-writer")),console.log(f(` cwd: ${e}`));let n=Np(e);if(console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(Fp(e,t)),!_p(e))console.log(O(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{try{Mn(e);for(let o of On(e))console.log(O(` ${o}`))}catch{}try{let o=_t(Nt(e));o&&console.log(O(` \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 Fp(e,t){try{let n=Ba(e,t),o=n.production?O(" \u26A0 PRODUCTION"):"",r=Op(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Fa(r.idToken)??{},...Fa(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return Mp(r)&&!r.refreshToken?O(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function Hp(){console.error(""),console.error(`Sign in with your Claude subscription: run ${N("claude")} once, then retry.`),console.error(` (No Claude Code? ${N("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${N("https://console.anthropic.com/settings/keys")}`)}function qp(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Ep({uuid:t,name:r??Ap(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Bp(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Ip(o,t).then(r=>{r&&jp(n,r)}).catch(()=>{})}async function Ha(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))Yp(c,o,r,n,s)}function Yp(e,t,n,o,r){switch(e.type){case"session":t.uuid||qp(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=to(e.name,e.input);s&&(process.stdout.write(`
|
|
250
251
|
|
|
251
|
-
`),console.log(`${E("\u25CF")} ${
|
|
252
|
-
`),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&&(qa(t.uuid),t.titleFired||Bp(t,n));break;case"error":console.error(""),console.error(
|
|
252
|
+
`),console.log(`${E("\u25CF")} ${ve(s.title)}${s.arg!==null?re(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=lt(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=p=>p===1?"":"s";console.log(re(` \u23BF Added ${s.added} line${c(s.added)}, removed ${s.removed} line${c(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(f(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let c=no(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?v:re;c.lines.forEach((h,b)=>console.log(p((b===0?" \u23BF ":" ")+h))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||Up(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
|
|
253
|
+
`),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&&(qa(t.uuid),t.titleFired||Bp(t,n));break;case"error":console.error(""),console.error(v(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Hp();break}}import{render as sm}from"ink";import{resolveAuth as im}from"document360-engine";import{useCallback as G,useEffect as Pe,useMemo as ps,useRef as X,useState as H}from"react";import{Box as ne,Text as T,useApp as cf,useInput as uf,useStdout as df}from"ink";import{existsSync as Ge,readFileSync as fs,readdirSync as ko}from"node:fs";import{spawnSync as pf}from"node:child_process";import{basename as ln,isAbsolute as ff,join as dt}from"node:path";import{createSession as yl,classifyClaudeAuth as ws,CLAUDE_CODE_SETUP_HINT as mf,loginPkce as hf,toStoredTokens as gf,saveTokens as wf,getAccessToken as yf,resolveActiveProfile as ue,resolveProjectId as kf,getArticle as bf,decodeJwtClaims as Ot,isExpired as Oe,loadTokens as Ve,clearTokens as xf,clearProfileProject as $f,setTitle as vf,slugify as Cf,touchSession as ms,upsertSession as Pf,generateTitle as kl,findByName as Rf,listSessions as Tf,renameSession as Sf,suggestNextAction as Df,readProjectConfig as ee,writeProjectConfig as bl,resolveModelSetting as ys,loadProfileMap as yo,applyPull as jf,computeSyncStatus as xl,countLocalAhead as Af,compareRemoteSources as Ef,planPull as If,establishBaselines as Nf,rebaselineServerMeta as _f,inventoryRepo as Mf,knownEnvironments as Of,resolveEnvironment as Lf,planPartitions as hs,partitionEvenly as Uf,screenshotPlaceholderIds as Wf,trackedArticlePaths as Ff,runPartitioned as ho,estimateBulkCost as $l,resolveModelForOperation as go,readDocsPlan as vl,checkForUpdate as Hf,detectInstallKind as qf,isSelfUpdatable as Bf,devHintsGuidePath as ks,toolFeedbackPath as Yf,reconcileToolFeedback as Gf,DEFAULT_DOCS_DIR as cn,setProfileProject as Vf,writeCrashLog as zf}from"document360-engine";at();import{spawn as Ga}from"node:child_process";function Gp(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Vp(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?Ga([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Ga(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",c=>o(c===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function Va(e){for(let[t,n]of Gp())if(await Vp(t,n,e))return!0;return!1}var zp=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function as(e,t){if(t.closed)return e;let n=e.split(`
|
|
253
254
|
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){zp.test(s)&&(t.cueSeen=!0);continue}let c=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);c?(n[r]=`${c[1]}${++t.num}. ${c[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
|
|
254
|
-
`)}import{existsSync as Kp,mkdirSync as Xp,readFileSync as Jp,writeFileSync as Qp}from"node:fs";import{join as za}from"node:path";import{writerDir as Zp}from"document360-engine";function Ka(e){return za(Zp(e),".sessions")}function Xa(e,t){return za(Ka(e),`${t}.json`)}function Ja(e,t,n){try{Xp(Ka(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Qp(Xa(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function ls(e,t){try{let n=Xa(e,t);if(!Kp(n))return[];let o=JSON.parse(Jp(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var ef=e=>`\x1B]0;${e}\x07`,tf=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Qa(e){process.stdout.isTTY&&process.stdout.write(e)}function Mt(e){Qa(ef(e))}function io(e){Qa(tf(e))}var ao=["\xB7 "," \xB7"],lo="\u{1F7E3}";Kn();var co=[{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:"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"}],Za={"/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 el(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Za[n])return Za[n];let o=co.find(r=>r.name===t);return o?o.desc:""}function tl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return co.filter(n=>n.name.startsWith(t))}function nl(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}F();import{Box as ol,Text as se}from"ink";import{jsx as ae,jsxs as uo}from"react/jsx-runtime";function nf({row:e}){switch(e.t){case"head":return ae(se,{color:W,bold:!0,children:e.s});case"text":return ae(se,{children:e.s});case"dim":return ae(se,{dimColor:!0,children:e.s});case"sub":return ae(se,{bold:!0,dimColor:!0,children:e.s});case"good":return ae(se,{color:"green",children:e.s});case"step":return uo(se,{children:[ae(se,{color:W,children:`${e.n}. `}),e.s]});case"cmd":return uo(se,{children:[" ",ae(se,{color:W,children:e.name.padEnd(20)}),ae(se,{dimColor:!0,children:e.s})]});case"gap":return ae(se,{children:" "})}}function rl({tab:e,width:t}){let n=
|
|
255
|
+
`)}import{existsSync as Kp,mkdirSync as Xp,readFileSync as Jp,writeFileSync as Qp}from"node:fs";import{join as za}from"node:path";import{writerDir as Zp}from"document360-engine";function Ka(e){return za(Zp(e),".sessions")}function Xa(e,t){return za(Ka(e),`${t}.json`)}function Ja(e,t,n){try{Xp(Ka(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Qp(Xa(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function ls(e,t){try{let n=Xa(e,t);if(!Kp(n))return[];let o=JSON.parse(Jp(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var ef=e=>`\x1B]0;${e}\x07`,tf=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Qa(e){process.stdout.isTTY&&process.stdout.write(e)}function Mt(e){Qa(ef(e))}function io(e){Qa(tf(e))}var ao=["\xB7 "," \xB7"],lo="\u{1F7E3}";Kn();var co=[{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:"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"}],Za={"/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 el(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Za[n])return Za[n];let o=co.find(r=>r.name===t);return o?o.desc:""}function tl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return co.filter(n=>n.name.startsWith(t))}function nl(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}F();import{Box as ol,Text as se}from"ink";import{jsx as ae,jsxs as uo}from"react/jsx-runtime";function nf({row:e}){switch(e.t){case"head":return ae(se,{color:W,bold:!0,children:e.s});case"text":return ae(se,{children:e.s});case"dim":return ae(se,{dimColor:!0,children:e.s});case"sub":return ae(se,{bold:!0,dimColor:!0,children:e.s});case"good":return ae(se,{color:"green",children:e.s});case"step":return uo(se,{children:[ae(se,{color:W,children:`${e.n}. `}),e.s]});case"cmd":return uo(se,{children:[" ",ae(se,{color:W,children:e.name.padEnd(20)}),ae(se,{dimColor:!0,children:e.s})]});case"gap":return ae(se,{children:" "})}}function rl({tab:e,width:t}){let n=Ce[e]??Ce[0],o=6+Ce.reduce((s,c)=>s+c.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return uo(ol,{flexDirection:"column",paddingX:1,children:[uo(se,{children:[ae(se,{color:W,bold:!0,children:"Help "}),Ce.map((s,c)=>c===e?ae(se,{color:"white",backgroundColor:W,bold:!0,children:` ${s.label} `},s.key):ae(se,{dimColor:!0,children:` ${s.label} `},s.key))]}),ae(se,{color:W,children:r}),ae(ol,{flexDirection:"column",marginTop:1,children:n.rows.map((s,c)=>ae(nf,{row:s},c))}),ae(se,{dimColor:!0,children:`
|
|
255
256
|
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var of=/^(?:\d+[.)]|[-*•])\s+/;function sl(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
256
257
|
`)){let c=s.trim().replace(of,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let h=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!h||!o.has(h[1].toLowerCase()))continue;let b=`/${h[1].toLowerCase()}${h[2]?` ${h[2]}`:""}`;if(r.includes(b)||r.push(b),r.length>=n)break}return r}F();function an(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function _e(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function cs(e){return e.replace(/^[\w.-]+\//,"")}var po=16,il={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function us(e){return e.trim().split(/\s+/).slice(1).join(" ")}function al(e,t){let n=us(t);return e.some(r=>r.trim()===t.trim()||!!n&&us(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&us(r)===n)):[]}var rf='\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 sf(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 Me(e){return e===1?"":"s"}function af(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 ds(e,t,n){let o=[];e.pendingWrites>0&&o.push(` \u2022 ${e.pendingWrites} planned article${Me(e.pendingWrites)} still unwritten`),e.localAhead>0&&o.push(` \u2022 ${e.localAhead} article${Me(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${Me(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 ${af(t[0])}.`]:[`Welcome back. Your ${e.tracked} tracked article${Me(e.tracked)} are all in sync.`];return r.push("",...t.map((s,c)=>` ${c+1} ${s.padEnd(9)} ${sf(s,n)}`),"Or just tell me what to write or update."),r.join(`
|
|
257
258
|
`)}function ll(e){if(!e.ready)return{kind:"idle"};let t=!!e.pendingText;if(!e.hasDocs)return{kind:"noDocs",note:rf,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${Me(e.pendingWrites)} not written yet \u2014 pick up where you left off:`;return{kind:"actions",note:ds(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${Me(e.localAhead)} changed locally \u2014 ready to publish to Document360:`;return{kind:"actions",note:ds(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${Me(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${Me(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${Me(e.tracked)} tracked for "${e.profileName}". What next?`;return{kind:"actions",note:ds(e,n,t),title:o,options:n}}var lf=/\[Pasted text #\d+ \+\d+ lines?\]/g;function cl(e){return e.replace(/\r\n?/g,`
|
|
@@ -263,25 +264,25 @@ Articles:
|
|
|
263
264
|
`),truncated:c>0||h>0}}}return{text:e,truncated:!1}}function wl(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
264
265
|
`)){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 gs,jsx as A,jsxs as B}from"react/jsx-runtime";var Kf={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},Cl=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
265
266
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
266
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Xf(e,t,n,o){let r=ws(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",c=ys(e),p=ee(e),h=(p?.docsDir??cn).replace(/\/+$/,""),b=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${h}/ + config`,x={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:Kf[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:b};if(p===null)return x;try{let D=ue(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 y=Ve(D.name);if(y){let P={...Ot(y.idToken)??{},...Ot(y.accessToken)??{}},C=P.email??P.preferred_username??"signed in";Oe(y)?y.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(y.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return x}function Jf(e,t){try{let n=ue(e,t),o=Ve(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 Oe(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 Pl=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],bo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Qf="Ask me to write or update an article\u2026";function wo({ch:e,dim:t}){let[n,o]=H(!0);return
|
|
267
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Xf(e,t,n,o){let r=ws(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",c=ys(e),p=ee(e),h=(p?.docsDir??cn).replace(/\/+$/,""),b=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${h}/ + config`,x={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:Kf[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:b};if(p===null)return x;try{let D=ue(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 y=Ve(D.name);if(y){let P={...Ot(y.idToken)??{},...Ot(y.accessToken)??{}},C=P.email??P.preferred_username??"signed in";Oe(y)?y.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(y.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return x}function Jf(e,t){try{let n=ue(e,t),o=Ve(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 Oe(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 Pl=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],bo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Qf="Ask me to write or update an article\u2026";function wo({ch:e,dim:t}){let[n,o]=H(!0);return Pe(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),A(T,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Zf=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Rl(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var em=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Tl(e){try{return ko(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Sl(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Tl(dt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Tl(dt(e,o)))}function Dl(e,t){try{let n=ee(e);if(!n)return!1;let o=ue(e,t),r=yo(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=dt(e,(n.docsDir??cn).replace(/\/+$/,""));return!!(Ge(s)&&ko(s).length>0||Ge(ks(e)))}catch{return!1}}function tm({startTime:e,chars:t}){let[n,o]=H(0);Pe(()=>{let h=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(h)},[]);let r=bo[n%bo.length],s=Pl[Math.floor(n/16)%Pl.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return B(ne,{children:[A(T,{color:W,children:` ${r} ${s}\u2026 `}),A(T,{color:"gray",children:`(${Zt(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var nm=12e4;function om({p:e}){let[t,n]=H(0);Pe(()=>{let _=setInterval(()=>n(L=>L+1),150);return()=>clearInterval(_)},[]);let o=bo[t%bo.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),p=Date.now()-e.lastAt>=nm,h=e.verb??"Converting",b=e.unit??"article",x=e.rows.reduce((_,L)=>_+L.items,0),D=h.toLowerCase(),y=e.rows,P=0;if(y.length>po){let _=y.findIndex(Q=>Q.status==="active"||Q.status==="pending"),L=Math.max(0,Math.min(_-2,y.length-po));P=y.slice(0,L).filter(Q=>Q.status==="done").length,y=y.slice(L,L+po)}let C=Math.min(40,Math.max(...y.map(_=>cs(_.label).length),0)),I=_=>_==="failed"?"red":_==="active"?W:void 0;return B(ne,{flexDirection:"column",children:[B(ne,{children:[A(T,{color:W,children:` ${o} ${h} ${x} ${b}${x===1?"":"s"} `}),A(T,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${Zt(r)} \xB7 esc to stop`})]}),P>0&&A(T,{dimColor:!0,children:` \u2714 +${P} done`}),y.map(_=>B(T,{color:I(_.status),dimColor:_.status==="done"||_.status==="pending",children:[` ${il[_.status]} ${cs(_.label).padEnd(C)}`,_.status!=="pending"?` (${_.items} ${b}${_.items===1?"":"s"})`:"",_.status==="active"?` \u2190 ${D}\u2026`:""]},_.label)),p&&A(T,{color:"yellow",children:` \u26A0 no activity for ${Zt(s)} \u2014 press esc to stop if it's wedged`})]})}var rm=10800*1e3;function jl({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=cf(),[s,c]=H(n),[p,h]=H(null),[b,x]=H({text:"",pos:0}),D=b.text,y=G(l=>{x(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),P=G(l=>{x(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),C=G(()=>{x(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=fl(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[I,_]=H(!1),[L,Q]=H(!1),[de,ie]=H(0),[Re,le]=H(null),[ze,Y]=H([]),pt=X(0),[Ol,un]=H(!1),[Ll,dn]=H(!1),[xo,vs]=H(null),[Ul,ft]=H(0),Ke=X(0),[Lt,mt]=H(0),[ht,pn]=H(null),Cs=X(new Map),Wl=X(0),gt=X([]),ye=X(null);ye.current===null&&(ye.current=yl({cwd:e,profileName:s,allowProdWrites:!1}));let De=X({uuid:null,firstPrompt:null,titleFired:!1}),fn=X(new Map),wt=X(!1),$o=X([]),Ue=X([]),vo=X(null),[Ps,Xe]=H(null),Co=X(null),[Je,Qe]=H(null),[je,yt]=H(null),[We,kt]=H(null),[pe,bt]=H(null),[ke,Ze]=H(null),[et,xt]=H(null),[Rs,tt]=H(null),[be,nt]=H(null),[me,$t]=H(null),[Ts,Po]=H([]),ot=X([]),Ut=X(!1),xe=X(null),[Ss,te]=H(null),mn=X(!1),hn=X(null),Wt=X(null),[$e,rt]=H(null),[Ro,Ft]=H(null),[Ds,vt]=H(0),[js,Ct]=H(0),[Fl,As]=H(0),To=ps(()=>{try{return ys(e).model??"auto"}catch{return null}},[e,Fl]),{stdout:Te}=df(),[,Hl]=H(0),Es=X(`${Te.columns??80}x${Te.rows??24}`),Fe=G(()=>Math.max(20,(Te.columns??80)-1),[Te]),d=G(l=>{gt.current.push(l),console.log(sr(l,Fe()))},[Fe]),[So,Do]=H(null),Pt=G(l=>{Do(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]),jo=X(!1),Ao=G(async()=>{try{if(jo.current||!Bf(qf())||ee(e)?.mode==="engineer")return;let l=await Hf({pkg:ut,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;jo.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${ut} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),dn(!0),(await Zn().finally(()=>dn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),Y(a=>a.includes("/exit")?a:[...a,"/exit"]),vs(l.latest)):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${Qn}`})}catch{}},[e,o,d]),Eo=G(l=>{let i=Ne(e,s);return i.ok?!0:(d({kind:"note",tone:"warn",text:i.reason}),Wt.current=l,Y(["/login"]),!1)},[e,s,d]),[Io,No]=H(null),Ht=X(!0),gn=X(0),qt=X(0);Pe(()=>{let l=setInterval(()=>{if(Ht.current){gn.current=0,qt.current=0;return}if(!I)try{if(!Ge(ks(e)))return;if(Ie(e).status==="current"){Ht.current=!0,gn.current=0,qt.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."}),Do(null),le("write the docs for this repo");return}gn.current+=1;let i=gn.current;if((i===4||i%15===0)&&qt.current<3){qt.current+=1;let a=qt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Xt(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,I,d]),Pe(()=>{let l=Ps??ln(e);if(!I){io(0),Mt(`${lo} ${l}`);return}io(3);let i=0;Mt(`${ao[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%ao.length,Mt(`${ao[i]} ${l}`)},400);return()=>clearInterval(a)},[I,e,Ps]),Pe(()=>()=>io(0),[]);let _o=G(l=>{try{let i=ee(e);if(!i)return{kind:"idle"};let a=ue(e,s),g=Ve(a.name),u=!!g&&(!Oe(g)||!!g.refreshToken),m=Dl(e,s)||!Sl(e,i.authoritativeSourceFiles),w=ws(t).state==="missing",k=yo(e,a.name),R=k?Object.keys(k.articles).length:0,S=dt(e,(i.docsDir??cn).replace(/\/+$/,"")),J=!1;try{J=Ge(S)&&ko(S).length>0}catch{}let q=0;if(k?.lastAnalyzedCommit)try{let U=pf("git",["rev-list","--count",`${k.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});U.status===0&&(q=parseInt((U.stdout||"").trim(),10)||0)}catch{}let M=0;try{let U=vl(e);if(U.length>0){let z=(i.docsDir??cn).replace(/\/+$/,"");M=Pr(e,z,U.map(ge=>ge.path)).length}}catch{}let $=Af(e,s),j={ready:u&&m&&!w,hasDocs:J,tracked:R,pendingText:_t(Nt(e)),behind:q,pendingWrites:M,localAhead:$,autoAudit:!!i.autoAudit,profileName:a.name,allowAutoAudit:l};return ll(j)}catch{return{kind:"idle"}}},[e,s,t]);Pe(()=>{let l=performance.now(),i=[],a=(w,k)=>{let R=performance.now();try{return k()}finally{let S=Math.round(performance.now()-R);S>=80&&i.push(`${w}: ${S}ms`)}};d({kind:"banner",info:a("banner",()=>Xf(e,o,t,s))});let g=ws(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.
|
|
267
268
|
${mf}
|
|
268
269
|
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!ee(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:
|
|
269
270
|
${Cl}`}),Y(g?["/doctor","/init"]:["/init"]);return}g&&Y(["/doctor"]);try{let w=ue(e,s),k=Ve(w.name);k&&Oe(k)&&k.refreshToken?yf({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),ie(R=>R+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),Y(["/login"])}):(!k||Oe(k))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),Y(["/login"]))}catch{}try{let w=ee(e),k=ue(e,s),R=Ve(k.name);w&&R&&!Oe(R)&&Sl(e,w.authoritativeSourceFiles)&&!Dl(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."}),Y(["/scope"]))}catch{}try{if(a("reconcile-devhints",()=>Mn(e)),Ie(e).status!=="current")if(Xt(e))d({kind:"note",tone:"info",text:`\u{1F514} A newer dev\u2194docs protocol (v${oe}) is available \u2014 your builder can re-run /devhints when convenient. Your docs aren't blocked.`});else{let w=On(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
|
|
270
271
|
`)}),Pt(it()),Ht.current=!1)}}catch{}try{let w=a("reconcile-feedback",()=>Gf(e));w.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}let u=a("ready-decision",()=>_o(!0));u.kind==="autoAudit"?(d({kind:"note",tone:"info",text:u.note}),nn().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&ce(w.prompt,{display:w.display,quietUser:!0})})):u.kind==="noDocs"?(d({kind:"note",tone:"info",text:u.note}),le(u.ghost),Y(u.options),u.title&&tt(u.title)):u.kind==="actions"&&(d({kind:"note",tone:"info",text:u.note}),Y(u.options),tt(u.title));let m=Math.round(performance.now()-l);m>=800&&zf({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(`
|
|
271
272
|
`):"no single phase \u226580ms"}
|
|
272
|
-
cwd: ${e}`}),Ao()},[]),
|
|
273
|
-
`)});let k=cr(e,s);k&&d({kind:"note",tone:"info",text:k})}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{
|
|
273
|
+
cwd: ${e}`}),Ao()},[]),Pe(()=>{let l=setInterval(()=>{Ao()},rm);return()=>clearInterval(l)},[Ao]),Pe(()=>{if(I||ze.length>0)return;let l=_o(!1);(l.kind==="actions"||l.kind==="noDocs")&&(Y(l.options),tt(l.title??null))},[I,ze,de,_o]),Pe(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${Te.columns??80}x${Te.rows??24}`;g!==Es.current&&(Es.current=g,Hl(u=>u+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Ni(gt.current,Fe())+"\x1B[?2026l")},80))},400)};return Te.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),Te.off("resize",a)}},[Te,Fe]);let Ae=Math.max(20,(Te.columns??80)-1),Is=ps(()=>Jf(e,s),[e,s,de]),Mo=(()=>{if(Ll)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(xo!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${xo?` v${xo}`:""}\u2026`,isSetup:!0};let l=ee(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=dt(e,(l.docsDir??cn).replace(/\/+$/,"")),a=(()=>{try{return Ge(i)&&ko(i).length>0}catch{return!1}})();try{let g=ue(e,s),u=Ve(g.name);if(!(!!u&&!(Oe(u)&&!u.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:Qf,isSetup:!1}:So?{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}})(),Bt=tl(D),Ns=Bt.length>0&&!I,Oo=p!==null?gl(p,8,Ae):null,wn=be?be.paths.filter(l=>!be.query||l.toLowerCase().includes(be.query.toLowerCase())).slice(0,8):[],yn=$e?$e.sessions.filter(l=>{let i=$e.query.toLowerCase();return!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],he=G((l,i)=>{ye.current?.close(),ye.current=yl({cwd:e,resume:l,profileName:i??s,allowProdWrites:wt.current}),l||(De.current={uuid:null,firstPrompt:null,titleFired:!1},Xe(null)),vt(0),Ct(0)},[e,s]),_s=G((l,i,a)=>{if(Zf.test(l))try{let g=ue(e,s),u=typeof i.project_id=="string"&&i.project_id||g.project.projectId,m=ro(i,a),w=[],k=so(a);l.endsWith("publish_article")&&k&&w.push(`Live: ${k}`),m&&u&&w.push(`Preview: ${oo(g.connection.portalUrl,u,m,g.project.languageCode??"en")}`),w.length>0&&d({kind:"link",lines:w})}catch{}},[e,s,d]),ce=G(async(l,i)=>{un(!0),le(null),Y([]),tt(null),Do(null),No(null);let a=++pt.current;i?.quietUser||d({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let g=De.current;g.firstPrompt||(g.firstPrompt=i?.display??l),Ke.current=Date.now(),ft(0),_(!0),fn.current.clear();let u="",m=!1,w=!1,k="",R={num:0,closed:!1,cueSeen:!1},S=null,J=()=>{S||(S=setTimeout(()=>{S=null,h(k.length>0?k:null)},60))},q=()=>{S&&clearTimeout(S),S=null,h(null)},M=()=>{if(k.trim()){let $=as(k.trimEnd(),R);d({kind:"assistant",text:$})}k="",q()};try{for await(let $ of ye.current.send(l))if($.type==="session"){if(!g.uuid){g.uuid=$.sessionId;let j=new Date().toISOString(),U=Co.current,z=U??Cf(g.firstPrompt??"session");Pf({uuid:$.sessionId,name:z,renamed:!!U,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:j,updatedAt:j}),Xe(z),Co.current=null}}else if($.type==="text"){k+=$.delta,u+=$.delta;let j=wl(k);if(j>0){let U=k.slice(0,j).trimEnd();U&&d({kind:"assistant",text:as(U,R)}),k=k.slice(j)}J(),ft(U=>U+$.delta.length)}else if($.type==="tool"){m=!0;let j=to($.name,$.input);j&&(M(),d({kind:"tool",title:j.title,sep:j.sep,arg:j.arg}),fn.current.set($.id,{name:$.name,input:$.input}))}else if($.type==="article_diff"){let j=lt($.oldContent,$.newContent,Fe());j&&(M(),d({kind:"diff",added:j.added,removed:j.removed,lines:j.lines,hidden:j.hidden}))}else if($.type==="tool_result"){$.isError&&/run \/login|not logged in|session expired|rejected the token/i.test($.output)&&(mn.current=!0);let j=fn.current.get($.id);if(j){fn.current.delete($.id),M();let U=no($.output,4,$.isError?void 0:j.name,j.input);d({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:$.isError}),$.isError||_s(j.name,j.input,$.output)}}else if($.type==="result"){if(M(),vt(U=>U+$.outputTokens),Ct(U=>U+$.costUsd),d({kind:"done",seconds:Math.round((Date.now()-Ke.current)/1e3),tokens:$.outputTokens,costUsd:$.costUsd,ok:$.ok}),!w&&!m&&!u.trim()&&!Ut.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)."}),$.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let U=Yf(e);if(Ge(U)){let z=fs(U,"utf8").trim();z&&(No(z),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=$.ok?sl(u,co.map(U=>U.name)):[];if(j.length>0?Y(j):$.ok&&u.trim()&&Df(l,u,e).then(U=>{U&&pt.current===a&&le(U)}).catch(()=>{}),g.uuid&&(ms(g.uuid),!g.titleFired)){g.titleFired=!0;let U=g.uuid,z=g.firstPrompt;z&&kl(z,e).then(ge=>{ge&&(vf(U,ge),Xe(ge))}).catch(()=>{})}}else $.type==="error"&&(M(),w=!0,$.kind==="auth"&&(mn.current=!0),d({kind:"note",text:`agent error: ${$.message}`,tone:"error"}))}finally{_(!1),q(),ie($=>$+1),De.current.uuid&&Ja(e,De.current.uuid,gt.current),mn.current&&(mn.current=!1,hn.current=i?.display??l,Y(["/login"])),Ut.current&&(Ut.current=!1,ot.current.length>0&&(d({kind:"note",tone:"info",text:`(${ot.current.length} queued message(s) discarded)`}),ot.current=[],Po([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,_s,Fe]),kn=G(async l=>{let i=hs(l),a=go(e,"standard");Ke.current=Date.now(),ft(0),_(!0);let g=new AbortController;xe.current=g,te({verb:"Publishing",total:i.length,done:0,active:[],rows:an(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${en} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let u of ho({cwd:e,partitions:i,promptFor:m=>Hn(m.paths),concurrency:en,profileName:s,allowProdWrites:wt.current,model:a.model,signal:g.signal}))if(u.type==="partition_status")u.status==="running"?te(m=>m&&{...m,active:[...m.active,u.label],rows:_e(m.rows,u.label,"active"),lastAt:Date.now()}):te(m=>m&&{...m,active:m.active.filter(w=>w!==u.label),done:m.done+1,rows:_e(m.rows,u.label,u.status==="done"?"done":"failed"),lastAt:Date.now()});else if(u.type==="partition_event")te(m=>{if(!m)return m;let w={...m,lastAt:Date.now()};return u.event.type==="tool"?w.tools=m.tools+1:u.event.type==="text"&&(w.chars=m.chars+u.event.delta.length),w});else if(u.type==="run_done"){Ct(R=>R+u.totalCostUsd),vt(R=>R+u.results.reduce((S,J)=>S+J.outputTokens,0));let m=u.aborted?"Stopped. ":"",w=t.kind==="api"?"api":"subscription";d({kind:"note",tone:u.aborted?"warn":u.ok?"ok":"warn",text:m+ur(u.results,i,w).join(`
|
|
274
|
+
`)});let k=cr(e,s);k&&d({kind:"note",tone:"info",text:k})}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{xe.current=null,te(null),_(!1),ie(u=>u+1)}},[e,s,d,t]),Lo=G(async l=>{await ce(lr(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await qn(e,s,l.replace(/\\/g,"/"));i.length>0&&(tt(`Related articles not yet published (${i.length}):`),Y([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ce]),Uo=G(l=>{let i=Ve(l);if(!i||Oe(i)&&!i.refreshToken)return null;let a={...Ot(i.idToken)??{},...Ot(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),Wo=G((l,i)=>{if(i){let a=ee(e);a&&(a.defaultProfile=l,bl(a,e))}c(l),he(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Uo(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),Y(["/login"])),ie(a=>a+1)},[e,d,he,Uo]),bn=G((l,i,a)=>{Rn(e,l,i,a.id,a.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),he(),yo(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:At(jt(e)).join(`
|
|
274
275
|
`)}),Pt(it()),Ht.current=Ie(e).status==="current"||Xt(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,he,Pt]),xn=G(async l=>{let i;try{i=await Vt(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Y(["/workspace"]);return}if(i.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),g=a.length>0?a:i.workspaces;if(g.length===1){let u=g[0],m=i.workspaces.length-g.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),bn(i.profile,i.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),Y(["/workspace"])},[e,d,bn]),$n=G((l,i)=>{Yo(e,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),he(),xn(l)},[e,d,he,xn]),Ms=G(async l=>{let i;try{i=ue(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await st(e,i.name),g=a.find(u=>u.id===i.project.projectId);g?.name&&Vf(e,i.name,{projectName:g.name})}catch{}await xn(i.name);return}try{let{projects:a}=await st(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}".`}),$n(i.name,{id:g.id,name:g.name});return}if(a.length>1){let g=a.map(u=>({id:u.id,name:u.name??u.id,sub:u.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),Ze({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."}),Y(["/project"])}},[e,d,xn,$n]),vn=G(()=>{let l=Ue.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=lt(l.oldContent,l.newContent,Fe());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,Fe]),Os=G(l=>{if(Ue.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Ue.current.shift();try{jf({cwd:e,profileName:s},a),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Ue.current.length===0&&Y(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=Ue.current.shift();d({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Ue.current.length;return Ue.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return vn(),!0},[e,s,vn,d]),Ls=G(l=>{let i=vo.current;if(!i)return!1;if(vo.current=null,le(null),pt.current++,l.trim()!==i.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:g}=ns(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 u of g)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return i.hadDevhints&&(d({kind:"note",tone:"warn",text:Ln().join(`
|
|
275
276
|
`)}),Pt(Jo())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
276
|
-
${Cl}`}),Y(["/init"]),un(!1),!0},[e,d,Pt]),Us=G(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),g=i.slice(1);switch(un(!0),a){case"help":Ft({tab:0});return;case"exit":case"quit":
|
|
277
|
+
${Cl}`}),Y(["/init"]),un(!1),!0},[e,d,Pt]),Us=G(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),g=i.slice(1);switch(un(!0),a){case"help":Ft({tab:0});return;case"exit":case"quit":ye.current?.close(),r();return;case"clear":he(),gt.current=[],un(!1),le(null),pt.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=ue(e,s)}catch(m){d({kind:"note",tone:"error",text:m.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),Q(!0);try{let m=await hf(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},k=>d({kind:"note",tone:"info",text:k})),w=gf(u.name,m);if(wf(w),await Go(w,u.name,k=>d({kind:"note",tone:"info",text:k})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${Sn(w)}`}),await Ms(s),Wt.current){let k=Wt.current;Wt.current=null;let R=Ne(e,s);R.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${k}.`}),Y([k])):(d({kind:"note",tone:"warn",text:`${R.reason} (then ${k}.)`}),Y(["/login"]),Wt.current=k)}else hn.current&&(le(hn.current),hn.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),ie(m=>m+1)}return}case"allow-prod":{let u=!1;try{u=ue(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}wt.current=!0,he(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Lr(g.join(" ")),m=De.current.uuid;if(!m){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Co.current=u,Xe(u),Mt(`${lo} ${u}`),d({kind:"note",tone:"ok",text:`Session will be named "${u}" once it starts.`});return}if(!u){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=De.current.firstPrompt??"";kl(w,e).then(k=>{k?(le(`/rename ${k}`),d({kind:"note",tone:"info",text:`Suggestion: "${k}" \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}Sf(m,u),Xe(u),Mt(`${lo} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=g[0],m=ee(e);if(!u){let w=Object.entries(m?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let k=w.map(([J,q])=>({name:J,env:q.connection?.environment??"custom",prod:q.production===!0,who:Uo(J)})),R=s??m?.defaultProfile,S=Math.max(0,k.findIndex(J=>J.name===R));yt({cursor:S,current:S,rows:k});return}if(u==="add"){let w=Ur(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]}).`}),Wo(g[1],!1);return}if(!m?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}Wo(u,!0);return}case"doctor":await rn(g,{cwd:e});return;case"mcp":await Wn(g);return;case"init":{if(ee(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 u=Of().map(m=>({name:m,apiUrl:Lf(m).apiUrl}));kt({cursor:0,rows:u});return}case"resume":{let u=g.join(" ").trim(),m=Tf(e).filter(R=>R.uuid!==De.current.uuid);if(!u){if(!m.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}rt({query:"",cursor:0,sessions:m});return}let w=Rf(e,u);if(!w){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}he(w.uuid),De.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},Xe(w.name),ms(w.uuid),gt.current=[];let k=ls(e,w.uuid);for(let R of k)d(R);d({kind:"note",tone:"ok",text:k.length?`Resumed "${w.name}" \u2014 restored ${k.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=g.join(" ").trim(),m;try{m=await Vt(e,s)}catch(k){d({kind:"note",tone:"error",text:`Could not list workspaces: ${k.message}`});return}if(!u){let k=m.workspaces.map(S=>({id:S.id,name:S.name??S.id,type:S.workspace_type}));if(k.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let R=Math.max(0,k.findIndex(S=>S.id===m.current));bt({cursor:R,current:R,rows:k,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let w=Bo(m.workspaces,u);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}bn(m.profile,m.projectId,w);return}case"project":{let u=g.join(" ").trim(),m;try{m=await st(e,s)}catch(k){d({kind:"note",tone:"error",text:`Could not list projects: ${k.message} (signed in? try /login)`});return}if(!u){let k=m.projects.map(S=>({id:S.id,name:S.name??S.id,sub:S.sub_domain}));if(k.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let R=k.findIndex(S=>S.id===m.current);Ze({cursor:Math.max(0,R),current:R,rows:k,profile:m.profile,environment:m.environment});return}let w=Vs(m.projects,u);if(!w){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${m.projects.map(k=>k.name??k.id).join(", ")}`});return}$n(m.profile,w);return}case"logout":{let u;try{u=ue(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let m=xf(u);$f(e,u),he(),ie(w=>w+1),d({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${u}" and cleared its project/workspace selection.`:`Profile "${u}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Y(["/login"]);return}case"publish":{if(!Eo(l.trim()))return;if(g[0]==="--related"&&g[1]){let m=await qn(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 kn(m);return}if(g[0]&&g[0]!=="--all"){await Lo(g[0]);return}let u=g[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await xl({cwd:e,profileName:s}),w=tn(m.entries),k=Fn(m.entries);if(k>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${k} article${k===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:k>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(u){await kn(w.map(R=>R.path));return}xt({cursor:0,rows:Oi(w)})}catch(m){d({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let u=g.join(" ").trim();if(!u){let w=[];try{w=Object.keys(yo(e,ue(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}nt({query:"",cursor:0,paths:w});return}let m=ff(u)?u:dt(e,u);if(Ge(m)){try{d({kind:"preview",name:ln(m),text:Rl(fs(m,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${m}: ${w.message}`})}return}if(em.test(u)){try{let w=ue(e,s),k={profile:w.name,connection:w.connection},R=w.project.projectId??kf(k),S=await bf(k,R,u);d({kind:"preview",name:S.title??u,text:S.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${u}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let u=g[0]?.trim();if(!u){let R=zn(ys(e));Qe({cursor:R,current:R});return}let{lines:m,changed:w,effective:k}=on(e,u);for(let R of m)d({kind:"note",tone:R.startsWith("\u26A0")?"warn":R.startsWith("\u2713")?"ok":"info",text:R});w&&(As(R=>R+1),ye.current?.setModel(k));return}case"convert":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:m}=wr(g),w=Ff(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 k=yr(w,u);if(k.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${w.length} are tracked overall.)`});return}let R=hs(k),S=3,J=`/convert${u?` --scope ${u}`:""} --run`,q=go(e,"light");if(!m){let $=$l({files:kr(e,k),op:"convert",model:q.model}),j=u?`Scope: ${u} (${k.length} of ${w.length} tracked)
|
|
277
278
|
`:"",U=`
|
|
278
|
-
Model: ${q.model}${q.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:j+xr(R
|
|
279
|
-
`)+U}),Y([J]);return}Ke.current=Date.now(),ft(0),_(!0);let M=new AbortController;
|
|
280
|
-
`)})}}catch(
|
|
279
|
+
Model: ${q.model}${q.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:j+xr(R,$,S).join(`
|
|
280
|
+
`)+U}),Y([J]);return}Ke.current=Date.now(),ft(0),_(!0);let M=new AbortController;xe.current=M,te({verb:"Converting",total:R.length,done:0,active:[],rows:an(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${k.length} articles across ${R.length} partitions (\u2264${S} agents at once) on ${q.model}\u2026 (esc to stop)`});try{for await(let $ of ho({cwd:e,partitions:R,promptFor:br,concurrency:S,profileName:s,allowProdWrites:wt.current,model:q.model,signal:M.signal}))if($.type==="partition_status")$.status==="running"?te(j=>j&&{...j,active:[...j.active,$.label],rows:_e(j.rows,$.label,"active"),lastAt:Date.now()}):te(j=>j&&{...j,active:j.active.filter(U=>U!==$.label),done:j.done+1,rows:_e(j.rows,$.label,$.status==="done"?"done":"failed"),lastAt:Date.now()});else if($.type==="partition_event")te(j=>{if(!j)return j;let U={...j,lastAt:Date.now()};return $.event.type==="tool"?U.tools=j.tools+1:$.event.type==="text"&&(U.chars=j.chars+$.event.delta.length),U});else if($.type==="run_done"){Ct(z=>z+$.totalCostUsd),vt(z=>z+$.results.reduce((ge,Tt)=>ge+Tt.outputTokens,0));let j=$.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";d({kind:"note",tone:$.aborted?"warn":$.ok?"ok":"warn",text:j+$r($.results,R,U).join(`
|
|
281
|
+
`)})}}catch($){d({kind:"note",tone:"error",text:`Convert run failed: ${$.message}`})}finally{xe.current=null,te(null),_(!1),ie($=>$+1)}return}case"write":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=vl(e);if(u.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:w,preview:k,concurrency:R,rewrite:S}=Cr(g),{docsDir:J,targets:q,reason:M,rewriting:$}=jr(e,u,{scope:m,path:w,rewrite:S});if(q.length===0){d({kind:"note",tone:"warn",text:M??"Nothing to write."});return}$&&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=hs(q),U=vr(R),z=go(e,"standard"),ge=!!w;if(k&&!ge){let K=$l({files:Rr(e,u,q),op:"write",model:z.model}),Z=m?`Scope: ${m} (${q.length} pending)
|
|
281
282
|
`:"",Ee=`
|
|
282
283
|
Model: ${z.model}${z.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:Z+Sr(j,K,U).join(`
|
|
283
|
-
`)+Ee}),Y([`/write${m?` --scope ${m}`:""}`]);return}Ke.current=Date.now(),ft(0),_(!0);let Tt=new AbortController;
|
|
284
|
-
`)}),!K.aborted&&K.ok&&Y(["/publish --all","/screenshot --all"])}}catch(K){d({kind:"note",tone:"error",text:`Write run failed: ${K.message}`})}finally{
|
|
284
|
+
`)+Ee}),Y([`/write${m?` --scope ${m}`:""}`]);return}Ke.current=Date.now(),ft(0),_(!0);let Tt=new AbortController;xe.current=Tt,te({verb:"Writing",total:j.length,done:0,active:[],rows:an(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 ${z.model}${z.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let K of ho({cwd:e,partitions:j,promptFor:Z=>Tr(Z,J,{rewrite:$||ge}),concurrency:U,profileName:s,allowProdWrites:wt.current,model:z.model,signal:Tt.signal}))if(K.type==="partition_status")K.status==="running"?te(Z=>Z&&{...Z,active:[...Z.active,K.label],rows:_e(Z.rows,K.label,"active"),lastAt:Date.now()}):te(Z=>Z&&{...Z,active:Z.active.filter(Ee=>Ee!==K.label),done:Z.done+1,rows:_e(Z.rows,K.label,K.status==="done"?"done":"failed"),lastAt:Date.now()});else if(K.type==="partition_event")te(Z=>{if(!Z)return Z;let Ee={...Z,lastAt:Date.now()};return K.event.type==="tool"?Ee.tools=Z.tools+1:K.event.type==="text"&&(Ee.chars=Z.chars+K.event.delta.length),Ee});else if(K.type==="run_done"){Ct(Ho=>Ho+K.totalCostUsd),vt(Ho=>Ho+K.results.reduce((Yl,Gl)=>Yl+Gl.outputTokens,0));let Z=K.aborted?"Stopped. ":"",Ee=t.kind==="api"?"api":"subscription";d({kind:"note",tone:K.aborted?"warn":K.ok?"ok":"warn",text:Z+Dr(K.results,j,Ee).join(`
|
|
285
|
+
`)}),!K.aborted&&K.ok&&Y(["/publish --all","/screenshot --all"])}}catch(K){d({kind:"note",tone:"error",text:`Write run failed: ${K.message}`})}finally{xe.current=null,te(null),_(!1),ie(K=>K+1)}return}case"draft":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:m}=Ar(e);if(u.length===0&&m===0){d({kind:"note",tone:"info",text:Ir});return}let w=g.join(" ").trim();if(!w&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
285
286
|
${u.map(S=>` \u2022 ${S.name} (${S.docCount} doc${S.docCount===1?"":"s"})`).join(`
|
|
286
287
|
`)}`}),Y(u.map(S=>`/draft ${S.name}`));return}let k="",R;if(w){let S=Er(u,w);S?k=S:R=w}else k=u[0]?.name??"";await ce(Vn(k,R),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!Eo(l.trim()))return;let u=g.find(m=>m.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let k=Date.now(),R=await xl({cwd:e,profileName:s});d({kind:"note",tone:"info",text:Yn(R,Date.now()-k).join(`
|
|
287
288
|
`)});return}if(u==="--baseline"){let k=g.find(q=>!q.startsWith("--")),R=k?k.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 Nf({cwd:e,profileName:s,relPaths:R?[R]:void 0}),J=R?{rebaselined:[],skipped:[]}:await _f({cwd:e,profileName:s});if(S.baselined.length===0&&S.skipped.length===0&&J.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.`}),J.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${J.rebaselined.length} article${J.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),S.skipped.length>0&&d({kind:"note",tone:"warn",text:`${S.skipped.length} skipped:
|
|
@@ -290,11 +291,11 @@ ${S.skipped.map(q=>` - ${q.path} (${q.reason})`).join(`
|
|
|
290
291
|
`)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=g[0];if(m){let k=await If({cwd:e,profileName:s,relPath:m.replace(/\\/g,"/")});Ue.current=[k],vn();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let w=await mr({cwd:e,profileName:s});for(let k of hr(w))d({kind:"note",tone:k.tone,text:k.text});ie(k=>k+1)}catch(m){d({kind:"note",tone:"error",text:`Pull failed: ${m.message}`})}return}case"scope":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Mf(e);if(u.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}$t({cursor:0,rows:u.map(m=>({...m,checked:m.recommended}))});return}case"audit":{if(g[0]==="--auto"){let m=ee(e);if(!m){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=g[1]!=="off";bl({...m,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let u=await nn();u.kind==="forward-to-agent"&&u.prompt&&await ce(u.prompt,{display:u.display,quietUser:!0});return}case"capture-setup":{let u=await sn();u.kind==="forward-to-agent"&&u.prompt&&await ce(u.prompt,{display:u.display,quietUser:!0});let m=Yr(e);m&&d({kind:"note",tone:"info",text:m.join(`
|
|
291
292
|
`)});return}case"devhints":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:At(jt(e)).join(`
|
|
292
293
|
`)}),Pt(it()),Ht.current=Ie(e).status==="current"||Xt(e);return}case"inbox":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Gr(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 ce(Vr(),{display:"/inbox",quietUser:!0});return}case"document":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:m}=_r(g);if(!m&&Nr(e)===0){d({kind:"note",tone:"info",text:Or});return}let w=`/document${m?` ${m}`:""}${u?" --publish":""}`;await ce(Mr(m,u),{display:w,quietUser:!0});return}case"catch-up":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Eo(l.trim()))return;let{publish:u}=Kr(g);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let m=await Jr({cwd:e,profileName:s});for(let k of Qr(m))d({kind:"note",tone:k.startsWith("\u2713")?"ok":k.startsWith("\u2139")?"info":"warn",text:k});let w=_t(Nt(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ce(Xr({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{jo.current=!0,d({kind:"note",tone:"info",text:`Updating ${ut}\u2026 (don\u2019t close this window)`}),dn(!0),(await Zn().finally(()=>dn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),Y(m=>m.includes("/exit")?m:[...m,"/exit"]),vs("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Qn}`});return}case"screenshot":{let u=Hr(g);if(u.mode==="list"){if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Br(qr(e,u.scope),u.scope).join(`
|
|
293
|
-
`)});return}if(u.mode==="single"){let M=await Xn(g);M.kind==="forward-to-agent"&&M.prompt&&await ce(M.prompt,{display:M.display,quietUser:!0});return}if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=u.mode==="scope"?u.scope:void 0,w=Wf(e,{scope:m}).map(M=>M.id);if(w.length===0){d({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let k=6,R=Uf(w,3),S=go(e,"standard");Ke.current=Date.now(),ft(0),_(!0);let J=new AbortController;
|
|
294
|
+
`)});return}if(u.mode==="single"){let M=await Xn(g);M.kind==="forward-to-agent"&&M.prompt&&await ce(M.prompt,{display:M.display,quietUser:!0});return}if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=u.mode==="scope"?u.scope:void 0,w=Wf(e,{scope:m}).map(M=>M.id);if(w.length===0){d({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let k=6,R=Uf(w,3),S=go(e,"standard");Ke.current=Date.now(),ft(0),_(!0);let J=new AbortController;xe.current=J,te({verb:"Authoring",unit:"spec",total:R.length,done:0,active:[],rows:an(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${k} agents at once) on ${S.model}${S.forced?" (forced)":""}\u2026 (esc to stop)`});let q=!1;try{for await(let M of ho({cwd:e,partitions:R,promptFor:Ra,concurrency:k,profileName:s,allowProdWrites:wt.current,model:S.model,signal:J.signal}))if(M.type==="partition_status")M.status==="running"?te($=>$&&{...$,active:[...$.active,M.label],rows:_e($.rows,M.label,"active"),lastAt:Date.now()}):te($=>$&&{...$,active:$.active.filter(j=>j!==M.label),done:$.done+1,rows:_e($.rows,M.label,M.status==="done"?"done":"failed"),lastAt:Date.now()});else if(M.type==="partition_event")te($=>{if(!$)return $;let j={...$,lastAt:Date.now()};return M.event.type==="tool"?j.tools=$.tools+1:M.event.type==="text"&&(j.chars=$.chars+M.event.delta.length),j});else if(M.type==="run_done"){Ct(z=>z+M.totalCostUsd),vt(z=>z+M.results.reduce((ge,Tt)=>ge+Tt.outputTokens,0));let $=M.results.filter(z=>z.ok).length,j=M.aborted?"Stopped. ":"";q=!M.aborted&&u.setup;let U=M.aborted?"":q?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:M.aborted?"warn":M.ok?"ok":"warn",text:`${j}Authored specs \u2014 ${$}/${M.results.length} batches ok.${U}`})}}catch(M){d({kind:"note",tone:"error",text:`Spec authoring failed: ${M.message}`})}finally{xe.current=null,te(null),_(!1),ie(M=>M+1)}if(q){let M=await sn();M.kind==="forward-to-agent"&&M.prompt&&await ce(M.prompt,{display:M.display,quietUser:!0});let $=Yr(e);$&&d({kind:"note",tone:"info",text:$.join(`
|
|
294
295
|
`)})}return}case"reset":{let u=ts(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}vo.current={repoName:ln(e),targets:u,hadDevhints:Ge(ks(e))},d({kind:"note",tone:"warn",text:os(e,u).join(`
|
|
295
|
-
`)}),le(ln(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,vn,d,he,ce,kn,Lo,Ms]),Cn=G(l=>{let i=(l??D).trim();if(y(""),pn(null),mt(0),i.startsWith("/")&&(le(null),pt.current++,tt(null),Y(g=>al(g,i))),!i||Ls(i)||Os(i))return;$o.current.push(i);let a=pl(i,Cs.current);i.startsWith("/")?(d({kind:"user",text:i}),Us(a)):ce(a,{display:i})},[D,Ls,Os,Us,ce]),Ws=G(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=cl(l);if(ul(i)){let a=dl(++Wl.current,i);Cs.current.set(a,i),P(a)}else P(i);return}P(l)},[P]),Rt=Math.max(10,Ae-6),Fs=ps(()=>fo(b.text,Rt),[b.text,Rt]),Fo=G(l=>x(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),Pn=G(l=>x(i=>({...i,pos:ml(fo(i.text,Rt),i.pos,l)})),[Rt]),Yt=G(l=>x(i=>({...i,pos:hl(fo(i.text,Rt),i.pos,l)})),[Rt]),ql=["\x1B[H","\x1B[1~","\x1BOH"],Bl=["\x1B[F","\x1B[4~","\x1BOF"],Hs=G((l,i)=>i.leftArrow?(Fo(-1),!0):i.rightArrow?(Fo(1),!0):l&&ql.includes(l)?(Yt("start"),!0):l&&Bl.includes(l)?(Yt("end"),!0):i.ctrl&&l==="a"?(Yt("start"),!0):i.ctrl&&l==="e"?(Yt("end"),!0):!1,[Fo,Yt]);return uf((l,i)=>{if(i.ctrl&&l==="c"){we.current?.close(),r();return}if(!L){if(I){if(i.escape){if(be.current){be.current.signal.aborted||(d({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),be.current.abort());return}Ut.current||(Ut.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),we.current?.interrupt());return}if(i.return){let a=D.trim();if(!a)return;ot.current.push(a),Po([...ot.current]),y("");return}if(Hs(l,i))return;if(i.upArrow){Pn(-1);return}if(i.downArrow){Pn(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&Ws(l);return}if(Je){if(i.upArrow){Qe(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Qe(a=>a&&{...a,cursor:Math.min(Se.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Se.length){Qe(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Se[Je.cursor];Qe(null);let{lines:g,changed:u,effective:m}=on(e,a.value??"default");for(let w of g)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});u&&(As(w=>w+1),we.current?.setModel(m));return}if(l==="s"){let a=Se[Je.cursor];Qe(null),we.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){Qe(null);return}return}if(je){if(i.upArrow){yt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){yt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=je.rows.length){yt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=je.rows[je.cursor];yt(null),Wo(a.name,i.return===!0);return}if(i.escape){yt(null);return}return}if(Ro){if(i.escape){Ft(null);return}if(i.leftArrow||i.tab&&i.shift){Ft(a=>a&&{tab:(a.tab-1+ve.length)%ve.length});return}if(i.rightArrow||i.tab){Ft(a=>a&&{tab:(a.tab+1)%ve.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ve.length){Ft({tab:Number(l)-1});return}return}if(We){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)<=We.rows.length){kt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=We.rows[We.cursor].name;if(kt(null),!$i(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 u=!1;try{let m=Ve(a);u=!!m&&!(Oe(m)&&!m.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),Y(["/login"]),ie(m=>m+1);return}if(i.escape){kt(null);return}return}if(pe){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)<=pe.rows.length){bt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=pe.rows[pe.cursor],{profile:g,projectId:u}=pe;bt(null),bn(g,u,a);return}if(i.escape){bt(null);return}return}if(ye){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(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ye.rows.length){Ze(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ye.rows[ye.cursor],{profile:g}=ye;Ze(null),$n(g,a);return}if(i.escape){Ze(null);return}return}if(me){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===" "){$t(a=>a&&{...a,rows:a.rows.map((g,u)=>u===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=me.rows.filter(g=>g.checked).map(g=>g.path);if($t(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}dr(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){$t(null);return}return}if(et){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)<=et.rows.length){xt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=et.rows[et.cursor];xt(null),a.kind==="article"?Lo(a.paths[0]):kn(a.paths);return}if(i.escape){xt(null);return}return}if(ke){if(i.escape){nt(null);return}if(i.upArrow){nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){nt(a=>a&&{...a,cursor:Math.min(Math.max(0,wn.length-1),a.cursor+1)});return}if(i.return){let a=wn[ke.cursor];if(a){nt(null);try{d({kind:"preview",name:ln(a),text:Rl(fs(dt(e,a),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){nt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){nt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(xe){if(i.escape){rt(null);return}if(i.upArrow){rt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){rt(a=>a&&{...a,cursor:Math.min(Math.max(0,yn.length-1),a.cursor+1)});return}if(i.return){let a=yn[xe.cursor];if(a){rt(null),he(a.uuid),De.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Xe(a.name),ms(a.uuid),gt.current=[];let g=ls(e,a.uuid);for(let u of g)d(u);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){rt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){rt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!D&&Pe){y(Pe),le(null),pt.current++;return}if(!D&&ze.length>0&&l&&/^[1-9]$/.test(l)){let a=ze[Number(l)-1];if(a){y(a);return}}if(!D&&(Io||So)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=Io!=null;Va(Io??So).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?a?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&a&&No(null)});return}if(!Hs(l,i)){if(Ns){if(i.upArrow){mt(a=>Math.max(0,a-1));return}if(i.downArrow){mt(a=>Math.min(Bt.length-1,a+1));return}if(i.tab){y("/"+(Bt[Lt]?.name??"")+" "),mt(0);return}if(i.return){let a=Bt[Lt];if(a){let g=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(nl(a.usage)&&!g){y("/"+a.name+" "),mt(0);return}Cn("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(D!==""&&ht===null){Pn(-1);return}let a=$o.current;if(!a.length)return;let g=ht===null?a.length-1:Math.max(0,ht-1);pn(g),y(a[g]??"");return}if(i.downArrow){if(D!==""&&ht===null){Pn(1);return}let a=$o.current;if(ht===null)return;let g=ht+1;g>=a.length?(pn(null),y("")):(pn(g),y(a[g]??""));return}}if(i.return){Cn();return}if(i.backspace||i.delete){C();return}if(i.escape){y(""),mt(0),le(null),Y([]),tt(null);return}l&&!i.ctrl&&!i.meta&&Ws(l)}}}),Ce(()=>{if(I||L)return;let l=ot.current.shift();l!==void 0&&(Po([...ot.current]),Cn(l))},[I,L,Cn]),B(ne,{flexDirection:"column",width:Ae,children:[Oo!==null&&B(ne,{marginTop:1,flexDirection:"column",children:[Oo.truncated&&A(T,{dimColor:!0,children:"\u2026"}),A(T,{children:Oo.text})]}),I&&(Ss?A(om,{p:Ss}):A(tm,{startTime:Ke.current,chars:Ul})),A(ne,{borderStyle:"round",borderColor:Is.prod?"yellow":W,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?Fs.map((l,i)=>{let a=b.text.slice(l.start,l.end),g=i===mo(Fs,b.pos),u=Math.min(b.pos,l.end)-l.start;return B(T,{children:[A(T,{color:W,children:i===0?"> ":" "}),g?B(gs,{children:[a.slice(0,u),A(wo,{ch:a[u]??" "}),a.slice(u+1)]}):a||" "]},`${i}-${l.start}`)}):B(T,{children:[A(T,{color:W,children:"> "}),Pe&&!I?B(gs,{children:[A(wo,{ch:Pe[0],dim:!0}),A(T,{color:"gray",children:Pe.slice(1)}),A(T,{dimColor:!0,children:" (tab)"})]}):(Mo.isSetup||!Ol)&&!I?B(gs,{children:[A(wo,{ch:Mo.text[0],dim:!0}),A(T,{color:"gray",children:Mo.text.slice(1)})]}):A(wo,{ch:" "})]})}),Ts.length>0&&A(ne,{flexDirection:"column",paddingX:1,children:Ts.map((l,i)=>A(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Ro?A(rl,{tab:Ro.tab,width:Ae}):Je?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Select model"}),A(T,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),Se.map((l,i)=>B(T,{color:i===Je.cursor?W:void 0,children:[i===Je.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===Je.current?" \u2714":""}`.padEnd(16),A(T,{color:"gray",children:l.desc})]},l.label)),A(T,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):je?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Switch connection profile"}),je.rows.map((l,i)=>B(T,{color:i===je.cursor?W:void 0,children:[i===je.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===je.current?" \u2714":""}`.padEnd(20),A(T,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?A(T,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),A(T,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):We?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Pick your Document360 environment"}),We.rows.map((l,i)=>B(T,{color:i===We.cursor?W:void 0,children:[i===We.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),A(T,{color:"gray",children:l.apiUrl})]},l.name)),A(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):pe?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Switch workspace"}),A(T,{dimColor:!0,children:`environment ${pe.environment} \xB7 project ${pe.projectName??`${pe.projectId.slice(0,8)}\u2026`}`}),pe.rows.map((l,i)=>B(T,{color:i===pe.cursor?W:void 0,children:[i===pe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===pe.current?" \u2714":""}`.padEnd(30),A(T,{color:"gray",children:l.type??""})]},l.id)),A(T,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ye?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Choose project"}),A(T,{dimColor:!0,children:`environment ${ye.environment}`}),ye.rows.map((l,i)=>B(T,{color:i===ye.cursor?W:void 0,children:[i===ye.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===ye.current?" \u2714":""}`.padEnd(30),A(T,{color:"gray",children:l.sub??""})]},l.id)),A(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):me?(()=>{let i=Math.min(Math.max(0,me.cursor-Math.floor(7)),Math.max(0,me.rows.length-14)),a=me.rows.slice(i,i+14),g=me.rows.filter(u=>u.checked).length;return B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:`Which folders back the user docs? (${g} selected of ${me.rows.length})`}),i>0?A(T,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((u,m)=>{let w=i+m;return B(T,{color:w===me.cursor?W:void 0,children:[w===me.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Ae-34)),A(T,{color:"gray",children:Bn(u)})]},u.path)}),i+14<me.rows.length?A(T,{dimColor:!0,children:` \u2193 ${me.rows.length-i-14} more`}):null,A(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():et?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),et.rows.map((l,i)=>{let a=i===et.cursor,g=l.indent?" ":" ",u=`${i+1}.`.padEnd(3);return B(T,{color:a?W:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${u} ${l.label}`.padEnd(Math.min(56,Ae-24)),l.note?A(T,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),A(T,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ke?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:`Preview article${ke.query?` \u2014 filter: ${ke.query}`:" (type to filter)"}`}),wn.length===0?A(T,{color:"gray",children:"no articles match"}):wn.map((l,i)=>B(T,{color:i===ke.cursor?W:void 0,children:[i===ke.cursor?"\u276F ":" ",l]},l)),A(T,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):xe?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:`Resume session${xe.query?` \u2014 filter: ${xe.query}`:" (type to filter)"}`}),yn.length===0?A(T,{color:"gray",children:"no sessions match"}):yn.map((l,i)=>B(T,{color:i===xe.cursor?W:void 0,children:[i===xe.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),A(T,{color:i===xe.cursor?W:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ae-40))})]},l.uuid)),A(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Ns?B(ne,{flexDirection:"column",children:[Bt.map((l,i)=>B(T,{color:i===Lt?W:void 0,children:[i===Lt?"\u276F ":" ",l.usage.padEnd(22)," ",A(T,{color:i===Lt?W:"gray",children:l.name==="model"&&To?`${l.desc} (currently ${To})`:l.desc})]},l.name)),A(T,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!I&&!D&&ze.length>0?B(ne,{flexDirection:"column",paddingX:1,children:[Rs?A(T,{color:W,children:Rs}):null,ze.map((l,i)=>{let a=l.slice(0,Math.max(20,Ae-5)),g=Ae-a.length-7,u=g>=12?el(l).slice(0,g):"";return B(T,{children:[A(T,{color:W,children:i+1})," ",a,u?A(T,{dimColor:!0,children:` \u2014 ${u}`}):null]},l)}),A(T,{dimColor:!0,children:`press 1-${ze.length} to fill the command \xB7 esc dismiss`})]}):A(ne,{paddingX:1,children:B(T,{color:"gray",children:[Is.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${To??"model n/a"}${t.kind==="api"?js>0?` \xB7 ${fe(js)}`:"":Ds>0?` \xB7 ${Be(Ds)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}F();import{jsx as am}from"react/jsx-runtime";async function Al(e=process.cwd(),t="auto",n,o="0.0.0"){let r=im(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${N("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${N("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=sm(am(jl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
296
|
+
`)}),le(ln(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,vn,d,he,ce,kn,Lo,Ms]),Cn=G(l=>{let i=(l??D).trim();if(y(""),pn(null),mt(0),i.startsWith("/")&&(le(null),pt.current++,tt(null),Y(g=>al(g,i))),!i||Ls(i)||Os(i))return;$o.current.push(i);let a=pl(i,Cs.current);i.startsWith("/")?(d({kind:"user",text:i}),Us(a)):ce(a,{display:i})},[D,Ls,Os,Us,ce]),Ws=G(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=cl(l);if(ul(i)){let a=dl(++Wl.current,i);Cs.current.set(a,i),P(a)}else P(i);return}P(l)},[P]),Rt=Math.max(10,Ae-6),Fs=ps(()=>fo(b.text,Rt),[b.text,Rt]),Fo=G(l=>x(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),Pn=G(l=>x(i=>({...i,pos:ml(fo(i.text,Rt),i.pos,l)})),[Rt]),Yt=G(l=>x(i=>({...i,pos:hl(fo(i.text,Rt),i.pos,l)})),[Rt]),ql=["\x1B[H","\x1B[1~","\x1BOH"],Bl=["\x1B[F","\x1B[4~","\x1BOF"],Hs=G((l,i)=>i.leftArrow?(Fo(-1),!0):i.rightArrow?(Fo(1),!0):l&&ql.includes(l)?(Yt("start"),!0):l&&Bl.includes(l)?(Yt("end"),!0):i.ctrl&&l==="a"?(Yt("start"),!0):i.ctrl&&l==="e"?(Yt("end"),!0):!1,[Fo,Yt]);return uf((l,i)=>{if(i.ctrl&&l==="c"){ye.current?.close(),r();return}if(!L){if(I){if(i.escape){if(xe.current){xe.current.signal.aborted||(d({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),xe.current.abort());return}Ut.current||(Ut.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),ye.current?.interrupt());return}if(i.return){let a=D.trim();if(!a)return;ot.current.push(a),Po([...ot.current]),y("");return}if(Hs(l,i))return;if(i.upArrow){Pn(-1);return}if(i.downArrow){Pn(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&Ws(l);return}if(Je){if(i.upArrow){Qe(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Qe(a=>a&&{...a,cursor:Math.min(Se.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Se.length){Qe(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Se[Je.cursor];Qe(null);let{lines:g,changed:u,effective:m}=on(e,a.value??"default");for(let w of g)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});u&&(As(w=>w+1),ye.current?.setModel(m));return}if(l==="s"){let a=Se[Je.cursor];Qe(null),ye.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){Qe(null);return}return}if(je){if(i.upArrow){yt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){yt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=je.rows.length){yt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=je.rows[je.cursor];yt(null),Wo(a.name,i.return===!0);return}if(i.escape){yt(null);return}return}if(Ro){if(i.escape){Ft(null);return}if(i.leftArrow||i.tab&&i.shift){Ft(a=>a&&{tab:(a.tab-1+Ce.length)%Ce.length});return}if(i.rightArrow||i.tab){Ft(a=>a&&{tab:(a.tab+1)%Ce.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ce.length){Ft({tab:Number(l)-1});return}return}if(We){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)<=We.rows.length){kt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=We.rows[We.cursor].name;if(kt(null),!$i(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 u=!1;try{let m=Ve(a);u=!!m&&!(Oe(m)&&!m.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),Y(["/login"]),ie(m=>m+1);return}if(i.escape){kt(null);return}return}if(pe){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)<=pe.rows.length){bt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=pe.rows[pe.cursor],{profile:g,projectId:u}=pe;bt(null),bn(g,u,a);return}if(i.escape){bt(null);return}return}if(ke){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(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ke.rows.length){Ze(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ke.rows[ke.cursor],{profile:g}=ke;Ze(null),$n(g,a);return}if(i.escape){Ze(null);return}return}if(me){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===" "){$t(a=>a&&{...a,rows:a.rows.map((g,u)=>u===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=me.rows.filter(g=>g.checked).map(g=>g.path);if($t(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}dr(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){$t(null);return}return}if(et){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)<=et.rows.length){xt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=et.rows[et.cursor];xt(null),a.kind==="article"?Lo(a.paths[0]):kn(a.paths);return}if(i.escape){xt(null);return}return}if(be){if(i.escape){nt(null);return}if(i.upArrow){nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){nt(a=>a&&{...a,cursor:Math.min(Math.max(0,wn.length-1),a.cursor+1)});return}if(i.return){let a=wn[be.cursor];if(a){nt(null);try{d({kind:"preview",name:ln(a),text:Rl(fs(dt(e,a),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){nt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){nt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if($e){if(i.escape){rt(null);return}if(i.upArrow){rt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){rt(a=>a&&{...a,cursor:Math.min(Math.max(0,yn.length-1),a.cursor+1)});return}if(i.return){let a=yn[$e.cursor];if(a){rt(null),he(a.uuid),De.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Xe(a.name),ms(a.uuid),gt.current=[];let g=ls(e,a.uuid);for(let u of g)d(u);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){rt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){rt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!D&&Re){y(Re),le(null),pt.current++;return}if(!D&&ze.length>0&&l&&/^[1-9]$/.test(l)){let a=ze[Number(l)-1];if(a){y(a);return}}if(!D&&(Io||So)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=Io!=null;Va(Io??So).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?a?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&a&&No(null)});return}if(!Hs(l,i)){if(Ns){if(i.upArrow){mt(a=>Math.max(0,a-1));return}if(i.downArrow){mt(a=>Math.min(Bt.length-1,a+1));return}if(i.tab){y("/"+(Bt[Lt]?.name??"")+" "),mt(0);return}if(i.return){let a=Bt[Lt];if(a){let g=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(nl(a.usage)&&!g){y("/"+a.name+" "),mt(0);return}Cn("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(D!==""&&ht===null){Pn(-1);return}let a=$o.current;if(!a.length)return;let g=ht===null?a.length-1:Math.max(0,ht-1);pn(g),y(a[g]??"");return}if(i.downArrow){if(D!==""&&ht===null){Pn(1);return}let a=$o.current;if(ht===null)return;let g=ht+1;g>=a.length?(pn(null),y("")):(pn(g),y(a[g]??""));return}}if(i.return){Cn();return}if(i.backspace||i.delete){C();return}if(i.escape){y(""),mt(0),le(null),Y([]),tt(null);return}l&&!i.ctrl&&!i.meta&&Ws(l)}}}),Pe(()=>{if(I||L)return;let l=ot.current.shift();l!==void 0&&(Po([...ot.current]),Cn(l))},[I,L,Cn]),B(ne,{flexDirection:"column",width:Ae,children:[Oo!==null&&B(ne,{marginTop:1,flexDirection:"column",children:[Oo.truncated&&A(T,{dimColor:!0,children:"\u2026"}),A(T,{children:Oo.text})]}),I&&(Ss?A(om,{p:Ss}):A(tm,{startTime:Ke.current,chars:Ul})),A(ne,{borderStyle:"round",borderColor:Is.prod?"yellow":W,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?Fs.map((l,i)=>{let a=b.text.slice(l.start,l.end),g=i===mo(Fs,b.pos),u=Math.min(b.pos,l.end)-l.start;return B(T,{children:[A(T,{color:W,children:i===0?"> ":" "}),g?B(gs,{children:[a.slice(0,u),A(wo,{ch:a[u]??" "}),a.slice(u+1)]}):a||" "]},`${i}-${l.start}`)}):B(T,{children:[A(T,{color:W,children:"> "}),Re&&!I?B(gs,{children:[A(wo,{ch:Re[0],dim:!0}),A(T,{color:"gray",children:Re.slice(1)}),A(T,{dimColor:!0,children:" (tab)"})]}):(Mo.isSetup||!Ol)&&!I?B(gs,{children:[A(wo,{ch:Mo.text[0],dim:!0}),A(T,{color:"gray",children:Mo.text.slice(1)})]}):A(wo,{ch:" "})]})}),Ts.length>0&&A(ne,{flexDirection:"column",paddingX:1,children:Ts.map((l,i)=>A(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Ro?A(rl,{tab:Ro.tab,width:Ae}):Je?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Select model"}),A(T,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),Se.map((l,i)=>B(T,{color:i===Je.cursor?W:void 0,children:[i===Je.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===Je.current?" \u2714":""}`.padEnd(16),A(T,{color:"gray",children:l.desc})]},l.label)),A(T,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):je?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Switch connection profile"}),je.rows.map((l,i)=>B(T,{color:i===je.cursor?W:void 0,children:[i===je.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===je.current?" \u2714":""}`.padEnd(20),A(T,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?A(T,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),A(T,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):We?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Pick your Document360 environment"}),We.rows.map((l,i)=>B(T,{color:i===We.cursor?W:void 0,children:[i===We.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),A(T,{color:"gray",children:l.apiUrl})]},l.name)),A(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):pe?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Switch workspace"}),A(T,{dimColor:!0,children:`environment ${pe.environment} \xB7 project ${pe.projectName??`${pe.projectId.slice(0,8)}\u2026`}`}),pe.rows.map((l,i)=>B(T,{color:i===pe.cursor?W:void 0,children:[i===pe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===pe.current?" \u2714":""}`.padEnd(30),A(T,{color:"gray",children:l.type??""})]},l.id)),A(T,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ke?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Choose project"}),A(T,{dimColor:!0,children:`environment ${ke.environment}`}),ke.rows.map((l,i)=>B(T,{color:i===ke.cursor?W:void 0,children:[i===ke.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===ke.current?" \u2714":""}`.padEnd(30),A(T,{color:"gray",children:l.sub??""})]},l.id)),A(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):me?(()=>{let i=Math.min(Math.max(0,me.cursor-Math.floor(7)),Math.max(0,me.rows.length-14)),a=me.rows.slice(i,i+14),g=me.rows.filter(u=>u.checked).length;return B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:`Which folders back the user docs? (${g} selected of ${me.rows.length})`}),i>0?A(T,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((u,m)=>{let w=i+m;return B(T,{color:w===me.cursor?W:void 0,children:[w===me.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Ae-34)),A(T,{color:"gray",children:Bn(u)})]},u.path)}),i+14<me.rows.length?A(T,{dimColor:!0,children:` \u2193 ${me.rows.length-i-14} more`}):null,A(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():et?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),et.rows.map((l,i)=>{let a=i===et.cursor,g=l.indent?" ":" ",u=`${i+1}.`.padEnd(3);return B(T,{color:a?W:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${u} ${l.label}`.padEnd(Math.min(56,Ae-24)),l.note?A(T,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),A(T,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):be?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:`Preview article${be.query?` \u2014 filter: ${be.query}`:" (type to filter)"}`}),wn.length===0?A(T,{color:"gray",children:"no articles match"}):wn.map((l,i)=>B(T,{color:i===be.cursor?W:void 0,children:[i===be.cursor?"\u276F ":" ",l]},l)),A(T,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):$e?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:`Resume session${$e.query?` \u2014 filter: ${$e.query}`:" (type to filter)"}`}),yn.length===0?A(T,{color:"gray",children:"no sessions match"}):yn.map((l,i)=>B(T,{color:i===$e.cursor?W:void 0,children:[i===$e.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),A(T,{color:i===$e.cursor?W:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ae-40))})]},l.uuid)),A(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Ns?B(ne,{flexDirection:"column",children:[Bt.map((l,i)=>B(T,{color:i===Lt?W:void 0,children:[i===Lt?"\u276F ":" ",l.usage.padEnd(22)," ",A(T,{color:i===Lt?W:"gray",children:l.name==="model"&&To?`${l.desc} (currently ${To})`:l.desc})]},l.name)),A(T,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!I&&!D&&ze.length>0?B(ne,{flexDirection:"column",paddingX:1,children:[Rs?A(T,{color:W,children:Rs}):null,ze.map((l,i)=>{let a=l.slice(0,Math.max(20,Ae-5)),g=Ae-a.length-7,u=g>=12?el(l).slice(0,g):"";return B(T,{children:[A(T,{color:W,children:i+1})," ",a,u?A(T,{dimColor:!0,children:` \u2014 ${u}`}):null]},l)}),A(T,{dimColor:!0,children:`press 1-${ze.length} to fill the command \xB7 esc dismiss`})]}):A(ne,{paddingX:1,children:B(T,{color:"gray",children:[Is.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${To??"model n/a"}${t.kind==="api"?js>0?` \xB7 ${fe(js)}`:"":Ds>0?` \xB7 ${Be(Ds)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}F();import{jsx as am}from"react/jsx-runtime";async function Al(e=process.cwd(),t="auto",n,o="0.0.0"){let r=im(t);r.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${N("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${N("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=sm(am(jl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
296
297
|
`),process.exit(0)}F();import{writeCrashLog as El,isBenignTransportError as lm}from"document360-engine";var Il=!1;function bs(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Nl(e){if(Il)return;Il=!0;let t=(n,o)=>{if(lm(o)){El({kind:n,level:"transport",message:bs(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=El({kind:n,level:"fatal",message:bs(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
297
|
-
|
|
298
|
+
`+v(`\u2717 d360-writer crashed: ${bs(o)}`)+`
|
|
298
299
|
`),r&&process.stderr.write(f(` Crash details: ${r}`)+`
|
|
299
300
|
`+f(" Run: d360-writer logs")+`
|
|
300
301
|
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var pm=um(import.meta.url),_l=pm("../package.json");Nl("d360-writer");var Le=new cm;function xs(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Le.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=>{xs(e),await Dn({profile:e.profile,manual:e.manual})});Le.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{xs(e),await ei({profile:e.profile})});Le.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{xs(e),await Zs({profile:e.profile})});var $s=Le.command("profile").description("Manage connection profiles for the current repo");$s.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>jn(process.cwd()));$s.command("use <name>").description("Set the default profile for this repo").action(e=>An(process.cwd(),e));$s.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>En(process.cwd(),e));var Ml=Le.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Ml.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>St(process.cwd(),e.profile));Ml.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Ys(process.cwd(),e,t.profile)});Le.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>ri());Le.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(()=>(Kn(),ya)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Le.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(_l.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 si(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 Ya(e.cwd,e.auth,e.profile):await Al(e.cwd,e.auth,e.profile,_l.version)});Le.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|
package/dist/commands/write.d.ts
CHANGED
|
@@ -30,8 +30,13 @@ export declare function pendingArticles(cwd: string, docsDir: string, paths: str
|
|
|
30
30
|
1-byte floor keeps every planned article in the estimate so its per-article overhead counts. */
|
|
31
31
|
export declare function sizeWriteTargets(cwd: string, entries: DocsPlanEntry[], paths: string[]): TargetFile[];
|
|
32
32
|
/** The agent prompt for one partition: author each listed article from the plan. Each is
|
|
33
|
-
independent; purpose + sources are looked up from the pinned plan, grounded in source.
|
|
34
|
-
|
|
33
|
+
independent; purpose + sources are looked up from the pinned plan, grounded in source.
|
|
34
|
+
`rewrite` ⇒ the targets already exist (a `--rewrite`/single-path re-author): tell the agent to rebuild
|
|
35
|
+
from plan + sources + the active doc-type playbook, NOT to preserve or lightly-edit the old file — else
|
|
36
|
+
it anchors on the prior (possibly junior) output and reproduces it (dogfood P-A A5). */
|
|
37
|
+
export declare function buildWritePrompt(partition: Partition, docsDir: string, opts?: {
|
|
38
|
+
rewrite?: boolean;
|
|
39
|
+
}): string;
|
|
35
40
|
/** Preview lines for `/write --preview`: the partition plan + the cost band, before any spend. */
|
|
36
41
|
export declare function previewLines(partitions: Partition[], estimate: CostEstimate, concurrency: number): string[];
|
|
37
42
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "document360-writer",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.38",
|
|
4
4
|
"description": "Standalone documentation agent CLI. Reads your code, writes your docs. Specialized for Document360 publishing.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"@inquirer/prompts": "^8.4.3",
|
|
35
35
|
"commander": "^14.0.3",
|
|
36
36
|
"diff": "^8.0.4",
|
|
37
|
-
"document360-engine": "^0.2.
|
|
37
|
+
"document360-engine": "^0.2.76",
|
|
38
38
|
"ink": "^5.2.1",
|
|
39
39
|
"picocolors": "^1.1.1",
|
|
40
40
|
"react": "^18.3.1",
|