document360-writer 0.5.79 → 0.5.80

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.
Files changed (2) hide show
  1. package/dist/cli.js +96 -96
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var fd=Object.defineProperty;var Gn=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Is=(e,t)=>{for(var n in t)fd(e,n,{get:t[n],enumerable:!0})};import Be from"picocolors";var F,md,hd,gd,Ns,nn,f,$,L,I,_,ae,Pe,U=Gn(()=>{"use strict";F="#7f56d9",[md,hd,gd]=[127,86,217],Ns=e=>Be.isColorSupported?`\x1B[38;2;${md};${hd};${gd}m${e}\x1B[39m`:e,nn=e=>Be.bold(Ns(e)),f=e=>Be.dim(e),$=e=>Be.red(e),L=e=>Be.yellow(e),I=e=>Be.green(e),_=Ns,ae=e=>Be.gray(e),Pe=e=>Be.bold(e)});import{existsSync as Lt,writeFileSync as ct,readFileSync as eu,readdirSync as tu}from"node:fs";import{join as nu}from"node:path";import{devHintsGuidePath as oo,hintsDir as Js,architectureDir as oa,messagesDir as wr,creatorNotesPath as Zs,devhintsStatePath as ra,directivesPath as ea,DIRECTIVES_HEADER as ou,roadmapPath as ta,ROADMAP_HEADER as ru,ensureDir as no,writeMessage as iu,listOpenForDev as su}from"document360-engine";function ia(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var md=Object.defineProperty;var Yn=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Ns=(e,t)=>{for(var n in t)md(e,n,{get:t[n],enumerable:!0})};import Ve from"picocolors";var F,hd,gd,yd,_s,on,f,$,L,I,_,ae,Pe,U=Yn(()=>{"use strict";F="#7f56d9",[hd,gd,yd]=[127,86,217],_s=e=>Ve.isColorSupported?`\x1B[38;2;${hd};${gd};${yd}m${e}\x1B[39m`:e,on=e=>Ve.bold(_s(e)),f=e=>Ve.dim(e),$=e=>Ve.red(e),L=e=>Ve.yellow(e),I=e=>Ve.green(e),_=_s,ae=e=>Ve.gray(e),Pe=e=>Ve.bold(e)});import{existsSync as Lt,writeFileSync as ct,readFileSync as tu,readdirSync as nu}from"node:fs";import{join as ou}from"node:path";import{devHintsGuidePath as ro,hintsDir as Zs,architectureDir as ra,messagesDir as kr,creatorNotesPath as ea,devhintsStatePath as ia,directivesPath as ta,DIRECTIVES_HEADER as ru,roadmapPath as na,ROADMAP_HEADER as iu,ensureDir as oo,writeMessage as su,listOpenForDev as au}from"document360-engine";function sa(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
3
3
 
4
4
  <!-- devhints script v${se} \xB7 maintained by document360-writer (/devhints). -->
5
5
 
@@ -193,7 +193,7 @@ do it**:
193
193
  **Do NOT write or action the documentation yourself** \u2014 same boundary as Part 2. Writing the article is the
194
194
  docs agent's job; it actions open directives on its next \`/catch-up\` (as drafts) and flips each to \`[done]\`
195
195
  with the article it wrote. You are only the relay so the ask is captured durably and travels via git.
196
- `}function au(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
196
+ `}function lu(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
197
197
 
198
198
  <!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
199
199
  The builder agent reads this FIRST and treats it as authoritative when writing the architecture
@@ -207,60 +207,60 @@ Anything only a human knows that would help document this product. For example:
207
207
  - Gotchas or non-obvious behavior.
208
208
 
209
209
  (Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
210
- `}function Mt(e){no(Js(e)),no(oa(e)),no(wr(e));for(let n of[Js(e),wr(e)]){let o=nu(n,".gitkeep");Lt(o)||ct(o,`# Keeps this document360-writer inbox tracked in git even when empty.
211
- `)}Lt(Zs(e))||ct(Zs(e),au()),Lt(ea(e))||ct(ea(e),ou),Lt(ta(e))||ct(ta(e),ru),ct(oo(e),ia());let t=Se(e);return aa(e,new Date().toISOString()),t}async function sa(e,t){for(let n of Ut(Mt(t.cwd)))console.log(n);return{kind:"continue"}}function dt(){return[`This is document360-writer's dev hand-off setup (v${se}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20136). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current \u2014 and SURFACE each hint drop in"," your reply (name the file + the one-line surface), never silently; NEVER write or publish the"," user-facing articles yourself (that is the docs agent's job \u2014 you only hand off); each session,"," check `.d360-writer/messages/` for open questions from the docs agent and answer them; AND when the"," human types `@d360-writer <directive>` in your session, append it as an `## [open] <directive>` block"," to `.d360-writer/directives.md` (create if absent) and commit \u2014 do NOT action it yourself (the docs"," agent picks it up on its next /catch-up) \u2014 all per `.d360-writer/DEV-HINTS-GUIDE.md`. If that section"," is already there, leave it (refine in place only if"," wrong) \u2014 do NOT add a duplicate. Then commit `.d360-writer/` and the memory-file change ONLY if"," something actually changed.","4. Two-way messages (Part 3): check `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each \u2014 fold durable facts into the architecture brief and/or drop"," a reply (`from: dev`, `kind: answer`, `re: <id>`) \u2014 then set the question's frontmatter `status: done`."," If there are none, continue.","5. Then STOP and ask me for tribal knowledge \u2014 present it as a clearly-marked, standalone prompt on its"," own line (NOT buried in prose) and WAIT for my reply before doing anything else. Use this shape:",' "\u23F8 YOUR INPUT NEEDED \u2014 Any tribal knowledge that would help document this product? (folder map,',` terminology, what to prioritize or skip, gotchas.) Type it below, or reply 'none' / 'carry on' to skip."`," If I give you anything, phrase it clearly and append it to `.d360-writer/architecture/CREATOR-NOTES.md`"," (keep the existing header comment and every note already there; only add). If I say 'none'/'carry on', continue.",`6. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${se},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","7. When everything is done, print the completion line, THEN the next command as its own copy-paste"," block so it is unmistakable. Pick the matching first line:",' \u2022 first-time setup: "\u2705 Setup complete. Now switch to the document360-writer terminal and paste this:"',' \u2022 a refresh (brief/notes already existed): "\u2705 Hand-off refreshed. Back in the document360-writer terminal, paste this:"'," Then, on its OWN line, fenced as a code block so it copies cleanly:"," ```"," write the docs for this repo"," ```"].join(`
212
- `)}function kr(e){try{let t=eu(ra(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function aa(e,t){let o={...kr(e)??{},emittedVersion:se,emittedAt:t};ct(ra(e),`${JSON.stringify(o,null,2)}
213
- `)}function Oe(e){try{return tu(oa(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Se(e){let n=kr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<se?"stale":"current",completedVersion:n}}function ro(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:se};try{if(!Lt(oo(e)))return n;let o=kr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let i=o?.completedVersion??0;se>r&&(no(wr(e)),ct(oo(e),ia()),aa(e,t),n.guideRefreshed=!0),se>i&&(su(e).some(p=>p.kind==="request"&&p.subject.startsWith(na))||(iu(e,{id:`onb${se}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${na}${se})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${se}${i?` (you last completed v${i})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",dt()].join(`
214
- `)}),n.notifiedBuilder=!0))}catch{}return n}function io(e){if(!Lt(oo(e)))return[];let t=Se(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${se}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Ot,dt(),Ot,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function br(){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, checking"," `.d360-writer/messages/`, and relaying `@d360-writer` directives to `.d360-writer/directives.md`)."," 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(`
215
- `)}function so(){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):",Ot,br(),Ot]}function Ut(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${se}.`," 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):",Ot,dt(),Ot,"","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 Ot,se,na,Ge=Gn(()=>{"use strict";Ot="-".repeat(64),se=7;na="Re-run dev\u2194docs onboarding (protocol v"});var ya={};Is(ya,{initCommand:()=>$r,scaffoldInit:()=>xr});import{input as sn,confirm as lu}from"@inquirer/prompts";import{basename as la,join as ao}from"node:path";import{existsSync as Wt,readFileSync as cu,readdirSync as du,writeFileSync as uu}from"node:fs";import{writeProjectConfig as ca,readProjectConfig as pu,projectConfigPath as da,writerDir as fu,DEFAULT_DOCS_DIR as ua,DEFAULT_CAPTURE_DIR as pa,DEFAULT_OUTPUT_DIR as fa}from"document360-engine";function xr(e,t="berlin"){let n=da(e);if(Wt(n))return{created:!1,path:n,profileName:""};let o={projectId:ha(e)??la(e),docsDir:ua,captureDir:pa,outputDir:fa,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:ga(e)};return ca(o,e),ma(e),{created:!0,path:n,profileName:t}}function ma(e){let t=ao(fu(e),".gitignore");Wt(t)||uu(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
216
- `),"utf8")}async function $r(){let e=process.cwd(),t=da(e);if(Wt(t)&&!await lu({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=ha(e)??la(e),o=await sn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await sn({message:"Capture directory (where document360-capture .spec.ts files live):",default:pa}),i=await sn({message:"Screenshot output directory:",default:fa}),c=await sn({message:"Default connection profile name:",default:"berlin"}),p=await sn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:ua,captureDir:r,outputDir:i,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:ga(e)},w=pu(e);w?.terminologyGlossary&&(g.terminologyGlossary=w.terminologyGlossary),ca(g,e),ma(e);let k=Mt(e);console.log(""),console.log(I(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of Ut(k))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function ha(e){let t=ao(e,"package.json");if(!Wt(t))return null;try{return JSON.parse(cu(t,"utf8")).name??null}catch{return null}}function ga(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Wt(ao(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=ao(e,n);Wt(o)&&!mu(o)&&t.push(n)}return t}function mu(e){try{return du(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var lo=Gn(()=>{"use strict";U();Ge()});var hl={};Is(hl,{doctorCommand:()=>fn,renderDoctorChecks:()=>ml,runDoctorChecks:()=>fl});import{existsSync as Qp}from"node:fs";import{d360GetAll as Jp,getAccessToken as Zp,isExpired as hi,loadProfileMap as ef,loadTokens as tf,packageSkillsDir as ul,projectConfigPath as nf,readProjectConfig as of,DEFAULT_DOCS_DIR as rf,fetchManifestSummary as sf,resolveActiveProfile as af,classifyClaudeAuth as lf,CLAUDE_CODE_SETUP_HINT as pl,resolveModelSetting as cf,probeModel as df,detectAppType as uf,playbookSkillName as pf,D360AuthError as ff}from"document360-engine";async function fl(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=lf();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. ${pl}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:pl});let r=cf(e);if(t.push({level:"ok",label:`Model: ${r.model} (${r.source==="auto"?"auto \u2014 right-sized for docs; /model to change":r.source})`}),o.state==="ready"){let P=await df(e,r.model??void 0);P.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(P.latencyMs/1e3).toFixed(1)}s`}):P.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 ${P.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 i=of(e);if(!i)return t.push({level:"fail",label:`No ${nf(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${i.projectId}`});let c=(i.docsDir??rf).replace(/\/+$/,"");t.push(i.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=i.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let g=i.appType??uf(e);if(g){let P=i.appType?"from config":"auto-detected",C=g==="web"||g==="cli";t.push({level:"ok",label:`Genre: ${g} (${P})${C?` \u2192 ${pf(g)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else t.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let w;try{w=af(e),t.push({level:"ok",label:`Profile: ${w.name} (${w.connection.name})${w.production?" \u26A0 PRODUCTION":""}`})}catch(P){return t.push({level:"fail",label:`Profile config: ${P.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=tf(w.name);k?hi(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):hi(k)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(k.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${w.name})`}),t.push(w.project.workspaceId?{level:"ok",label:`Workspace: ${w.project.workspaceName??w.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let D=ef(e,w.name);D?D.projectId&&w.project.projectId&&D.projectId!==w.project.projectId?t.push({level:"fail",label:`Category map projectId (${D.projectId}) \u2260 profile projectId (${w.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(D.articles).length} articles, ${Object.keys(D.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${w.name}" (created on first /publish)`}),t.push(Qp(ul())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ul()}`,fix:"Reinstall document360-writer (broken install)"});let x=Se(e);if(x.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${se})`}):x.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${x.completedVersion}, current is v${se}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!hi(k)||k.refreshToken)){let P={profile:w.name,connection:w.connection};try{await Zp(P);let S=await Jp(P,"/v3/projects");t.push({level:"ok",label:`API reachable (${w.connection.apiUrl}) \u2014 ${S.length} project(s) visible`})}catch(S){t.push({level:"fail",label:`API call failed: ${S.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let C=D?.projectId??w.project.projectId;if(C&&w.project.workspaceId)try{let S=await sf(P,C,w.project.workspaceId);if(S){let N=(S.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${w.connection.name} (${S.languages?.length??0} language${(S.languages?.length??0)===1?"":"s"}) \xB7 hash ${N||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${w.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(S){S instanceof ff||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(S.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${w.project.projectName??C})`,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 (${S.message.slice(0,80)})`})}}return t}function ml(e){let t=[""];for(let r of e){let i=r.level==="ok"?I("\u2713"):r.level==="warn"?L("\u26A0"):$("\u2717");t.push(` ${i} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${_(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?I(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function fn(e,t){console.log(f("Running checks\u2026"));for(let n of ml(await fl(t.cwd)))console.log(n);return{kind:"continue"}}var bo=Gn(()=>{"use strict";Ge();U()});import{Command as Tg}from"commander";import{createRequire as Sg}from"node:module";import{AUTH_MODES as Dg}from"document360-engine";import{input as jd}from"@inquirer/prompts";import{loginPkce as Ad,refreshTokens as Ed,toStoredTokens as Ws,clearTokens as Id,decodeJwtClaims as Us,isExpired as Nd,loadTokens as _d,saveTokens as Fs,resolveActiveProfile as Xn,setProfileProject as Ld,readProjectConfig as Od}from"document360-engine";U();import{select as yd}from"@inquirer/prompts";import{resolveActiveProfile as wd,setProfileProject as kd,resolveProjectId as bd,listWorkspaces as xd}from"document360-engine";async function on(e,t){let n=wd(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??bd(o);return{workspaces:await xd(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var _s=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function fr(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 Yn(e,t,n,o,r){kd(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Ls(e,t,n){let o;try{o=await on(e,n)}catch(i){return console.log($(`Could not list workspaces: ${i.message}`)),1}let r=fr(o.workspaces,t);return r?(Yn(e,o.profile,o.projectId,r.id,r.name),console.log(I(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${o.workspaces.map(i=>i.name??i.id).join(", ")}`)),1)}async function _t(e,t){let n;try{n=await on(e,t)}catch(w){console.log($(`Could not list workspaces: ${w.message}`));return}let{workspaces:o,projectId:r,profile:i,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 w of o)console.log(` ${w.id===c?_("\u25CF"):" "} ${_s(w)} ${f(w.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await yd({message:"Select the Document360 workspace for this repo:",choices:o.map(w=>({name:`${_s(w)}${w.id===c?" (current)":""}`,value:w.id}))}),g=o.find(w=>w.id===p);Yn(e,i,r,p,g?.name),console.log(I(`\u2713 Workspace set to "${g?.name??p}" for profile "${i}".`))}U();import{select as $d}from"@inquirer/prompts";import{resolveActiveProfile as vd,setProfileProject as Cd,listProjects as Rd}from"document360-engine";async function Ve(e,t){let n=vd(e,t),o={profile:n.name,connection:n.connection};return{projects:await Rd(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Os=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function mr(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 zn(e,t,n,o){Cd(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Ms(e,t,n){let o;try{o=await Ve(e,n)}catch(i){return console.log($(`Could not list projects: ${i.message}`)),1}let r=mr(o.projects,t);return r?(zn(e,o.profile,r.id,r.name),console.log(I(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log($(`No project matches "${t}". Available: ${o.projects.map(i=>i.name??i.id).join(", ")}`)),1)}async function Kn(e,t){let n;try{n=await Ve(e,t)}catch(g){console.log($(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:i}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===i?_("\u25CF"):" "} ${Os(g)} ${f(g.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await $d({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${Os(g)}${g.id===i?" (current)":""}`,value:g.id}))}),p=o.find(g=>g.id===c);zn(e,r,c,p?.name),console.log(I(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}U();import Pd from"picocolors";function Td(e=process.env){return e.FORCE_HYPERLINK==="0"||!Pd.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 Sd(e,t=e,n){return Td(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Dd=/https?:\/\/[^\s\x1b]+/g;function rn(e,t){return e.replace(Dd,n=>Sd(n,n,t))}function Hs(e){return{...Us(e.idToken)??{},...Us(e.accessToken)??{}}}function Qn(e){let t=Hs(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 Jn(e){let t=Xn(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 Ad(n,{manual:e.manual,promptForRedirect:i=>jd({message:i})},i=>console.log(rn(i))),r=Ws(t.name,o);if(Fs(r),await hr(r,t.name,i=>console.log(f(i))),console.log(""),console.log(I(`\u2713 Logged in to "${t.name}" as ${Qn(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{Od(process.cwd())?.profiles?.[t.name]&&(console.log(""),await _t(process.cwd(),t.name))}catch{}}async function hr(e,t,n){let r=Hs(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Xn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await Ve(process.cwd(),t);c=p.find(g=>g.id===r)?.name}catch{}Ld(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function qs(e){let t=Xn(process.cwd(),e.profile),n=t.connection,o=_d(t.name);if(!o){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${_(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Qn(o)}`),Nd(o))if(o.refreshToken)try{let r=Ws(t.name,await Ed(n,o.refreshToken));Fs(r),console.log(I(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(L("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function Bs(e){let t=Xn(process.cwd(),e.profile);Id(t.name)?console.log(I(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}U();import{readProjectConfig as Vs,writeProjectConfig as Md,resolveActiveProfile as Ud,loadTokens as Wd,isExpired as Fd}from"document360-engine";function Zn(e){let t=Vs(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?_("\u25CF "):" ",i=o.production?L(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Wd(n),g=p?Fd(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${c}${i} [${g}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function eo(e,t){let n=Vs(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,Md(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(I(`\u2713 Default profile is now "${t}"${o}`))}function to(e,t){try{let n=Ud(e,t);console.log(""),console.log(`Profile ${_(n.name)}${n.production?L(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}U();import{existsSync as Hd,readdirSync as qd,statSync as Gs}from"node:fs";import{join as Ys}from"node:path";import{apiLogDir as Bd}from"document360-engine";function zs(){let e=Bd();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Hd(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=qd(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 i=(Gs(Ys(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${i} 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 i=(Gs(Ys(e,r)).size/1024).toFixed(1);console.log(` ${$(r)} ${f(`${i} 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("")}U();import{createSession as Vd,resolveAuth as Gd,findByName as Yd,slugify as zd,touchSession as Kd,upsertSession as Xd,resolveActiveProfile as Qd}from"document360-engine";async function Ks(e,t,n,o,r,i){let c=Gd(n);c.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Qd(e,r)}catch(x){console.error($(`Document360 profile error: ${x.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),i||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let g;if(o){let x=Yd(e,o);x||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),g=x.uuid,console.error(f(`Resuming "${x.name}"`))}let w=Vd({cwd:e,resume:g,profileName:r,allowProdWrites:i===!0}),k=g??null,D=1;for await(let x of w.send(t))switch(x.type){case"session":if(!k){k=x.sessionId;let P=new Date().toISOString();Xd({uuid:k,name:zd(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(ae(` \u2699 ${x.name}`));break;case"result":D=x.ok?0:1,console.error(f(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${x.message}`)),process.exit(1)}k&&Kd(k),process.stdout.write(`
217
- `),process.exit(D)}import{createInterface as Om}from"node:readline/promises";import{createSession as Gi,resolveAuth as Mm,getSession as Um,setTitle as Wm,slugify as Fm,touchSession as nc,upsertSession as Hm,generateTitle as qm,resolveActiveProfile as oc,resolveModelSetting as Bm,readProjectConfig as Vm,resolveAndPersistAppType as Gm,decodeJwtClaims as tc,isExpired as Ym,loadTokens as zm,isDirectiveMention as Km,stripDirectiveMention as Xm,appendDirective as Qm}from"document360-engine";var Te=[{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:"/roadmap",s:"The docs campaign: progress + the next step."},{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 Jd(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 Xs(){let e=["document360-writer \u2014 help",""];for(let t of Te){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push(Jd(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function gr(){console.log("");for(let e of Xs())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}U();import{getSession as Zd}from"document360-engine";async function Qs(e,t){let n=t.currentUuid(),o=n?Zd(n):void 0;return console.log(o?f(`
210
+ `}function Mt(e){oo(Zs(e)),oo(ra(e)),oo(kr(e));for(let n of[Zs(e),kr(e)]){let o=ou(n,".gitkeep");Lt(o)||ct(o,`# Keeps this document360-writer inbox tracked in git even when empty.
211
+ `)}Lt(ea(e))||ct(ea(e),lu()),Lt(ta(e))||ct(ta(e),ru),Lt(na(e))||ct(na(e),iu),ct(ro(e),sa());let t=Se(e);return la(e,new Date().toISOString()),t}async function aa(e,t){for(let n of Ut(Mt(t.cwd)))console.log(n);return{kind:"continue"}}function dt(){return[`This is document360-writer's dev hand-off setup (v${se}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20136). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current \u2014 and SURFACE each hint drop in"," your reply (name the file + the one-line surface), never silently; NEVER write or publish the"," user-facing articles yourself (that is the docs agent's job \u2014 you only hand off); each session,"," check `.d360-writer/messages/` for open questions from the docs agent and answer them; AND when the"," human types `@d360-writer <directive>` in your session, append it as an `## [open] <directive>` block"," to `.d360-writer/directives.md` (create if absent) and commit \u2014 do NOT action it yourself (the docs"," agent picks it up on its next /catch-up) \u2014 all per `.d360-writer/DEV-HINTS-GUIDE.md`. If that section"," is already there, leave it (refine in place only if"," wrong) \u2014 do NOT add a duplicate. Then commit `.d360-writer/` and the memory-file change ONLY if"," something actually changed.","4. Two-way messages (Part 3): check `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each \u2014 fold durable facts into the architecture brief and/or drop"," a reply (`from: dev`, `kind: answer`, `re: <id>`) \u2014 then set the question's frontmatter `status: done`."," If there are none, continue.","5. Then STOP and ask me for tribal knowledge \u2014 present it as a clearly-marked, standalone prompt on its"," own line (NOT buried in prose) and WAIT for my reply before doing anything else. Use this shape:",' "\u23F8 YOUR INPUT NEEDED \u2014 Any tribal knowledge that would help document this product? (folder map,',` terminology, what to prioritize or skip, gotchas.) Type it below, or reply 'none' / 'carry on' to skip."`," If I give you anything, phrase it clearly and append it to `.d360-writer/architecture/CREATOR-NOTES.md`"," (keep the existing header comment and every note already there; only add). If I say 'none'/'carry on', continue.",`6. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${se},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","7. When everything is done, print the completion line, THEN the next command as its own copy-paste"," block so it is unmistakable. Pick the matching first line:",' \u2022 first-time setup: "\u2705 Setup complete. Now switch to the document360-writer terminal and paste this:"',' \u2022 a refresh (brief/notes already existed): "\u2705 Hand-off refreshed. Back in the document360-writer terminal, paste this:"'," Then, on its OWN line, fenced as a code block so it copies cleanly:"," ```"," write the docs for this repo"," ```"].join(`
212
+ `)}function br(e){try{let t=tu(ia(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function la(e,t){let o={...br(e)??{},emittedVersion:se,emittedAt:t};ct(ia(e),`${JSON.stringify(o,null,2)}
213
+ `)}function Ue(e){try{return nu(ra(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Se(e){let n=br(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<se?"stale":"current",completedVersion:n}}function io(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:se};try{if(!Lt(ro(e)))return n;let o=br(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let i=o?.completedVersion??0;se>r&&(oo(kr(e)),ct(ro(e),sa()),la(e,t),n.guideRefreshed=!0),se>i&&(au(e).some(p=>p.kind==="request"&&p.subject.startsWith(oa))||(su(e,{id:`onb${se}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${oa}${se})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${se}${i?` (you last completed v${i})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",dt()].join(`
214
+ `)}),n.notifiedBuilder=!0))}catch{}return n}function so(e){if(!Lt(ro(e)))return[];let t=Se(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${se}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Ot,dt(),Ot,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function xr(){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, checking"," `.d360-writer/messages/`, and relaying `@d360-writer` directives to `.d360-writer/directives.md`)."," 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(`
215
+ `)}function ao(){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):",Ot,xr(),Ot]}function Ut(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${se}.`," 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):",Ot,dt(),Ot,"","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 Ot,se,oa,Ye=Yn(()=>{"use strict";Ot="-".repeat(64),se=7;oa="Re-run dev\u2194docs onboarding (protocol v"});var wa={};Ns(wa,{initCommand:()=>vr,scaffoldInit:()=>$r});import{input as an,confirm as cu}from"@inquirer/prompts";import{basename as ca,join as lo}from"node:path";import{existsSync as Wt,readFileSync as du,readdirSync as uu,writeFileSync as pu}from"node:fs";import{writeProjectConfig as da,readProjectConfig as fu,projectConfigPath as ua,writerDir as mu,DEFAULT_DOCS_DIR as pa,DEFAULT_CAPTURE_DIR as fa,DEFAULT_OUTPUT_DIR as ma}from"document360-engine";function $r(e,t="berlin"){let n=ua(e);if(Wt(n))return{created:!1,path:n,profileName:""};let o={projectId:ga(e)??ca(e),docsDir:pa,captureDir:fa,outputDir:ma,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:ya(e)};return da(o,e),ha(e),{created:!0,path:n,profileName:t}}function ha(e){let t=lo(mu(e),".gitignore");Wt(t)||pu(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
216
+ `),"utf8")}async function vr(){let e=process.cwd(),t=ua(e);if(Wt(t)&&!await cu({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=ga(e)??ca(e),o=await an({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await an({message:"Capture directory (where document360-capture .spec.ts files live):",default:fa}),i=await an({message:"Screenshot output directory:",default:ma}),c=await an({message:"Default connection profile name:",default:"berlin"}),p=await an({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:pa,captureDir:r,outputDir:i,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:ya(e)},w=fu(e);w?.terminologyGlossary&&(g.terminologyGlossary=w.terminologyGlossary),da(g,e),ha(e);let k=Mt(e);console.log(""),console.log(I(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of Ut(k))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function ga(e){let t=lo(e,"package.json");if(!Wt(t))return null;try{return JSON.parse(du(t,"utf8")).name??null}catch{return null}}function ya(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Wt(lo(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=lo(e,n);Wt(o)&&!hu(o)&&t.push(n)}return t}function hu(e){try{return uu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var co=Yn(()=>{"use strict";U();Ye()});var gl={};Ns(gl,{doctorCommand:()=>mn,renderDoctorChecks:()=>hl,runDoctorChecks:()=>ml});import{existsSync as Jp}from"node:fs";import{d360GetAll as Zp,getAccessToken as ef,isExpired as gi,loadProfileMap as tf,loadTokens as nf,packageSkillsDir as pl,projectConfigPath as of,readProjectConfig as rf,DEFAULT_DOCS_DIR as sf,fetchManifestSummary as af,resolveActiveProfile as lf,classifyClaudeAuth as cf,CLAUDE_CODE_SETUP_HINT as fl,resolveModelSetting as df,probeModel as uf,detectAppType as pf,playbookSkillName as ff,D360AuthError as mf}from"document360-engine";async function ml(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=cf();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. ${fl}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:fl});let r=df(e);if(t.push({level:"ok",label:`Model: ${r.model} (${r.source==="auto"?"auto \u2014 right-sized for docs; /model to change":r.source})`}),o.state==="ready"){let P=await uf(e,r.model??void 0);P.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(P.latencyMs/1e3).toFixed(1)}s`}):P.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 ${P.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 i=rf(e);if(!i)return t.push({level:"fail",label:`No ${of(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${i.projectId}`});let c=(i.docsDir??sf).replace(/\/+$/,"");t.push(i.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=i.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let g=i.appType??pf(e);if(g){let P=i.appType?"from config":"auto-detected",C=g==="web"||g==="cli";t.push({level:"ok",label:`Genre: ${g} (${P})${C?` \u2192 ${ff(g)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else t.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let w;try{w=lf(e),t.push({level:"ok",label:`Profile: ${w.name} (${w.connection.name})${w.production?" \u26A0 PRODUCTION":""}`})}catch(P){return t.push({level:"fail",label:`Profile config: ${P.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=nf(w.name);k?gi(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):gi(k)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(k.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${w.name})`}),t.push(w.project.workspaceId?{level:"ok",label:`Workspace: ${w.project.workspaceName??w.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let D=tf(e,w.name);D?D.projectId&&w.project.projectId&&D.projectId!==w.project.projectId?t.push({level:"fail",label:`Category map projectId (${D.projectId}) \u2260 profile projectId (${w.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(D.articles).length} articles, ${Object.keys(D.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${w.name}" (created on first /publish)`}),t.push(Jp(pl())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${pl()}`,fix:"Reinstall document360-writer (broken install)"});let x=Se(e);if(x.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${se})`}):x.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${x.completedVersion}, current is v${se}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!gi(k)||k.refreshToken)){let P={profile:w.name,connection:w.connection};try{await ef(P);let S=await Zp(P,"/v3/projects");t.push({level:"ok",label:`API reachable (${w.connection.apiUrl}) \u2014 ${S.length} project(s) visible`})}catch(S){t.push({level:"fail",label:`API call failed: ${S.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let C=D?.projectId??w.project.projectId;if(C&&w.project.workspaceId)try{let S=await af(P,C,w.project.workspaceId);if(S){let N=(S.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${w.connection.name} (${S.languages?.length??0} language${(S.languages?.length??0)===1?"":"s"}) \xB7 hash ${N||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${w.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(S){S instanceof mf||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(S.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${w.project.projectName??C})`,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 (${S.message.slice(0,80)})`})}}return t}function hl(e){let t=[""];for(let r of e){let i=r.level==="ok"?I("\u2713"):r.level==="warn"?L("\u26A0"):$("\u2717");t.push(` ${i} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${_(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?I(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function mn(e,t){console.log(f("Running checks\u2026"));for(let n of hl(await ml(t.cwd)))console.log(n);return{kind:"continue"}}var xo=Yn(()=>{"use strict";Ye();U()});import{Command as Sg}from"commander";import{createRequire as Dg}from"node:module";import{AUTH_MODES as jg}from"document360-engine";import{input as Ad}from"@inquirer/prompts";import{loginPkce as Ed,refreshTokens as Id,toStoredTokens as Fs,clearTokens as Nd,decodeJwtClaims as Ws,isExpired as _d,loadTokens as Ld,saveTokens as Hs,resolveActiveProfile as Qn,setProfileProject as Od,readProjectConfig as Md}from"document360-engine";U();import{select as wd}from"@inquirer/prompts";import{resolveActiveProfile as kd,setProfileProject as bd,resolveProjectId as xd,listWorkspaces as $d}from"document360-engine";async function rn(e,t){let n=kd(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??xd(o);return{workspaces:await $d(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Ls=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function mr(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 zn(e,t,n,o,r){bd(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Os(e,t,n){let o;try{o=await rn(e,n)}catch(i){return console.log($(`Could not list workspaces: ${i.message}`)),1}let r=mr(o.workspaces,t);return r?(zn(e,o.profile,o.projectId,r.id,r.name),console.log(I(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${o.workspaces.map(i=>i.name??i.id).join(", ")}`)),1)}async function _t(e,t){let n;try{n=await rn(e,t)}catch(w){console.log($(`Could not list workspaces: ${w.message}`));return}let{workspaces:o,projectId:r,profile:i,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 w of o)console.log(` ${w.id===c?_("\u25CF"):" "} ${Ls(w)} ${f(w.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await wd({message:"Select the Document360 workspace for this repo:",choices:o.map(w=>({name:`${Ls(w)}${w.id===c?" (current)":""}`,value:w.id}))}),g=o.find(w=>w.id===p);zn(e,i,r,p,g?.name),console.log(I(`\u2713 Workspace set to "${g?.name??p}" for profile "${i}".`))}U();import{select as vd}from"@inquirer/prompts";import{resolveActiveProfile as Cd,setProfileProject as Rd,listProjects as Pd}from"document360-engine";async function Ge(e,t){let n=Cd(e,t),o={profile:n.name,connection:n.connection};return{projects:await Pd(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Ms=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function hr(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 Kn(e,t,n,o){Rd(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Us(e,t,n){let o;try{o=await Ge(e,n)}catch(i){return console.log($(`Could not list projects: ${i.message}`)),1}let r=hr(o.projects,t);return r?(Kn(e,o.profile,r.id,r.name),console.log(I(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log($(`No project matches "${t}". Available: ${o.projects.map(i=>i.name??i.id).join(", ")}`)),1)}async function Xn(e,t){let n;try{n=await Ge(e,t)}catch(g){console.log($(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:i}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===i?_("\u25CF"):" "} ${Ms(g)} ${f(g.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await vd({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${Ms(g)}${g.id===i?" (current)":""}`,value:g.id}))}),p=o.find(g=>g.id===c);Kn(e,r,c,p?.name),console.log(I(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}U();import Td from"picocolors";function Sd(e=process.env){return e.FORCE_HYPERLINK==="0"||!Td.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 Dd(e,t=e,n){return Sd(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var jd=/https?:\/\/[^\s\x1b]+/g;function sn(e,t){return e.replace(jd,n=>Dd(n,n,t))}function qs(e){return{...Ws(e.idToken)??{},...Ws(e.accessToken)??{}}}function Jn(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 Zn(e){let t=Qn(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 Ed(n,{manual:e.manual,promptForRedirect:i=>Ad({message:i})},i=>console.log(sn(i))),r=Fs(t.name,o);if(Hs(r),await gr(r,t.name,i=>console.log(f(i))),console.log(""),console.log(I(`\u2713 Logged in to "${t.name}" as ${Jn(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Md(process.cwd())?.profiles?.[t.name]&&(console.log(""),await _t(process.cwd(),t.name))}catch{}}async function gr(e,t,n){let r=qs(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Qn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await Ge(process.cwd(),t);c=p.find(g=>g.id===r)?.name}catch{}Od(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Bs(e){let t=Qn(process.cwd(),e.profile),n=t.connection,o=Ld(t.name);if(!o){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${_(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Jn(o)}`),_d(o))if(o.refreshToken)try{let r=Fs(t.name,await Id(n,o.refreshToken));Hs(r),console.log(I(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(L("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function Vs(e){let t=Qn(process.cwd(),e.profile);Nd(t.name)?console.log(I(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}U();import{readProjectConfig as Gs,writeProjectConfig as Ud,resolveActiveProfile as Wd,loadTokens as Fd,isExpired as Hd}from"document360-engine";function eo(e){let t=Gs(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?_("\u25CF "):" ",i=o.production?L(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Fd(n),g=p?Hd(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${c}${i} [${g}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function to(e,t){let n=Gs(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,Ud(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(I(`\u2713 Default profile is now "${t}"${o}`))}function no(e,t){try{let n=Wd(e,t);console.log(""),console.log(`Profile ${_(n.name)}${n.production?L(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}U();import{existsSync as qd,readdirSync as Bd,statSync as Ys}from"node:fs";import{join as zs}from"node:path";import{apiLogDir as Vd}from"document360-engine";function Ks(){let e=Vd();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!qd(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Bd(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 i=(Ys(zs(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${i} 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 i=(Ys(zs(e,r)).size/1024).toFixed(1);console.log(` ${$(r)} ${f(`${i} 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("")}U();import{createSession as Gd,resolveAuth as Yd,findByName as zd,slugify as Kd,touchSession as Xd,upsertSession as Qd,resolveActiveProfile as Jd}from"document360-engine";async function Xs(e,t,n,o,r,i){let c=Yd(n);c.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Jd(e,r)}catch(x){console.error($(`Document360 profile error: ${x.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),i||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let g;if(o){let x=zd(e,o);x||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),g=x.uuid,console.error(f(`Resuming "${x.name}"`))}let w=Gd({cwd:e,resume:g,profileName:r,allowProdWrites:i===!0}),k=g??null,D=1;for await(let x of w.send(t))switch(x.type){case"session":if(!k){k=x.sessionId;let P=new Date().toISOString();Qd({uuid:k,name:Kd(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(ae(` \u2699 ${x.name}`));break;case"result":D=x.ok?0:1,console.error(f(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${x.message}`)),process.exit(1)}k&&Xd(k),process.stdout.write(`
217
+ `),process.exit(D)}import{createInterface as Mm}from"node:readline/promises";import{createSession as Yi,resolveAuth as Um,getSession as Wm,setTitle as Fm,slugify as Hm,touchSession as oc,upsertSession as qm,generateTitle as Bm,resolveActiveProfile as rc,resolveModelSetting as Vm,readProjectConfig as Gm,resolveAndPersistAppType as Ym,decodeJwtClaims as nc,isExpired as zm,loadTokens as Km,isDirectiveMention as Xm,stripDirectiveMention as Qm,appendDirective as Jm}from"document360-engine";var Te=[{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:"/roadmap",s:"The docs campaign: progress + the next step."},{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 Zd(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 Qs(){let e=["document360-writer \u2014 help",""];for(let t of Te){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push(Zd(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function yr(){console.log("");for(let e of Qs())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}U();import{getSession as eu}from"document360-engine";async function Js(e,t){let n=t.currentUuid(),o=n?eu(n):void 0;return console.log(o?f(`
218
218
  (conversation reset \u2014 "${o.name}" is still available via /resume)
219
219
  `):f(`
220
220
  (conversation reset \u2014 agent will start fresh on the next prompt)
221
- `)),{kind:"clear"}}async function yr(){return{kind:"exit"}}lo();U();import{readMcpConfig as vr,writeMcpConfig as wa}from"document360-engine";async function co(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(hu(),{kind:"continue"}):t==="add"?(gu(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(yu(e.slice(1)),{kind:"continue"}):(console.log($(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function hu(){let e=vr(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
221
+ `)),{kind:"clear"}}async function wr(){return{kind:"exit"}}co();U();import{readMcpConfig as Cr,writeMcpConfig as ka}from"document360-engine";async function uo(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(gu(),{kind:"continue"}):t==="add"?(yu(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(wu(e.slice(1)),{kind:"continue"}):(console.log($(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function gu(){let e=Cr(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
222
222
  No MCP servers registered. Add one with /mcp add <name> <type> <ref>
223
- `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${_(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),i=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${_(n)} ${f(`(${o.type})`)} ${o.url}${i}`)}}console.log("")}function gu(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log($("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log($(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=vr(),i;if(n==="stdio")i={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let g=o[++p],w=g?.match(/^([^:=]+)[:=](.+)$/);if(!w){console.log($(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}c[w[1].trim()]=w[2].trim()}else{console.log($(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}i={type:n,url:o[0],headers:Object.keys(c).length>0?c:void 0}}r.servers[t]=i,wa(r),console.log(""),console.log(I(`\u2713 Registered "${t}" (${n})`)),console.log(L(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function yu(e){let t=e[0];if(!t){console.log($("Usage: /mcp remove <name>"));return}let n=vr();if(!n.servers[t]){console.log($(`No server named "${t}".`));return}delete n.servers[t],wa(n),console.log(I(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}U();import{readFileSync as Eu}from"node:fs";import{join as Iu}from"node:path";import{select as Nu}from"@inquirer/prompts";import{computeSyncStatus as Er,planPartitions as _u,relatedArticlePaths as Lu,resolveModelForOperation as Ou,runPartitioned as Mu,loadProfileMap as Uu,resolveActiveProfile as Wu,resolveCrossLinks as Fu,applyStructureOrder as Sa,orderSyncLine as Da,applyRelatedArticles as ja,relatedSyncLine as Aa}from"document360-engine";import K from"picocolors";import Ca from"wrap-ansi";import Dr from"string-width";U();import Ye from"picocolors";import Cr from"wrap-ansi";import Rr from"string-width";var ka=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),ba=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),xa=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function wu(e){let t=e.replace(/\r/g,"").split(`
224
- `),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(ka(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&ba(t[o+1])){let p=xa(r);o+=2;let g=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)g.push(xa(t[o++]));n.push({kind:"table",header:p,rows:g});continue}let i=r.match(/^(#{1,6})\s+(.*)$/);if(i){n.push({kind:"heading",level:i[1].length,text:i[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let g=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(g),text:g.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])&&!ka(t[o])&&!(t[o].includes("|")&&o+1<t.length&&ba(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function Pr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ye.bold(t.slice(2,-2)):t.startsWith("`")?_(t.slice(1,-1)):Ye.italic(t.slice(1,-1)))}var ku=(e,t)=>e+" ".repeat(Math.max(0,t-Rr(e)));function bu(e,t,n){let o=e.length,r=e.map((C,S)=>Math.max(Rr(C),...t.map(N=>Rr(N[S]??"")))),i=Math.max(24,n),c=3*o+1,p=[...r],g=()=>p.reduce((C,S)=>C+S,0)+c,w=0;for(;g()>i&&w++<1e4;){let C=-1,S=6;for(let N=0;N<o;N++)p[N]>S&&(S=p[N],C=N);if(C===-1)break;p[C]-=1}let k=(C,S,N)=>Ye.gray(C+p.map(O=>"\u2500".repeat(O+2)).join(S)+N),D=Ye.gray("\u2502"),x=(C,S)=>{let N=p.map((re,Z)=>{let de=C[Z]??"",Cn=S?Ye.bold(de):Pr(de);return Cr(Cn,re,{hard:!0}).split(`
225
- `)}),O=Math.max(...N.map(re=>re.length)),J=[];for(let re=0;re<O;re++)J.push(p.map((Z,de)=>`${D} ${ku(N[de][re]??"",Z)} `).join("")+D);return J.join(`
223
+ `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${_(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),i=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${_(n)} ${f(`(${o.type})`)} ${o.url}${i}`)}}console.log("")}function yu(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log($("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log($(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Cr(),i;if(n==="stdio")i={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let g=o[++p],w=g?.match(/^([^:=]+)[:=](.+)$/);if(!w){console.log($(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}c[w[1].trim()]=w[2].trim()}else{console.log($(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}i={type:n,url:o[0],headers:Object.keys(c).length>0?c:void 0}}r.servers[t]=i,ka(r),console.log(""),console.log(I(`\u2713 Registered "${t}" (${n})`)),console.log(L(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function wu(e){let t=e[0];if(!t){console.log($("Usage: /mcp remove <name>"));return}let n=Cr();if(!n.servers[t]){console.log($(`No server named "${t}".`));return}delete n.servers[t],ka(n),console.log(I(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}U();import{readFileSync as Iu}from"node:fs";import{join as Nu}from"node:path";import{select as _u}from"@inquirer/prompts";import{computeSyncStatus as Ir,planPartitions as Lu,relatedArticlePaths as Ou,resolveModelForOperation as Mu,runPartitioned as Uu,loadProfileMap as Wu,resolveActiveProfile as Fu,resolveCrossLinks as Hu,applyStructureOrder as Da,orderSyncLine as ja,applyRelatedArticles as Aa,relatedSyncLine as Ea}from"document360-engine";import K from"picocolors";import Ra from"wrap-ansi";import jr from"string-width";U();import ze from"picocolors";import Rr from"wrap-ansi";import Pr from"string-width";var ba=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),xa=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),$a=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function ku(e){let t=e.replace(/\r/g,"").split(`
224
+ `),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(ba(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&xa(t[o+1])){let p=$a(r);o+=2;let g=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)g.push($a(t[o++]));n.push({kind:"table",header:p,rows:g});continue}let i=r.match(/^(#{1,6})\s+(.*)$/);if(i){n.push({kind:"heading",level:i[1].length,text:i[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let g=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(g),text:g.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])&&!ba(t[o])&&!(t[o].includes("|")&&o+1<t.length&&xa(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("**")?ze.bold(t.slice(2,-2)):t.startsWith("`")?_(t.slice(1,-1)):ze.italic(t.slice(1,-1)))}var bu=(e,t)=>e+" ".repeat(Math.max(0,t-Pr(e)));function xu(e,t,n){let o=e.length,r=e.map((C,S)=>Math.max(Pr(C),...t.map(N=>Pr(N[S]??"")))),i=Math.max(24,n),c=3*o+1,p=[...r],g=()=>p.reduce((C,S)=>C+S,0)+c,w=0;for(;g()>i&&w++<1e4;){let C=-1,S=6;for(let N=0;N<o;N++)p[N]>S&&(S=p[N],C=N);if(C===-1)break;p[C]-=1}let k=(C,S,N)=>ze.gray(C+p.map(O=>"\u2500".repeat(O+2)).join(S)+N),D=ze.gray("\u2502"),x=(C,S)=>{let N=p.map((re,Z)=>{let de=C[Z]??"",Cn=S?ze.bold(de):Tr(de);return Rr(Cn,re,{hard:!0}).split(`
225
+ `)}),O=Math.max(...N.map(re=>re.length)),J=[];for(let re=0;re<O;re++)J.push(p.map((Z,de)=>`${D} ${bu(N[de][re]??"",Z)} `).join("")+D);return J.join(`
226
226
  `)},P=[k("\u250C","\u252C","\u2510"),x(e,!0)];return P.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((C,S)=>{P.push(x(C,!1)),P.push(S===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),P.join(`
227
- `)}function xu(e,t){switch(e.kind){case"heading":return Ye.bold(e.text);case"hr":return Ye.gray("\u2500".repeat(t));case"para":return Cr(Pr(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",i=" ".repeat(2+r.length+1),[c="",...p]=Cr(Pr(o.text),Math.max(10,t-i.length)).split(`
227
+ `)}function $u(e,t){switch(e.kind){case"heading":return ze.bold(e.text);case"hr":return ze.gray("\u2500".repeat(t));case"para":return Rr(Tr(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",i=" ".repeat(2+r.length+1),[c="",...p]=Rr(Tr(o.text),Math.max(10,t-i.length)).split(`
228
228
  `);return` ${r} ${c}`+p.map(g=>`
229
229
  ${i}${g}`).join("")}).join(`
230
- `)}case"code":return e.lines.map(n=>Ye.gray(" "+n)).join(`
231
- `);case"table":return bu(e.header,e.rows,t)}}function Tr(e,t){let n=Math.max(20,t);return wu(e).map(o=>xu(o,n)).join(`
230
+ `)}case"code":return e.lines.map(n=>ze.gray(" "+n)).join(`
231
+ `);case"table":return xu(e.header,e.rows,t)}}function Sr(e,t){let n=Math.max(20,t);return ku(e).map(o=>$u(o,n)).join(`
232
232
 
233
- `)}U();import $u from"picocolors";var vu=[127,86,217],Cu=[22,38,43],$a={T:vu,E:Cu},an=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Sr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Ru=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function va(){if(!$u.isColorSupported)return[];let e=an[0].length,t=[];for(let n=0;n<an.length;n+=2){let o="";for(let r=0;r<e;r++){let i=$a[an[n][r]],c=n+1<an.length?$a[an[n+1][r]]:void 0;i&&c?o+=`${Sr(i)}${Ru(c)}\u2580\x1B[49m\x1B[39m`:i?o+=`${Sr(i)}\u2580\x1B[39m`:c?o+=`${Sr(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function ln(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function me(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function ze(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Ft=(e,t)=>` ${e.padEnd(13)}${t}`;function Pu(e,t){let n=[nn("\u270E document360-writer")+K.gray(` v${e.version}`),K.gray(" Reads your code, writes your docs."),"",Ft("Claude:",`${e.claude}${K.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Ft("Document360:",e.configured?e.loggedOut?K.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?K.gray(` (${e.sessionHint})`):""}`:K.yellow("not set up \u2014 run /init")),Ft("Profile:",e.configured?`${e.profile}${K.gray(` (${e.apiUrl})`)}${e.prod?K.bold(K.yellow(" \u26A0 PRODUCTION")):""}`:K.gray("\u2014 (run /init)")),Ft("Project:",e.project),Ft("Mode:",K.gray(e.mode)),Ft("cwd:",K.gray(e.cwd))],o=va();if(o.length===0)return n.join(`
234
- `);let r=2,i=3,c=Dr(o[0]);if(!(t>=r+c+i+Math.max(...n.map(k=>Dr(k)))))return[...o.map(k=>" "+k),...n].join(`
233
+ `)}U();import vu from"picocolors";var Cu=[127,86,217],Ru=[22,38,43],va={T:Cu,E:Ru},ln=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Dr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Pu=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Ca(){if(!vu.isColorSupported)return[];let e=ln[0].length,t=[];for(let n=0;n<ln.length;n+=2){let o="";for(let r=0;r<e;r++){let i=va[ln[n][r]],c=n+1<ln.length?va[ln[n+1][r]]:void 0;i&&c?o+=`${Dr(i)}${Pu(c)}\u2580\x1B[49m\x1B[39m`:i?o+=`${Dr(i)}\u2580\x1B[39m`:c?o+=`${Dr(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function cn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function he(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Ke(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Ft=(e,t)=>` ${e.padEnd(13)}${t}`;function Tu(e,t){let n=[on("\u270E document360-writer")+K.gray(` v${e.version}`),K.gray(" Reads your code, writes your docs."),"",Ft("Claude:",`${e.claude}${K.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Ft("Document360:",e.configured?e.loggedOut?K.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?K.gray(` (${e.sessionHint})`):""}`:K.yellow("not set up \u2014 run /init")),Ft("Profile:",e.configured?`${e.profile}${K.gray(` (${e.apiUrl})`)}${e.prod?K.bold(K.yellow(" \u26A0 PRODUCTION")):""}`:K.gray("\u2014 (run /init)")),Ft("Project:",e.project),Ft("Mode:",K.gray(e.mode)),Ft("cwd:",K.gray(e.cwd))],o=Ca();if(o.length===0)return n.join(`
234
+ `);let r=2,i=3,c=jr(o[0]);if(!(t>=r+c+i+Math.max(...n.map(k=>jr(k)))))return[...o.map(k=>" "+k),...n].join(`
235
235
  `);let g=Math.max(0,Math.floor((n.length-o.length)/2)),w=[];for(let k=0;k<Math.max(o.length+g,n.length);k++){let D=o[k-g]??" ".repeat(c);w.push((" ".repeat(r)+D+" ".repeat(i)+(n[k]??"")).trimEnd())}return w.join(`
236
- `)}var Tu={error:K.red,warn:K.yellow,ok:K.green,info:K.gray};function jr(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Pu(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",i=Math.max(10,n-4),c=50,p=e.text.split(`
237
- `).flatMap(w=>Ca(w,i,{hard:!0}).split(`
236
+ `)}var Su={error:K.red,warn:K.yellow,ok:K.green,info:K.gray};function Ar(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Tu(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",i=Math.max(10,n-4),c=50,p=e.text.split(`
237
+ `).flatMap(w=>Ra(w,i,{hard:!0}).split(`
238
238
  `)),g=Math.max(0,p.length-c);return g>0&&(p=[...p.slice(0,c),K.dim(`\u2026 +${g} more lines`)]),`
239
- `+p.map((w,k)=>o+(k===0?_(" \u276F "):" ")+w+" ".repeat(Math.max(0,i-Dr(w))+1)+r).join(`
239
+ `+p.map((w,k)=>o+(k===0?_(" \u276F "):" ")+w+" ".repeat(Math.max(0,i-jr(w))+1)+r).join(`
240
240
  `)}case"assistant":return`
241
- `+Tr(e.text,n);case"tool":{let o=e.arg!==null?K.gray(`${e.sep}(${e.arg})`):"";return`
242
- `+Ca(K.green("\u25CF ")+K.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?K.red:K.gray,r=e.lines.map((i,c)=>o((c===0?" \u23BF ":" ")+i));return e.hidden>0&&r.push(K.dim(` \u2026 +${e.hidden} lines`)),r.join(`
241
+ `+Sr(e.text,n);case"tool":{let o=e.arg!==null?K.gray(`${e.sep}(${e.arg})`):"";return`
242
+ `+Ra(K.green("\u25CF ")+K.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?K.red:K.gray,r=e.lines.map((i,c)=>o((c===0?" \u23BF ":" ")+i));return e.hidden>0&&r.push(K.dim(` \u2026 +${e.hidden} lines`)),r.join(`
243
243
  `)}case"diff":{let o=c=>c===1?"":"s",i=[K.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&i.push(K.dim(` \u2026 +${e.hidden} more diff lines`)),i.join(`
244
- `)}case"link":return e.lines.map(o=>_(rn(` \u2B95 ${o}`))).join(`
244
+ `)}case"link":return e.lines.map(o=>_(sn(` \u2B95 ${o}`))).join(`
245
245
  `);case"preview":return`
246
- `+nn(`\u25A3 Preview \u2014 ${e.name}`)+`
247
-
248
- `+Tr(e.text,n);case"note":return`
249
- `+Tu[e.tone](rn(e.text));case"done":return`
250
- `+(e.ok?K.magenta("\u2736 "):K.red("\u2736 "))+K.gray(`Cooked for ${ln(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${me(e.costUsd)}`:""))}}function Ra(e,t){return e.map(n=>jr(n,t)).join(`
251
- `)}import{resolveActiveProfile as Su,loadTokens as Du,isExpired as ju,decodeJwtClaims as Pa}from"document360-engine";function Au(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Me(e,t){try{let n=Su(e,t),o=Du(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(ju(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={...Pa(o.idToken)??{},...Pa(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 ${Au(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var cn=3;function Ir(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(`
252
- `)}var Ta={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function dn(e){return e.filter(t=>t.path!==null&&t.status in Ta&&!t.link).map(t=>({path:t.path,label:Ta[t.status]}))}function uo(e){return e.filter(t=>t.link).length}function Nr(e,t){try{let n=Uu(e,Wu(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Fu(Eu(Iu(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 Hu(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 Ea(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("/"),i=n.get(r);i?i.push(o):n.set(r,[o])}for(let o of[...n.keys()].sort()){let r=n.get(o).sort((i,c)=>i.path.localeCompare(c.path));t.push({kind:"category",label:`${Hu(o)} (${r.length})`,paths:r.map(i=>i.path),indent:!1});for(let i of r){let c=i.path.replace(/\\/g,"/").split("/").pop()??i.path;t.push({kind:"article",label:c,paths:[i.path],indent:!0,note:i.label})}}return t}function po(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(`
253
- `)}function _r(e,t,n){let o=x=>t[x.index]?.paths.length??0,r=e.filter(x=>x.ok),i=e.filter(x=>!x.ok),c=e.reduce((x,P)=>x+o(P),0),p=r.reduce((x,P)=>x+o(P),0),g=n==="api"?`${me(e.reduce((x,P)=>x+P.costUsd,0))} total`:ze(e.reduce((x,P)=>x+P.outputTokens,0)),w=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,k=x=>`${x} article${x===1?"":"s"}`,D=[];if(i.length===0)D.push(`Published ${k(c)} (${w}) successfully \xB7 ${g}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${k(c)} (${w}) \xB7 ${g}.`),D.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let x of i)D.push(` \u2717 ${x.label}${x.error?` \u2014 ${x.error}`:""}`)}return D}async function Ar(e,t){let n=_u(t),{model:o}=Ou(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${cn} 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 Mu({cwd:e.cwd,partitions:n,promptFor:i=>po(i.paths),concurrency:cn,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(I(` \u2713 ${r.label}`)):console.log($(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let i=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of _r(r.results,n,i))console.log(r.ok?I(p):L(p));let c=Nr(e.cwd,e.profileName);c&&console.log(f(c));try{let p=Da(await Sa({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}try{let p=Aa(await ja({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}}}catch(r){console.log($(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function fo(e,t,n){let o=Lu(e,n);if(o.length===0)return[];let r=new Set(dn((await Er({cwd:e,profileName:t})).entries).map(i=>i.path));return o.filter(i=>r.has(i))}async function Ia(e,t){let n=Me(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await fo(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(I("\u2713 All related articles are already published.")),{kind:"continue"}):await Ar(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await Er({cwd:t?.cwd??process.cwd()}),i=dn(r.entries),c=uo(r.entries);if(c>0&&console.log(L(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),i.length===0){if(console.log(I(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let p=Da(await Sa({cwd:t.cwd,profileName:t.profileName}));p&&console.log(f(p));let g=Aa(await ja({cwd:t.cwd,profileName:t.profileName}));g&&console.log(f(g))}catch{}return{kind:"continue"}}return t?await Ar(t,i.map(p=>p.path)):{kind:"forward-to-agent",prompt:po(i.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log($(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let i=await Er({cwd:t?.cwd??process.cwd()});r=dn(i.entries);let c=uo(i.entries);c>0&&console.log(L(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`))}catch(i){return console.log($(`Could not compute sync status: ${i.message}`)),console.log(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(I("\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 i of r)console.log(` ${i.path} ${f(`(${i.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>Nu({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(i=>({name:i.path,value:i.path,description:i.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await Ar(t,r.map(i=>i.path))}return{kind:"forward-to-agent",prompt:Ir(o),display:`/publish ${o}`}}async function un(){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(`
254
- `),display:"/audit"}}U();import{checkbox as qu}from"@inquirer/prompts";import{inventoryRepo as Bu,readProjectConfig as Na,writeProjectConfig as Vu}from"document360-engine";function Lr(e,t){let n=Na(e);n&&(n.authoritativeSourceFiles=t,Vu(n,e))}function mo(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 _a(e,t){let n=t?.cwd??process.cwd();if(!Na(n))return console.log($("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Bu(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(_("Recommended documentation scope (run /scope in the REPL to choose):"));for(let i of o)console.log(` ${i.recommended?"\u25C9":"\u25CB"} ${i.path} ${f(mo(i))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>qu({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(i=>({name:`${i.path} (${mo(i)})`,value:i.path,checked:i.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"};Lr(n,r),console.log(I(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let i of r)console.log(` ${i}`);return console.log(""),{kind:"continue"}}U();import{confirm as Qu}from"@inquirer/prompts";import{applyPull as Mr,computeSyncStatus as Wa,compareRemoteSources as Ju,planPull as Fa,planImport as Zu,applyImport as ep,establishBaselines as tp,rebaselineServerMeta as np,D360AuthError as op}from"document360-engine";U();var La=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:$,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:L,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:_,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:$,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:$,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ae,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:ae,mark:"\xB7"}];function Gu(e){return e.path?e.path:`${e.title??"(untitled)"} ${ae(`[${e.articleId}]`)}`}function Yu(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 ho(e,t){let n=[],o=e.entries.filter(k=>k.link);if(o.length>0){n.push(""),n.push(Pe("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let k of o)n.push(` ${L("~")} ${L(k.path??"")} ${ae(`\u2192 "${k.link.title}"`)}`)}for(let k of La){let D=e.entries.filter(x=>x.status===k.status&&!(k.status==="untracked-local"&&x.link));if(D.length!==0){n.push(""),n.push(Pe(k.header));for(let x of D)n.push(` ${k.paint(k.mark)} ${k.paint(Gu(x))}${x.detail?ae(` (${x.detail})`):""}`)}}let r=e.counts["in-sync"]??0,i=e.entries.length;n.push("");let c={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},p=o.length,g=i===r?I("\u2713 everything up to date"):[r>0?I(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...La.map(k=>{let D=(e.counts[k.status]??0)-(k.status==="untracked-local"?p:0);return D>0?`${D} ${c[k.status]}`:null})].filter(Boolean).join(ae(" \xB7 ")),w=t!==void 0?` \xB7 synced in ${Yu(t)}`:"";return n.push(g+ae(` \xB7 ${i} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${w}`)),n}import{structuredPatch as zu}from"diff";import Oa from"picocolors";var Ma=80,Ku="\x1B[48;2;74;28;28m",Xu="\x1B[48;2;24;66;24m",Ua="\x1B[49m",Or=e=>String(e).padStart(5);function ut(e,t,n){let o=x=>{let P=x.replace(/\r\n/g,`
246
+ `+on(`\u25A3 Preview \u2014 ${e.name}`)+`
247
+
248
+ `+Sr(e.text,n);case"note":return`
249
+ `+Su[e.tone](sn(e.text));case"done":return`
250
+ `+(e.ok?K.magenta("\u2736 "):K.red("\u2736 "))+K.gray(`Cooked for ${cn(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${he(e.costUsd)}`:""))}}function Pa(e,t){return e.map(n=>Ar(n,t)).join(`
251
+ `)}import{resolveActiveProfile as Du,loadTokens as ju,isExpired as Au,decodeJwtClaims as Ta}from"document360-engine";function Eu(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function We(e,t){try{let n=Du(e,t),o=ju(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Au(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={...Ta(o.idToken)??{},...Ta(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 ${Eu(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var dn=3;function Nr(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(`
252
+ `)}var Sa={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function un(e){return e.filter(t=>t.path!==null&&t.status in Sa&&!t.link).map(t=>({path:t.path,label:Sa[t.status]}))}function po(e){return e.filter(t=>t.link).length}function _r(e,t){try{let n=Wu(e,Fu(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Hu(Iu(Nu(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 qu(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 Ia(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("/"),i=n.get(r);i?i.push(o):n.set(r,[o])}for(let o of[...n.keys()].sort()){let r=n.get(o).sort((i,c)=>i.path.localeCompare(c.path));t.push({kind:"category",label:`${qu(o)} (${r.length})`,paths:r.map(i=>i.path),indent:!1});for(let i of r){let c=i.path.replace(/\\/g,"/").split("/").pop()??i.path;t.push({kind:"article",label:c,paths:[i.path],indent:!0,note:i.label})}}return t}function fo(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(`
253
+ `)}function Lr(e,t,n){let o=x=>t[x.index]?.paths.length??0,r=e.filter(x=>x.ok),i=e.filter(x=>!x.ok),c=e.reduce((x,P)=>x+o(P),0),p=r.reduce((x,P)=>x+o(P),0),g=n==="api"?`${he(e.reduce((x,P)=>x+P.costUsd,0))} total`:Ke(e.reduce((x,P)=>x+P.outputTokens,0)),w=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,k=x=>`${x} article${x===1?"":"s"}`,D=[];if(i.length===0)D.push(`Published ${k(c)} (${w}) successfully \xB7 ${g}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${k(c)} (${w}) \xB7 ${g}.`),D.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let x of i)D.push(` \u2717 ${x.label}${x.error?` \u2014 ${x.error}`:""}`)}return D}async function Er(e,t){let n=Lu(t),{model:o}=Mu(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${dn} 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 Uu({cwd:e.cwd,partitions:n,promptFor:i=>fo(i.paths),concurrency:dn,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(I(` \u2713 ${r.label}`)):console.log($(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let i=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of Lr(r.results,n,i))console.log(r.ok?I(p):L(p));let c=_r(e.cwd,e.profileName);c&&console.log(f(c));try{let p=ja(await Da({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}try{let p=Ea(await Aa({cwd:e.cwd,profileName:e.profileName}));p&&console.log(f(p))}catch{}}}catch(r){console.log($(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function mo(e,t,n){let o=Ou(e,n);if(o.length===0)return[];let r=new Set(un((await Ir({cwd:e,profileName:t})).entries).map(i=>i.path));return o.filter(i=>r.has(i))}async function Na(e,t){let n=We(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await mo(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(I("\u2713 All related articles are already published.")),{kind:"continue"}):await Er(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await Ir({cwd:t?.cwd??process.cwd()}),i=un(r.entries),c=po(r.entries);if(c>0&&console.log(L(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),i.length===0){if(console.log(I(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let p=ja(await Da({cwd:t.cwd,profileName:t.profileName}));p&&console.log(f(p));let g=Ea(await Aa({cwd:t.cwd,profileName:t.profileName}));g&&console.log(f(g))}catch{}return{kind:"continue"}}return t?await Er(t,i.map(p=>p.path)):{kind:"forward-to-agent",prompt:fo(i.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log($(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let i=await Ir({cwd:t?.cwd??process.cwd()});r=un(i.entries);let c=po(i.entries);c>0&&console.log(L(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`))}catch(i){return console.log($(`Could not compute sync status: ${i.message}`)),console.log(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(I("\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 i of r)console.log(` ${i.path} ${f(`(${i.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>_u({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(i=>({name:i.path,value:i.path,description:i.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await Er(t,r.map(i=>i.path))}return{kind:"forward-to-agent",prompt:Nr(o),display:`/publish ${o}`}}async function pn(){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(`
254
+ `),display:"/audit"}}U();import{checkbox as Bu}from"@inquirer/prompts";import{inventoryRepo as Vu,readProjectConfig as _a,writeProjectConfig as Gu}from"document360-engine";function Or(e,t){let n=_a(e);n&&(n.authoritativeSourceFiles=t,Gu(n,e))}function ho(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 La(e,t){let n=t?.cwd??process.cwd();if(!_a(n))return console.log($("No .d360-writer/config.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/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(_("Recommended documentation scope (run /scope in the REPL to choose):"));for(let i of o)console.log(` ${i.recommended?"\u25C9":"\u25CB"} ${i.path} ${f(ho(i))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Bu({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(i=>({name:`${i.path} (${ho(i)})`,value:i.path,checked:i.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"};Or(n,r),console.log(I(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let i of r)console.log(` ${i}`);return console.log(""),{kind:"continue"}}U();import{confirm as Ju}from"@inquirer/prompts";import{applyPull as Ur,computeSyncStatus as Fa,compareRemoteSources as Zu,planPull as Ha,planImport as ep,applyImport as tp,establishBaselines as np,rebaselineServerMeta as op,D360AuthError as rp}from"document360-engine";U();var Oa=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:$,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:L,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:_,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:$,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:$,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ae,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:ae,mark:"\xB7"}];function Yu(e){return e.path?e.path:`${e.title??"(untitled)"} ${ae(`[${e.articleId}]`)}`}function zu(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 go(e,t){let n=[],o=e.entries.filter(k=>k.link);if(o.length>0){n.push(""),n.push(Pe("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let k of o)n.push(` ${L("~")} ${L(k.path??"")} ${ae(`\u2192 "${k.link.title}"`)}`)}for(let k of Oa){let D=e.entries.filter(x=>x.status===k.status&&!(k.status==="untracked-local"&&x.link));if(D.length!==0){n.push(""),n.push(Pe(k.header));for(let x of D)n.push(` ${k.paint(k.mark)} ${k.paint(Yu(x))}${x.detail?ae(` (${x.detail})`):""}`)}}let r=e.counts["in-sync"]??0,i=e.entries.length;n.push("");let c={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},p=o.length,g=i===r?I("\u2713 everything up to date"):[r>0?I(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...Oa.map(k=>{let D=(e.counts[k.status]??0)-(k.status==="untracked-local"?p:0);return D>0?`${D} ${c[k.status]}`:null})].filter(Boolean).join(ae(" \xB7 ")),w=t!==void 0?` \xB7 synced in ${zu(t)}`:"";return n.push(g+ae(` \xB7 ${i} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${w}`)),n}import{structuredPatch as Ku}from"diff";import Ma from"picocolors";var Ua=80,Xu="\x1B[48;2;74;28;28m",Qu="\x1B[48;2;24;66;24m",Wa="\x1B[49m",Mr=e=>String(e).padStart(5);function ut(e,t,n){let o=x=>{let P=x.replace(/\r\n/g,`
255
255
  `);return P.endsWith(`
256
256
  `)||P===""?P:P+`
257
- `},r=o(e),i=o(t);if(r===i)return null;let c=Math.max(20,n-10),p=zu("a","b",r,i,"","",{context:3}),g=0,w=0,k=[];p.hunks.forEach((x,P)=>{P>0&&k.push(Oa.gray(" \u2026"));let C=x.oldStart,S=x.newStart;for(let N of x.lines){let O=N[0],J=N.slice(1).slice(0,c);O==="-"?(w++,k.push(`${Ku}${Or(C++)} - ${J}${Ua}`)):O==="+"?(g++,k.push(`${Xu}${Or(S++)} + ${J}${Ua}`)):(k.push(Oa.gray(Or(S))+" "+J),C++,S++)}});let D=k.slice(0,Ma);return{added:g,removed:w,lines:D,hidden:Math.max(0,k.length-Ma)}}async function Ha(e,t){let n=Me(t.cwd,t.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await rp(t),{kind:"continue"};if(o==="--baseline")return await ip(t,e.filter(c=>c!=="--baseline")),{kind:"continue"};if(o==="--compare")return await sp(t),{kind:"continue"};if(o)return console.log($(`Unknown option: ${o}`)),console.log(f("Usage: /pull pull portal edits + import new portal articles")),console.log(f(" /pull <path> pull one article (or resolve a conflict)")),console.log(f(" /pull --status drift report only (no writes)")),console.log(f(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await ap(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let i=await Ur({cwd:t.cwd,profileName:t.profileName});for(let c of Wr(i))console.log(c.tone==="ok"?I(c.text):c.tone==="warn"?L(c.text):f(c.text));console.log("")}catch(r){r instanceof op?console.log($(r.message)):console.log($(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Ur(e){let t=await Wa({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 Fa({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Mr({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 Zu({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});ep({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 go=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,pt=e=>e===1?"":"s";function Wr(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${pt(e.pulled.length)} into local: ${go(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${pt(e.imported.length)}: ${go(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${pt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${pt(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Take the portal copy: /pull <path> \xB7 keep yours: /publish <path>. (${go(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${pt(e.failed.length)} failed: ${go(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 rp(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Wa({cwd:e.cwd,profileName:e.profileName});for(let o of ho(n,Date.now()-t))console.log(o);console.log("")}async function ip(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 tp({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await np({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(I("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(I(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(I(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(L(`${o.skipped.length} skipped:`));for(let i of o.skipped)console.log(f(` - ${i.path} (${i.reason})`))}}async function sp(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Ju({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Pe(String(t.legacyCount))} \xB7 Manifest: ${Pe(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(I("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log($(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(L(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(L(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(f(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function ap(e,t){let n=t.replace(/\\/g,"/"),o=await Fa({cwd:e.cwd,profileName:e.profileName,relPath:n});console.log(""),console.log(`${_("\u25CF")} ${Pe(o.title)} ${ae(`(${o.path})`)}`);for(let c of o.notes)console.log(L(` \u26A0 ${c}`));o.overwritesLocalChanges&&console.log(L(" \u26A0 This OVERWRITES local edits made since the last sync."));let r=ut(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(f(" Local file already matches the remote content \u2014 advancing the sync base only.")),Mr({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ae(` \u23BF Added ${r.added} line${pt(r.added)}, removed ${r.removed} line${pt(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(()=>Qu({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}Mr({cwd:e.cwd,profileName:e.profileName},o),console.log(I(` \u2713 Pulled ${o.path} (sync base advanced).`))}U();import{statSync as lp}from"node:fs";import{resolve as cp}from"node:path";import{estimateBulkCost as dp,planPartitions as up,readProjectConfig as pp,resolveModelForOperation as fp,runPartitioned as mp,trackedArticlePaths as hp}from"document360-engine";var Fr=3;function Hr(e){let t,n=!1;for(let r=0;r<e.length;r++){let i=e[r];i==="--run"||i==="--yes"?n=!0:i==="--scope"?t=e[++r]:i?.startsWith("--scope=")&&(t=i.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function qr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Br(e,t){return t.map(n=>{let o=0;try{o=lp(cp(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Vr(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:
257
+ `},r=o(e),i=o(t);if(r===i)return null;let c=Math.max(20,n-10),p=Ku("a","b",r,i,"","",{context:3}),g=0,w=0,k=[];p.hunks.forEach((x,P)=>{P>0&&k.push(Ma.gray(" \u2026"));let C=x.oldStart,S=x.newStart;for(let N of x.lines){let O=N[0],J=N.slice(1).slice(0,c);O==="-"?(w++,k.push(`${Xu}${Mr(C++)} - ${J}${Wa}`)):O==="+"?(g++,k.push(`${Qu}${Mr(S++)} + ${J}${Wa}`)):(k.push(Ma.gray(Mr(S))+" "+J),C++,S++)}});let D=k.slice(0,Ua);return{added:g,removed:w,lines:D,hidden:Math.max(0,k.length-Ua)}}async function qa(e,t){let n=We(t.cwd,t.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await ip(t),{kind:"continue"};if(o==="--baseline")return await sp(t,e.filter(c=>c!=="--baseline")),{kind:"continue"};if(o==="--compare")return await ap(t),{kind:"continue"};if(o)return console.log($(`Unknown option: ${o}`)),console.log(f("Usage: /pull pull portal edits + import new portal articles")),console.log(f(" /pull <path> pull one article (or resolve a conflict)")),console.log(f(" /pull --status drift report only (no writes)")),console.log(f(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await lp(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let i=await Wr({cwd:t.cwd,profileName:t.profileName});for(let c of Fr(i))console.log(c.tone==="ok"?I(c.text):c.tone==="warn"?L(c.text):f(c.text));console.log("")}catch(r){r instanceof rp?console.log($(r.message)):console.log($(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Wr(e){let t=await Fa({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 Ha({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Ur({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 ep({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});tp({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 yo=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,pt=e=>e===1?"":"s";function Fr(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${pt(e.pulled.length)} into local: ${yo(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${pt(e.imported.length)}: ${yo(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${pt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${pt(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Take the portal copy: /pull <path> \xB7 keep yours: /publish <path>. (${yo(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${pt(e.failed.length)} failed: ${yo(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 ip(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Fa({cwd:e.cwd,profileName:e.profileName});for(let o of go(n,Date.now()-t))console.log(o);console.log("")}async function sp(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 np({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await op({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(I("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(I(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(I(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(L(`${o.skipped.length} skipped:`));for(let i of o.skipped)console.log(f(` - ${i.path} (${i.reason})`))}}async function ap(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Zu({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Pe(String(t.legacyCount))} \xB7 Manifest: ${Pe(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(I("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log($(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(L(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(L(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(f(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function lp(e,t){let n=t.replace(/\\/g,"/"),o=await Ha({cwd:e.cwd,profileName:e.profileName,relPath:n});console.log(""),console.log(`${_("\u25CF")} ${Pe(o.title)} ${ae(`(${o.path})`)}`);for(let c of o.notes)console.log(L(` \u26A0 ${c}`));o.overwritesLocalChanges&&console.log(L(" \u26A0 This OVERWRITES local edits made since the last sync."));let r=ut(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(f(" Local file already matches the remote content \u2014 advancing the sync base only.")),Ur({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ae(` \u23BF Added ${r.added} line${pt(r.added)}, removed ${r.removed} line${pt(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}Ur({cwd:e.cwd,profileName:e.profileName},o),console.log(I(` \u2713 Pulled ${o.path} (sync base advanced).`))}U();import{statSync as cp}from"node:fs";import{resolve as dp}from"node:path";import{estimateBulkCost as up,planPartitions as pp,readProjectConfig as fp,resolveModelForOperation as mp,runPartitioned as hp,trackedArticlePaths as gp}from"document360-engine";var Hr=3;function qr(e){let t,n=!1;for(let r=0;r<e.length;r++){let i=e[r];i==="--run"||i==="--yes"?n=!0:i==="--scope"?t=e[++r]:i?.startsWith("--scope=")&&(t=i.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function Br(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Vr(e,t){return t.map(n=>{let o=0;try{o=cp(dp(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Gr(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:
258
258
  - 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.
259
259
  - 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.
260
260
  - 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.
261
261
  - Work only on these files:
262
262
  `+e.paths.map(t=>`- ${t}`).join(`
263
- `)}function Gr(e,t,n){let o=e.reduce((p,g)=>p+g.paths.length,0),[r,i]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${me(r)}\u2013${me(i)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Yr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),i=e.filter(C=>!C.ok),c=e.reduce((C,S)=>C+o(S),0),p=r.reduce((C,S)=>C+o(S),0),g=e.reduce((C,S)=>C+S.costUsd,0),w=e.reduce((C,S)=>C+S.outputTokens,0),k=n==="api"?`${me(g)} total`:ze(w),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=C=>`${C} article${C===1?"":"s"}`,P=[];if(i.length===0)P.push(`Converted ${x(c)} (${D}) successfully \xB7 ${k}.`);else{P.push(`Converted ${p}/${x(c)} (${D}) \xB7 ${k}.`),P.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of i)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}async function qa(e,t){if(!pp(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Hr(e),r=hp(t.cwd,t.profileName);if(r.length===0)return console.log($("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let i=qr(r,n);if(i.length===0)return console.log($(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=up(i),p=`/convert${n?` --scope ${n}`:""} --run`,{model:g,forced:w}=fp(t.cwd,"light");if(!o){let k=dp({files:Br(t.cwd,i),op:"convert",model:g});n&&console.log(f(`Scope: ${n} (${i.length} of ${r.length} tracked articles).`));for(let D of Gr(c,k,Fr))console.log(D);return console.log(f(`Model: ${g}${w?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${i.length} articles across ${c.length} partitions (\u2264${Fr} agents at once) on ${g}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let k of mp({cwd:t.cwd,partitions:c,promptFor:Vr,concurrency:Fr,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:g}))if(k.type==="partition_status")k.status==="running"?console.log(f(` \u25B8 ${k.label} \u2014 converting\u2026`)):k.status==="done"?console.log(I(` \u2713 ${k.label}`)):console.log($(` \u2717 ${k.label}`));else if(k.type==="run_done"){console.log("");let D=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let x of Yr(k.results,c,D))console.log(k.ok?I(x):L(x))}}catch(k){console.log($(`Convert run failed: ${k.message}`))}return console.log(""),{kind:"continue"}}U();import{statSync as Ga}from"node:fs";import{resolve as Ya}from"node:path";import{estimateBulkCost as Cp,lintDocs as Rp,planPartitions as Pp,readDocsPlan as Tp,readProjectConfig as za,DEFAULT_DOCS_DIR as Sp,resolveModelForOperation as Dp,runPartitioned as jp}from"document360-engine";import{readProjectConfig as gp,loadProfileMap as yp,resolveActiveProfile as wp,desiredCategoryOrder as kp,desiredArticleOrder as bp,DEFAULT_DOCS_DIR as xp}from"document360-engine";var zr=e=>e.replace(/\\/g,"/"),$p=e=>zr(e).split("/").pop()??e;function vp(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function Kr(e,t){try{let n=gp(e);if(!n)return[];let o=wp(e,t),r=yp(e,o.name);if(!r)return[];let i=zr(n.docsDir??xp).replace(/\/+$/,""),c=new Map;for(let g of bp(r))c.set(g.categoryPath,(c.get(g.categoryPath)??0)+1);let p=[];for(let g of kp(r)){let w=zr(g.path),k=w.startsWith(`${i}/`)?w.slice(i.length+1):w===i?"":w;k&&p.push({token:k,label:vp($p(w)),count:c.get(g.path)??0})}return p}catch{return[]}}function Ba(e,t){let n=Kr(e,t);return n.length===0?["No categories yet \u2014 author some articles first, then scope to one."]:["Which category? Re-run with one of:",...n.map(o=>` --scope ${o.token} (${o.label} \xB7 ${o.count} article${o.count===1?"":"s"})`)]}function yo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Va(e,t){let n=e.indexOf("--scope");if(n===-1)return["--scope",t,...e];let o=e[n+1],r=[...e];return o===void 0||o.startsWith("-")?r.splice(n+1,0,t):r[n+1]=t,r}var Ap=3,Ep=8;function Xr(e){return e===void 0||!Number.isFinite(e)?Ap:Math.max(1,Math.min(Math.floor(e),Ep))}function Qr(e){let t,n,o=!1,r=!1,i,c=g=>{let w=Number(g);return g!==void 0&&Number.isFinite(w)?w:void 0};for(let g=0;g<e.length;g++){let w=e[g];if(w==="--preview"||w==="--dry-run")o=!0;else if(w==="--rewrite"||w==="--force")r=!0;else{if(w==="--run"||w==="--yes"||w==="--all")continue;w==="--scope"?t=e[++g]:w?.startsWith("--scope=")?t=w.slice(8):w==="--concurrency"?i=c(e[++g]):w?.startsWith("--concurrency=")?i=c(w.slice(14)):w&&!w.startsWith("--")&&(n=w)}}let p=g=>g?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:i,rewrite:r}}function Ip(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Np(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Jr(e,t,n){return n.filter(o=>{try{return Ga(Ya(e,t,o)).size===0}catch{return!0}})}function Zr(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let i=1;for(let c of o.get(r)?.sources??[])try{i+=Ga(Ya(e,c)).size}catch{}return{path:r,bytes:i}})}function ei(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.
263
+ `)}function Yr(e,t,n){let o=e.reduce((p,g)=>p+g.paths.length,0),[r,i]=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: ${he(r)}\u2013${he(i)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function zr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),i=e.filter(C=>!C.ok),c=e.reduce((C,S)=>C+o(S),0),p=r.reduce((C,S)=>C+o(S),0),g=e.reduce((C,S)=>C+S.costUsd,0),w=e.reduce((C,S)=>C+S.outputTokens,0),k=n==="api"?`${he(g)} total`:Ke(w),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=C=>`${C} article${C===1?"":"s"}`,P=[];if(i.length===0)P.push(`Converted ${x(c)} (${D}) successfully \xB7 ${k}.`);else{P.push(`Converted ${p}/${x(c)} (${D}) \xB7 ${k}.`),P.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of i)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}async function Ba(e,t){if(!fp(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=qr(e),r=gp(t.cwd,t.profileName);if(r.length===0)return console.log($("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let i=Br(r,n);if(i.length===0)return console.log($(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=pp(i),p=`/convert${n?` --scope ${n}`:""} --run`,{model:g,forced:w}=mp(t.cwd,"light");if(!o){let k=up({files:Vr(t.cwd,i),op:"convert",model:g});n&&console.log(f(`Scope: ${n} (${i.length} of ${r.length} tracked articles).`));for(let D of Yr(c,k,Hr))console.log(D);return console.log(f(`Model: ${g}${w?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${i.length} articles across ${c.length} partitions (\u2264${Hr} agents at once) on ${g}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let k of hp({cwd:t.cwd,partitions:c,promptFor:Gr,concurrency:Hr,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:g}))if(k.type==="partition_status")k.status==="running"?console.log(f(` \u25B8 ${k.label} \u2014 converting\u2026`)):k.status==="done"?console.log(I(` \u2713 ${k.label}`)):console.log($(` \u2717 ${k.label}`));else if(k.type==="run_done"){console.log("");let D=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let x of zr(k.results,c,D))console.log(k.ok?I(x):L(x))}}catch(k){console.log($(`Convert run failed: ${k.message}`))}return console.log(""),{kind:"continue"}}U();import{statSync as Ya}from"node:fs";import{resolve as za}from"node:path";import{estimateBulkCost as Rp,lintDocs as Pp,planPartitions as Tp,readDocsPlan as Sp,readProjectConfig as Ka,DEFAULT_DOCS_DIR as Dp,resolveModelForOperation as jp,runPartitioned as Ap}from"document360-engine";import{readProjectConfig as yp,loadProfileMap as wp,resolveActiveProfile as kp,desiredCategoryOrder as bp,desiredArticleOrder as xp,DEFAULT_DOCS_DIR as $p}from"document360-engine";var Kr=e=>e.replace(/\\/g,"/"),vp=e=>Kr(e).split("/").pop()??e;function Cp(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function Xr(e,t){try{let n=yp(e);if(!n)return[];let o=kp(e,t),r=wp(e,o.name);if(!r)return[];let i=Kr(n.docsDir??$p).replace(/\/+$/,""),c=new Map;for(let g of xp(r))c.set(g.categoryPath,(c.get(g.categoryPath)??0)+1);let p=[];for(let g of bp(r)){let w=Kr(g.path),k=w.startsWith(`${i}/`)?w.slice(i.length+1):w===i?"":w;k&&p.push({token:k,label:Cp(vp(w)),count:c.get(g.path)??0})}return p}catch{return[]}}function Va(e,t){let n=Xr(e,t);return n.length===0?["No categories yet \u2014 author some articles first, then scope to one."]:["Which category? Re-run with one of:",...n.map(o=>` --scope ${o.token} (${o.label} \xB7 ${o.count} article${o.count===1?"":"s"})`)]}function wo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Ga(e,t){let n=e.indexOf("--scope");if(n===-1)return["--scope",t,...e];let o=e[n+1],r=[...e];return o===void 0||o.startsWith("-")?r.splice(n+1,0,t):r[n+1]=t,r}var Ep=3,Ip=8;function Qr(e){return e===void 0||!Number.isFinite(e)?Ep:Math.max(1,Math.min(Math.floor(e),Ip))}function Jr(e){let t,n,o=!1,r=!1,i,c=g=>{let w=Number(g);return g!==void 0&&Number.isFinite(w)?w:void 0};for(let g=0;g<e.length;g++){let w=e[g];if(w==="--preview"||w==="--dry-run")o=!0;else if(w==="--rewrite"||w==="--force")r=!0;else{if(w==="--run"||w==="--yes"||w==="--all")continue;w==="--scope"?t=e[++g]:w?.startsWith("--scope=")?t=w.slice(8):w==="--concurrency"?i=c(e[++g]):w?.startsWith("--concurrency=")?i=c(w.slice(14)):w&&!w.startsWith("--")&&(n=w)}}let p=g=>g?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:i,rewrite:r}}function Np(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function _p(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Zr(e,t,n){return n.filter(o=>{try{return Ya(za(e,t,o)).size===0}catch{return!0}})}function ei(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let i=1;for(let c of o.get(r)?.sources??[])try{i+=Ya(za(e,c)).size}catch{}return{path:r,bytes:i}})}function ti(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.
264
264
  `:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
265
265
  - 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).
266
266
  - 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.
@@ -269,78 +269,78 @@ ${i}${g}`).join("")}).join(`
269
269
  - 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.
270
270
  Articles:
271
271
  `+e.paths.map(r=>`- ${r}`).join(`
272
- `)}function ti(e,t,n){let o=e.reduce((c,p)=>c+p.paths.length,0),[r,i]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${me(r)}\u2013${me(i)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function ni(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),i=e.filter(C=>!C.ok),c=e.reduce((C,S)=>C+o(S),0),p=r.reduce((C,S)=>C+o(S),0),g=e.reduce((C,S)=>C+S.costUsd,0),w=e.reduce((C,S)=>C+S.outputTokens,0),k=n==="api"?`${me(g)} total`:ze(w),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=C=>`${C} article${C===1?"":"s"}`,P=[];if(i.length===0)P.push(`Wrote ${x(c)} (${D}) successfully \xB7 ${k}.`),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}/${x(c)} (${D}) \xB7 ${k}.`),P.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of i)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}function oi(e,t,n){try{let o=Rp({cwd:e,paths:n.map(i=>`${t}/${i}`)});if(o.length===0)return null;let r=new Set(o.map(i=>i.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 /check --fix corrects them.`}catch{return null}}function ri(e,t,n){let o=(za(e)?.docsDir??Sp).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Ip(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 i=Np(r,n.scope);if(n.scope&&i.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:i,planCount:r.length,rewriting:!0};let c=Jr(e,o,i);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"",g=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${g} --rewrite to regenerate them all.`}}return{docsDir:o,targets:c,planCount:r.length}}async function Ka(e,t){if(!za(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};if(yo(e)){for(let O of Ba(t.cwd,t.profileName))console.log(f(O));return{kind:"continue"}}let n=Tp(t.cwd);if(n.length===0)return console.log($("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:i,concurrency:c,rewrite:p}=Qr(e),{docsDir:g,targets:w,reason:k,rewriting:D}=ri(t.cwd,n,{scope:o,path:r,rewrite:p});if(w.length===0)return console.log(k?L(k):L("Nothing to write.")),{kind:"continue"};D&&console.log(L(`--rewrite: regenerating ${w.length} already-written article${w.length===1?"":"s"} (overwrites them; git has your baseline).`));let x=Pp(w),P=Xr(c),{model:C,forced:S}=Dp(t.cwd,"standard"),N=!!r;if(i&&!N){let O=Cp({files:Zr(t.cwd,n,w),op:"write",model:C});o&&console.log(f(`Scope: ${o} (${w.length} pending).`));for(let J of ti(x,O,P))console.log(J);return console.log(f(`Model: ${C}${S?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${w.length} article${w.length===1?"":"s"} across ${x.length} partition${x.length===1?"":"s"} (\u2264${P} agents at once) on ${C}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let O of jp({cwd:t.cwd,partitions:x,promptFor:J=>ei(J,g,{rewrite:D||N}),concurrency:P,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(O.type==="partition_status")O.status==="running"?console.log(f(` \u25B8 ${O.label} \u2014 writing\u2026`)):O.status==="done"?console.log(I(` \u2713 ${O.label}`)):console.log($(` \u2717 ${O.label}`));else if(O.type==="run_done"){console.log("");let J=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let Z of ni(O.results,x,J))console.log(O.ok?I(Z):L(Z));let re=oi(t.cwd,g,w);re&&console.log(L(re))}}catch(O){console.log($(`Write run failed: ${O.message}`))}return console.log(""),{kind:"continue"}}U();import{existsSync as _p,readdirSync as Xa,statSync as Qa}from"node:fs";import{join as Ja}from"node:path";import{inputDir as Lp,readProjectConfig as Op}from"document360-engine";var Za=/\.(md|markdown|pdf|txt)$/i;function ii(e){let t=Lp(e);if(!_p(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Xa(t)){let i=Ja(t,r),c=!1;try{c=Qa(i).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=Mp(i);p>0&&n.push({name:r,docCount:p})}else Za.test(r)&&o++}return n.sort((r,i)=>r.name.localeCompare(i.name)),{features:n,looseDocs:o}}function Mp(e){let t=0;for(let n of Xa(e))try{Qa(Ja(e,n)).isFile()&&Za.test(n)&&t++}catch{}return t}function si(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 wo(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(`
273
- `)}var ai="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function el(e,t){let n=t?.cwd??process.cwd();if(!Op(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=ii(n);if(o.length===0&&r===0)return console.log(f(ai)),{kind:"continue"};let i=e.join(" ").trim();if(!i){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let g of o)console.log(` ${g.name} ${f(`(${g.docCount} doc${g.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:wo(p),display:p?`/draft ${p}`:"/draft"}}let c=si(o,i);return{kind:"forward-to-agent",prompt:wo(c??"",c?void 0:i),display:`/draft ${i}`}}U();import{listOpenForDocs as Up,readProjectConfig as Wp}from"document360-engine";function li(e){try{return Up(e).filter(t=>t.kind==="request").length}catch{return 0}}function ci(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function di(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(`
274
- `)}var ui="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 tl(e,t){let n=t?.cwd??process.cwd();if(!Wp(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=ci(e);if(!r&&li(n)===0)return console.log(f(ui)),{kind:"continue"};let i=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:di(r,o),display:i}}U();import{search as Fp}from"@inquirer/prompts";import{findByName as Hp,getSession as qp,listSessions as Bp,relativeTime as ol}from"document360-engine";async function rl(e,t){let n=Bp(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=Hp(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),nl(n),{kind:"continue"})}if(!process.stdin.isTTY)return nl(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Fp({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async i=>{let c=(i??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${ol(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=qp(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function nl(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${f(ol(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}U();import{renameSession as Vp}from"document360-engine";function pi(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 il(e,t){let n=pi(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Vp(o,n)?console.log(I(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(I(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as sl,readProjectConfig as Gp,writeProjectConfig as Yp}from"document360-engine";U();function fi(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Gp(e);if(!o)return"No .d360-writer/config.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return sl().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Yp(o,e),null):`Unknown environment "${r}". Known: ${sl().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function al(e,t){let n=e[0];if(!n)return Zn(t.cwd),{kind:"continue"};if(n==="add"){let o=fi(t.cwd,e[1],e[2]);return o?(console.log($(o)),{kind:"continue"}):(console.log(I(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/login")}`),{kind:"continue"})}return eo(t.cwd,n),to(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}U();import{select as zp}from"@inquirer/prompts";import{readProjectConfig as Kp,readUserConfig as ll,resolveModelSetting as mi,writeUserConfig as cl}from"document360-engine";var Ne=[{value:null,label:"Auto",desc:"Sonnet (latest) \u2014 right-sized for docs work (recommended); heavier models only when you pin them"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus (latest) \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet (latest) \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku (latest) \xB7 fastest for quick answers"}];function ko(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Ne.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Xp(e){switch(e.source){case"project":return".d360-writer/config.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"auto":return"auto \u2014 the docs-right default (newest Sonnet); /model to pin another"}}function pn(e,t){let n=()=>mi(e).model;if(t==="default"){let i=ll();return i.defaultModel?(delete i.defaultModel,cl(i),{lines:[`\u2713 Personal model override cleared \u2014 now: ${mi(e).model} (auto; applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}cl({...ll(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Kp(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer/config.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function dl(e,t){let n=e[0]?.trim();if(!n){let c=mi(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${_(c.model)}${c.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${Xp(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=ko(c),g;try{g=await t.withPausedInput(()=>zp({message:`Select model (current: ${c.model}${c.source==="auto"?" \xB7 auto":""})`,default:Ne[p].value,choices:Ne.map((x,P)=>({name:`${x.label}${P===p?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:w,changed:k,effective:D}=pn(t.cwd,g??"default");for(let x of w)console.log(x.startsWith("\u26A0")?L(x):x.startsWith("\u2713")?I(x):f(x));return k&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:i}=pn(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?L(c):c.startsWith("\u2713")?I(c):f(c));return r&&await t.setModel(i),{kind:"continue"}}bo();async function gl(e,t){return await t.withPausedInput(()=>_t(t.cwd)),{kind:"clear"}}async function yl(e,t){return await t.withPausedInput(()=>Kn(t.cwd,t.profileName)),{kind:"clear"}}U();import{resolveActiveProfile as mf}from"document360-engine";async function wl(e,t){let n=!1;try{n=mf(t.cwd).production}catch{}return n?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}U();var kl=async(e,t)=>{try{await t.withPausedInput(()=>Jn({}))}catch(n){console.log($(`Login failed: ${n.message}`))}return{kind:"continue"}};U();import{resolveActiveProfile as hf,clearTokens as gf,clearProfileProject as yf}from"document360-engine";async function bl(e,t){let n;try{n=hf(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let o=gf(n);return yf(t.cwd,n),console.log(o?I(`\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 xl}from"node:fs";import{isAbsolute as wf,join as kf,resolve as bf}from"node:path";import{readProjectConfig as xf,screenshotPlaceholderIds as $f,DEFAULT_CAPTURE_DIR as vf,DEFAULT_OUTPUT_DIR as Cf}from"document360-engine";var $l=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function gi(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?$l(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:$l(o),setup:t}:{mode:"single",id:o}}function yi(e,t){let n=xf(e),o=n?.captureDir??vf,r=n?.outputDir??Cf,i=(c,p)=>wf(c)?kf(c,p):bf(e,c,p);return $f(e,{scope:t}).map(({id:c,file:p})=>{let g=xl(i(r,`${c}.png`))?"captured":xl(i(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:g}})}var Rf={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Pf={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function wi(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(i=>i.file))].sort(),o=e.filter(i=>i.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 i of n){r.push(i);for(let c of e.filter(p=>p.file===i))r.push(` ${Rf[c.state]} ${c.id.padEnd(34)} ${Pf[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function vl(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(`
272
+ `)}function ni(e,t,n){let o=e.reduce((c,p)=>c+p.paths.length,0),[r,i]=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: ${he(r)}\u2013${he(i)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function oi(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),i=e.filter(C=>!C.ok),c=e.reduce((C,S)=>C+o(S),0),p=r.reduce((C,S)=>C+o(S),0),g=e.reduce((C,S)=>C+S.costUsd,0),w=e.reduce((C,S)=>C+S.outputTokens,0),k=n==="api"?`${he(g)} total`:Ke(w),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=C=>`${C} article${C===1?"":"s"}`,P=[];if(i.length===0)P.push(`Wrote ${x(c)} (${D}) successfully \xB7 ${k}.`),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}/${x(c)} (${D}) \xB7 ${k}.`),P.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of i)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}function ri(e,t,n){try{let o=Pp({cwd:e,paths:n.map(i=>`${t}/${i}`)});if(o.length===0)return null;let r=new Set(o.map(i=>i.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 /check --fix corrects them.`}catch{return null}}function ii(e,t,n){let o=(Ka(e)?.docsDir??Dp).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Np(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 i=_p(r,n.scope);if(n.scope&&i.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:i,planCount:r.length,rewriting:!0};let c=Zr(e,o,i);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"",g=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${g} --rewrite to regenerate them all.`}}return{docsDir:o,targets:c,planCount:r.length}}async function Xa(e,t){if(!Ka(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};if(wo(e)){for(let O of Va(t.cwd,t.profileName))console.log(f(O));return{kind:"continue"}}let n=Sp(t.cwd);if(n.length===0)return console.log($("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:i,concurrency:c,rewrite:p}=Jr(e),{docsDir:g,targets:w,reason:k,rewriting:D}=ii(t.cwd,n,{scope:o,path:r,rewrite:p});if(w.length===0)return console.log(k?L(k):L("Nothing to write.")),{kind:"continue"};D&&console.log(L(`--rewrite: regenerating ${w.length} already-written article${w.length===1?"":"s"} (overwrites them; git has your baseline).`));let x=Tp(w),P=Qr(c),{model:C,forced:S}=jp(t.cwd,"standard"),N=!!r;if(i&&!N){let O=Rp({files:ei(t.cwd,n,w),op:"write",model:C});o&&console.log(f(`Scope: ${o} (${w.length} pending).`));for(let J of ni(x,O,P))console.log(J);return console.log(f(`Model: ${C}${S?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${w.length} article${w.length===1?"":"s"} across ${x.length} partition${x.length===1?"":"s"} (\u2264${P} agents at once) on ${C}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let O of Ap({cwd:t.cwd,partitions:x,promptFor:J=>ti(J,g,{rewrite:D||N}),concurrency:P,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(O.type==="partition_status")O.status==="running"?console.log(f(` \u25B8 ${O.label} \u2014 writing\u2026`)):O.status==="done"?console.log(I(` \u2713 ${O.label}`)):console.log($(` \u2717 ${O.label}`));else if(O.type==="run_done"){console.log("");let J=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let Z of oi(O.results,x,J))console.log(O.ok?I(Z):L(Z));let re=ri(t.cwd,g,w);re&&console.log(L(re))}}catch(O){console.log($(`Write run failed: ${O.message}`))}return console.log(""),{kind:"continue"}}U();import{existsSync as Lp,readdirSync as Qa,statSync as Ja}from"node:fs";import{join as Za}from"node:path";import{inputDir as Op,readProjectConfig as Mp}from"document360-engine";var el=/\.(md|markdown|pdf|txt)$/i;function si(e){let t=Op(e);if(!Lp(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Qa(t)){let i=Za(t,r),c=!1;try{c=Ja(i).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=Up(i);p>0&&n.push({name:r,docCount:p})}else el.test(r)&&o++}return n.sort((r,i)=>r.name.localeCompare(i.name)),{features:n,looseDocs:o}}function Up(e){let t=0;for(let n of Qa(e))try{Ja(Za(e,n)).isFile()&&el.test(n)&&t++}catch{}return t}function ai(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 ko(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(`
273
+ `)}var li="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function tl(e,t){let n=t?.cwd??process.cwd();if(!Mp(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=si(n);if(o.length===0&&r===0)return console.log(f(li)),{kind:"continue"};let i=e.join(" ").trim();if(!i){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let g of o)console.log(` ${g.name} ${f(`(${g.docCount} doc${g.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:ko(p),display:p?`/draft ${p}`:"/draft"}}let c=ai(o,i);return{kind:"forward-to-agent",prompt:ko(c??"",c?void 0:i),display:`/draft ${i}`}}U();import{listOpenForDocs as Wp,readProjectConfig as Fp}from"document360-engine";function ci(e){try{return Wp(e).filter(t=>t.kind==="request").length}catch{return 0}}function di(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function ui(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(`
274
+ `)}var pi="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 nl(e,t){let n=t?.cwd??process.cwd();if(!Fp(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=di(e);if(!r&&ci(n)===0)return console.log(f(pi)),{kind:"continue"};let i=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:ui(r,o),display:i}}U();import{search as Hp}from"@inquirer/prompts";import{findByName as qp,getSession as Bp,listSessions as Vp,relativeTime as rl}from"document360-engine";async function il(e,t){let n=Vp(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=qp(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),ol(n),{kind:"continue"})}if(!process.stdin.isTTY)return ol(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Hp({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async i=>{let c=(i??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${rl(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Bp(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function ol(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${f(rl(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}U();import{renameSession as Gp}from"document360-engine";function fi(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 sl(e,t){let n=fi(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Gp(o,n)?console.log(I(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(I(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as al,readProjectConfig as Yp,writeProjectConfig as zp}from"document360-engine";U();function mi(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Yp(e);if(!o)return"No .d360-writer/config.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return al().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},zp(o,e),null):`Unknown environment "${r}". Known: ${al().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function ll(e,t){let n=e[0];if(!n)return eo(t.cwd),{kind:"continue"};if(n==="add"){let o=mi(t.cwd,e[1],e[2]);return o?(console.log($(o)),{kind:"continue"}):(console.log(I(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/login")}`),{kind:"continue"})}return to(t.cwd,n),no(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}U();import{select as Kp}from"@inquirer/prompts";import{readProjectConfig as Xp,readUserConfig as cl,resolveModelSetting as hi,writeUserConfig as dl}from"document360-engine";var Ne=[{value:null,label:"Auto",desc:"Sonnet (latest) \u2014 right-sized for docs work (recommended); heavier models only when you pin them"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus (latest) \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet (latest) \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku (latest) \xB7 fastest for quick answers"}];function bo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Ne.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Qp(e){switch(e.source){case"project":return".d360-writer/config.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"auto":return"auto \u2014 the docs-right default (newest Sonnet); /model to pin another"}}function fn(e,t){let n=()=>hi(e).model;if(t==="default"){let i=cl();return i.defaultModel?(delete i.defaultModel,dl(i),{lines:[`\u2713 Personal model override cleared \u2014 now: ${hi(e).model} (auto; applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}dl({...cl(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Xp(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer/config.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function ul(e,t){let n=e[0]?.trim();if(!n){let c=hi(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${_(c.model)}${c.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${Qp(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=bo(c),g;try{g=await t.withPausedInput(()=>Kp({message:`Select model (current: ${c.model}${c.source==="auto"?" \xB7 auto":""})`,default:Ne[p].value,choices:Ne.map((x,P)=>({name:`${x.label}${P===p?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:w,changed:k,effective:D}=fn(t.cwd,g??"default");for(let x of w)console.log(x.startsWith("\u26A0")?L(x):x.startsWith("\u2713")?I(x):f(x));return k&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:i}=fn(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?L(c):c.startsWith("\u2713")?I(c):f(c));return r&&await t.setModel(i),{kind:"continue"}}xo();async function yl(e,t){return await t.withPausedInput(()=>_t(t.cwd)),{kind:"clear"}}async function wl(e,t){return await t.withPausedInput(()=>Xn(t.cwd,t.profileName)),{kind:"clear"}}U();import{resolveActiveProfile as hf}from"document360-engine";async function kl(e,t){let n=!1;try{n=hf(t.cwd).production}catch{}return n?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}U();var bl=async(e,t)=>{try{await t.withPausedInput(()=>Zn({}))}catch(n){console.log($(`Login failed: ${n.message}`))}return{kind:"continue"}};U();import{resolveActiveProfile as gf,clearTokens as yf,clearProfileProject as wf}from"document360-engine";async function xl(e,t){let n;try{n=gf(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let o=yf(n);return wf(t.cwd,n),console.log(o?I(`\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 $l}from"node:fs";import{isAbsolute as kf,join as bf,resolve as xf}from"node:path";import{readProjectConfig as $f,screenshotPlaceholderIds as vf,DEFAULT_CAPTURE_DIR as Cf,DEFAULT_OUTPUT_DIR as Rf}from"document360-engine";var vl=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function yi(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?vl(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:vl(o),setup:t}:{mode:"single",id:o}}function wi(e,t){let n=$f(e),o=n?.captureDir??Cf,r=n?.outputDir??Rf,i=(c,p)=>kf(c)?bf(c,p):xf(e,c,p);return vf(e,{scope:t}).map(({id:c,file:p})=>{let g=$l(i(r,`${c}.png`))?"captured":$l(i(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:g}})}var Pf={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Tf={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function ki(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(i=>i.file))].sort(),o=e.filter(i=>i.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 i of n){r.push(i);for(let c of e.filter(p=>p.file===i))r.push(` ${Pf[c.state]} ${c.id.padEnd(34)} ${Tf[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Cl(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(`
275
275
  `),"","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(`
276
- `)}async function xo(e,t){let n=gi(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of wi(yi(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(`
276
+ `)}async function $o(e,t){let n=yi(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of ki(wi(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(`
277
277
  `),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(`
278
- `),i=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:i}}import{existsSync as Tf,readFileSync as Sf}from"node:fs";import{isAbsolute as Df,join as jf,resolve as Af}from"node:path";import{readProjectConfig as Ef,DEFAULT_CAPTURE_DIR as If}from"document360-engine";async function mn(){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(`
279
- `),display:"/capture-setup"}}var Cl="-".repeat(64);function ki(e){let t=If;try{let k=Ef(e);k?.captureDir&&(t=k.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Df(t)?jf(t,"CAPTURE-TESTID-REQUESTS.json"):Af(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Tf(n))return null;let o;try{let k=JSON.parse(Sf(n,"utf8").replace(/^/,""));o=Array.isArray(k?.requests)?k.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(k=>k.file).filter(Boolean)).size,i=o.length,c=`${i} data-testid attribute${i===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,g=`${t}/CAPTURE-TESTID-REQUESTS.md`,w=`${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.","",Cl,`Read ${g} and ${w}. 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.",Cl]}Ge();U();import{listOpenForDocs as Nf,readProjectConfig as _f}from"document360-engine";function bi(e){try{return Nf(e).length}catch{return 0}}function xi(){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(`
280
- `)}async function Rl(e,t){let n=t?.cwd??process.cwd();return _f(n)?bi(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:xi(),display:"/inbox"}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{listOpenHints as Lf,listOpenForDocs as Of,listOpenDirectives as Mf,readProjectConfig as Uf,computeSyncStatus as Wf,planPull as Ff,applyPull as Hf,planImport as qf,applyImport as Bf}from"document360-engine";function hn(e){let t=0,n=0,o=0,r=0;try{t=Lf(e).length}catch{}try{let i=Of(e);n=i.filter(c=>c.kind==="request").length,o=i.filter(c=>c.kind==="answer").length}catch{}try{r=Mf(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function gn(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),t.length?t.join(", "):null}function vi(e){return{publish:e.includes("--publish")}}function Ci({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page" \u2014 .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback once (idempotent \u2014 it creates the hidden feedback category + seed articles if this workspace has none, else no-ops), then d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY \u2014 triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","4. Decide the right doc actions across ALL of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief, address each feedback item (improve the doc it points at \u2014 as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts \u2014 following the active doc-type playbook).","5. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the loop:"," \u2022 stamp consumed hints, and mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done), and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed \u2014 never delete existing steps;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article \u2014 `**d360-writer response:** \u2713 actioned in <article> \u2014 <date>` (or `declined \u2014 <reason>`) \u2014 NEVER overwriting the person's own text \u2014 then call d360_feedback_done(article_id, resulting_articles);"," \u2022 EXCEPT the Creator-notes item (is_creator_notes:true): do NOT reply in it \u2014 instead fold its content into `.d360-writer/architecture/CREATOR-NOTES.md` as an appended, dated `## From portal Creator notes (<date>)` section (preserve every existing note + human edit), then call d360_feedback_done for it.","8. Push the drafts to Document360.","9. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs \u2014 only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)"];return t.push(e?"10. Then publish the new/updated articles live (publish-to-d360 skill), respecting the production write-guard.":"Leave everything as DRAFTS for review \u2014 do not publish live (run /publish when you want them live)."),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (plus the d360_ask_builder question you left for it)."),t.join(`
281
- `)}var Vf={status:Wf,plan:Ff,apply:Hf,planImport:qf,applyImport:Bf};async function Ri(e,t=Vf){let n={pulled:[],imported:[],conflicts:[],failed:[]},o;try{o=await t.status({cwd:e.cwd,profileName:e.profileName})}catch(r){return n.error=r.message,n}for(let r of o.entries)if(r.status==="conflict"&&r.path)n.conflicts.push(r.path);else if(r.status==="untracked-remote"&&r.articleId)try{let i=await t.planImport({cwd:e.cwd,profileName:e.profileName,articleId:r.articleId});t.applyImport({cwd:e.cwd,profileName:e.profileName},i),n.imported.push(i.path)}catch(i){n.failed.push({path:r.title??r.articleId,error:i.message})}else if(r.status==="remote-ahead"&&r.path)try{let i=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},i),n.pulled.push(r.path)}catch(i){n.failed.push({path:r.path,error:i.message})}return n}var $i=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,$o=e=>e===1?"":"s";function Pi(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${$o(e.pulled.length)} into local: ${$i(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${$o(e.imported.length)} into local drafts: ${$i(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${$o(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${$i(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${$o(e.failed.length)} failed \u2014 left for /pull.`),t}async function Pl(e,t){let n=t?.cwd??process.cwd();if(!Uf(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Me(n,t?.profileName);if(!o.ok)return console.log($(o.reason)),{kind:"continue"};let{publish:r}=vi(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let i=await Ri({cwd:n,profileName:t?.profileName});for(let p of Pi(i))console.log(p.startsWith("\u2713")?I(p):p.startsWith("\u2139")?f(p):L(p));let c=gn(hn(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:Ci({publish:r}),display:`/catch-up${r?" --publish":""}`}}U();import{spawn as Gf}from"node:child_process";var ft="document360-writer",vo=`npm i -g ${ft}@latest`;async function Co(){let e=process.platform==="win32";return new Promise(t=>{try{let n=Gf(`npm i -g ${ft}@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 Tl(){return console.log(f(`Updating ${ft}\u2026`)),(await Co()).ok?console.log(I("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log($(`Update failed \u2014 run manually: ${vo}`)),{kind:"continue"}}U();Ge();import{existsSync as Ti,rmSync as Yf}from"node:fs";import{basename as Sl,resolve as Si}from"node:path";import{execFileSync as zf}from"node:child_process";import{input as Kf}from"@inquirer/prompts";import{readProjectConfig as Xf,devHintsGuidePath as Qf}from"document360-engine";var Jf=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Zf=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Ro=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Dl=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function jl(e){let t=Ro(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Dl(t)?!0:Zf.has(t)}function Di(e){let t=null;try{t=Xf(e)}catch{t=null}let n=new Set(Jf);for(let o of[Ro(t?.docsDir),Ro(t?.captureDir),Ro(t?.outputDir)])o&&Dl(o)&&n.add(o);return[...n].filter(o=>jl(o)&&Ti(Si(e,o)))}function ji(e,t){let n=[],o=[];for(let r of t){if(!jl(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Yf(Si(e,r),{recursive:!0,force:!0}),n.push(r)}catch(i){o.push({path:r,error:i.message})}}return{removed:n,failed:o}}function Al(e,t){try{return zf("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
282
- `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function em(e){return Al(e,".d360-writer/hints")}function tm(e){return Al(e,".d360-writer/messages")}function Ai(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=em(e),o=tm(e),r=Ti(Si(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(i=>` \u2022 ${i}`),"",...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: ${Sl(e)}`]}async function El(e,t){let n=Di(t.cwd);for(let g of Ai(t.cwd,n))console.log(n.length===0?f(g):g);if(n.length===0)return{kind:"continue"};let o=Sl(t.cwd);if((await t.withPausedInput(()=>Kf({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let i=Ti(Qf(t.cwd)),{removed:c,failed:p}=ji(t.cwd,n);console.log(I(`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`));for(let g of p)console.log($(` \u2717 ${g.path}: ${g.error}`));if(i){for(let g of so())console.log(g);console.log(f("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}U();import{lintDocs as nm}from"document360-engine";function Po(e){if(e.length===0)return["\u2713 No issues found \u2014 no leaked internals, unknown commands, stale version facts, or AI-tells in the docs."];let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}let n=[`\u26A0 ${e.length} doc issue${e.length===1?"":"s"} in ${t.size} article${t.size===1?"":"s"} (leaked internals / unknown commands / stale facts / AI-tells):`];for(let[o,r]of t){n.push(` ${o}`);for(let i of r)n.push(` L${i.line}: "${i.term}" \u2014 ${i.message}`)}return n}function Ei(e){let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}return["The documentation quality check found issues in already-written articles. FIX each one by EDITING the","article in place \u2014 do not rewrite whole articles, just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","How to fix, by issue type:","- internal-leak (an agent codename, an internal skill name, or a d360_* tool name): this is the"," documentation engine's own machinery and must NOT appear in user docs. Reword the sentence to describe"," the behavior in plain user terms, or delete the internal aside. Do NOT swap it for another internal term.","- unknown-command: the named /command or --flag does not exist in the product source. Find the correct"," command/flag in the source and use it; if there is no real equivalent, remove the claim.","- stale-fact: the version contradicts the product's package.json engines \u2014 correct it to the real value.","- ai-tell: a machine-sounding buzzword (e.g. delve, leverage, furthermore, robust). Rewrite the phrase in"," plain, direct developer language; preserve the meaning; do NOT swap one buzzword for another.","","Rules: edit ONLY the listed articles; do not touch others; do not publish; introduce no new internal","nouns, invented commands, or wrong facts. When done, every listed issue should be gone.","","Issues:",[...t.entries()].map(([o,r])=>[o,...r.map(i=>` - L${i.line} [${i.kind}]: "${i.term}" \u2014 ${i.message}`)].join(`
278
+ `),i=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:i}}import{existsSync as Sf,readFileSync as Df}from"node:fs";import{isAbsolute as jf,join as Af,resolve as Ef}from"node:path";import{readProjectConfig as If,DEFAULT_CAPTURE_DIR as Nf}from"document360-engine";async function hn(){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(`
279
+ `),display:"/capture-setup"}}var Rl="-".repeat(64);function bi(e){let t=Nf;try{let k=If(e);k?.captureDir&&(t=k.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=jf(t)?Af(t,"CAPTURE-TESTID-REQUESTS.json"):Ef(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Sf(n))return null;let o;try{let k=JSON.parse(Df(n,"utf8").replace(/^/,""));o=Array.isArray(k?.requests)?k.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(k=>k.file).filter(Boolean)).size,i=o.length,c=`${i} data-testid attribute${i===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,g=`${t}/CAPTURE-TESTID-REQUESTS.md`,w=`${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.","",Rl,`Read ${g} and ${w}. 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.",Rl]}Ye();U();import{listOpenForDocs as _f,readProjectConfig as Lf}from"document360-engine";function xi(e){try{return _f(e).length}catch{return 0}}function $i(){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(`
280
+ `)}async function Pl(e,t){let n=t?.cwd??process.cwd();return Lf(n)?xi(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:$i(),display:"/inbox"}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{listOpenHints as Of,listOpenForDocs as Mf,listOpenDirectives as Uf,readProjectConfig as Wf,computeSyncStatus as Ff,planPull as Hf,applyPull as qf,planImport as Bf,applyImport as Vf}from"document360-engine";function gn(e){let t=0,n=0,o=0,r=0;try{t=Of(e).length}catch{}try{let i=Mf(e);n=i.filter(c=>c.kind==="request").length,o=i.filter(c=>c.kind==="answer").length}catch{}try{r=Uf(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function yn(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),t.length?t.join(", "):null}function Ci(e){return{publish:e.includes("--publish")}}function Ri({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page" \u2014 .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback once (idempotent \u2014 it creates the hidden feedback category + seed articles if this workspace has none, else no-ops), then d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY \u2014 triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","4. Decide the right doc actions across ALL of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief, address each feedback item (improve the doc it points at \u2014 as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts \u2014 following the active doc-type playbook).","5. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the loop:"," \u2022 stamp consumed hints, and mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done), and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed \u2014 never delete existing steps;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article \u2014 `**d360-writer response:** \u2713 actioned in <article> \u2014 <date>` (or `declined \u2014 <reason>`) \u2014 NEVER overwriting the person's own text \u2014 then call d360_feedback_done(article_id, resulting_articles);"," \u2022 EXCEPT the Creator-notes item (is_creator_notes:true): do NOT reply in it \u2014 instead fold its content into `.d360-writer/architecture/CREATOR-NOTES.md` as an appended, dated `## From portal Creator notes (<date>)` section (preserve every existing note + human edit), then call d360_feedback_done for it.","8. Push the drafts to Document360.","9. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs \u2014 only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)"];return t.push(e?"10. Then publish the new/updated articles live (publish-to-d360 skill), respecting the production write-guard.":"Leave everything as DRAFTS for review \u2014 do not publish live (run /publish when you want them live)."),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (plus the d360_ask_builder question you left for it)."),t.join(`
281
+ `)}var Gf={status:Ff,plan:Hf,apply:qf,planImport:Bf,applyImport:Vf};async function Pi(e,t=Gf){let n={pulled:[],imported:[],conflicts:[],failed:[]},o;try{o=await t.status({cwd:e.cwd,profileName:e.profileName})}catch(r){return n.error=r.message,n}for(let r of o.entries)if(r.status==="conflict"&&r.path)n.conflicts.push(r.path);else if(r.status==="untracked-remote"&&r.articleId)try{let i=await t.planImport({cwd:e.cwd,profileName:e.profileName,articleId:r.articleId});t.applyImport({cwd:e.cwd,profileName:e.profileName},i),n.imported.push(i.path)}catch(i){n.failed.push({path:r.title??r.articleId,error:i.message})}else if(r.status==="remote-ahead"&&r.path)try{let i=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},i),n.pulled.push(r.path)}catch(i){n.failed.push({path:r.path,error:i.message})}return n}var vi=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,vo=e=>e===1?"":"s";function Ti(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${vo(e.pulled.length)} into local: ${vi(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${vo(e.imported.length)} into local drafts: ${vi(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${vo(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${vi(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${vo(e.failed.length)} failed \u2014 left for /pull.`),t}async function Tl(e,t){let n=t?.cwd??process.cwd();if(!Wf(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=We(n,t?.profileName);if(!o.ok)return console.log($(o.reason)),{kind:"continue"};let{publish:r}=Ci(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let i=await Pi({cwd:n,profileName:t?.profileName});for(let p of Ti(i))console.log(p.startsWith("\u2713")?I(p):p.startsWith("\u2139")?f(p):L(p));let c=yn(gn(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:Ri({publish:r}),display:`/catch-up${r?" --publish":""}`}}U();import{spawn as Yf}from"node:child_process";var ft="document360-writer",Co=`npm i -g ${ft}@latest`;async function Ro(){let e=process.platform==="win32";return new Promise(t=>{try{let n=Yf(`npm i -g ${ft}@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 Sl(){return console.log(f(`Updating ${ft}\u2026`)),(await Ro()).ok?console.log(I("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log($(`Update failed \u2014 run manually: ${Co}`)),{kind:"continue"}}U();Ye();import{existsSync as Si,rmSync as zf}from"node:fs";import{basename as Dl,resolve as Di}from"node:path";import{execFileSync as Kf}from"node:child_process";import{input as Xf}from"@inquirer/prompts";import{readProjectConfig as Qf,devHintsGuidePath as Jf}from"document360-engine";var Zf=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],em=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Po=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),jl=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Al(e){let t=Po(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:jl(t)?!0:em.has(t)}function ji(e){let t=null;try{t=Qf(e)}catch{t=null}let n=new Set(Zf);for(let o of[Po(t?.docsDir),Po(t?.captureDir),Po(t?.outputDir)])o&&jl(o)&&n.add(o);return[...n].filter(o=>Al(o)&&Si(Di(e,o)))}function Ai(e,t){let n=[],o=[];for(let r of t){if(!Al(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{zf(Di(e,r),{recursive:!0,force:!0}),n.push(r)}catch(i){o.push({path:r,error:i.message})}}return{removed:n,failed:o}}function El(e,t){try{return Kf("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
282
+ `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function tm(e){return El(e,".d360-writer/hints")}function nm(e){return El(e,".d360-writer/messages")}function Ei(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=tm(e),o=nm(e),r=Si(Di(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(i=>` \u2022 ${i}`),"",...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: ${Dl(e)}`]}async function Il(e,t){let n=ji(t.cwd);for(let g of Ei(t.cwd,n))console.log(n.length===0?f(g):g);if(n.length===0)return{kind:"continue"};let o=Dl(t.cwd);if((await t.withPausedInput(()=>Xf({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let i=Si(Jf(t.cwd)),{removed:c,failed:p}=Ai(t.cwd,n);console.log(I(`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`));for(let g of p)console.log($(` \u2717 ${g.path}: ${g.error}`));if(i){for(let g of ao())console.log(g);console.log(f("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}U();import{lintDocs as om}from"document360-engine";function To(e){if(e.length===0)return["\u2713 No issues found \u2014 no leaked internals, unknown commands, stale version facts, or AI-tells in the docs."];let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}let n=[`\u26A0 ${e.length} doc issue${e.length===1?"":"s"} in ${t.size} article${t.size===1?"":"s"} (leaked internals / unknown commands / stale facts / AI-tells):`];for(let[o,r]of t){n.push(` ${o}`);for(let i of r)n.push(` L${i.line}: "${i.term}" \u2014 ${i.message}`)}return n}function Ii(e){let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}return["The documentation quality check found issues in already-written articles. FIX each one by EDITING the","article in place \u2014 do not rewrite whole articles, just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","How to fix, by issue type:","- internal-leak (an agent codename, an internal skill name, or a d360_* tool name): this is the"," documentation engine's own machinery and must NOT appear in user docs. Reword the sentence to describe"," the behavior in plain user terms, or delete the internal aside. Do NOT swap it for another internal term.","- unknown-command: the named /command or --flag does not exist in the product source. Find the correct"," command/flag in the source and use it; if there is no real equivalent, remove the claim.","- stale-fact: the version contradicts the product's package.json engines \u2014 correct it to the real value.","- ai-tell: a machine-sounding buzzword (e.g. delve, leverage, furthermore, robust). Rewrite the phrase in"," plain, direct developer language; preserve the meaning; do NOT swap one buzzword for another.","","Rules: edit ONLY the listed articles; do not touch others; do not publish; introduce no new internal","nouns, invented commands, or wrong facts. When done, every listed issue should be gone.","","Issues:",[...t.entries()].map(([o,r])=>[o,...r.map(i=>` - L${i.line} [${i.kind}]: "${i.term}" \u2014 ${i.message}`)].join(`
283
283
  `)).join(`
284
284
  `)].join(`
285
- `)}async function Il(e,t){let n=e.includes("--fix"),o=e.find(c=>!c.startsWith("--")),r=o?` ${o}`:"",i=nm({cwd:t.cwd,scope:o});if(n)return i.length===0?(console.log(I("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${i.length} doc issue${i.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:Ei(i),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let c of Po(i))console.log(i.length===0?I(c):L(c));return i.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}U();import{lintDocs as lm,loadStyleGuide as cm,buildReviewPrompt as dm,readProjectConfig as um,DEFAULT_DOCS_DIR as pm}from"document360-engine";U();import{readProjectConfig as om,loadProfileMap as rm,resolveActiveProfile as im,desiredCategoryOrder as sm,desiredArticleOrder as am}from"document360-engine";function Nl(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var _l=e=>e.replace(/\\/g,"/").split("/").pop()??e;function yn(e,t){try{if(!om(e))return[];let n=im(e,t),o=rm(e,n.name);if(!o)return[];let r=new Map;for(let c of am(o)){let p=r.get(c.categoryPath);p?p.push(c):r.set(c.categoryPath,[c])}let i=[];for(let c of sm(o)){i.push(Nl(_l(c.path)));for(let p of(r.get(c.path)??[]).sort((g,w)=>g.order-w.order))i.push(` ${Nl(_l(p.path))}`)}return i}catch{return[]}}async function Ll(e,t){let n=yn(t.cwd,t.profileName);if(n.length===0)return console.log(f("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(_("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Ii(e,t){let n=um(e);if(!n)return null;let o=(n.docsDir??pm).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),i=t.find(k=>!k.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),c=lm({cwd:e}),p=i?c.filter(k=>k.path===`${o}/${i}`||k.path.startsWith(`${o}/${i}/`)):c,g=i?"":yn(e).join(`
286
- `);return{prompt:dm({docsRoot:o,scope:i,styleGuide:cm(e),deterministicFindings:p,fix:r,structure:g||void 0}),display:`/review${i?` ${i}`:""}${r?" --fix":""}`}}async function Ol(e,t){let n=Ii(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{readProjectConfig as fm}from"document360-engine";function Ni(e,t){if(!fm(e))return null;let n=t.find(r=>!r.startsWith("--"));return{prompt:[`Reorder the articles within ${n?`the "${n}" category`:"each category"} to the best reading order.`,"Follow the manage-structure skill: decide the ideal order with senior-editor judgment per the doc-genre","playbook (overview / mental-model first; reference and troubleshooting/FAQ last), then APPLY it with the","d360_reorder_articles tool \u2014 one category at a time, all paths in the same category folder. Do not rename","files or edit the map by hand; the tool handles it. Report the new order, and remind me it reaches","Document360 on the next /publish."].join(`
287
- `),display:`/reorder${n?` ${n}`:""}`}}async function Ml(e,t){let n=Ni(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{readProjectConfig as mm,writeProjectConfig as Ul,isAppType as hm,playbookSkillName as gm,detectAppType as Wl}from"document360-engine";var Fl=["web","cli","service","library"],ym=new Set(["web","cli"]);function _i(e){return ym.has(e)?`${gm(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function To(e,t){let n=t.cwd,o=mm(n);if(!o)return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let i=o.appType??Wl(n);if(i){let c=o.appType?"set in config":"auto-detected";console.log(`${_("Genre:")} ${i} (${c}) \u2014 ${_i(i)}`)}else console.log(L("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${Fl.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(f("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:i,...c}=o;Ul(c,n);let p=Wl(n);return console.log(I(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${_i(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return hm(r)?(Ul({...o,appType:r},n),console.log(I(`\u2713 Genre set to ${r} \u2014 ${_i(r)} (applies from your next command).`)),{kind:"continue"}):(console.log($(`Unknown genre "${r}". Choose one of: ${Fl.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}U();import{listRoadmap as Hl,roadmapProgress as ql,stampRoadmapDone as wm}from"document360-engine";function Li(e){let t=Hl(e);if(t.length===0)return["No docs roadmap yet \u2014 the docs agent seeds .d360-writer/roadmap.md when it pins a structure,","and adds steps as the app changes. You can also write steps by hand (## [open] <step>), or ask:",'"propose the docs roadmap for this repo".'];let n=ql(e),o=[`Docs roadmap \u2014 ${n.done} of ${n.total} step${n.total===1?"":"s"} done:`,""];for(let r of t)o.push(` ${r.status==="done"?"\u2713":"\u25CB"} ${r.title}${r.run?` \xB7 ${r.run}`:""}`);return o.push(""),o.push(n.next?`Next: ${n.next.title}${n.next.run?` \u2014 ${n.next.run}`:""}`:"Campaign complete \u2014 the docs agent adds new steps as the app changes."),o.push("(Edit .d360-writer/roadmap.md freely \xB7 /roadmap done <step> marks one you finished yourself.)"),o}function Oi(e,t){if(!t.trim())return{ok:!1,line:"Usage: /roadmap done <step title>"};if(!wm(e,t,{doneAt:new Date().toISOString()})){let r=Hl(e).filter(i=>i.status==="open");return{ok:!1,line:r.length?`No open step titled "${t}". Open steps: ${r.map(i=>`"${i.title}"`).join(", ")}`:`No open step titled "${t}" \u2014 the roadmap has no open steps.`}}let o=ql(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${t}${o?` \u2014 next up: ${o.title}${o.run?` (${o.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}async function Bl(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Oi(n,e.slice(1).join(" ").trim());return console.log(r.ok?I(r.line):L(r.line)),{kind:"continue"}}let o=Li(n);console.log(_(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?f(r):r);return{kind:"continue"}}var Vl={help:gr,"?":gr,clear:Qs,exit:yr,quit:yr,init:$r,mcp:co,publish:Ia,audit:un,scope:_a,pull:Ha,convert:qa,write:Ka,draft:el,document:tl,resume:rl,rename:il,profile:al,model:dl,doctor:fn,workspace:gl,project:yl,"allow-prod":wl,login:kl,logout:bl,screenshot:xo,"capture-setup":mn,devhints:sa,inbox:Rl,"catch-up":Pl,update:Tl,reset:El,check:Il,review:Ol,reorder:Ml,structure:Ll,genre:To,roadmap:Bl};function Gl(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}Ge();var km="Or just tell me what to write or update.",bm='\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 ye(e){return e===1?"":"s"}function So(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Mi(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var xm={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",options:[{cmd:"/genre web",desc:"web app / SaaS UI"},{cmd:"/genre cli",desc:"command-line tool"},{cmd:"/genre service",desc:"API / backend service"},{cmd:"/genre library",desc:"SDK / library"}]};function $m(e){let t=[];if(e.devhints!=="current"&&e.builderStarted){let n=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",o=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";t.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${n}${o} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${n}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&t.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:xm,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${ye(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${ye(n)}.`})}if(e.directives>0||e.pendingText){let n=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",o=[];e.directives>0&&o.push(`${e.directives} owner directive${ye(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
288
- \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ye(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${ye(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${ye(n)} up.`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${ye(n.total)} done \u2014 next: ${o.title}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${ye(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${ye(n)}.`})}return t}function Yl(e,t){let n=t.filter(i=>i.bullet).map(i=>` \u2022 ${i.bullet}`),o=t[0],r=[];o.lead?r.push(Mi(o.lead)):o.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let i of t.slice(1,3))i.follow&&r.push(i.follow);return[e,...n,r.join(" "),km].join(`
289
- `)}function wn(e){if(!e.ready)return{kind:"idle"};let t=$m(e);if(!e.hasDocs){let r=t[0];return r&&(r.lead?.kind==="cmd"||r.picker)?{kind:"recommend",rec:{note:Yl("\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",t),tone:r.tone??"info",lead:r.lead,picker:r.picker}}:{kind:"recommend",rec:{note:bm,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null}}}if(t.length===0){let r=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${ye(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${ye(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${r}`,tone:"info",lead:null,picker:null}}}let n=t[0];return(n.key==="audit"||n.key==="roadmap"&&t[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${ye(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:Yl("Welcome back \u2014 where your docs stand:",t),tone:n.tone??"info",lead:n.lead,picker:n.picker}}}import{existsSync as Ui,readdirSync as Fi}from"node:fs";import{spawnSync as vm}from"node:child_process";import{join as Do}from"node:path";import{readProjectConfig as Kl,resolveActiveProfile as Xl,loadTokens as Cm,isExpired as Rm,loadProfileMap as Ql,countLocalAhead as Pm,readDocsPlan as Tm,devHintsGuidePath as Sm,DEFAULT_DOCS_DIR as Wi,roadmapProgress as Dm}from"document360-engine";Ge();function zl(e){try{return Fi(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Hi(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>zl(Do(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&zl(Do(e,o)))}function qi(e,t){try{let n=Kl(e);if(!n)return!1;let o=Xl(e,t),r=Ql(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let i=Do(e,(n.docsDir??Wi).replace(/\/+$/,""));return!!(Ui(i)&&Fi(i).length>0||Ui(Sm(e)))}catch{return!1}}function kn(e,t,n){try{let o=Kl(e);if(!o)return null;let r=Xl(e,t),i=Cm(r.name),c=!!i&&(!Rm(i)||!!i.refreshToken),p=qi(e,t)||!Hi(e,o.authoritativeSourceFiles),g=Ql(e,r.name),w=g?Object.keys(g.articles).length:0,k=Do(e,(o.docsDir??Wi).replace(/\/+$/,"")),D=!1;try{D=Ui(k)&&Fi(k).length>0}catch{}let x=0;if(g?.lastAnalyzedCommit)try{let re=vm("git",["rev-list","--count",`${g.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});re.status===0&&(x=parseInt((re.stdout||"").trim(),10)||0)}catch{}let P=0;try{let re=Tm(e);if(re.length>0){let Z=(o.docsDir??Wi).replace(/\/+$/,"");P=Jr(e,Z,re.map(de=>de.path)).length}}catch{}let C=hn(e),S=gn({...C,directives:0}),N=Pm(e,t),O=Se(e),J=Dm(e);return{ready:c&&p&&!n.claudeMissing,hasDocs:D,tracked:w,pendingText:S,directives:C.directives,behind:x,pendingWrites:P,localAhead:N,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:O.status,devhintsCompletedVersion:O.completedVersion,devhintsToVersion:se,builderStarted:Oe(e),genreUnknown:n.genreUnknown,roadmap:J}}catch{return null}}U();var jm={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"},Zl=160,Vi=200,ec=40;function we(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Jl(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),ec)}`);return t.length>4&&n.push("\u2026"),we(n.join(", "),Zl)}var Ke=e=>typeof e=="string"&&e?e:null,Bi=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Am(e){let t=Ke(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(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ")}function Em(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Ke(t.title);if(!o)return null;let r=Am(t.local_path);return n("Create article",`"${we(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Ke(t.title),r=Bi(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)",Bi(t.article_id)?`id ${Bi(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",Ke(t.name)?`"${we(Ke(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Ke(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 jo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...i]=e.split("__"),c=i.join("__");if(r==="document360"){let w=Em(c,t);if(w)return w}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Jl(t)}}let n=jm[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:we(o,Zl)}:{title:e,sep:"",arg:Jl(t)}}function Im(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 Nm(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Im).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>we(r,Vi))]}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),ec)}`);return n.length>0?[we(n.join(" \xB7 "),Vi)]:null}return null}function _m(e){let t=Ke(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Lm(e,t,n){switch(e){case"d360_create_article":{let o=_m(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=Ke(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 Ao(e,t=4,n,o){let r=e.replace(/\r\n/g,`
290
- `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=Lm(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let i=Nm(r)??r.split(`
291
- `);return{lines:i.slice(0,t).map(c=>we(c,Vi)),hidden:Math.max(0,i.length-t)}}function Eo(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Io(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 No(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 Jm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Zm(e,t,n,o){if(Jm.test(e))try{let r=oc(o),i=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=Io(t,n),p=No(n);e.endsWith("publish_article")&&p&&console.log(_(` \u2B95 Live: ${p}`)),c&&i&&console.log(_(` \u2B95 Preview: ${Eo(r.connection.portalUrl,i,c,r.project.languageCode??"en")}`))}catch{}}async function rc(e=process.cwd(),t="auto",n){let o=Mm(t);o.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${_("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${_('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),eh(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,i=Gi({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=Om({input:process.stdin,output:process.stdout}),g=[],w=null,k=!1;p.on("line",P=>{if(w){let C=w;w=null,C(P)}else g.push(P)}),p.on("close",()=>{if(k=!0,w){let P=w;w=null,P(null)}});function D(){return g.length>0?Promise.resolve(g.shift()):k?Promise.resolve(null):(process.stdout.write(_("> ")),new Promise(P=>{w=P}))}let x={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{i.close(),i=Gi({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setPendingName:P=>{c.pendingName=P},setModel:async P=>i.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 S=Gl(C);if(!S)continue;let N=Vl[S.name];if(!N){console.log($(`Unknown command: /${S.name}`)),console.log(f("Type /help for the list."));continue}let O=await N(S.args,x);if(O.kind==="exit")break;if(O.kind==="clear"){x.restartAgent();continue}if(O.kind==="allow-prod"){r=!0,x.restartAgent(),console.log(I("\u2713 Production writes authorized for this session.")),console.log("");continue}if(O.kind==="resume"){i.close(),i=Gi({cwd:e,resume:O.uuid,profileName:n,allowProdWrites:r});let J=Um(O.uuid);c={uuid:O.uuid,firstPrompt:J?.firstPrompt??null,titleFired:!0},nc(O.uuid),console.log(I(`\u2713 Resumed "${O.name}"`)),console.log("");continue}O.kind==="forward-to-agent"?(c.firstPrompt||(c.firstPrompt=O.display??O.prompt),await Yi(i,O.prompt,o,c,e)):th(e,n);continue}if(Km(C)){let S=Xm(C);if(S){try{Qm(e,{title:S,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}c.firstPrompt||(c.firstPrompt=C),await Yi(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${S}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${S}" and the article path(s) you wrote.`,o,c,e);continue}}c.firstPrompt||(c.firstPrompt=C),await Yi(i,C,o,c,e)}}}finally{i.close(),p.close()}}function eh(e,t){console.log(""),console.log(nn("document360-writer")),console.log(f(` cwd: ${e}`));let n=Bm(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(nh(e,t)),!Vm(e))console.log(L(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{let o=!1;try{if(ro(e),!Oe(e))for(let r of io(e))console.log(L(` ${r}`))}catch{}try{let r=Gm(e);r.persisted&&r.appType?console.log(f(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=kn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),i=r?wn(r):null;if(i?.kind==="recommend"&&i.rec.note){let c=i.rec.tone==="warn"?L:f;for(let p of i.rec.note.split(`
292
- `))console.log(c(` ${p}`));i.rec.picker&&console.log(_(` Pick one: ${i.rec.picker.options.map(p=>p.cmd).join(" \xB7 ")}`))}}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function th(e,t){try{let n=kn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?wn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(f(` Next: ${Mi(o.rec.lead)}`))}catch{}}function nh(e,t){try{let n=oc(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=zm(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let i={...tc(r.idToken)??{},...tc(r.accessToken)??{}},c=i.email??i.preferred_username??"signed in";return Ym(r)&&!r.refreshToken?L(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function oh(){console.error(""),console.error(`Sign in with your Claude subscription: run ${_("claude")} once, then retry.`),console.error(` (No Claude Code? ${_("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${_("https://console.anthropic.com/settings/keys")}`)}function rh(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Hm({uuid:t,name:r??Fm(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function ih(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||qm(o,t).then(r=>{r&&Wm(n,r)}).catch(()=>{})}async function Yi(e,t,n,o,r){let i=new Map;for await(let c of e.send(t))sh(c,o,r,n,i)}function sh(e,t,n,o,r){switch(e.type){case"session":t.uuid||rh(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=jo(e.name,e.input);i&&(process.stdout.write(`
293
-
294
- `),console.log(`${I("\u25CF")} ${Pe(i.title)}${i.arg!==null?ae(`${i.sep}(${i.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=ut(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let c=p=>p===1?"":"s";console.log(ae(` \u23BF Added ${i.added} line${c(i.added)}, removed ${i.removed} line${c(i.removed)}`));for(let p of i.lines)console.log(p);i.hidden>0&&console.log(f(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let c=Ao(e.output,4,e.isError?void 0:i.name,i.input),p=e.isError?$:ae;c.lines.forEach((g,w)=>console.log(p((w===0?" \u23BF ":" ")+g))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||Zm(i.name,i.input,e.output,n);break}case"result":process.stdout.write(`
295
- `),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&&(nc(t.uuid),t.titleFired||ih(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&oh();break}}import{render as vg}from"ink";import{resolveAuth as Cg}from"document360-engine";import{useCallback as V,useEffect as be,useMemo as Ji,useRef as Q,useState as W}from"react";import{Box as te,Text as j,useApp as xh,useInput as $h,useStdout as vh}from"ink";import{existsSync as xn,readFileSync as Zi,readdirSync as Ch}from"node:fs";import{basename as $n,isAbsolute as Rh,join as es}from"node:path";import{createSession as Ic,classifyClaudeAuth as os,CLAUDE_CODE_SETUP_HINT as Ph,loginPkce as Th,toStoredTokens as Sh,saveTokens as Dh,getAccessToken as jh,resolveActiveProfile as ke,resolveProjectId as Ah,getArticle as Eh,decodeJwtClaims as qt,isExpired as Xe,loadTokens as ht,clearTokens as Ih,clearProfileProject as Nh,setTitle as _h,slugify as Lh,touchSession as ts,upsertSession as Oh,generateTitle as Nc,findByName as Mh,listSessions as Uh,renameSession as Wh,suggestNextAction as Fh,readProjectConfig as ee,writeProjectConfig as _c,resolveAndPersistAppType as Hh,detectAppType as qh,resolveModelSetting as rs,loadProfileMap as Lc,applyPull as Bh,computeSyncStatus as Oc,lintDocs as Mc,compareRemoteSources as Vh,planPull as Gh,establishBaselines as Yh,rebaselineServerMeta as zh,inventoryRepo as Kh,knownEnvironments as Xh,resolveEnvironment as Qh,planPartitions as ns,partitionEvenly as Jh,screenshotPlaceholderIds as Zh,trackedArticlePaths as eg,runPartitioned as qo,estimateBulkCost as Uc,resolveModelForOperation as Bo,readDocsPlan as tg,checkForUpdate as ng,detectInstallKind as og,isSelfUpdatable as rg,devHintsGuidePath as Wc,toolFeedbackPath as ig,reconcileToolFeedback as sg,DEFAULT_DOCS_DIR as zc,setProfileProject as ag,writeCrashLog as lg,applyStructureOrder as Fc,orderSyncLine as Hc,applyRelatedArticles as qc,relatedSyncLine as Bc}from"document360-engine";Ge();import{spawn as ic}from"node:child_process";function ah(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function lh(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?ic([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):ic(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 i=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(i)}catch{o(!1)}})}async function sc(e){for(let[t,n]of ah())if(await lh(t,n,e))return!0;return!1}var ch=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function zi(e,t){if(t.closed)return e;let n=e.split(`
296
- `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let i=n[r];if(!t.cueSeen){ch.test(i)&&(t.cueSeen=!0);continue}let c=/^(\s{0,3})[-*•]\s+(.*)$/.exec(i);c?(n[r]=`${c[1]}${++t.num}. ${c[2]}`,o=!0):o&&i.trim()!==""&&/^\S/.test(i)&&(t.closed=!0)}return n.join(`
297
- `)}import{existsSync as dh,mkdirSync as uh,readFileSync as ph,writeFileSync as fh}from"node:fs";import{join as ac}from"node:path";import{writerDir as mh}from"document360-engine";function lc(e){return ac(mh(e),".sessions")}function cc(e,t){return ac(lc(e),`${t}.json`)}function dc(e,t,n){try{uh(lc(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");fh(cc(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Ki(e,t){try{let n=cc(e,t);if(!dh(n))return[];let o=JSON.parse(ph(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var hh=e=>`\x1B]0;${e}\x07`,gh=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function uc(e){process.stdout.isTTY&&process.stdout.write(e)}function Ht(e){uc(hh(e))}function _o(e){uc(gh(e))}var Lo=["\xB7 "," \xB7"],Oo="\u{1F7E3}";bo();lo();var Mo=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path>] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Reports issues; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category>]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"roadmap",usage:"/roadmap [done <step>]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done <step>` marks one you finished yourself",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],pc={"/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","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function fc(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(pc[n])return pc[n];let o=Mo.find(r=>r.name===t);return o?o.desc:""}function mc(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Mo.filter(n=>n.name.startsWith(t))}function hc(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}U();import{Box as gc,Text as le}from"ink";import{jsx as ce,jsxs as Uo}from"react/jsx-runtime";function yh({row:e}){switch(e.t){case"head":return ce(le,{color:F,bold:!0,children:e.s});case"text":return ce(le,{children:e.s});case"dim":return ce(le,{dimColor:!0,children:e.s});case"sub":return ce(le,{bold:!0,dimColor:!0,children:e.s});case"good":return ce(le,{color:"green",children:e.s});case"step":return Uo(le,{children:[ce(le,{color:F,children:`${e.n}. `}),e.s]});case"cmd":return Uo(le,{children:[" ",ce(le,{color:F,children:e.name.padEnd(20)}),ce(le,{dimColor:!0,children:e.s})]});case"gap":return ce(le,{children:" "})}}function yc({tab:e,width:t}){let n=Te[e]??Te[0],o=6+Te.reduce((i,c)=>i+c.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return Uo(gc,{flexDirection:"column",paddingX:1,children:[Uo(le,{children:[ce(le,{color:F,bold:!0,children:"Help "}),Te.map((i,c)=>c===e?ce(le,{color:"white",backgroundColor:F,bold:!0,children:` ${i.label} `},i.key):ce(le,{dimColor:!0,children:` ${i.label} `},i.key))]}),ce(le,{color:F,children:r}),ce(gc,{flexDirection:"column",marginTop:1,children:n.rows.map((i,c)=>ce(yh,{row:i},c))}),ce(le,{dimColor:!0,children:`
298
- \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var wh=/^(?:\d+[.)]|[-*•])\s+/;function wc(e,t,n=4){let o=new Set(t.map(i=>i.toLowerCase())),r=[];for(let i of e.split(`
299
- `)){let c=i.trim().replace(wh,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let g=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!g||!o.has(g[1].toLowerCase()))continue;let w=`/${g[1].toLowerCase()}${g[2]?` ${g[2]}`:""}`;if(r.includes(w)||r.push(w),r.length>=n)break}return r}U();function bn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Ue(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function kc(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var kh=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function bc(e,t,n){if(!kh.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(i=>{let c=i.replace(/\\/g,"/");return r===c||r.endsWith(`/${c}`)})??null}function Xi(e){return e.replace(/^[\w.-]+\//,"")}var Wo=16,xc={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function mt(e){return typeof e=="string"?e:e.cmd}function $c(e){return typeof e=="string"?void 0:e.desc}function Qi(e){return e.trim().split(/\s+/).slice(1).join(" ")}function vc(e,t){let n=Qi(t);return e.some(r=>mt(r).trim()===t.trim()||!!n&&Qi(mt(r))===n)?e.filter(r=>mt(r).trim()!==t.trim()&&!(n&&Qi(mt(r))===n)):[]}import{isDirectiveMention as cg,stripDirectiveMention as dg,appendDirective as ug}from"document360-engine";var bh=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Cc(e){return e.replace(/\r\n?/g,`
300
- `)}function Rc(e){return e.includes(`
301
- `)||e.length>200}function Pc(e,t){let n=t.split(`
302
- `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Tc(e,t){return e.replace(bh,n=>t.get(n)??n)}function Sc(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Fo(e,t){let n=Math.max(1,t),o=[],r=0;for(let i of e.split(`
303
- `)){if(i.length===0)o.push({start:r,end:r});else for(let c=0;c<i.length;c+=n)o.push({start:r+c,end:r+Math.min(c+n,i.length)});r+=i.length+1}return o.length>0?o:[{start:0,end:0}]}function Ho(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Dc(e,t,n){let o=Ho(e,t),r=o+n;if(r<0||r>=e.length)return t;let i=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+i,e[r].end)}function jc(e,t,n){let o=e[Ho(e,t)];return n==="start"?o.start:o.end}function Ac(e,t,n){let o=Math.max(1,n),r=e.split(`
285
+ `)}async function Nl(e,t){let n=e.includes("--fix"),o=e.find(c=>!c.startsWith("--")),r=o?` ${o}`:"",i=om({cwd:t.cwd,scope:o});if(n)return i.length===0?(console.log(I("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${i.length} doc issue${i.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:Ii(i),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let c of To(i))console.log(i.length===0?I(c):L(c));return i.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}U();import{lintDocs as cm,loadStyleGuide as dm,buildReviewPrompt as um,readProjectConfig as pm,DEFAULT_DOCS_DIR as fm}from"document360-engine";U();import{readProjectConfig as rm,loadProfileMap as im,resolveActiveProfile as sm,desiredCategoryOrder as am,desiredArticleOrder as lm}from"document360-engine";function _l(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Ll=e=>e.replace(/\\/g,"/").split("/").pop()??e;function wn(e,t){try{if(!rm(e))return[];let n=sm(e,t),o=im(e,n.name);if(!o)return[];let r=new Map;for(let c of lm(o)){let p=r.get(c.categoryPath);p?p.push(c):r.set(c.categoryPath,[c])}let i=[];for(let c of am(o)){i.push(_l(Ll(c.path)));for(let p of(r.get(c.path)??[]).sort((g,w)=>g.order-w.order))i.push(` ${_l(Ll(p.path))}`)}return i}catch{return[]}}async function Ol(e,t){let n=wn(t.cwd,t.profileName);if(n.length===0)return console.log(f("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(_("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Ni(e,t){let n=pm(e);if(!n)return null;let o=(n.docsDir??fm).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),i=t.find(k=>!k.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),c=cm({cwd:e}),p=i?c.filter(k=>k.path===`${o}/${i}`||k.path.startsWith(`${o}/${i}/`)):c,g=i?"":wn(e).join(`
286
+ `);return{prompt:um({docsRoot:o,scope:i,styleGuide:dm(e),deterministicFindings:p,fix:r,structure:g||void 0}),display:`/review${i?` ${i}`:""}${r?" --fix":""}`}}async function Ml(e,t){let n=Ni(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{readProjectConfig as mm}from"document360-engine";function _i(e,t){if(!mm(e))return null;let n=t.find(r=>!r.startsWith("--"));return{prompt:[`Reorder the articles within ${n?`the "${n}" category`:"each category"} to the best reading order.`,"Follow the manage-structure skill: decide the ideal order with senior-editor judgment per the doc-genre","playbook (overview / mental-model first; reference and troubleshooting/FAQ last), then APPLY it with the","d360_reorder_articles tool \u2014 one category at a time, all paths in the same category folder. Do not rename","files or edit the map by hand; the tool handles it. Report the new order, and remind me it reaches","Document360 on the next /publish."].join(`
287
+ `),display:`/reorder${n?` ${n}`:""}`}}async function Ul(e,t){let n=_i(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"})}U();import{readProjectConfig as hm,writeProjectConfig as Wl,isAppType as gm,playbookSkillName as ym,detectAppType as Fl}from"document360-engine";var Hl=["web","cli","service","library"],wm=new Set(["web","cli"]);function Li(e){return wm.has(e)?`${ym(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function So(e,t){let n=t.cwd,o=hm(n);if(!o)return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let i=o.appType??Fl(n);if(i){let c=o.appType?"set in config":"auto-detected";console.log(`${_("Genre:")} ${i} (${c}) \u2014 ${Li(i)}`)}else console.log(L("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${Hl.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(f("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:i,...c}=o;Wl(c,n);let p=Fl(n);return console.log(I(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${Li(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return gm(r)?(Wl({...o,appType:r},n),console.log(I(`\u2713 Genre set to ${r} \u2014 ${Li(r)} (applies from your next command).`)),{kind:"continue"}):(console.log($(`Unknown genre "${r}". Choose one of: ${Hl.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}U();import{listRoadmap as ql,roadmapProgress as Bl,stampRoadmapDone as km}from"document360-engine";function Oi(e){let t=ql(e);if(t.length===0)return["No docs roadmap yet \u2014 the docs agent seeds .d360-writer/roadmap.md when it pins a structure,","and adds steps as the app changes. You can also write steps by hand (## [open] <step>), or ask:",'"propose the docs roadmap for this repo".'];let n=Bl(e),o=[`Docs roadmap \u2014 ${n.done} of ${n.total} step${n.total===1?"":"s"} done:`,""];for(let r of t)o.push(` ${r.status==="done"?"\u2713":"\u25CB"} ${r.title}${r.run?` \xB7 ${r.run}`:""}`);return o.push(""),o.push(n.next?`Next: ${n.next.title}${n.next.run?` \u2014 ${n.next.run}`:""}`:"Campaign complete \u2014 the docs agent adds new steps as the app changes."),o.push("(Edit .d360-writer/roadmap.md freely \xB7 /roadmap done <step> marks one you finished yourself.)"),o}function Mi(e,t){if(!t.trim())return{ok:!1,line:"Usage: /roadmap done <step title>"};if(!km(e,t,{doneAt:new Date().toISOString()})){let r=ql(e).filter(i=>i.status==="open");return{ok:!1,line:r.length?`No open step titled "${t}". Open steps: ${r.map(i=>`"${i.title}"`).join(", ")}`:`No open step titled "${t}" \u2014 the roadmap has no open steps.`}}let o=Bl(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${t}${o?` \u2014 next up: ${o.title}${o.run?` (${o.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}async function Vl(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Mi(n,e.slice(1).join(" ").trim());return console.log(r.ok?I(r.line):L(r.line)),{kind:"continue"}}let o=Oi(n);console.log(_(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?f(r):r);return{kind:"continue"}}var Gl={help:yr,"?":yr,clear:Js,exit:wr,quit:wr,init:vr,mcp:uo,publish:Na,audit:pn,scope:La,pull:qa,convert:Ba,write:Xa,draft:tl,document:nl,resume:il,rename:sl,profile:ll,model:ul,doctor:mn,workspace:yl,project:wl,"allow-prod":kl,login:bl,logout:xl,screenshot:$o,"capture-setup":hn,devhints:aa,inbox:Pl,"catch-up":Tl,update:Sl,reset:Il,check:Nl,review:Ml,reorder:Ul,structure:Ol,genre:So,roadmap:Vl};function Yl(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}Ye();var bm="Or just tell me what to write or update.",xm='\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 be(e){return e===1?"":"s"}function Do(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Ui(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var $m={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",options:[{cmd:"/genre web",desc:"web app / SaaS UI"},{cmd:"/genre cli",desc:"command-line tool"},{cmd:"/genre service",desc:"API / backend service"},{cmd:"/genre library",desc:"SDK / library"}]};function vm(e){let t=[];if(e.devhints!=="current"&&e.builderStarted){let n=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",o=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";t.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${n}${o} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${n}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&t.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:$m,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${be(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${be(n)}.`})}if(e.directives>0||e.pendingText){let n=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",o=[];e.directives>0&&o.push(`${e.directives} owner directive${be(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
288
+ \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${be(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${be(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${be(n)} up.`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${be(n.total)} done \u2014 next: ${o.title}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${be(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${be(n)}.`})}return t}function zl(e,t){let n=t.filter(i=>i.bullet).map(i=>` \u2022 ${i.bullet}`),o=t[0],r=[];o.lead?r.push(Ui(o.lead)):o.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let i of t.slice(1,3))i.follow&&r.push(i.follow);return[e,...n,r.join(" "),bm].join(`
289
+ `)}function kn(e){if(!e.ready)return{kind:"idle"};let t=vm(e);if(!e.hasDocs){let r=t[0];return r&&(r.lead?.kind==="cmd"||r.picker)?{kind:"recommend",rec:{note:zl("\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",t),tone:r.tone??"info",lead:r.lead,picker:r.picker}}:{kind:"recommend",rec:{note:xm,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null}}}if(t.length===0){let r=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${be(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${be(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${r}`,tone:"info",lead:null,picker:null}}}let n=t[0];return(n.key==="audit"||n.key==="roadmap"&&t[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${be(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:zl("Welcome back \u2014 where your docs stand:",t),tone:n.tone??"info",lead:n.lead,picker:n.picker}}}import{existsSync as Wi,readdirSync as Hi}from"node:fs";import{spawnSync as Cm}from"node:child_process";import{join as jo}from"node:path";import{readProjectConfig as Xl,resolveActiveProfile as Ql,loadTokens as Rm,isExpired as Pm,loadProfileMap as Jl,countLocalAhead as Tm,readDocsPlan as Sm,devHintsGuidePath as Dm,DEFAULT_DOCS_DIR as Fi,roadmapProgress as jm}from"document360-engine";Ye();function Kl(e){try{return Hi(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function qi(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Kl(jo(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Kl(jo(e,o)))}function Bi(e,t){try{let n=Xl(e);if(!n)return!1;let o=Ql(e,t),r=Jl(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let i=jo(e,(n.docsDir??Fi).replace(/\/+$/,""));return!!(Wi(i)&&Hi(i).length>0||Wi(Dm(e)))}catch{return!1}}function bn(e,t,n){try{let o=Xl(e);if(!o)return null;let r=Ql(e,t),i=Rm(r.name),c=!!i&&(!Pm(i)||!!i.refreshToken),p=Bi(e,t)||!qi(e,o.authoritativeSourceFiles),g=Jl(e,r.name),w=g?Object.keys(g.articles).length:0,k=jo(e,(o.docsDir??Fi).replace(/\/+$/,"")),D=!1;try{D=Wi(k)&&Hi(k).length>0}catch{}let x=0;if(g?.lastAnalyzedCommit)try{let re=Cm("git",["rev-list","--count",`${g.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});re.status===0&&(x=parseInt((re.stdout||"").trim(),10)||0)}catch{}let P=0;try{let re=Sm(e);if(re.length>0){let Z=(o.docsDir??Fi).replace(/\/+$/,"");P=Zr(e,Z,re.map(de=>de.path)).length}}catch{}let C=gn(e),S=yn({...C,directives:0}),N=Tm(e,t),O=Se(e),J=jm(e);return{ready:c&&p&&!n.claudeMissing,hasDocs:D,tracked:w,pendingText:S,directives:C.directives,behind:x,pendingWrites:P,localAhead:N,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:O.status,devhintsCompletedVersion:O.completedVersion,devhintsToVersion:se,builderStarted:Ue(e),genreUnknown:n.genreUnknown,roadmap:J}}catch{return null}}U();var Am={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"},ec=160,Gi=200,tc=40;function xe(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Zl(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}: ${xe(typeof r=="string"?r:JSON.stringify(r),tc)}`);return t.length>4&&n.push("\u2026"),xe(n.join(", "),ec)}var Xe=e=>typeof e=="string"&&e?e:null,Vi=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Em(e){let t=Xe(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(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ")}function Im(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Xe(t.title);if(!o)return null;let r=Em(t.local_path);return n("Create article",`"${xe(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Xe(t.title),r=Vi(t.article_id);return n("Update article",o?`"${xe(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Vi(t.article_id)?`id ${Vi(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",Xe(t.name)?`"${xe(Xe(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Xe(t.file_path);return n("Upload image",o?xe(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Ao(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...i]=e.split("__"),c=i.join("__");if(r==="document360"){let w=Im(c,t);if(w)return w}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Zl(t)}}let n=Am[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:xe(o,ec)}:{title:e,sep:"",arg:Zl(t)}}function Nm(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 _m(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Nm).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>xe(r,Gi))]}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}: ${xe(String(r),tc)}`);return n.length>0?[xe(n.join(" \xB7 "),Gi)]:null}return null}function Lm(e){let t=Xe(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Om(e,t,n){switch(e){case"d360_create_article":{let o=Lm(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=Xe(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 ${xe(o[0],120)}`:""}`]}default:return null}}function Eo(e,t=4,n,o){let r=e.replace(/\r\n/g,`
290
+ `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=Om(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let i=_m(r)??r.split(`
291
+ `);return{lines:i.slice(0,t).map(c=>xe(c,Gi)),hidden:Math.max(0,i.length-t)}}function Io(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function No(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 _o(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 Zm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function eh(e,t,n,o){if(Zm.test(e))try{let r=rc(o),i=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=No(t,n),p=_o(n);e.endsWith("publish_article")&&p&&console.log(_(` \u2B95 Live: ${p}`)),c&&i&&console.log(_(` \u2B95 Preview: ${Io(r.connection.portalUrl,i,c,r.project.languageCode??"en")}`))}catch{}}async function ic(e=process.cwd(),t="auto",n){let o=Um(t);o.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${_("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${_('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),th(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,i=Yi({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=Mm({input:process.stdin,output:process.stdout}),g=[],w=null,k=!1;p.on("line",P=>{if(w){let C=w;w=null,C(P)}else g.push(P)}),p.on("close",()=>{if(k=!0,w){let P=w;w=null,P(null)}});function D(){return g.length>0?Promise.resolve(g.shift()):k?Promise.resolve(null):(process.stdout.write(_("> ")),new Promise(P=>{w=P}))}let x={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{i.close(),i=Yi({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setPendingName:P=>{c.pendingName=P},setModel:async P=>i.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 S=Yl(C);if(!S)continue;let N=Gl[S.name];if(!N){console.log($(`Unknown command: /${S.name}`)),console.log(f("Type /help for the list."));continue}let O=await N(S.args,x);if(O.kind==="exit")break;if(O.kind==="clear"){x.restartAgent();continue}if(O.kind==="allow-prod"){r=!0,x.restartAgent(),console.log(I("\u2713 Production writes authorized for this session.")),console.log("");continue}if(O.kind==="resume"){i.close(),i=Yi({cwd:e,resume:O.uuid,profileName:n,allowProdWrites:r});let J=Wm(O.uuid);c={uuid:O.uuid,firstPrompt:J?.firstPrompt??null,titleFired:!0},oc(O.uuid),console.log(I(`\u2713 Resumed "${O.name}"`)),console.log("");continue}O.kind==="forward-to-agent"?(c.firstPrompt||(c.firstPrompt=O.display??O.prompt),await zi(i,O.prompt,o,c,e)):nh(e,n);continue}if(Xm(C)){let S=Qm(C);if(S){try{Jm(e,{title:S,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}c.firstPrompt||(c.firstPrompt=C),await zi(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${S}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${S}" and the article path(s) you wrote.`,o,c,e);continue}}c.firstPrompt||(c.firstPrompt=C),await zi(i,C,o,c,e)}}}finally{i.close(),p.close()}}function th(e,t){console.log(""),console.log(on("document360-writer")),console.log(f(` cwd: ${e}`));let n=Vm(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(oh(e,t)),!Gm(e))console.log(L(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{let o=!1;try{if(io(e),!Ue(e))for(let r of so(e))console.log(L(` ${r}`))}catch{}try{let r=Ym(e);r.persisted&&r.appType?console.log(f(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=bn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),i=r?kn(r):null;if(i?.kind==="recommend"&&i.rec.note){let c=i.rec.tone==="warn"?L:f;for(let p of i.rec.note.split(`
292
+ `))console.log(c(` ${p}`));i.rec.picker&&console.log(_(` Pick one: ${i.rec.picker.options.map(p=>p.cmd).join(" \xB7 ")}`))}}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function nh(e,t){try{let n=bn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?kn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(f(` Next: ${Ui(o.rec.lead)}`))}catch{}}function oh(e,t){try{let n=rc(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=Km(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let i={...nc(r.idToken)??{},...nc(r.accessToken)??{}},c=i.email??i.preferred_username??"signed in";return zm(r)&&!r.refreshToken?L(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function rh(){console.error(""),console.error(`Sign in with your Claude subscription: run ${_("claude")} once, then retry.`),console.error(` (No Claude Code? ${_("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${_("https://console.anthropic.com/settings/keys")}`)}function ih(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;qm({uuid:t,name:r??Hm(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function sh(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Bm(o,t).then(r=>{r&&Fm(n,r)}).catch(()=>{})}async function zi(e,t,n,o,r){let i=new Map;for await(let c of e.send(t))ah(c,o,r,n,i)}function ah(e,t,n,o,r){switch(e.type){case"session":t.uuid||ih(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=Ao(e.name,e.input);i&&(process.stdout.write(`
293
+
294
+ `),console.log(`${I("\u25CF")} ${Pe(i.title)}${i.arg!==null?ae(`${i.sep}(${i.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=ut(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let c=p=>p===1?"":"s";console.log(ae(` \u23BF Added ${i.added} line${c(i.added)}, removed ${i.removed} line${c(i.removed)}`));for(let p of i.lines)console.log(p);i.hidden>0&&console.log(f(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let c=Eo(e.output,4,e.isError?void 0:i.name,i.input),p=e.isError?$:ae;c.lines.forEach((g,w)=>console.log(p((w===0?" \u23BF ":" ")+g))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||eh(i.name,i.input,e.output,n);break}case"result":process.stdout.write(`
295
+ `),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&&(oc(t.uuid),t.titleFired||sh(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&rh();break}}import{render as Cg}from"ink";import{resolveAuth as Rg}from"document360-engine";import{useCallback as V,useEffect as ve,useMemo as Zi,useRef as Q,useState as W}from"react";import{Box as te,Text as j,useApp as $h,useInput as vh,useStdout as Ch}from"ink";import{existsSync as $n,readFileSync as es,readdirSync as Rh}from"node:fs";import{basename as vn,isAbsolute as Ph,join as ts}from"node:path";import{createSession as Nc,classifyClaudeAuth as rs,CLAUDE_CODE_SETUP_HINT as Th,loginPkce as Sh,toStoredTokens as Dh,saveTokens as jh,getAccessToken as Ah,resolveActiveProfile as $e,resolveProjectId as Eh,getArticle as Ih,decodeJwtClaims as Bt,isExpired as Qe,loadTokens as ht,clearTokens as Nh,clearProfileProject as _h,setTitle as Lh,slugify as Oh,touchSession as ns,upsertSession as Mh,generateTitle as _c,findByName as Uh,listSessions as Wh,renameSession as Fh,suggestNextAction as Hh,readProjectConfig as ee,writeProjectConfig as Lc,resolveAndPersistAppType as qh,detectAppType as Bh,resolveModelSetting as is,loadProfileMap as Oc,applyPull as Vh,computeSyncStatus as Mc,lintDocs as Uc,compareRemoteSources as Gh,planPull as Yh,establishBaselines as zh,rebaselineServerMeta as Kh,inventoryRepo as Xh,knownEnvironments as Qh,resolveEnvironment as Jh,planPartitions as os,partitionEvenly as Zh,screenshotPlaceholderIds as eg,trackedArticlePaths as tg,runPartitioned as Bo,estimateBulkCost as Wc,resolveModelForOperation as Vo,readDocsPlan as ng,checkForUpdate as og,detectInstallKind as rg,isSelfUpdatable as ig,devHintsGuidePath as Fc,toolFeedbackPath as sg,reconcileToolFeedback as ag,DEFAULT_DOCS_DIR as Kc,setProfileProject as lg,writeCrashLog as cg,applyStructureOrder as Hc,orderSyncLine as qc,applyRelatedArticles as Bc,relatedSyncLine as Vc}from"document360-engine";Ye();import{spawn as sc}from"node:child_process";function lh(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function ch(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?sc([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):sc(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 i=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(i)}catch{o(!1)}})}async function ac(e){for(let[t,n]of lh())if(await ch(t,n,e))return!0;return!1}var dh=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Ki(e,t){if(t.closed)return e;let n=e.split(`
296
+ `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let i=n[r];if(!t.cueSeen){dh.test(i)&&(t.cueSeen=!0);continue}let c=/^(\s{0,3})[-*•]\s+(.*)$/.exec(i);c?(n[r]=`${c[1]}${++t.num}. ${c[2]}`,o=!0):o&&i.trim()!==""&&/^\S/.test(i)&&(t.closed=!0)}return n.join(`
297
+ `)}import{existsSync as uh,mkdirSync as ph,readFileSync as fh,writeFileSync as mh}from"node:fs";import{join as lc}from"node:path";import{writerDir as hh}from"document360-engine";function cc(e){return lc(hh(e),".sessions")}function dc(e,t){return lc(cc(e),`${t}.json`)}function uc(e,t,n){try{ph(cc(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");mh(dc(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Xi(e,t){try{let n=dc(e,t);if(!uh(n))return[];let o=JSON.parse(fh(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var gh=e=>`\x1B]0;${e}\x07`,yh=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function pc(e){process.stdout.isTTY&&process.stdout.write(e)}function Ht(e){pc(gh(e))}function Lo(e){pc(yh(e))}var Oo=["\xB7 "," \xB7"],Mo="\u{1F7E3}";xo();co();var Uo=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path>] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Reports issues; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category>]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"roadmap",usage:"/roadmap [done <step>]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done <step>` marks one you finished yourself",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],fc={"/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","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function mc(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(fc[n])return fc[n];let o=Uo.find(r=>r.name===t);return o?o.desc:""}function hc(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Uo.filter(n=>n.name.startsWith(t))}function gc(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}U();import{Box as yc,Text as le}from"ink";import{jsx as ce,jsxs as Wo}from"react/jsx-runtime";function wh({row:e}){switch(e.t){case"head":return ce(le,{color:F,bold:!0,children:e.s});case"text":return ce(le,{children:e.s});case"dim":return ce(le,{dimColor:!0,children:e.s});case"sub":return ce(le,{bold:!0,dimColor:!0,children:e.s});case"good":return ce(le,{color:"green",children:e.s});case"step":return Wo(le,{children:[ce(le,{color:F,children:`${e.n}. `}),e.s]});case"cmd":return Wo(le,{children:[" ",ce(le,{color:F,children:e.name.padEnd(20)}),ce(le,{dimColor:!0,children:e.s})]});case"gap":return ce(le,{children:" "})}}function wc({tab:e,width:t}){let n=Te[e]??Te[0],o=6+Te.reduce((i,c)=>i+c.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return Wo(yc,{flexDirection:"column",paddingX:1,children:[Wo(le,{children:[ce(le,{color:F,bold:!0,children:"Help "}),Te.map((i,c)=>c===e?ce(le,{color:"white",backgroundColor:F,bold:!0,children:` ${i.label} `},i.key):ce(le,{dimColor:!0,children:` ${i.label} `},i.key))]}),ce(le,{color:F,children:r}),ce(yc,{flexDirection:"column",marginTop:1,children:n.rows.map((i,c)=>ce(wh,{row:i},c))}),ce(le,{dimColor:!0,children:`
298
+ \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var kh=/^(?:\d+[.)]|[-*•])\s+/;function kc(e,t,n=4){let o=new Set(t.map(i=>i.toLowerCase())),r=[];for(let i of e.split(`
299
+ `)){let c=i.trim().replace(kh,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let g=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!g||!o.has(g[1].toLowerCase()))continue;let w=`/${g[1].toLowerCase()}${g[2]?` ${g[2]}`:""}`;if(r.includes(w)||r.push(w),r.length>=n)break}return r}U();function xn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Fe(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function bc(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var bh=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function xc(e,t,n){if(!bh.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(i=>{let c=i.replace(/\\/g,"/");return r===c||r.endsWith(`/${c}`)})??null}function Qi(e){return e.replace(/^[\w.-]+\//,"")}var Fo=16,$c={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function mt(e){return typeof e=="string"?e:e.cmd}function vc(e){return typeof e=="string"?void 0:e.desc}function Ji(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Cc(e,t){let n=Ji(t);return e.some(r=>mt(r).trim()===t.trim()||!!n&&Ji(mt(r))===n)?e.filter(r=>mt(r).trim()!==t.trim()&&!(n&&Ji(mt(r))===n)):[]}import{isDirectiveMention as dg,stripDirectiveMention as ug,appendDirective as pg}from"document360-engine";var xh=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Rc(e){return e.replace(/\r\n?/g,`
300
+ `)}function Pc(e){return e.includes(`
301
+ `)||e.length>200}function Tc(e,t){let n=t.split(`
302
+ `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Sc(e,t){return e.replace(xh,n=>t.get(n)??n)}function Dc(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Ho(e,t){let n=Math.max(1,t),o=[],r=0;for(let i of e.split(`
303
+ `)){if(i.length===0)o.push({start:r,end:r});else for(let c=0;c<i.length;c+=n)o.push({start:r+c,end:r+Math.min(c+n,i.length)});r+=i.length+1}return o.length>0?o:[{start:0,end:0}]}function qo(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function jc(e,t,n){let o=qo(e,t),r=o+n;if(r<0||r>=e.length)return t;let i=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+i,e[r].end)}function Ac(e,t,n){let o=e[qo(e,t)];return n==="start"?o.start:o.end}function Ec(e,t,n){let o=Math.max(1,n),r=e.split(`
304
304
  `),i=0;for(let c=r.length-1;c>=0;c--){let p=r[c];if(i+=Math.max(1,Math.ceil(p.length/o)),i>=t){let g=i-t;return{text:[g>0?p.slice(g*o):p,...r.slice(c+1)].join(`
305
- `),truncated:c>0||g>0}}}return{text:e,truncated:!1}}function Ec(e){let t=!1,n=0,o=0;for(let r of e.split(`
306
- `)){let i=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&i<e.length&&(n=i+1),o=i+1}return n}import{Fragment as Vo,jsx as E,jsxs as B}from"react/jsx-runtime";var pg={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},Vc=` 1. /init \u2014 pick your Document360 environment & scaffold config
305
+ `),truncated:c>0||g>0}}}return{text:e,truncated:!1}}function Ic(e){let t=!1,n=0,o=0;for(let r of e.split(`
306
+ `)){let i=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&i<e.length&&(n=i+1),o=i+1}return n}import{Fragment as Go,jsx as A,jsxs as B}from"react/jsx-runtime";var fg={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},Gc=` 1. /init \u2014 pick your Document360 environment & scaffold config
307
307
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
308
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function fg(e,t,n,o){let r=os(n),i=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=rs(e),p=ee(e),g=(p?.docsDir??zc).replace(/\/+$/,""),w=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${g}/ + config`,k={version:t,claude:i,model:c.model,modelSource:pg[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:w};if(p===null)return k;try{let D=ke(e,o);k.profile=D.name,k.apiUrl=D.connection.apiUrl,k.prod=D.production,k.project=D.project.projectName??D.project.projectId??"(chosen at login)";let x=ht(D.name);if(x){let P={...qt(x.idToken)??{},...qt(x.accessToken)??{}},C=P.email??P.preferred_username??"signed in";Xe(x)?x.refreshToken&&(k.who=C,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=C,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(x.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function mg(e,t){try{let n=ke(e,t),o=ht(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...qt(o.idToken)??{},...qt(o.accessToken)??{}},i=r.email??r.preferred_username??"signed in";return Xe(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${i} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var Gc=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Bt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],hg="Ask me to write or update an article\u2026";function vn({ch:e,dim:t}){let[n,o]=W(!0);return be(()=>{let r=setInterval(()=>o(i=>!i),530);return()=>clearInterval(r)},[]),E(j,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var gg=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Yc(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var yg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function wg({startTime:e,chars:t}){let[n,o]=W(0);be(()=>{let g=setInterval(()=>o(w=>w+1),120);return()=>clearInterval(g)},[]);let r=Bt[n%Bt.length],i=Gc[Math.floor(n/16)%Gc.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return B(te,{children:[E(j,{color:F,children:` ${r} ${i}\u2026 `}),E(j,{color:"gray",children:`(${ln(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function kg({text:e}){let[t,n]=W(0);return be(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),E(te,{paddingX:1,children:E(j,{color:F,children:`${Bt[t%Bt.length]} ${e}`})})}var bg=12e4;function xg({p:e}){let[t,n]=W(0);be(()=>{let N=setInterval(()=>n(O=>O+1),150);return()=>clearInterval(N)},[]);let o=Bt[t%Bt.length],r=Math.floor((Date.now()-e.startedAt)/1e3),i=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),p=Date.now()-e.lastAt>=bg,g=e.verb??"Converting",w=e.unit??"article",k=e.rows.reduce((N,O)=>N+O.items,0),D=g.toLowerCase(),x=e.rows,P=0;if(x.length>Wo){let N=x.findIndex(J=>J.status==="active"||J.status==="pending"),O=Math.max(0,Math.min(N-2,x.length-Wo));P=x.slice(0,O).filter(J=>J.status==="done").length,x=x.slice(O,O+Wo)}let C=Math.min(40,Math.max(...x.map(N=>Xi(N.label).length),0)),S=N=>N==="failed"?"red":N==="active"?F:void 0;return B(te,{flexDirection:"column",children:[B(te,{children:[E(j,{color:F,children:` ${o} ${g} ${k} ${w}${k===1?"":"s"} `}),E(j,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${ln(r)} \xB7 esc to stop`})]}),P>0&&E(j,{dimColor:!0,children:` \u2714 +${P} done`}),x.map(N=>B(j,{color:S(N.status),dimColor:N.status==="done"||N.status==="pending",children:[` ${xc[N.status]} ${Xi(N.label).padEnd(C)}`,N.status==="active"&&N.itemsDone!==void 0?` (${N.itemsDone}/${N.items} ${w}${N.items===1?"":"s"})`:N.status!=="pending"?` (${N.items} ${w}${N.items===1?"":"s"})`:"",N.status==="active"?` \u2190 ${D}\u2026`:""]},N.label)),p&&E(j,{color:"yellow",children:` \u26A0 no activity for ${ln(i)} \u2014 press esc to stop if it's wedged`})]})}var $g=10800*1e3;function Kc({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=xh(),[i,c]=W(n),[p,g]=W(null),[w,k]=W({text:"",pos:0}),D=w.text,x=V(l=>{k(a=>{let s=typeof l=="function"?l(a.text):l;return{text:s,pos:s.length}})},[]),P=V(l=>{k(a=>({text:a.text.slice(0,a.pos)+l+a.text.slice(a.pos),pos:a.pos+l.length}))},[]),C=V(()=>{k(l=>{if(l.pos===0)return l;let a=l.text.slice(0,l.pos),s=Sc(a)??a.slice(0,-1);return{text:s+l.text.slice(l.pos),pos:s.length}})},[]),[S,N]=W(!1),[O,J]=W(!1),[re,Z]=W(0),[de,Cn]=W(null),[Go,ls]=W(null),[Qe,Je]=W([]),Rn=Q(!1),Yo=Q(!1),[zo,cs]=W(!1),Pn=Q(0),[od,Tn]=W(!1),[rd,Sn]=W(!1),[Ko,ds]=W(null),[id,gt]=W(0),Ze=Q(0),[Vt,yt]=W(0),[wt,Dn]=W(null),us=Q(new Map),sd=Q(0),kt=Q([]),xe=Q(null);xe.current===null&&(xe.current=Ic({cwd:e,profileName:i,allowProdWrites:!1}));let _e=Q({uuid:null,firstPrompt:null,titleFired:!1}),jn=Q(new Map),bt=Q(!1),Xo=Q([]),je=Q([]),An=Q(null),[ps,et]=W(null),Qo=Q(null),[tt,nt]=W(null),[Le,xt]=W(null),[We,$t]=W(null),[pe,vt]=W(null),[$e,ot]=W(null),[rt,Ct]=W(null),[Fe,Rt]=W(null),[fs,Gt]=W(null),[ve,it]=W(null),[he,Pt]=W(null),[ms,Jo]=W([]),st=Q([]),Yt=Q(!1),Ce=Q(null),[En,ne]=W(null),[hs,gs]=W(null),In=Q(!1),Nn=Q(null),zt=Q(null),[Re,at]=W(null),[Zo,Kt]=W(null),[ys,Tt]=W(0),[ws,St]=W(0),[ad,ks]=W(0),er=Ji(()=>{try{let l=rs(e);return l.source==="auto"?`${l.model} (auto)`:l.model}catch{return null}},[e,ad]),{stdout:Ae}=vh(),[,ld]=W(0),bs=Q(`${Ae.columns??80}x${Ae.rows??24}`),He=V(()=>Math.max(20,(Ae.columns??80)-1),[Ae]),u=V(l=>{kt.current.push(l),console.log(jr(l,He()))},[He]),fe=V((l,a)=>{Pn.current++,Cn(l),ls(a??null)},[]),qe=V(()=>{Pn.current++,Cn(null),ls(null)},[]),Y=V(l=>fe(l,So({kind:"cmd",cmd:l,reason:""})),[fe]),xs=V((l,a)=>{!a?.silent&&l.note&&u({kind:"note",tone:l.tone,text:l.note}),l.picker&&(Je(l.picker.options.map(s=>({cmd:s.cmd,desc:s.desc}))),Gt(l.picker.title)),l.lead&&fe(l.lead.kind==="cmd"?l.lead.cmd:l.lead.text,So(l.lead))},[u,fe]),Dt=V((l,a,s="info")=>{l&&u({kind:"note",tone:s,text:l}),a&&fe(a.kind==="cmd"?a.cmd:a.text,So(a))},[u,fe]),[Xt,tr]=W(null),[cd,$s]=W(!1),jt=V(l=>{tr(l),$s(!1),u({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),nr=Q(!1),or=V(async()=>{try{if(nr.current||!rg(og())||ee(e)?.mode==="engineer")return;let l=await ng({pkg:ft,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;nr.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${ft} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),Sn(!0),(await Co().finally(()=>Sn(!1))).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),Y("/exit"),ds(l.latest)):u({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${vo}`})}catch{}},[e,o,u,Y]),rr=V(l=>{let a=Me(e,i);return a.ok?!0:(u({kind:"note",tone:"warn",text:a.reason}),zt.current=l,Y("/login"),!1)},[e,i,u,Y]),[ir,sr]=W(null),Qt=Q(!0),_n=Q(0),Jt=Q(0);be(()=>{let l=setInterval(()=>{if(Qt.current){_n.current=0,Jt.current=0;return}if(!S)try{if(!xn(Wc(e)))return;if(Se(e).status==="current"){Qt.current=!0,_n.current=0,Jt.current=0,u({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."}),tr(null),fe("write the docs for this repo");return}_n.current+=1;let a=_n.current;if((a===4||a%15===0)&&Jt.current<3){Jt.current+=1;let s=Jt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";u({kind:"note",tone:"info",text:Oe(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${s}`:`\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.${s}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,S,u]),be(()=>{let l=ps??$n(e);if(!S){_o(0),Ht(`${Oo} ${l}`);return}_o(3);let a=0;Ht(`${Lo[0]} ${l}`);let s=setInterval(()=>{a=(a+1)%Lo.length,Ht(`${Lo[a]} ${l}`)},400);return()=>clearInterval(s)},[S,e,ps]),be(()=>()=>_o(0),[]);let Zt=V(l=>{let a=kn(e,i,{claudeMissing:os(t).state==="missing",allowAutoAudit:l,genreUnknown:Yo.current});return a?wn(a):{kind:"idle"}},[e,i,t]);be(()=>{let l=performance.now(),a=[],s=(y,R)=>{let T=performance.now();try{return R()}finally{let z=Math.round(performance.now()-T);z>=80&&a.push(`${y}: ${z}ms`)}};u({kind:"banner",info:s("banner",()=>fg(e,o,t,i))});let h=os(t).state==="missing";if(h&&u({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.
309
- ${Ph}
308
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function mg(e,t,n,o){let r=rs(n),i=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=is(e),p=ee(e),g=(p?.docsDir??Kc).replace(/\/+$/,""),w=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${g}/ + config`,k={version:t,claude:i,model:c.model,modelSource:fg[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:w};if(p===null)return k;try{let D=$e(e,o);k.profile=D.name,k.apiUrl=D.connection.apiUrl,k.prod=D.production,k.project=D.project.projectName??D.project.projectId??"(chosen at login)";let x=ht(D.name);if(x){let P={...Bt(x.idToken)??{},...Bt(x.accessToken)??{}},C=P.email??P.preferred_username??"signed in";Qe(x)?x.refreshToken&&(k.who=C,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=C,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(x.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function hg(e,t){try{let n=$e(e,t),o=ht(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Bt(o.idToken)??{},...Bt(o.accessToken)??{}},i=r.email??r.preferred_username??"signed in";return Qe(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${i} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var Yc=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Vt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],gg="Ask me to write or update an article\u2026";function qt({ch:e,dim:t}){let[n,o]=W(!0);return ve(()=>{let r=setInterval(()=>o(i=>!i),530);return()=>clearInterval(r)},[]),A(j,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var yg=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function zc(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var wg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function kg({startTime:e,chars:t}){let[n,o]=W(0);ve(()=>{let g=setInterval(()=>o(w=>w+1),120);return()=>clearInterval(g)},[]);let r=Vt[n%Vt.length],i=Yc[Math.floor(n/16)%Yc.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return B(te,{children:[A(j,{color:F,children:` ${r} ${i}\u2026 `}),A(j,{color:"gray",children:`(${cn(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function bg({text:e}){let[t,n]=W(0);return ve(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),A(te,{paddingX:1,children:A(j,{color:F,children:`${Vt[t%Vt.length]} ${e}`})})}var xg=12e4;function $g({p:e}){let[t,n]=W(0);ve(()=>{let N=setInterval(()=>n(O=>O+1),150);return()=>clearInterval(N)},[]);let o=Vt[t%Vt.length],r=Math.floor((Date.now()-e.startedAt)/1e3),i=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),p=Date.now()-e.lastAt>=xg,g=e.verb??"Converting",w=e.unit??"article",k=e.rows.reduce((N,O)=>N+O.items,0),D=g.toLowerCase(),x=e.rows,P=0;if(x.length>Fo){let N=x.findIndex(J=>J.status==="active"||J.status==="pending"),O=Math.max(0,Math.min(N-2,x.length-Fo));P=x.slice(0,O).filter(J=>J.status==="done").length,x=x.slice(O,O+Fo)}let C=Math.min(40,Math.max(...x.map(N=>Qi(N.label).length),0)),S=N=>N==="failed"?"red":N==="active"?F:void 0;return B(te,{flexDirection:"column",children:[B(te,{children:[A(j,{color:F,children:` ${o} ${g} ${k} ${w}${k===1?"":"s"} `}),A(j,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${cn(r)} \xB7 esc to stop`})]}),P>0&&A(j,{dimColor:!0,children:` \u2714 +${P} done`}),x.map(N=>B(j,{color:S(N.status),dimColor:N.status==="done"||N.status==="pending",children:[` ${$c[N.status]} ${Qi(N.label).padEnd(C)}`,N.status==="active"&&N.itemsDone!==void 0?` (${N.itemsDone}/${N.items} ${w}${N.items===1?"":"s"})`:N.status!=="pending"?` (${N.items} ${w}${N.items===1?"":"s"})`:"",N.status==="active"?` \u2190 ${D}\u2026`:""]},N.label)),p&&A(j,{color:"yellow",children:` \u26A0 no activity for ${cn(i)} \u2014 press esc to stop if it's wedged`})]})}var vg=10800*1e3;function Xc({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=$h(),[i,c]=W(n),[p,g]=W(null),[w,k]=W({text:"",pos:0}),D=w.text,x=V(l=>{k(a=>{let s=typeof l=="function"?l(a.text):l;return{text:s,pos:s.length}})},[]),P=V(l=>{k(a=>({text:a.text.slice(0,a.pos)+l+a.text.slice(a.pos),pos:a.pos+l.length}))},[]),C=V(()=>{k(l=>{if(l.pos===0)return l;let a=l.text.slice(0,l.pos),s=Dc(a)??a.slice(0,-1);return{text:s+l.text.slice(l.pos),pos:s.length}})},[]),[S,N]=W(!1),[O,J]=W(!1),[re,Z]=W(0),[de,Cn]=W(null),[Yo,cs]=W(null),[Je,Ze]=W([]),Rn=Q(!1),zo=Q(!1),[Ko,ds]=W(!1),Pn=Q(0),[rd,Tn]=W(!1),[id,Sn]=W(!1),[Xo,us]=W(null),[sd,gt]=W(0),et=Q(0),[Gt,yt]=W(0),[wt,Dn]=W(null),ps=Q(new Map),ad=Q(0),kt=Q([]),Ce=Q(null);Ce.current===null&&(Ce.current=Nc({cwd:e,profileName:i,allowProdWrites:!1}));let _e=Q({uuid:null,firstPrompt:null,titleFired:!1}),jn=Q(new Map),bt=Q(!1),Qo=Q([]),je=Q([]),An=Q(null),[fs,tt]=W(null),Jo=Q(null),[nt,ot]=W(null),[Le,xt]=W(null),[Oe,$t]=W(null),[pe,vt]=W(null),[ge,rt]=W(null),[He,Ct]=W(null),[Me,Rt]=W(null),[ms,Yt]=W(null),[ye,it]=W(null),[fe,Pt]=W(null),[hs,Zo]=W([]),st=Q([]),zt=Q(!1),Re=Q(null),[En,ne]=W(null),[gs,ys]=W(null),In=Q(!1),Nn=Q(null),Kt=Q(null),[we,at]=W(null),[_n,Xt]=W(null),er=!!(Oe||pe||ge||He||Me||ye||fe||we||_n),[ws,Tt]=W(0),[ks,St]=W(0),[ld,bs]=W(0),tr=Zi(()=>{try{let l=is(e);return l.source==="auto"?`${l.model} (auto)`:l.model}catch{return null}},[e,ld]),{stdout:Ae}=Ch(),[,cd]=W(0),xs=Q(`${Ae.columns??80}x${Ae.rows??24}`),qe=V(()=>Math.max(20,(Ae.columns??80)-1),[Ae]),u=V(l=>{kt.current.push(l),console.log(Ar(l,qe()))},[qe]),me=V((l,a)=>{Pn.current++,Cn(l),cs(a??null)},[]),Be=V(()=>{Pn.current++,Cn(null),cs(null)},[]),Y=V(l=>me(l,Do({kind:"cmd",cmd:l,reason:""})),[me]),$s=V((l,a)=>{!a?.silent&&l.note&&u({kind:"note",tone:l.tone,text:l.note}),l.picker&&(Ze(l.picker.options.map(s=>({cmd:s.cmd,desc:s.desc}))),Yt(l.picker.title)),l.lead&&me(l.lead.kind==="cmd"?l.lead.cmd:l.lead.text,Do(l.lead))},[u,me]),Dt=V((l,a,s="info")=>{l&&u({kind:"note",tone:s,text:l}),a&&me(a.kind==="cmd"?a.cmd:a.text,Do(a))},[u,me]),[Qt,nr]=W(null),[dd,vs]=W(!1),jt=V(l=>{nr(l),vs(!1),u({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),or=Q(!1),rr=V(async()=>{try{if(or.current||!ig(rg())||ee(e)?.mode==="engineer")return;let l=await og({pkg:ft,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;or.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${ft} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),Sn(!0),(await Ro().finally(()=>Sn(!1))).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),Y("/exit"),us(l.latest)):u({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${Co}`})}catch{}},[e,o,u,Y]),ir=V(l=>{let a=We(e,i);return a.ok?!0:(u({kind:"note",tone:"warn",text:a.reason}),Kt.current=l,Y("/login"),!1)},[e,i,u,Y]),[sr,ar]=W(null),Jt=Q(!0),Ln=Q(0),Zt=Q(0);ve(()=>{let l=setInterval(()=>{if(Jt.current){Ln.current=0,Zt.current=0;return}if(!S)try{if(!$n(Fc(e)))return;if(Se(e).status==="current"){Jt.current=!0,Ln.current=0,Zt.current=0,u({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."}),nr(null),me("write the docs for this repo");return}Ln.current+=1;let a=Ln.current;if((a===4||a%15===0)&&Zt.current<3){Zt.current+=1;let s=Zt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";u({kind:"note",tone:"info",text:Ue(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${s}`:`\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.${s}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,S,u]),ve(()=>{let l=fs??vn(e);if(!S){Lo(0),Ht(`${Mo} ${l}`);return}Lo(3);let a=0;Ht(`${Oo[0]} ${l}`);let s=setInterval(()=>{a=(a+1)%Oo.length,Ht(`${Oo[a]} ${l}`)},400);return()=>clearInterval(s)},[S,e,fs]),ve(()=>()=>Lo(0),[]);let en=V(l=>{let a=bn(e,i,{claudeMissing:rs(t).state==="missing",allowAutoAudit:l,genreUnknown:zo.current});return a?kn(a):{kind:"idle"}},[e,i,t]);ve(()=>{let l=performance.now(),a=[],s=(y,R)=>{let T=performance.now();try{return R()}finally{let z=Math.round(performance.now()-T);z>=80&&a.push(`${y}: ${z}ms`)}};u({kind:"banner",info:s("banner",()=>mg(e,o,t,i))});let h=rs(t).state==="missing";if(h&&u({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.
309
+ ${Th}
310
310
  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)){u({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
311
- ${Vc}`}),Y(h?"/doctor":"/init");return}h&&Y("/doctor");try{let y=ke(e,i),R=ht(y.name);R&&Xe(R)&&R.refreshToken?jh({profile:y.name,connection:y.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),Z(T=>T+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Y("/login")}):(!R||Xe(R))&&(u({kind:"note",tone:"warn",text:`Profile "${y.name}" is not signed in \u2014 sign in with /login.`}),Y("/login"))}catch{}try{let y=ee(e),R=ke(e,i),T=ht(R.name);y&&T&&!Xe(T)&&Hi(e,y.authoritativeSourceFiles)&&!qi(e,i)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),Y("/scope"))}catch{}try{let y=s("resolve-genre",()=>Hh(e));y.persisted&&y.appType?u({kind:"note",tone:"ok",text:`\u2713 Detected a ${y.appType} app \u2014 enabled the ${y.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):y.source==="unknown"&&ee(e)&&(Yo.current=!0)}catch{}let d=Se(e);try{if(s("reconcile-devhints",()=>ro(e)),d.status!=="current"&&!Oe(e)){let y=io(e);y.length&&(u({kind:"note",tone:"warn",text:y.join(`
312
- `)}),jt(dt()),Qt.current=!1)}}catch{}try{let y=s("reconcile-feedback",()=>sg(e));y.archived>0&&u({kind:"note",tone:"ok",text:`\u2713 Tidied ${y.archived} resolved item${y.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${y.open>0?`; ${y.open} still open`:""}.`})}catch{}let m=s("ready-decision",()=>Zt(!0));m.kind==="autoAudit"?(u({kind:"note",tone:"info",text:m.note}),un().then(y=>{y.kind==="forward-to-agent"&&y.prompt&&ie(y.prompt,{display:y.display,quietUser:!0})})):m.kind==="recommend"&&xs(m.rec);let b=Math.round(performance.now()-l);b>=800&&lg({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${b}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${a.length?a.join(`
311
+ ${Gc}`}),Y(h?"/doctor":"/init");return}h&&Y("/doctor");try{let y=$e(e,i),R=ht(y.name);R&&Qe(R)&&R.refreshToken?Ah({profile:y.name,connection:y.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),Z(T=>T+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Y("/login")}):(!R||Qe(R))&&(u({kind:"note",tone:"warn",text:`Profile "${y.name}" is not signed in \u2014 sign in with /login.`}),Y("/login"))}catch{}try{let y=ee(e),R=$e(e,i),T=ht(R.name);y&&T&&!Qe(T)&&qi(e,y.authoritativeSourceFiles)&&!Bi(e,i)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),Y("/scope"))}catch{}try{let y=s("resolve-genre",()=>qh(e));y.persisted&&y.appType?u({kind:"note",tone:"ok",text:`\u2713 Detected a ${y.appType} app \u2014 enabled the ${y.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):y.source==="unknown"&&ee(e)&&(zo.current=!0)}catch{}let d=Se(e);try{if(s("reconcile-devhints",()=>io(e)),d.status!=="current"&&!Ue(e)){let y=so(e);y.length&&(u({kind:"note",tone:"warn",text:y.join(`
312
+ `)}),jt(dt()),Jt.current=!1)}}catch{}try{let y=s("reconcile-feedback",()=>ag(e));y.archived>0&&u({kind:"note",tone:"ok",text:`\u2713 Tidied ${y.archived} resolved item${y.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${y.open>0?`; ${y.open} still open`:""}.`})}catch{}let m=s("ready-decision",()=>en(!0));m.kind==="autoAudit"?(u({kind:"note",tone:"info",text:m.note}),pn().then(y=>{y.kind==="forward-to-agent"&&y.prompt&&ie(y.prompt,{display:y.display,quietUser:!0})})):m.kind==="recommend"&&$s(m.rec);let b=Math.round(performance.now()-l);b>=800&&cg({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${b}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${a.length?a.join(`
313
313
  `):"no single phase \u226580ms"}
314
- cwd: ${e}`}),or()},[]),be(()=>{let l=setInterval(()=>{or()},$g);return()=>clearInterval(l)},[or]),be(()=>{if(S||zo||Rn.current||de!==null||Qe.length>0||D!==""||Xt!==null||je.current.length>0||An.current)return;let l=Zt(!1);l.kind==="recommend"&&(l.rec.lead||l.rec.picker)&&xs(l.rec,{silent:!0})},[S,de,Qe,D,Xt,re,Zt,zo]),be(()=>{let l=null,a=null,s=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let h=`${Ae.columns??80}x${Ae.rows??24}`;h!==bs.current&&(bs.current=h,ld(d=>d+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Ra(kt.current,He())+"\x1B[?2026l")},80))},400)};return Ae.on("resize",s),()=>{l&&clearTimeout(l),a&&clearTimeout(a),Ae.off("resize",s)}},[Ae,He]);let Ee=Math.max(20,(Ae.columns??80)-1),vs=Ji(()=>mg(e,i),[e,i,re]),ar=(()=>{if(rd)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Ko!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Ko?` v${Ko}`:""}\u2026`,isSetup:!0};if(Xt)return cd?{text:"\u2713 copied \u2014 paste it into your coding agent \xB7 I\u2019ll pick up automatically when it finishes\u2026",isSetup:!0}:{text:"\u2328 press c to copy the prompt above \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(je.current.length>0)return{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let l=ee(e);if(!l)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let a=es(e,(l.docsDir??zc).replace(/\/+$/,"")),s=(()=>{try{return xn(a)&&Ch(a).length>0}catch{return!1}})();try{let h=ke(e,i),d=ht(h.name);if(!(!!d&&!(Xe(d)&&!d.refreshToken)))return{text:`Sign in with /login (profile "${h.name}")\u2026`,isSetup:!0};if(!h.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!h.project.workspaceId&&!s)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return s?{text:hg,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),en=mc(D),Cs=en.length>0&&!S,lr=p!==null?Ac(p,8,Ee):null,Ln=ve?ve.paths.filter(l=>!ve.query||l.toLowerCase().includes(ve.query.toLowerCase())).slice(0,8):[],On=Re?Re.sessions.filter(l=>{let a=Re.query.toLowerCase();return!a||l.name.toLowerCase().includes(a)||l.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],ge=V((l,a)=>{xe.current?.close(),xe.current=Ic({cwd:e,resume:l,profileName:a??i,allowProdWrites:bt.current}),l||(_e.current={uuid:null,firstPrompt:null,titleFired:!1},et(null)),Tt(0),St(0)},[e,i]),Rs=V((l,a,s)=>{if(gg.test(l))try{let h=ke(e,i),d=typeof a.project_id=="string"&&a.project_id||h.project.projectId,m=Io(a,s),b=[],y=No(s);l.endsWith("publish_article")&&y&&b.push(`Live: ${y}`),m&&d&&b.push(`Preview: ${Eo(h.connection.portalUrl,d,m,h.project.languageCode??"en")}`),b.length>0&&u({kind:"link",lines:b})}catch{}},[e,i,u]),ie=V(async(l,a)=>{Tn(!0),Rn.current=!1,qe(),Je([]),Gt(null),tr(null),sr(null);let s=Pn.current;a?.quietUser||u({kind:"user",text:a?.echoDisplay&&a.display?a.display:l});let h=_e.current;h.firstPrompt||(h.firstPrompt=a?.display??l),Ze.current=Date.now(),gt(0),N(!0),jn.current.clear();let d="",m=!1,b=!1,y="",R={num:0,closed:!1,cueSeen:!1},T=null,z=()=>{T||(T=setTimeout(()=>{T=null,g(y.length>0?y:null)},60))},q=()=>{T&&clearTimeout(T),T=null,g(null)},M=()=>{if(y.trim()){let v=zi(y.trimEnd(),R);u({kind:"assistant",text:v})}y="",q()};try{for await(let v of xe.current.send(l))if(v.type==="session"){if(!h.uuid){h.uuid=v.sessionId;let A=new Date().toISOString(),H=Qo.current,X=H??Lh(h.firstPrompt??"session");Oh({uuid:v.sessionId,name:X,renamed:!!H,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:A,updatedAt:A}),et(X),Qo.current=null}}else if(v.type==="text"){y+=v.delta,d+=v.delta;let A=Ec(y);if(A>0){let H=y.slice(0,A).trimEnd();H&&u({kind:"assistant",text:zi(H,R)}),y=y.slice(A)}z(),gt(H=>H+v.delta.length)}else if(v.type==="tool"){m=!0;let A=jo(v.name,v.input);A&&(M(),u({kind:"tool",title:A.title,sep:A.sep,arg:A.arg}),jn.current.set(v.id,{name:v.name,input:v.input}))}else if(v.type==="article_diff"){let A=ut(v.oldContent,v.newContent,He());A&&(M(),u({kind:"diff",added:A.added,removed:A.removed,lines:A.lines,hidden:A.hidden}))}else if(v.type==="tool_result"){v.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(v.output)&&(In.current=!0);let A=jn.current.get(v.id);if(A){jn.current.delete(v.id),M();let H=Ao(v.output,4,v.isError?void 0:A.name,A.input);u({kind:"tool-result",lines:H.lines,hidden:H.hidden,isError:v.isError}),v.isError||Rs(A.name,A.input,v.output)}}else if(v.type==="result"){if(M(),Tt(A=>A+v.outputTokens),St(A=>A+v.costUsd),u({kind:"done",seconds:Math.round((Date.now()-Ze.current)/1e3),tokens:v.outputTokens,costUsd:v.costUsd,ok:v.ok}),!b&&!m&&!d.trim()&&!Yt.current&&u({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),v.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(d))try{let A=ig(e);if(xn(A)){let H=Zi(A,"utf8").trim();H&&(sr(H),u({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(v.ok&&R.cueSeen)cs(!0),Je([]);else{let A=v.ok?wc(d,Mo.map(H=>H.name)):[];if(A.length>0)Y(A[0]);else if(v.ok&&d.trim()){let H=Zt(!1);H.kind==="recommend"&&(H.rec.lead||H.rec.picker)||Fh(l,d,e).then(X=>{X&&Pn.current===s&&fe(X)}).catch(()=>{})}}if(h.uuid&&(ts(h.uuid),!h.titleFired)){h.titleFired=!0;let A=h.uuid,H=h.firstPrompt;H&&Nc(H,e).then(X=>{X&&(_h(A,X),et(X))}).catch(()=>{})}}else v.type==="error"&&(M(),b=!0,v.kind==="auth"&&(In.current=!0),u({kind:"note",text:`agent error: ${v.message}`,tone:"error"}))}finally{N(!1),q(),Z(v=>v+1),_e.current.uuid&&dc(e,_e.current.uuid,kt.current),In.current&&(In.current=!1,Nn.current=a?.display??l,fe("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")),Yt.current&&(Yt.current=!1,st.current.length>0&&(u({kind:"note",tone:"info",text:`(${st.current.length} queued message(s) discarded)`}),st.current=[],Jo([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,Rs,He,fe,Y,qe,Zt]),Mn=V(async l=>{let a=ns(l),s=Bo(e,"standard");Ze.current=Date.now(),gt(0),N(!0);let h=new AbortController;Ce.current=h,ne({verb:"Publishing",total:a.length,done:0,active:[],rows:bn(a),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${a.length} partition${a.length===1?"":"s"} (\u2264${cn} agents at once) on ${s.model}\u2026 (esc to stop)`});try{for await(let d of qo({cwd:e,partitions:a,promptFor:m=>po(m.paths),concurrency:cn,profileName:i,allowProdWrites:bt.current,model:s.model,signal:h.signal}))if(d.type==="partition_status")d.status==="running"?ne(m=>m&&{...m,active:[...m.active,d.label],rows:Ue(m.rows,d.label,"active"),lastAt:Date.now()}):ne(m=>m&&{...m,active:m.active.filter(b=>b!==d.label),done:m.done+1,rows:Ue(m.rows,d.label,d.status==="done"?"done":"failed"),lastAt:Date.now()});else if(d.type==="partition_event")ne(m=>{if(!m)return m;let b={...m,lastAt:Date.now()};return d.event.type==="tool"?b.tools=m.tools+1:d.event.type==="text"&&(b.chars=m.chars+d.event.delta.length),b});else if(d.type==="run_done"){St(R=>R+d.totalCostUsd),Tt(R=>R+d.results.reduce((T,z)=>T+z.outputTokens,0));let m=d.aborted?"Stopped. ":"",b=t.kind==="api"?"api":"subscription";u({kind:"note",tone:d.aborted?"warn":d.ok?"ok":"warn",text:m+_r(d.results,a,b).join(`
315
- `)});let y=Nr(e,i);if(y&&u({kind:"note",tone:"info",text:y}),!d.aborted){try{let R=await Fc({cwd:e,profileName:i}),T=Hc(R);T?u({kind:"note",tone:"info",text:T}):R.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${R.skipped}`})}catch(R){u({kind:"note",tone:"warn",text:`Order sync failed: ${R.message}`})}try{let R=Bc(await qc({cwd:e,profileName:i}));R&&u({kind:"note",tone:"info",text:R})}catch(R){u({kind:"note",tone:"warn",text:`Related-articles sync failed: ${R.message}`})}}}}catch(d){u({kind:"note",tone:"error",text:`Publish run failed: ${d.message}`})}finally{Ce.current=null,ne(null),N(!1),Z(d=>d+1)}},[e,i,u,t]),cr=V(async l=>{await ie(Ir(l),{display:`/publish ${l}`,quietUser:!0});try{let a=await fo(e,i,l.replace(/\\/g,"/"));a.length>0&&(Gt(`Related articles not yet published (${a.length}):`),Je([`/publish --related ${l}`,...a.map(s=>`/publish ${s}`)]))}catch{}},[e,i,ie]),dr=V(l=>{let a=ht(l);if(!a||Xe(a)&&!a.refreshToken)return null;let s={...qt(a.idToken)??{},...qt(a.accessToken)??{}};return s.email??s.preferred_username??"signed in"},[]),ur=V((l,a)=>{if(a){let s=ee(e);s&&(s.defaultProfile=l,_c(s,e))}c(l),ge(void 0,l),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),dr(l)||(u({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 sign in with /login.`}),Y("/login")),Z(s=>s+1)},[e,u,ge,dr,Y]),Un=V((l,a,s)=>{Yn(e,l,a,s.id,s.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${s.name??s.id}" (agent restarted).`}),ge(),Lc(e,l)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({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:"}),u({kind:"note",tone:"info",text:Ut(Mt(e)).join(`
316
- `)}),jt(dt()),Qt.current=Se(e).status==="current"||Oe(e),u({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,u,ge,jt]),Wn=V(async l=>{let a;try{a=await on(e,l)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Y("/workspace");return}if(a.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let s=a.workspaces.filter(d=>(d.workspace_type??"").toLowerCase()!=="apidocumentation"),h=s.length>0?s:a.workspaces;if(h.length===1){let d=h[0],m=a.workspaces.length-h.length;u({kind:"note",tone:"ok",text:`Selected the "${d.name??d.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),Un(a.profile,a.projectId,d);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),Y("/workspace")},[e,u,Un,Y]),Fn=V((l,a)=>{zn(e,l,a.id,a.name),u({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),ge(),Wn(l)},[e,u,ge,Wn]),Ps=V(async l=>{let a;try{a=ke(e,l)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:s}=await Ve(e,a.name),h=s.find(d=>d.id===a.project.projectId);h?.name&&ag(e,a.name,{projectName:h.name})}catch{}await Wn(a.name);return}try{let{projects:s}=await Ve(e,a.name);if(s.length===1){let h=s[0];u({kind:"note",tone:"ok",text:`Using your Document360 project "${h.name??h.id}".`}),Fn(a.name,{id:h.id,name:h.name});return}if(s.length>1){let h=s.map(d=>({id:d.id,name:d.name??d.id,sub:d.sub_domain}));u({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),ot({cursor:0,current:-1,rows:h,profile:a.name,environment:a.connection.name});return}}catch{}u({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Y("/project")}},[e,u,Wn,Fn,Y]),Hn=V(()=>{let l=je.current[0];if(!l)return;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let s of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${s}`});l.overwritesLocalChanges&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let a=ut(l.oldContent,l.newContent,He());u(a?{kind:"diff",added:a.added,removed:a.removed,lines:a.lines,hidden:a.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,He]),Ts=V(l=>{if(je.current.length===0)return!1;let a=l.trim().toLowerCase();if(a==="y"||a==="yes"){let s=je.current.shift();try{Bh({cwd:e,profileName:i},s),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${s.path} (sync base advanced).`}),je.current.length===0&&Y("/pull")}catch(h){u({kind:"note",tone:"error",text:`Pull failed: ${h.message}`})}}else if(a==="n"||a==="no"){let s=je.current.shift();u({kind:"note",tone:"info",text:`Skipped ${s.path}.`})}else{let s=je.current.length;return je.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${s} article(s) left untouched).`}),!0}return Hn(),!0},[e,i,Hn,u]),Ss=V(l=>{let a=An.current;if(!a)return!1;if(An.current=null,qe(),l.trim()!==a.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:s,failed:h}=ji(e,a.targets);u({kind:"note",tone:h.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${s.length} item${s.length===1?"":"s"}. The repo is back to its original state.`});for(let d of h)u({kind:"note",tone:"error",text:` \u2717 ${d.path}: ${d.error}`});return a.hadDevhints&&(u({kind:"note",tone:"warn",text:so().join(`
317
- `)}),jt(br())),u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
318
- ${Vc}`}),Y("/init"),Tn(!1),!0},[e,u,jt,qe,Y]),qn=V(async l=>{let a=l.slice(1).trim().split(/\s+/),s=(a[0]??"").toLowerCase(),h=a.slice(1);if(Tn(!0),yo(h)&&["write","check","review","reorder"].includes(s)){let d=Kr(e,i);if(d.length===0){u({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let m=b=>s==="write"?`/write ${Va(h,b).join(" ")}`.trim():`/${s} ${[b,...h.filter(y=>y!=="--scope")].join(" ")}`.trim();if(d.length===1){qn(m(d[0].token));return}Rt({cursor:0,rows:d,run:b=>{qn(m(b))}});return}switch(s){case"help":Kt({tab:0});return;case"exit":case"quit":xe.current?.close(),r();return;case"clear":ge(),kt.current=[],Tn(!1),qe(),u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let d;try{d=ke(e,i)}catch(m){u({kind:"note",tone:"error",text:m.message});return}u({kind:"note",tone:"info",text:`Profile "${d.name}" \u2192 ${d.connection.name} (${d.connection.apiUrl})${d.production?" \u26A0 PRODUCTION":""}`}),J(!0);try{let m=await Th(d.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},y=>u({kind:"note",tone:"info",text:y})),b=Sh(d.name,m);if(Dh(b),await hr(b,d.name,y=>u({kind:"note",tone:"info",text:y})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${d.name}" as ${Qn(b)}`}),await Ps(i),zt.current){let y=zt.current;zt.current=null;let R=Me(e,i);R.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${y}.`}),Y(y)):(u({kind:"note",tone:"warn",text:`${R.reason} (then ${y}.)`}),Y("/login"),zt.current=y)}else Nn.current&&(fe(Nn.current,"\u21E5 tab to re-send your last prompt\u2026"),Nn.current=null)}catch(m){u({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{J(!1),Z(m=>m+1)}return}case"allow-prod":{let d=!1;try{d=ke(e,i).production}catch{}if(!d){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}bt.current=!0,ge(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let d=pi(h.join(" ")),m=_e.current.uuid;if(!m){if(!d){u({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Qo.current=d,et(d),Ht(`${Oo} ${d}`),u({kind:"note",tone:"ok",text:`Session will be named "${d}" once it starts.`});return}if(!d){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let b=_e.current.firstPrompt??"";Nc(b,e).then(y=>{y?(fe(`/rename ${y}`),u({kind:"note",tone:"info",text:`Suggestion: "${y}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Wh(m,d),et(d),Ht(`${Oo} ${d}`),u({kind:"note",tone:"ok",text:`Session renamed to "${d}".`});return}case"profile":{let d=h[0],m=ee(e);if(!d){let b=Object.entries(m?.profiles??{});if(b.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let y=b.map(([z,q])=>({name:z,env:q.connection?.environment??"custom",prod:q.production===!0,who:dr(z)})),R=i??m?.defaultProfile,T=Math.max(0,y.findIndex(z=>z.name===R));xt({cursor:T,current:T,rows:y});return}if(d==="add"){let b=fi(e,h[1],h[2]);if(b){u({kind:"note",tone:"error",text:b});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),ur(h[1],!1);return}if(!m?.profiles?.[d]){u({kind:"note",tone:"error",text:`Unknown profile "${d}". Create it: /profile add ${d} <environment>`});return}ur(d,!0);return}case"doctor":await fn(h,{cwd:e});return;case"genre":{await To(h,{cwd:e});try{Yo.current=!(ee(e)?.appType??qh(e))}catch{}Z(d=>d+1);return}case"roadmap":{if(h[0]?.toLowerCase()==="done"){let d=Oi(e,h.slice(1).join(" ").trim());u({kind:"note",tone:d.ok?"ok":"warn",text:d.line}),Z(m=>m+1);return}u({kind:"note",tone:"info",text:Li(e).join(`
319
- `)});return}case"mcp":await co(h);return;case"init":{if(ee(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let d=Xh().map(m=>({name:m,apiUrl:Qh(m).apiUrl}));$t({cursor:0,rows:d});return}case"resume":{let d=h.join(" ").trim(),m=Uh(e).filter(R=>R.uuid!==_e.current.uuid);if(!d){if(!m.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}at({query:"",cursor:0,sessions:m});return}let b=Mh(e,d);if(!b){u({kind:"note",tone:"error",text:`No session matches "${d}".`});return}ge(b.uuid),_e.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},et(b.name),ts(b.uuid),kt.current=[];let y=Ki(e,b.uuid);for(let R of y)u(R);u({kind:"note",tone:"ok",text:y.length?`Resumed "${b.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${b.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let d=h.join(" ").trim(),m;try{m=await on(e,i)}catch(y){u({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!d){let y=m.workspaces.map(T=>({id:T.id,name:T.name??T.id,type:T.workspace_type}));if(y.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let R=Math.max(0,y.findIndex(T=>T.id===m.current));vt({cursor:R,current:R,rows:y,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let b=fr(m.workspaces,d);if(!b){u({kind:"note",tone:"error",text:`No workspace matches "${d}".`});return}Un(m.profile,m.projectId,b);return}case"project":{let d=h.join(" ").trim(),m;try{m=await Ve(e,i)}catch(y){u({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!d){let y=m.projects.map(T=>({id:T.id,name:T.name??T.id,sub:T.sub_domain}));if(y.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let R=y.findIndex(T=>T.id===m.current);ot({cursor:Math.max(0,R),current:R,rows:y,profile:m.profile,environment:m.environment});return}let b=mr(m.projects,d);if(!b){u({kind:"note",tone:"error",text:`No project matches "${d}". Available: ${m.projects.map(y=>y.name??y.id).join(", ")}`});return}Fn(m.profile,b);return}case"logout":{let d;try{d=ke(e,i).name}catch(b){u({kind:"note",tone:"error",text:b.message});return}let m=Ih(d);Nh(e,d),ge(),Z(b=>b+1),u({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${d}" and cleared its project/workspace selection.`:`Profile "${d}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Y("/login");return}case"publish":{if(!rr(l.trim()))return;if(h[0]==="--related"&&h[1]){let m=await fo(e,i,h[1].replace(/\\/g,"/"));if(m.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Mn(m);return}if(h[0]&&h[0]!=="--all"){await cr(h[0]);return}let d=h[0]==="--all";u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Oc({cwd:e,profileName:i}),b=dn(m.entries),y=uo(m.entries);if(y>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${y} article${y===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),b.length===0){u({kind:"note",tone:"ok",text:y>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let R=m.counts["unknown-base"]??0;R>0&&u({kind:"note",tone:"info",text:`(${R} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),gs("Reconciling structure on Document360 (order + related articles)\u2026");try{let T=await Fc({cwd:e,profileName:i}),z=Bc(await qc({cwd:e,profileName:i})),q=Hc(T);q?u({kind:"note",tone:"info",text:q}):T.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${T.skipped}`}),z&&u({kind:"note",tone:"info",text:z}),u({kind:"note",tone:"ok",text:q||z?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(q||z)&&Y("/structure")}catch(T){u({kind:"note",tone:"warn",text:`Structure sync failed: ${T.message}`})}finally{gs(null)}return}if(d){await Mn(b.map(R=>R.path));return}Ct({cursor:0,rows:Ea(b)})}catch(m){u({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let d=h.join(" ").trim();if(!d){let b=[];try{b=Object.keys(Lc(e,ke(e,i).name)?.articles??{})}catch{}if(b.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}it({query:"",cursor:0,paths:b});return}let m=Rh(d)?d:es(e,d);if(xn(m)){try{u({kind:"preview",name:$n(m),text:Yc(Zi(m,"utf8"))})}catch(b){u({kind:"note",tone:"error",text:`Could not read ${m}: ${b.message}`})}return}if(yg.test(d)){try{let b=ke(e,i),y={profile:b.name,connection:b.connection},R=b.project.projectId??Ah(y),T=await Eh(y,R,d);u({kind:"preview",name:T.title??d,text:T.content??"*(article has no content)*"})}catch(b){u({kind:"note",tone:"error",text:`Could not fetch article: ${b.message}`})}return}u({kind:"note",tone:"error",text:`"${d}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let d=h[0]?.trim();if(!d){let R=ko(rs(e));nt({cursor:R,current:R});return}let{lines:m,changed:b,effective:y}=pn(e,d);for(let R of m)u({kind:"note",tone:R.startsWith("\u26A0")?"warn":R.startsWith("\u2713")?"ok":"info",text:R});b&&(ks(R=>R+1),xe.current?.setModel(y));return}case"convert":{if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:d,run:m}=Hr(h),b=eg(e,i);if(b.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let y=qr(b,d);if(y.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${d}". (${b.length} are tracked overall.)`});return}let R=ns(y),T=3,z=`/convert${d?` --scope ${d}`:""} --run`,q=Bo(e,"light");if(!m){let v=Uc({files:Br(e,y),op:"convert",model:q.model}),A=d?`Scope: ${d} (${y.length} of ${b.length} tracked)
314
+ cwd: ${e}`}),rr()},[]),ve(()=>{let l=setInterval(()=>{rr()},vg);return()=>clearInterval(l)},[rr]),ve(()=>{if(S||Ko||Rn.current||de!==null||Je.length>0||D!==""||Qt!==null||je.current.length>0||An.current||er)return;let l=en(!1);l.kind==="recommend"&&(l.rec.lead||l.rec.picker)&&$s(l.rec,{silent:!0})},[S,de,Je,D,Qt,er,re,en,Ko]),ve(()=>{let l=null,a=null,s=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let h=`${Ae.columns??80}x${Ae.rows??24}`;h!==xs.current&&(xs.current=h,cd(d=>d+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Pa(kt.current,qe())+"\x1B[?2026l")},80))},400)};return Ae.on("resize",s),()=>{l&&clearTimeout(l),a&&clearTimeout(a),Ae.off("resize",s)}},[Ae,qe]);let Ee=Math.max(20,(Ae.columns??80)-1),Cs=Zi(()=>hg(e,i),[e,i,re]),lr=(()=>{if(id)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};if(Qt)return dd?{text:"\u2713 copied \u2014 paste it into your coding agent \xB7 I\u2019ll pick up automatically when it finishes\u2026",isSetup:!0}:{text:"\u2328 press c to copy the prompt above \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(je.current.length>0)return{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let l=ee(e);if(!l)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let a=ts(e,(l.docsDir??Kc).replace(/\/+$/,"")),s=(()=>{try{return $n(a)&&Rh(a).length>0}catch{return!1}})();try{let h=$e(e,i),d=ht(h.name);if(!(!!d&&!(Qe(d)&&!d.refreshToken)))return{text:`Sign in with /login (profile "${h.name}")\u2026`,isSetup:!0};if(!h.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!h.project.workspaceId&&!s)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return s?{text:gg,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),tn=hc(D),Rs=tn.length>0&&!S,cr=p!==null?Ec(p,8,Ee):null,On=ye?ye.paths.filter(l=>!ye.query||l.toLowerCase().includes(ye.query.toLowerCase())).slice(0,8):[],Mn=we?we.sessions.filter(l=>{let a=we.query.toLowerCase();return!a||l.name.toLowerCase().includes(a)||l.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],ke=V((l,a)=>{Ce.current?.close(),Ce.current=Nc({cwd:e,resume:l,profileName:a??i,allowProdWrites:bt.current}),l||(_e.current={uuid:null,firstPrompt:null,titleFired:!1},tt(null)),Tt(0),St(0)},[e,i]),Ps=V((l,a,s)=>{if(yg.test(l))try{let h=$e(e,i),d=typeof a.project_id=="string"&&a.project_id||h.project.projectId,m=No(a,s),b=[],y=_o(s);l.endsWith("publish_article")&&y&&b.push(`Live: ${y}`),m&&d&&b.push(`Preview: ${Io(h.connection.portalUrl,d,m,h.project.languageCode??"en")}`),b.length>0&&u({kind:"link",lines:b})}catch{}},[e,i,u]),ie=V(async(l,a)=>{Tn(!0),Rn.current=!1,Be(),Ze([]),Yt(null),nr(null),ar(null);let s=Pn.current;a?.quietUser||u({kind:"user",text:a?.echoDisplay&&a.display?a.display:l});let h=_e.current;h.firstPrompt||(h.firstPrompt=a?.display??l),et.current=Date.now(),gt(0),N(!0),jn.current.clear();let d="",m=!1,b=!1,y="",R={num:0,closed:!1,cueSeen:!1},T=null,z=()=>{T||(T=setTimeout(()=>{T=null,g(y.length>0?y:null)},60))},q=()=>{T&&clearTimeout(T),T=null,g(null)},M=()=>{if(y.trim()){let v=Ki(y.trimEnd(),R);u({kind:"assistant",text:v})}y="",q()};try{for await(let v of Ce.current.send(l))if(v.type==="session"){if(!h.uuid){h.uuid=v.sessionId;let E=new Date().toISOString(),H=Jo.current,X=H??Oh(h.firstPrompt??"session");Mh({uuid:v.sessionId,name:X,renamed:!!H,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:E,updatedAt:E}),tt(X),Jo.current=null}}else if(v.type==="text"){y+=v.delta,d+=v.delta;let E=Ic(y);if(E>0){let H=y.slice(0,E).trimEnd();H&&u({kind:"assistant",text:Ki(H,R)}),y=y.slice(E)}z(),gt(H=>H+v.delta.length)}else if(v.type==="tool"){m=!0;let E=Ao(v.name,v.input);E&&(M(),u({kind:"tool",title:E.title,sep:E.sep,arg:E.arg}),jn.current.set(v.id,{name:v.name,input:v.input}))}else if(v.type==="article_diff"){let E=ut(v.oldContent,v.newContent,qe());E&&(M(),u({kind:"diff",added:E.added,removed:E.removed,lines:E.lines,hidden:E.hidden}))}else if(v.type==="tool_result"){v.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(v.output)&&(In.current=!0);let E=jn.current.get(v.id);if(E){jn.current.delete(v.id),M();let H=Eo(v.output,4,v.isError?void 0:E.name,E.input);u({kind:"tool-result",lines:H.lines,hidden:H.hidden,isError:v.isError}),v.isError||Ps(E.name,E.input,v.output)}}else if(v.type==="result"){if(M(),Tt(E=>E+v.outputTokens),St(E=>E+v.costUsd),u({kind:"done",seconds:Math.round((Date.now()-et.current)/1e3),tokens:v.outputTokens,costUsd:v.costUsd,ok:v.ok}),!b&&!m&&!d.trim()&&!zt.current&&u({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),v.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(d))try{let E=sg(e);if($n(E)){let H=es(E,"utf8").trim();H&&(ar(H),u({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(v.ok&&R.cueSeen)ds(!0),Ze([]);else{let E=v.ok?kc(d,Uo.map(H=>H.name)):[];if(E.length>0)Y(E[0]);else if(v.ok&&d.trim()){let H=en(!1);H.kind==="recommend"&&(H.rec.lead||H.rec.picker)||Hh(l,d,e).then(X=>{X&&Pn.current===s&&me(X)}).catch(()=>{})}}if(h.uuid&&(ns(h.uuid),!h.titleFired)){h.titleFired=!0;let E=h.uuid,H=h.firstPrompt;H&&_c(H,e).then(X=>{X&&(Lh(E,X),tt(X))}).catch(()=>{})}}else v.type==="error"&&(M(),b=!0,v.kind==="auth"&&(In.current=!0),u({kind:"note",text:`agent error: ${v.message}`,tone:"error"}))}finally{N(!1),q(),Z(v=>v+1),_e.current.uuid&&uc(e,_e.current.uuid,kt.current),In.current&&(In.current=!1,Nn.current=a?.display??l,me("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")),zt.current&&(zt.current=!1,st.current.length>0&&(u({kind:"note",tone:"info",text:`(${st.current.length} queued message(s) discarded)`}),st.current=[],Zo([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,Ps,qe,me,Y,Be,en]),Un=V(async l=>{let a=os(l),s=Vo(e,"standard");et.current=Date.now(),gt(0),N(!0);let h=new AbortController;Re.current=h,ne({verb:"Publishing",total:a.length,done:0,active:[],rows:xn(a),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${a.length} partition${a.length===1?"":"s"} (\u2264${dn} agents at once) on ${s.model}\u2026 (esc to stop)`});try{for await(let d of Bo({cwd:e,partitions:a,promptFor:m=>fo(m.paths),concurrency:dn,profileName:i,allowProdWrites:bt.current,model:s.model,signal:h.signal}))if(d.type==="partition_status")d.status==="running"?ne(m=>m&&{...m,active:[...m.active,d.label],rows:Fe(m.rows,d.label,"active"),lastAt:Date.now()}):ne(m=>m&&{...m,active:m.active.filter(b=>b!==d.label),done:m.done+1,rows:Fe(m.rows,d.label,d.status==="done"?"done":"failed"),lastAt:Date.now()});else if(d.type==="partition_event")ne(m=>{if(!m)return m;let b={...m,lastAt:Date.now()};return d.event.type==="tool"?b.tools=m.tools+1:d.event.type==="text"&&(b.chars=m.chars+d.event.delta.length),b});else if(d.type==="run_done"){St(R=>R+d.totalCostUsd),Tt(R=>R+d.results.reduce((T,z)=>T+z.outputTokens,0));let m=d.aborted?"Stopped. ":"",b=t.kind==="api"?"api":"subscription";u({kind:"note",tone:d.aborted?"warn":d.ok?"ok":"warn",text:m+Lr(d.results,a,b).join(`
315
+ `)});let y=_r(e,i);if(y&&u({kind:"note",tone:"info",text:y}),!d.aborted){try{let R=await Hc({cwd:e,profileName:i}),T=qc(R);T?u({kind:"note",tone:"info",text:T}):R.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${R.skipped}`})}catch(R){u({kind:"note",tone:"warn",text:`Order sync failed: ${R.message}`})}try{let R=Vc(await Bc({cwd:e,profileName:i}));R&&u({kind:"note",tone:"info",text:R})}catch(R){u({kind:"note",tone:"warn",text:`Related-articles sync failed: ${R.message}`})}}}}catch(d){u({kind:"note",tone:"error",text:`Publish run failed: ${d.message}`})}finally{Re.current=null,ne(null),N(!1),Z(d=>d+1)}},[e,i,u,t]),dr=V(async l=>{await ie(Nr(l),{display:`/publish ${l}`,quietUser:!0});try{let a=await mo(e,i,l.replace(/\\/g,"/"));a.length>0&&(Yt(`Related articles not yet published (${a.length}):`),Ze([`/publish --related ${l}`,...a.map(s=>`/publish ${s}`)]))}catch{}},[e,i,ie]),ur=V(l=>{let a=ht(l);if(!a||Qe(a)&&!a.refreshToken)return null;let s={...Bt(a.idToken)??{},...Bt(a.accessToken)??{}};return s.email??s.preferred_username??"signed in"},[]),pr=V((l,a)=>{if(a){let s=ee(e);s&&(s.defaultProfile=l,Lc(s,e))}c(l),ke(void 0,l),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),ur(l)||(u({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 sign in with /login.`}),Y("/login")),Z(s=>s+1)},[e,u,ke,ur,Y]),Wn=V((l,a,s)=>{zn(e,l,a,s.id,s.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${s.name??s.id}" (agent restarted).`}),ke(),Oc(e,l)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({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:"}),u({kind:"note",tone:"info",text:Ut(Mt(e)).join(`
316
+ `)}),jt(dt()),Jt.current=Se(e).status==="current"||Ue(e),u({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,u,ke,jt]),Fn=V(async l=>{let a;try{a=await rn(e,l)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Y("/workspace");return}if(a.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let s=a.workspaces.filter(d=>(d.workspace_type??"").toLowerCase()!=="apidocumentation"),h=s.length>0?s:a.workspaces;if(h.length===1){let d=h[0],m=a.workspaces.length-h.length;u({kind:"note",tone:"ok",text:`Selected the "${d.name??d.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),Wn(a.profile,a.projectId,d);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),Y("/workspace")},[e,u,Wn,Y]),Hn=V((l,a)=>{Kn(e,l,a.id,a.name),u({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),ke(),Fn(l)},[e,u,ke,Fn]),Ts=V(async l=>{let a;try{a=$e(e,l)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:s}=await Ge(e,a.name),h=s.find(d=>d.id===a.project.projectId);h?.name&&lg(e,a.name,{projectName:h.name})}catch{}await Fn(a.name);return}try{let{projects:s}=await Ge(e,a.name);if(s.length===1){let h=s[0];u({kind:"note",tone:"ok",text:`Using your Document360 project "${h.name??h.id}".`}),Hn(a.name,{id:h.id,name:h.name});return}if(s.length>1){let h=s.map(d=>({id:d.id,name:d.name??d.id,sub:d.sub_domain}));u({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),rt({cursor:0,current:-1,rows:h,profile:a.name,environment:a.connection.name});return}}catch{}u({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Y("/project")}},[e,u,Fn,Hn,Y]),qn=V(()=>{let l=je.current[0];if(!l)return;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let s of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${s}`});l.overwritesLocalChanges&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let a=ut(l.oldContent,l.newContent,qe());u(a?{kind:"diff",added:a.added,removed:a.removed,lines:a.lines,hidden:a.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,qe]),Ss=V(l=>{if(je.current.length===0)return!1;let a=l.trim().toLowerCase();if(a==="y"||a==="yes"){let s=je.current.shift();try{Vh({cwd:e,profileName:i},s),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${s.path} (sync base advanced).`}),je.current.length===0&&Y("/pull")}catch(h){u({kind:"note",tone:"error",text:`Pull failed: ${h.message}`})}}else if(a==="n"||a==="no"){let s=je.current.shift();u({kind:"note",tone:"info",text:`Skipped ${s.path}.`})}else{let s=je.current.length;return je.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${s} article(s) left untouched).`}),!0}return qn(),!0},[e,i,qn,u]),Ds=V(l=>{let a=An.current;if(!a)return!1;if(An.current=null,Be(),l.trim()!==a.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:s,failed:h}=Ai(e,a.targets);u({kind:"note",tone:h.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${s.length} item${s.length===1?"":"s"}. The repo is back to its original state.`});for(let d of h)u({kind:"note",tone:"error",text:` \u2717 ${d.path}: ${d.error}`});return a.hadDevhints&&(u({kind:"note",tone:"warn",text:ao().join(`
317
+ `)}),jt(xr())),u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
318
+ ${Gc}`}),Y("/init"),Tn(!1),!0},[e,u,jt,Be,Y]),Bn=V(async l=>{let a=l.slice(1).trim().split(/\s+/),s=(a[0]??"").toLowerCase(),h=a.slice(1);if(Tn(!0),wo(h)&&["write","check","review","reorder"].includes(s)){let d=Xr(e,i);if(d.length===0){u({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let m=b=>s==="write"?`/write ${Ga(h,b).join(" ")}`.trim():`/${s} ${[b,...h.filter(y=>y!=="--scope")].join(" ")}`.trim();if(d.length===1){Bn(m(d[0].token));return}Rt({cursor:0,rows:d,run:b=>{Bn(m(b))}});return}switch(s){case"help":Xt({tab:0});return;case"exit":case"quit":Ce.current?.close(),r();return;case"clear":ke(),kt.current=[],Tn(!1),Be(),u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let d;try{d=$e(e,i)}catch(m){u({kind:"note",tone:"error",text:m.message});return}u({kind:"note",tone:"info",text:`Profile "${d.name}" \u2192 ${d.connection.name} (${d.connection.apiUrl})${d.production?" \u26A0 PRODUCTION":""}`}),J(!0);try{let m=await Sh(d.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},y=>u({kind:"note",tone:"info",text:y})),b=Dh(d.name,m);if(jh(b),await gr(b,d.name,y=>u({kind:"note",tone:"info",text:y})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${d.name}" as ${Jn(b)}`}),await Ts(i),Kt.current){let y=Kt.current;Kt.current=null;let R=We(e,i);R.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${y}.`}),Y(y)):(u({kind:"note",tone:"warn",text:`${R.reason} (then ${y}.)`}),Y("/login"),Kt.current=y)}else Nn.current&&(me(Nn.current,"\u21E5 tab to re-send your last prompt\u2026"),Nn.current=null)}catch(m){u({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{J(!1),Z(m=>m+1)}return}case"allow-prod":{let d=!1;try{d=$e(e,i).production}catch{}if(!d){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}bt.current=!0,ke(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let d=fi(h.join(" ")),m=_e.current.uuid;if(!m){if(!d){u({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Jo.current=d,tt(d),Ht(`${Mo} ${d}`),u({kind:"note",tone:"ok",text:`Session will be named "${d}" once it starts.`});return}if(!d){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let b=_e.current.firstPrompt??"";_c(b,e).then(y=>{y?(me(`/rename ${y}`),u({kind:"note",tone:"info",text:`Suggestion: "${y}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Fh(m,d),tt(d),Ht(`${Mo} ${d}`),u({kind:"note",tone:"ok",text:`Session renamed to "${d}".`});return}case"profile":{let d=h[0],m=ee(e);if(!d){let b=Object.entries(m?.profiles??{});if(b.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let y=b.map(([z,q])=>({name:z,env:q.connection?.environment??"custom",prod:q.production===!0,who:ur(z)})),R=i??m?.defaultProfile,T=Math.max(0,y.findIndex(z=>z.name===R));xt({cursor:T,current:T,rows:y});return}if(d==="add"){let b=mi(e,h[1],h[2]);if(b){u({kind:"note",tone:"error",text:b});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),pr(h[1],!1);return}if(!m?.profiles?.[d]){u({kind:"note",tone:"error",text:`Unknown profile "${d}". Create it: /profile add ${d} <environment>`});return}pr(d,!0);return}case"doctor":await mn(h,{cwd:e});return;case"genre":{await So(h,{cwd:e});try{zo.current=!(ee(e)?.appType??Bh(e))}catch{}Z(d=>d+1);return}case"roadmap":{if(h[0]?.toLowerCase()==="done"){let d=Mi(e,h.slice(1).join(" ").trim());u({kind:"note",tone:d.ok?"ok":"warn",text:d.line}),Z(m=>m+1);return}u({kind:"note",tone:"info",text:Oi(e).join(`
319
+ `)});return}case"mcp":await uo(h);return;case"init":{if(ee(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let d=Qh().map(m=>({name:m,apiUrl:Jh(m).apiUrl}));$t({cursor:0,rows:d});return}case"resume":{let d=h.join(" ").trim(),m=Wh(e).filter(R=>R.uuid!==_e.current.uuid);if(!d){if(!m.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}at({query:"",cursor:0,sessions:m});return}let b=Uh(e,d);if(!b){u({kind:"note",tone:"error",text:`No session matches "${d}".`});return}ke(b.uuid),_e.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},tt(b.name),ns(b.uuid),kt.current=[];let y=Xi(e,b.uuid);for(let R of y)u(R);u({kind:"note",tone:"ok",text:y.length?`Resumed "${b.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${b.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let d=h.join(" ").trim(),m;try{m=await rn(e,i)}catch(y){u({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!d){let y=m.workspaces.map(T=>({id:T.id,name:T.name??T.id,type:T.workspace_type}));if(y.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let R=Math.max(0,y.findIndex(T=>T.id===m.current));vt({cursor:R,current:R,rows:y,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let b=mr(m.workspaces,d);if(!b){u({kind:"note",tone:"error",text:`No workspace matches "${d}".`});return}Wn(m.profile,m.projectId,b);return}case"project":{let d=h.join(" ").trim(),m;try{m=await Ge(e,i)}catch(y){u({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!d){let y=m.projects.map(T=>({id:T.id,name:T.name??T.id,sub:T.sub_domain}));if(y.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let R=y.findIndex(T=>T.id===m.current);rt({cursor:Math.max(0,R),current:R,rows:y,profile:m.profile,environment:m.environment});return}let b=hr(m.projects,d);if(!b){u({kind:"note",tone:"error",text:`No project matches "${d}". Available: ${m.projects.map(y=>y.name??y.id).join(", ")}`});return}Hn(m.profile,b);return}case"logout":{let d;try{d=$e(e,i).name}catch(b){u({kind:"note",tone:"error",text:b.message});return}let m=Nh(d);_h(e,d),ke(),Z(b=>b+1),u({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${d}" and cleared its project/workspace selection.`:`Profile "${d}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Y("/login");return}case"publish":{if(!ir(l.trim()))return;if(h[0]==="--related"&&h[1]){let m=await mo(e,i,h[1].replace(/\\/g,"/"));if(m.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Un(m);return}if(h[0]&&h[0]!=="--all"){await dr(h[0]);return}let d=h[0]==="--all";u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Mc({cwd:e,profileName:i}),b=un(m.entries),y=po(m.entries);if(y>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${y} article${y===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),b.length===0){u({kind:"note",tone:"ok",text:y>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let R=m.counts["unknown-base"]??0;R>0&&u({kind:"note",tone:"info",text:`(${R} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),ys("Reconciling structure on Document360 (order + related articles)\u2026");try{let T=await Hc({cwd:e,profileName:i}),z=Vc(await Bc({cwd:e,profileName:i})),q=qc(T);q?u({kind:"note",tone:"info",text:q}):T.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${T.skipped}`}),z&&u({kind:"note",tone:"info",text:z}),u({kind:"note",tone:"ok",text:q||z?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(q||z)&&Y("/structure")}catch(T){u({kind:"note",tone:"warn",text:`Structure sync failed: ${T.message}`})}finally{ys(null)}return}if(d){await Un(b.map(R=>R.path));return}Ct({cursor:0,rows:Ia(b)})}catch(m){u({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let d=h.join(" ").trim();if(!d){let b=[];try{b=Object.keys(Oc(e,$e(e,i).name)?.articles??{})}catch{}if(b.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}it({query:"",cursor:0,paths:b});return}let m=Ph(d)?d:ts(e,d);if($n(m)){try{u({kind:"preview",name:vn(m),text:zc(es(m,"utf8"))})}catch(b){u({kind:"note",tone:"error",text:`Could not read ${m}: ${b.message}`})}return}if(wg.test(d)){try{let b=$e(e,i),y={profile:b.name,connection:b.connection},R=b.project.projectId??Eh(y),T=await Ih(y,R,d);u({kind:"preview",name:T.title??d,text:T.content??"*(article has no content)*"})}catch(b){u({kind:"note",tone:"error",text:`Could not fetch article: ${b.message}`})}return}u({kind:"note",tone:"error",text:`"${d}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let d=h[0]?.trim();if(!d){let R=bo(is(e));ot({cursor:R,current:R});return}let{lines:m,changed:b,effective:y}=fn(e,d);for(let R of m)u({kind:"note",tone:R.startsWith("\u26A0")?"warn":R.startsWith("\u2713")?"ok":"info",text:R});b&&(bs(R=>R+1),Ce.current?.setModel(y));return}case"convert":{if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:d,run:m}=qr(h),b=tg(e,i);if(b.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let y=Br(b,d);if(y.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${d}". (${b.length} are tracked overall.)`});return}let R=os(y),T=3,z=`/convert${d?` --scope ${d}`:""} --run`,q=Vo(e,"light");if(!m){let v=Wc({files:Vr(e,y),op:"convert",model:q.model}),E=d?`Scope: ${d} (${y.length} of ${b.length} tracked)
320
320
  `:"",H=`
321
- Model: ${q.model}${q.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:A+Gr(R,v,T).join(`
322
- `)+H}),Y(z);return}Ze.current=Date.now(),gt(0),N(!0);let M=new AbortController;Ce.current=M,ne({verb:"Converting",total:R.length,done:0,active:[],rows:bn(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${y.length} articles across ${R.length} partitions (\u2264${T} agents at once) on ${q.model}\u2026 (esc to stop)`});try{for await(let v of qo({cwd:e,partitions:R,promptFor:Vr,concurrency:T,profileName:i,allowProdWrites:bt.current,model:q.model,signal:M.signal}))if(v.type==="partition_status")v.status==="running"?ne(A=>A&&{...A,active:[...A.active,v.label],rows:Ue(A.rows,v.label,"active"),lastAt:Date.now()}):ne(A=>A&&{...A,active:A.active.filter(H=>H!==v.label),done:A.done+1,rows:Ue(A.rows,v.label,v.status==="done"?"done":"failed"),lastAt:Date.now()});else if(v.type==="partition_event")ne(A=>{if(!A)return A;let H={...A,lastAt:Date.now()};return v.event.type==="tool"?H.tools=A.tools+1:v.event.type==="text"&&(H.chars=A.chars+v.event.delta.length),H});else if(v.type==="run_done"){St(X=>X+v.totalCostUsd),Tt(X=>X+v.results.reduce((Et,It)=>Et+It.outputTokens,0));let A=v.aborted?"Stopped. ":"",H=t.kind==="api"?"api":"subscription";u({kind:"note",tone:v.aborted?"warn":v.ok?"ok":"warn",text:A+Yr(v.results,R,H).join(`
323
- `)})}}catch(v){u({kind:"note",tone:"error",text:`Convert run failed: ${v.message}`})}finally{Ce.current=null,ne(null),N(!1),Z(v=>v+1)}return}case"write":{if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=tg(e);if(d.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:b,preview:y,concurrency:R,rewrite:T}=Qr(h),{docsDir:z,targets:q,reason:M,rewriting:v}=ri(e,d,{scope:m,path:b,rewrite:T});if(q.length===0){u({kind:"note",tone:"warn",text:M??"Nothing to write."});return}v&&u({kind:"note",tone:"warn",text:`--rewrite: regenerating ${q.length} already-written article${q.length===1?"":"s"} (overwrites them; git has your baseline).`});let A=ns(q),H=Xr(R),X=Bo(e,"standard"),Et=!!b;if(y&&!Et){let G=Uc({files:Zr(e,d,q),op:"write",model:X.model}),oe=m?`Scope: ${m} (${q.length} pending)
321
+ Model: ${q.model}${q.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:E+Yr(R,v,T).join(`
322
+ `)+H}),Y(z);return}et.current=Date.now(),gt(0),N(!0);let M=new AbortController;Re.current=M,ne({verb:"Converting",total:R.length,done:0,active:[],rows:xn(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${y.length} articles across ${R.length} partitions (\u2264${T} agents at once) on ${q.model}\u2026 (esc to stop)`});try{for await(let v of Bo({cwd:e,partitions:R,promptFor:Gr,concurrency:T,profileName:i,allowProdWrites:bt.current,model:q.model,signal:M.signal}))if(v.type==="partition_status")v.status==="running"?ne(E=>E&&{...E,active:[...E.active,v.label],rows:Fe(E.rows,v.label,"active"),lastAt:Date.now()}):ne(E=>E&&{...E,active:E.active.filter(H=>H!==v.label),done:E.done+1,rows:Fe(E.rows,v.label,v.status==="done"?"done":"failed"),lastAt:Date.now()});else if(v.type==="partition_event")ne(E=>{if(!E)return E;let H={...E,lastAt:Date.now()};return v.event.type==="tool"?H.tools=E.tools+1:v.event.type==="text"&&(H.chars=E.chars+v.event.delta.length),H});else if(v.type==="run_done"){St(X=>X+v.totalCostUsd),Tt(X=>X+v.results.reduce((Et,It)=>Et+It.outputTokens,0));let E=v.aborted?"Stopped. ":"",H=t.kind==="api"?"api":"subscription";u({kind:"note",tone:v.aborted?"warn":v.ok?"ok":"warn",text:E+zr(v.results,R,H).join(`
323
+ `)})}}catch(v){u({kind:"note",tone:"error",text:`Convert run failed: ${v.message}`})}finally{Re.current=null,ne(null),N(!1),Z(v=>v+1)}return}case"write":{if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=ng(e);if(d.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:b,preview:y,concurrency:R,rewrite:T}=Jr(h),{docsDir:z,targets:q,reason:M,rewriting:v}=ii(e,d,{scope:m,path:b,rewrite:T});if(q.length===0){u({kind:"note",tone:"warn",text:M??"Nothing to write."});return}v&&u({kind:"note",tone:"warn",text:`--rewrite: regenerating ${q.length} already-written article${q.length===1?"":"s"} (overwrites them; git has your baseline).`});let E=os(q),H=Qr(R),X=Vo(e,"standard"),Et=!!b;if(y&&!Et){let G=Wc({files:ei(e,d,q),op:"write",model:X.model}),oe=m?`Scope: ${m} (${q.length} pending)
324
324
  `:"",ue=`
325
- Model: ${X.model}${X.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:oe+ti(A,G,H).join(`
326
- `)+ue}),Y(`/write${m?` --scope ${m}`:""}`);return}Ze.current=Date.now(),gt(0),N(!0);let It=new AbortController;Ce.current=It,ne({verb:"Writing",total:A.length,done:0,active:[],rows:bn(A),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${q.length} article${q.length===1?"":"s"} across ${A.length} partition${A.length===1?"":"s"} (\u2264${H} agents at once) on ${X.model}${X.forced?" (forced)":""}\u2026 (esc to stop)`});let Es=new Set;try{for await(let G of qo({cwd:e,partitions:A,promptFor:oe=>ei(oe,z,{rewrite:v||Et}),concurrency:H,profileName:i,allowProdWrites:bt.current,model:X.model,signal:It.signal}))if(G.type==="partition_status")G.status==="running"?ne(oe=>oe&&{...oe,active:[...oe.active,G.label],rows:Ue(oe.rows,G.label,"active"),lastAt:Date.now()}):ne(oe=>oe&&{...oe,active:oe.active.filter(ue=>ue!==G.label),done:oe.done+1,rows:Ue(oe.rows,G.label,G.status==="done"?"done":"failed"),lastAt:Date.now()});else if(G.type==="partition_event"){let oe=null;if(G.event.type==="tool"){let ue=bc(G.event.name,G.event.input,A[G.index]?.paths??[]);ue&&!Es.has(ue)&&(Es.add(ue),oe=G.label)}ne(ue=>{if(!ue)return ue;let Ie={...ue,lastAt:Date.now()};return G.event.type==="tool"?Ie.tools=ue.tools+1:G.event.type==="text"&&(Ie.chars=ue.chars+G.event.delta.length),oe&&(Ie.rows=kc(Ie.rows,oe)),Ie})}else if(G.type==="run_done"){St(Nt=>Nt+G.totalCostUsd),Tt(Nt=>Nt+G.results.reduce((lt,pd)=>lt+pd.outputTokens,0));let oe=G.aborted?"Stopped. ":"",ue=t.kind==="api"?"api":"subscription";u({kind:"note",tone:G.aborted?"warn":G.ok?"ok":"warn",text:oe+ni(G.results,A,ue).join(`
327
- `)});let Ie=G.aborted?null:oi(e,z,q);if(Ie&&u({kind:"note",tone:"warn",text:Ie}),!G.aborted&&G.ok){let Nt=m??b??"",lt=Nt?` ${Nt}`:"";Dt(Ie?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${lt} --fix, then /review${lt} --fix for editorial quality, then /publish --all (add /screenshot --all first if you want images).`:`Written. I\u2019d run /review${lt} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot --all first if you want images).`,{kind:"cmd",cmd:Ie?`/check${lt} --fix`:`/review${lt} --fix`,reason:""})}}}catch(G){u({kind:"note",tone:"error",text:`Write run failed: ${G.message}`})}finally{Ce.current=null,ne(null),N(!1),Z(G=>G+1)}return}case"draft":{if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:d,looseDocs:m}=ii(e);if(d.length===0&&m===0){u({kind:"note",tone:"info",text:ai});return}let b=h.join(" ").trim();if(!b&&d.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
325
+ Model: ${X.model}${X.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:oe+ni(E,G,H).join(`
326
+ `)+ue}),Y(`/write${m?` --scope ${m}`:""}`);return}et.current=Date.now(),gt(0),N(!0);let It=new AbortController;Re.current=It,ne({verb:"Writing",total:E.length,done:0,active:[],rows:xn(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${q.length} article${q.length===1?"":"s"} across ${E.length} partition${E.length===1?"":"s"} (\u2264${H} agents at once) on ${X.model}${X.forced?" (forced)":""}\u2026 (esc to stop)`});let Is=new Set;try{for await(let G of Bo({cwd:e,partitions:E,promptFor:oe=>ti(oe,z,{rewrite:v||Et}),concurrency:H,profileName:i,allowProdWrites:bt.current,model:X.model,signal:It.signal}))if(G.type==="partition_status")G.status==="running"?ne(oe=>oe&&{...oe,active:[...oe.active,G.label],rows:Fe(oe.rows,G.label,"active"),lastAt:Date.now()}):ne(oe=>oe&&{...oe,active:oe.active.filter(ue=>ue!==G.label),done:oe.done+1,rows:Fe(oe.rows,G.label,G.status==="done"?"done":"failed"),lastAt:Date.now()});else if(G.type==="partition_event"){let oe=null;if(G.event.type==="tool"){let ue=xc(G.event.name,G.event.input,E[G.index]?.paths??[]);ue&&!Is.has(ue)&&(Is.add(ue),oe=G.label)}ne(ue=>{if(!ue)return ue;let Ie={...ue,lastAt:Date.now()};return G.event.type==="tool"?Ie.tools=ue.tools+1:G.event.type==="text"&&(Ie.chars=ue.chars+G.event.delta.length),oe&&(Ie.rows=bc(Ie.rows,oe)),Ie})}else if(G.type==="run_done"){St(Nt=>Nt+G.totalCostUsd),Tt(Nt=>Nt+G.results.reduce((lt,fd)=>lt+fd.outputTokens,0));let oe=G.aborted?"Stopped. ":"",ue=t.kind==="api"?"api":"subscription";u({kind:"note",tone:G.aborted?"warn":G.ok?"ok":"warn",text:oe+oi(G.results,E,ue).join(`
327
+ `)});let Ie=G.aborted?null:ri(e,z,q);if(Ie&&u({kind:"note",tone:"warn",text:Ie}),!G.aborted&&G.ok){let Nt=m??b??"",lt=Nt?` ${Nt}`:"";Dt(Ie?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${lt} --fix, then /review${lt} --fix for editorial quality, then /publish --all (add /screenshot --all first if you want images).`:`Written. I\u2019d run /review${lt} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot --all first if you want images).`,{kind:"cmd",cmd:Ie?`/check${lt} --fix`:`/review${lt} --fix`,reason:""})}}}catch(G){u({kind:"note",tone:"error",text:`Write run failed: ${G.message}`})}finally{Re.current=null,ne(null),N(!1),Z(G=>G+1)}return}case"draft":{if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:d,looseDocs:m}=si(e);if(d.length===0&&m===0){u({kind:"note",tone:"info",text:li});return}let b=h.join(" ").trim();if(!b&&d.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
328
328
  ${d.map(T=>` \u2022 ${T.name} (${T.docCount} doc${T.docCount===1?"":"s"})`).join(`
329
- `)}`}),Je(d.map(T=>`/draft ${T.name}`));return}let y="",R;if(b){let T=si(d,b);T?y=T:R=b}else y=d[0]?.name??"";await ie(wo(y,R),{display:b?`/draft ${b}`:"/draft",quietUser:!0});return}case"pull":{if(!rr(l.trim()))return;let d=h.find(m=>m.startsWith("--"));try{if(d==="--status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let y=Date.now(),R=await Oc({cwd:e,profileName:i});u({kind:"note",tone:"info",text:ho(R,Date.now()-y).join(`
330
- `)});return}if(d==="--baseline"){let y=h.find(q=>!q.startsWith("--")),R=y?y.replace(/\\/g,"/"):void 0;u({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 T=await Yh({cwd:e,profileName:i,relPaths:R?[R]:void 0}),z=R?{rebaselined:[],skipped:[]}:await zh({cwd:e,profileName:i});if(T.baselined.length===0&&T.skipped.length===0&&z.rebaselined.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}T.baselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Baselined ${T.baselined.length} article${T.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),z.rebaselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${z.rebaselined.length} article${z.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),T.skipped.length>0&&u({kind:"note",tone:"warn",text:`${T.skipped.length} skipped:
329
+ `)}`}),Ze(d.map(T=>`/draft ${T.name}`));return}let y="",R;if(b){let T=ai(d,b);T?y=T:R=b}else y=d[0]?.name??"";await ie(ko(y,R),{display:b?`/draft ${b}`:"/draft",quietUser:!0});return}case"pull":{if(!ir(l.trim()))return;let d=h.find(m=>m.startsWith("--"));try{if(d==="--status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let y=Date.now(),R=await Mc({cwd:e,profileName:i});u({kind:"note",tone:"info",text:go(R,Date.now()-y).join(`
330
+ `)});return}if(d==="--baseline"){let y=h.find(q=>!q.startsWith("--")),R=y?y.replace(/\\/g,"/"):void 0;u({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 T=await zh({cwd:e,profileName:i,relPaths:R?[R]:void 0}),z=R?{rebaselined:[],skipped:[]}:await Kh({cwd:e,profileName:i});if(T.baselined.length===0&&T.skipped.length===0&&z.rebaselined.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}T.baselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Baselined ${T.baselined.length} article${T.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),z.rebaselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${z.rebaselined.length} article${z.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),T.skipped.length>0&&u({kind:"note",tone:"warn",text:`${T.skipped.length} skipped:
331
331
  ${T.skipped.map(q=>` - ${q.path} (${q.reason})`).join(`
332
- `)}`}),Z(q=>q+1);return}if(d==="--compare"){u({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let y=await Vh({cwd:e,profileName:i}),R=y.onlyInLegacy.length===0&&y.onlyInManifest.length===0&&y.mappedMissingFromManifest.length===0,T=[`Legacy listing: ${y.legacyCount} \xB7 Manifest: ${y.manifestCount} \xB7 in both: ${y.inBoth}`];R?T.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(y.mappedMissingFromManifest.length&&T.push(`\u2717 ${y.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${y.mappedMissingFromManifest.slice(0,5).join(", ")}`),y.onlyInLegacy.length&&T.push(`\u26A0 ${y.onlyInLegacy.length} only in the legacy listing: ${y.onlyInLegacy.slice(0,5).join(", ")}`),y.onlyInManifest.length&&T.push(`\u26A0 ${y.onlyInManifest.length} only in the manifest: ${y.onlyInManifest.slice(0,5).join(", ")}`),T.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),u({kind:"note",tone:R?"ok":"warn",text:T.join(`
333
- `)});return}if(d){u({kind:"note",tone:"error",text:`Unknown option: ${d} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=h[0];if(m){let y=await Gh({cwd:e,profileName:i,relPath:m.replace(/\\/g,"/")});je.current=[y],Hn();return}u({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let b=await Ur({cwd:e,profileName:i});for(let y of Wr(b))u({kind:"note",tone:y.tone,text:y.text});Z(y=>y+1)}catch(m){u({kind:"note",tone:"error",text:`Pull failed: ${m.message}`})}return}case"scope":{if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=Kh(e);if(d.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Pt({cursor:0,rows:d.map(m=>({...m,checked:m.recommended}))});return}case"audit":{if(h[0]==="--auto"){let m=ee(e);if(!m){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=h[1]!=="off";_c({...m,autoAudit:b},e),u({kind:"note",tone:"ok",text:b?"\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 d=await un();d.kind==="forward-to-agent"&&d.prompt&&await ie(d.prompt,{display:d.display,quietUser:!0});return}case"check":{let d=h.find(y=>!y.startsWith("--")),m=d?` ${d}`:"",b=Mc({cwd:e,scope:d});if(h.includes("--fix")){if(b.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}u({kind:"note",tone:"info",text:`Fixing ${b.length} doc issue${b.length===1?"":"s"}\u2026`}),await ie(Ei(b),{display:`/check${m} --fix`,quietUser:!0});let y=Mc({cwd:e,scope:d});u({kind:"note",tone:y.length===0?"ok":"warn",text:y.length===0?"\u2713 Doc-checker: all issues resolved.":Po(y).join(`
334
- `)}),Dt(y.length===0?`Deterministic issues fixed. Next: /review${m} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${m} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${m} --fix`,reason:""});return}u({kind:"note",tone:b.length===0?"ok":"warn",text:Po(b).join(`
335
- `)}),b.length>0&&Dt(`Found ${b.length} doc issue${b.length===1?"":"s"} above. /check${m} --fix has the agent fix them in place (or /review${m} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${m} --fix`,reason:""});return}case"structure":{let d=yn(e,i);if(d.length===0){u({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}u({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...d].join(`
336
- `)});return}case"reorder":{let d=Ni(e,h);if(!d){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ie(d.prompt,{display:d.display,quietUser:!0}),Dt("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let d=Ii(e,h);if(!d){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=h.includes("--fix");if(await ie(d.prompt,{display:d.display,quietUser:!0}),m)Dt("\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let b=h.filter(y=>y!=="--fix").join(" ");Dt(`The review listed issues above. /review${b?` ${b}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${b?` ${b}`:""} --fix`,reason:""})}return}case"capture-setup":{let d=await mn();d.kind==="forward-to-agent"&&d.prompt&&await ie(d.prompt,{display:d.display,quietUser:!0});let m=ki(e);m&&u({kind:"note",tone:"info",text:m.join(`
332
+ `)}`}),Z(q=>q+1);return}if(d==="--compare"){u({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let y=await Gh({cwd:e,profileName:i}),R=y.onlyInLegacy.length===0&&y.onlyInManifest.length===0&&y.mappedMissingFromManifest.length===0,T=[`Legacy listing: ${y.legacyCount} \xB7 Manifest: ${y.manifestCount} \xB7 in both: ${y.inBoth}`];R?T.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(y.mappedMissingFromManifest.length&&T.push(`\u2717 ${y.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${y.mappedMissingFromManifest.slice(0,5).join(", ")}`),y.onlyInLegacy.length&&T.push(`\u26A0 ${y.onlyInLegacy.length} only in the legacy listing: ${y.onlyInLegacy.slice(0,5).join(", ")}`),y.onlyInManifest.length&&T.push(`\u26A0 ${y.onlyInManifest.length} only in the manifest: ${y.onlyInManifest.slice(0,5).join(", ")}`),T.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),u({kind:"note",tone:R?"ok":"warn",text:T.join(`
333
+ `)});return}if(d){u({kind:"note",tone:"error",text:`Unknown option: ${d} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=h[0];if(m){let y=await Yh({cwd:e,profileName:i,relPath:m.replace(/\\/g,"/")});je.current=[y],qn();return}u({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let b=await Wr({cwd:e,profileName:i});for(let y of Fr(b))u({kind:"note",tone:y.tone,text:y.text});Z(y=>y+1)}catch(m){u({kind:"note",tone:"error",text:`Pull failed: ${m.message}`})}return}case"scope":{if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=Xh(e);if(d.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Pt({cursor:0,rows:d.map(m=>({...m,checked:m.recommended}))});return}case"audit":{if(h[0]==="--auto"){let m=ee(e);if(!m){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=h[1]!=="off";Lc({...m,autoAudit:b},e),u({kind:"note",tone:"ok",text:b?"\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 d=await pn();d.kind==="forward-to-agent"&&d.prompt&&await ie(d.prompt,{display:d.display,quietUser:!0});return}case"check":{let d=h.find(y=>!y.startsWith("--")),m=d?` ${d}`:"",b=Uc({cwd:e,scope:d});if(h.includes("--fix")){if(b.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}u({kind:"note",tone:"info",text:`Fixing ${b.length} doc issue${b.length===1?"":"s"}\u2026`}),await ie(Ii(b),{display:`/check${m} --fix`,quietUser:!0});let y=Uc({cwd:e,scope:d});u({kind:"note",tone:y.length===0?"ok":"warn",text:y.length===0?"\u2713 Doc-checker: all issues resolved.":To(y).join(`
334
+ `)}),Dt(y.length===0?`Deterministic issues fixed. Next: /review${m} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${m} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${m} --fix`,reason:""});return}u({kind:"note",tone:b.length===0?"ok":"warn",text:To(b).join(`
335
+ `)}),b.length>0&&Dt(`Found ${b.length} doc issue${b.length===1?"":"s"} above. /check${m} --fix has the agent fix them in place (or /review${m} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${m} --fix`,reason:""});return}case"structure":{let d=wn(e,i);if(d.length===0){u({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}u({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...d].join(`
336
+ `)});return}case"reorder":{let d=_i(e,h);if(!d){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ie(d.prompt,{display:d.display,quietUser:!0}),Dt("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let d=Ni(e,h);if(!d){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=h.includes("--fix");if(await ie(d.prompt,{display:d.display,quietUser:!0}),m)Dt("\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let b=h.filter(y=>y!=="--fix").join(" ");Dt(`The review listed issues above. /review${b?` ${b}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${b?` ${b}`:""} --fix`,reason:""})}return}case"capture-setup":{let d=await hn();d.kind==="forward-to-agent"&&d.prompt&&await ie(d.prompt,{display:d.display,quietUser:!0});let m=bi(e);m&&u({kind:"note",tone:"info",text:m.join(`
337
337
  `)});return}case"devhints":{if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:Ut(Mt(e)).join(`
338
- `)}),jt(dt()),Qt.current=Se(e).status==="current"||Oe(e);return}case"inbox":{if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(bi(e)===0){u({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 ie(xi(),{display:"/inbox",quietUser:!0});return}case"document":{if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:d,what:m}=ci(h);if(!m&&li(e)===0){u({kind:"note",tone:"info",text:ui});return}let b=`/document${m?` ${m}`:""}${d?" --publish":""}`;await ie(di(m,d),{display:b,quietUser:!0});return}case"catch-up":{if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!rr(l.trim()))return;let{publish:d}=vi(h);u({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let m=await Ri({cwd:e,profileName:i});for(let y of Pi(m))u({kind:"note",tone:y.startsWith("\u2713")?"ok":y.startsWith("\u2139")?"info":"warn",text:y});let b=gn(hn(e));u({kind:"note",tone:"info",text:b?`Catching up on ${b}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ie(Ci({publish:d}),{display:`/catch-up${d?" --publish":""}`,quietUser:!0});return}case"update":{nr.current=!0,u({kind:"note",tone:"info",text:`Updating ${ft}\u2026 (don\u2019t close this window)`}),Sn(!0),(await Co().finally(()=>Sn(!1))).ok?(u({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),Y("/exit"),ds("")):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${vo}`});return}case"screenshot":{let d=gi(h);if(d.mode==="list"){if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:wi(yi(e,d.scope),d.scope).join(`
339
- `)});return}if(d.mode==="single"){let M=await xo(h);M.kind==="forward-to-agent"&&M.prompt&&await ie(M.prompt,{display:M.display,quietUser:!0});return}if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=d.mode==="scope"?d.scope:void 0,b=Zh(e,{scope:m}).map(M=>M.id);if(b.length===0){u({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let y=6,R=Jh(b,3),T=Bo(e,"standard");Ze.current=Date.now(),gt(0),N(!0);let z=new AbortController;Ce.current=z,ne({verb:"Authoring",unit:"spec",total:R.length,done:0,active:[],rows:bn(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${b.length} screenshot spec${b.length===1?"":"s"} across ${R.length} partition${R.length===1?"":"s"} (\u2264${y} agents at once) on ${T.model}${T.forced?" (forced)":""}\u2026 (esc to stop)`});let q=!1;try{for await(let M of qo({cwd:e,partitions:R,promptFor:vl,concurrency:y,profileName:i,allowProdWrites:bt.current,model:T.model,signal:z.signal}))if(M.type==="partition_status")M.status==="running"?ne(v=>v&&{...v,active:[...v.active,M.label],rows:Ue(v.rows,M.label,"active"),lastAt:Date.now()}):ne(v=>v&&{...v,active:v.active.filter(A=>A!==M.label),done:v.done+1,rows:Ue(v.rows,M.label,M.status==="done"?"done":"failed"),lastAt:Date.now()});else if(M.type==="partition_event")ne(v=>{if(!v)return v;let A={...v,lastAt:Date.now()};return M.event.type==="tool"?A.tools=v.tools+1:M.event.type==="text"&&(A.chars=v.chars+M.event.delta.length),A});else if(M.type==="run_done"){St(X=>X+M.totalCostUsd),Tt(X=>X+M.results.reduce((Et,It)=>Et+It.outputTokens,0));let v=M.results.filter(X=>X.ok).length,A=M.aborted?"Stopped. ":"";q=!M.aborted&&d.setup;let H=M.aborted?"":q?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";u({kind:"note",tone:M.aborted?"warn":M.ok?"ok":"warn",text:`${A}Authored specs \u2014 ${v}/${M.results.length} batches ok.${H}`})}}catch(M){u({kind:"note",tone:"error",text:`Spec authoring failed: ${M.message}`})}finally{Ce.current=null,ne(null),N(!1),Z(M=>M+1)}if(q){let M=await mn();M.kind==="forward-to-agent"&&M.prompt&&await ie(M.prompt,{display:M.display,quietUser:!0});let v=ki(e);v&&u({kind:"note",tone:"info",text:v.join(`
340
- `)})}return}case"reset":{let d=Di(e);if(d.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}An.current={repoName:$n(e),targets:d,hadDevhints:xn(Wc(e))},u({kind:"note",tone:"warn",text:Ai(e,d).join(`
341
- `)}),fe($n(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${s} \u2014 type /help.`})}},[e,r,i,Hn,u,ge,ie,Mn,cr,Ps]),Bn=V(l=>{let a=(l??D).trim();if(x(""),Dn(null),yt(0),a.startsWith("/")&&(Rn.current=!1,qe(),Gt(null),Je(h=>vc(h,a))),!a||(cs(!1),Ss(a))||Ts(a))return;Xo.current.push(a);let s=Tc(a,us.current);if(a.startsWith("/"))u({kind:"user",text:a}),qn(s);else if(cg(s)){u({kind:"user",text:a});let h=dg(s);if(!h)ie(s,{display:a,quietUser:!0});else{try{ug(e,{title:h,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ie(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${h}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${h}" and the article path(s) you wrote.`,{display:a,quietUser:!0})}}else ie(s,{display:a})},[D,Ss,Ts,qn,ie]),Ds=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let a=Cc(l);if(Rc(a)){let s=Pc(++sd.current,a);us.current.set(s,a),P(s)}else P(a);return}P(l)},[P]),At=Math.max(10,Ee-6),js=Ji(()=>Fo(w.text,At),[w.text,At]),pr=V(l=>k(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+l))})),[]),Vn=V(l=>k(a=>({...a,pos:Dc(Fo(a.text,At),a.pos,l)})),[At]),tn=V(l=>k(a=>({...a,pos:jc(Fo(a.text,At),a.pos,l)})),[At]),dd=["\x1B[H","\x1B[1~","\x1BOH"],ud=["\x1B[F","\x1B[4~","\x1BOF"],As=V((l,a)=>a.leftArrow?(pr(-1),!0):a.rightArrow?(pr(1),!0):l&&dd.includes(l)?(tn("start"),!0):l&&ud.includes(l)?(tn("end"),!0):a.ctrl&&l==="a"?(tn("start"),!0):a.ctrl&&l==="e"?(tn("end"),!0):!1,[pr,tn]);return $h((l,a)=>{if(a.ctrl&&l==="c"){xe.current?.close(),r();return}if(!O){if(S){if(a.escape){if(Ce.current){if(!Ce.current.signal.aborted){let s=(En?.verb??"work").toLowerCase(),h=En?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${s} run (finishing in-flight ${h}s)\u2026`}),Ce.current.abort()}return}Yt.current||(Yt.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),xe.current?.interrupt());return}if(a.return){let s=D.trim();if(!s)return;st.current.push(s),Jo([...st.current]),x("");return}if(As(l,a))return;if(a.upArrow){Vn(-1);return}if(a.downArrow){Vn(1);return}if(a.backspace||a.delete){C();return}l&&!a.ctrl&&!a.meta&&Ds(l);return}if(tt){if(a.upArrow){nt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){nt(s=>s&&{...s,cursor:Math.min(Ne.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ne.length){nt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Ne[tt.cursor];nt(null);let{lines:h,changed:d,effective:m}=pn(e,s.value??"default");for(let b of h)u({kind:"note",tone:b.startsWith("\u26A0")?"warn":b.startsWith("\u2713")?"ok":"info",text:b});d&&(ks(b=>b+1),xe.current?.setModel(m));return}if(l==="s"){let s=Ne[tt.cursor];nt(null),xe.current?.setModel(s.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${s.label} for this session only (your saved default is unchanged).`});return}if(a.escape){nt(null);return}return}if(Le){if(a.upArrow){xt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){xt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Le.rows.length){xt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return||l==="s"){let s=Le.rows[Le.cursor];xt(null),ur(s.name,a.return===!0);return}if(a.escape){xt(null);return}return}if(Zo){if(a.escape){Kt(null);return}if(a.leftArrow||a.tab&&a.shift){Kt(s=>s&&{tab:(s.tab-1+Te.length)%Te.length});return}if(a.rightArrow||a.tab){Kt(s=>s&&{tab:(s.tab+1)%Te.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Te.length){Kt({tab:Number(l)-1});return}return}if(We){if(a.upArrow){$t(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){$t(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=We.rows.length){$t(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=We.rows[We.cursor].name;if($t(null),!xr(e,s).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${s}").`});let d=!1;try{let m=ht(s);d=!!m&&!(Xe(m)&&!m.refreshToken)}catch{d=!1}u({kind:"note",tone:"info",text:d?`Next: sign in to ${s} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${s}) and pick your project.`}),Y("/login"),Z(m=>m+1);return}if(a.escape){$t(null);return}return}if(pe){if(a.upArrow){vt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){vt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=pe.rows.length){vt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=pe.rows[pe.cursor],{profile:h,projectId:d}=pe;vt(null),Un(h,d,s);return}if(a.escape){vt(null);return}return}if($e){if(a.upArrow){ot(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){ot(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=$e.rows.length){ot(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=$e.rows[$e.cursor],{profile:h}=$e;ot(null),Fn(h,s);return}if(a.escape){ot(null);return}return}if(he){if(a.upArrow){Pt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Pt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l===" "){Pt(s=>s&&{...s,rows:s.rows.map((h,d)=>d===s.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let s=he.rows.filter(h=>h.checked).map(h=>h.path);if(Pt(null),s.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Lr(e,s),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${s.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of s)u({kind:"note",tone:"info",text:` ${h}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){Pt(null);return}return}if(Fe){if(a.upArrow){Rt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Rt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Fe.rows.length){Rt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Fe.rows[Fe.cursor],h=Fe.run;Rt(null),h(s.token);return}if(a.escape){Rt(null);return}return}if(rt){if(a.upArrow){Ct(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Ct(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=rt.rows.length){Ct(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=rt.rows[rt.cursor];Ct(null),s.kind==="article"?cr(s.paths[0]):Mn(s.paths);return}if(a.escape){Ct(null);return}return}if(ve){if(a.escape){it(null);return}if(a.upArrow){it(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){it(s=>s&&{...s,cursor:Math.min(Math.max(0,Ln.length-1),s.cursor+1)});return}if(a.return){let s=Ln[ve.cursor];if(s){it(null);try{u({kind:"preview",name:$n(s),text:Yc(Zi(es(e,s),"utf8"))})}catch(h){u({kind:"note",tone:"error",text:`Could not read ${s}: ${h.message}`})}}return}if(a.backspace||a.delete){it(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){it(s=>s&&{...s,query:s.query+l,cursor:0});return}return}if(Re){if(a.escape){at(null);return}if(a.upArrow){at(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){at(s=>s&&{...s,cursor:Math.min(Math.max(0,On.length-1),s.cursor+1)});return}if(a.return){let s=On[Re.cursor];if(s){at(null),ge(s.uuid),_e.current={uuid:s.uuid,firstPrompt:s.firstPrompt,titleFired:!0},et(s.name),ts(s.uuid),kt.current=[];let h=Ki(e,s.uuid);for(let d of h)u(d);u({kind:"note",tone:"ok",text:h.length?`Resumed "${s.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${s.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){at(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){at(s=>s&&{...s,query:s.query+l,cursor:0});return}return}if(a.tab&&!D&&de){x(de),qe();return}if(!D&&Qe.length>0&&!zo&&l&&/^[1-9]$/.test(l)){let s=Qe[Number(l)-1];if(s){x(mt(s));return}}if(!D&&(ir||Xt)&&l==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let s=ir!=null;sc(ir??Xt).then(d=>{u({kind:"note",tone:d?"ok":"warn",text:d?s?"\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.":s?"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."}),d&&s&&sr(null),d&&!s&&$s(!0)});return}if(!As(l,a)){if(Cs){if(a.upArrow){yt(s=>Math.max(0,s-1));return}if(a.downArrow){yt(s=>Math.min(en.length-1,s+1));return}if(a.tab){x("/"+(en[Vt]?.name??"")+" "),yt(0);return}if(a.return){let s=en[Vt];if(s){let h=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(hc(s.usage)&&!h){x("/"+s.name+" "),yt(0);return}Bn("/"+s.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(D!==""&&wt===null){Vn(-1);return}let s=Xo.current;if(!s.length)return;let h=wt===null?s.length-1:Math.max(0,wt-1);Dn(h),x(s[h]??"");return}if(a.downArrow){if(D!==""&&wt===null){Vn(1);return}let s=Xo.current;if(wt===null)return;let h=wt+1;h>=s.length?(Dn(null),x("")):(Dn(h),x(s[h]??""));return}}if(a.return){Bn();return}if(a.backspace||a.delete){C();return}if(a.escape){x(""),yt(0),qe(),Je([]),Gt(null),Rn.current=!0;return}l&&!a.ctrl&&!a.meta&&Ds(l)}}}),be(()=>{if(S||O)return;let l=st.current.shift();l!==void 0&&(Jo([...st.current]),Bn(l))},[S,O,Bn]),B(te,{flexDirection:"column",width:Ee,children:[lr!==null&&B(te,{marginTop:1,flexDirection:"column",children:[lr.truncated&&E(j,{dimColor:!0,children:"\u2026"}),E(j,{children:lr.text})]}),S&&(En?E(xg,{p:En}):E(wg,{startTime:Ze.current,chars:id})),!S&&hs?E(kg,{text:hs}):null,E(te,{borderStyle:"round",borderColor:vs.prod?"yellow":F,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?js.map((l,a)=>{let s=w.text.slice(l.start,l.end),h=a===Ho(js,w.pos),d=Math.min(w.pos,l.end)-l.start;return B(j,{children:[E(j,{color:F,children:a===0?"> ":" "}),h?B(Vo,{children:[s.slice(0,d),E(vn,{ch:s[d]??" "}),s.slice(d+1)]}):s||" "]},`${a}-${l.start}`)}):B(j,{children:[E(j,{color:F,children:"> "}),de&&!S&&Go?B(Vo,{children:[E(vn,{ch:Go[0],dim:!0}),E(j,{color:"gray",children:Go.slice(1)})]}):de&&!S?B(Vo,{children:[E(vn,{ch:de[0],dim:!0}),E(j,{color:"gray",children:de.slice(1)}),E(j,{dimColor:!0,children:" (tab)"})]}):(ar.isSetup||!od)&&!S?B(Vo,{children:[E(vn,{ch:ar.text[0],dim:!0}),E(j,{color:"gray",children:ar.text.slice(1)})]}):E(vn,{ch:" "})]})}),ms.length>0&&E(te,{flexDirection:"column",paddingX:1,children:ms.map((l,a)=>E(j,{color:"gray",children:`\u29D7 queued: ${l}`},`${a}-${l.slice(0,24)}`))}),Zo?E(yc,{tab:Zo.tab,width:Ee}):tt?B(te,{flexDirection:"column",paddingX:1,children:[E(j,{color:F,bold:!0,children:"Select model"}),E(j,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ne.map((l,a)=>B(j,{color:a===tt.cursor?F:void 0,children:[a===tt.cursor?"\u276F ":" ",`${a+1}. ${l.label}${a===tt.current?" \u2714":""}`.padEnd(16),E(j,{color:"gray",children:l.desc})]},l.label)),E(j,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Le?B(te,{flexDirection:"column",paddingX:1,children:[E(j,{color:F,bold:!0,children:"Switch connection profile"}),Le.rows.map((l,a)=>B(j,{color:a===Le.cursor?F:void 0,children:[a===Le.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===Le.current?" \u2714":""}`.padEnd(20),E(j,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?E(j,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),E(j,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):We?B(te,{flexDirection:"column",paddingX:1,children:[E(j,{color:F,bold:!0,children:"Pick your Document360 environment"}),We.rows.map((l,a)=>B(j,{color:a===We.cursor?F:void 0,children:[a===We.cursor?"\u276F ":" ",`${a+1}. ${l.name}`.padEnd(16),E(j,{color:"gray",children:l.apiUrl})]},l.name)),E(j,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):pe?B(te,{flexDirection:"column",paddingX:1,children:[E(j,{color:F,bold:!0,children:"Switch workspace"}),E(j,{dimColor:!0,children:`environment ${pe.environment} \xB7 project ${pe.projectName??`${pe.projectId.slice(0,8)}\u2026`}`}),pe.rows.map((l,a)=>B(j,{color:a===pe.cursor?F:void 0,children:[a===pe.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===pe.current?" \u2714":""}`.padEnd(30),E(j,{color:"gray",children:l.type??""})]},l.id)),E(j,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):$e?B(te,{flexDirection:"column",paddingX:1,children:[E(j,{color:F,bold:!0,children:"Choose project"}),E(j,{dimColor:!0,children:`environment ${$e.environment}`}),$e.rows.map((l,a)=>B(j,{color:a===$e.cursor?F:void 0,children:[a===$e.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===$e.current?" \u2714":""}`.padEnd(30),E(j,{color:"gray",children:l.sub??""})]},l.id)),E(j,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):he?(()=>{let a=Math.min(Math.max(0,he.cursor-Math.floor(7)),Math.max(0,he.rows.length-14)),s=he.rows.slice(a,a+14),h=he.rows.filter(d=>d.checked).length;return B(te,{flexDirection:"column",paddingX:1,children:[E(j,{color:F,bold:!0,children:`Which folders back the user docs? (${h} selected of ${he.rows.length})`}),a>0?E(j,{dimColor:!0,children:` \u2191 ${a} more`}):null,s.map((d,m)=>{let b=a+m;return B(j,{color:b===he.cursor?F:void 0,children:[b===he.cursor?"\u276F ":" ",d.checked?"\u25C9 ":"\u25CB ",d.path.padEnd(Math.min(48,Ee-34)),E(j,{color:"gray",children:mo(d)})]},d.path)}),a+14<he.rows.length?E(j,{dimColor:!0,children:` \u2193 ${he.rows.length-a-14} more`}):null,E(j,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Fe?B(te,{flexDirection:"column",paddingX:1,children:[E(j,{color:F,bold:!0,children:"Which category? (pick one to scope to)"}),Fe.rows.map((l,a)=>{let s=a===Fe.cursor,h=`${a+1}.`.padEnd(3);return B(j,{color:s?F:void 0,children:[s?"\u276F ":" ",`${h} ${l.label} (${l.count})`.padEnd(Math.min(44,Math.max(20,Ee-24))),E(j,{color:"gray",children:` ${l.token}`})]},l.token)}),E(j,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):rt?B(te,{flexDirection:"column",paddingX:1,children:[E(j,{color:F,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),rt.rows.map((l,a)=>{let s=a===rt.cursor,h=l.indent?" ":" ",d=`${a+1}.`.padEnd(3);return B(j,{color:s?F:void 0,bold:l.kind==="category"&&!s,children:[s?"\u276F ":" ",`${h}${d} ${l.label}`.padEnd(Math.min(56,Ee-24)),l.note?E(j,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),E(j,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ve?B(te,{flexDirection:"column",paddingX:1,children:[E(j,{color:F,bold:!0,children:`Preview article${ve.query?` \u2014 filter: ${ve.query}`:" (type to filter)"}`}),Ln.length===0?E(j,{color:"gray",children:"no articles match"}):Ln.map((l,a)=>B(j,{color:a===ve.cursor?F:void 0,children:[a===ve.cursor?"\u276F ":" ",l]},l)),E(j,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Re?B(te,{flexDirection:"column",paddingX:1,children:[E(j,{color:F,bold:!0,children:`Resume session${Re.query?` \u2014 filter: ${Re.query}`:" (type to filter)"}`}),On.length===0?E(j,{color:"gray",children:"no sessions match"}):On.map((l,a)=>B(j,{color:a===Re.cursor?F:void 0,children:[a===Re.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),E(j,{color:a===Re.cursor?F:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ee-40))})]},l.uuid)),E(j,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Cs?B(te,{flexDirection:"column",children:[en.map((l,a)=>B(j,{color:a===Vt?F:void 0,children:[a===Vt?"\u276F ":" ",l.usage.padEnd(22)," ",E(j,{color:a===Vt?F:"gray",children:l.name==="model"&&er?`${l.desc} (currently ${er})`:l.desc})]},l.name)),E(j,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!S&&!D&&Qe.length>0?B(te,{flexDirection:"column",paddingX:1,children:[fs?E(j,{color:F,children:fs}):null,Qe.map((l,a)=>{let s=mt(l),h=s.slice(0,Math.max(20,Ee-5)),d=Ee-h.length-7,m=d>=12?($c(l)??fc(s)).slice(0,d):"";return B(j,{children:[E(j,{color:F,children:a+1})," ",h,m?E(j,{dimColor:!0,children:` \u2014 ${m}`}):null]},s)}),E(j,{dimColor:!0,children:`press 1-${Qe.length} to fill \xB7 esc cancel`})]}):E(te,{paddingX:1,children:B(j,{color:"gray",children:[vs.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${er??"model n/a"}${t.kind==="api"?ws>0?` \xB7 ${me(ws)}`:"":ys>0?` \xB7 ${ze(ys)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}U();import{jsx as Rg}from"react/jsx-runtime";async function Xc(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Cg(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:i}=vg(Rg(Kc,{cwd:e,auth:r,profileName:n,version:o}));await i(),process.stdout.write(`
342
- `),process.exit(0)}U();import{writeCrashLog as Qc,isBenignTransportError as Pg}from"document360-engine";var Jc=!1;function is(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Zc(e){if(Jc)return;Jc=!0;let t=(n,o)=>{if(Pg(o)){Qc({kind:n,level:"transport",message:is(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=Qc({kind:n,level:"fatal",message:is(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
343
- `+$(`\u2717 d360-writer crashed: ${is(o)}`)+`
338
+ `)}),jt(dt()),Jt.current=Se(e).status==="current"||Ue(e);return}case"inbox":{if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(xi(e)===0){u({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 ie($i(),{display:"/inbox",quietUser:!0});return}case"document":{if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:d,what:m}=di(h);if(!m&&ci(e)===0){u({kind:"note",tone:"info",text:pi});return}let b=`/document${m?` ${m}`:""}${d?" --publish":""}`;await ie(ui(m,d),{display:b,quietUser:!0});return}case"catch-up":{if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!ir(l.trim()))return;let{publish:d}=Ci(h);u({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let m=await Pi({cwd:e,profileName:i});for(let y of Ti(m))u({kind:"note",tone:y.startsWith("\u2713")?"ok":y.startsWith("\u2139")?"info":"warn",text:y});let b=yn(gn(e));u({kind:"note",tone:"info",text:b?`Catching up on ${b}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ie(Ri({publish:d}),{display:`/catch-up${d?" --publish":""}`,quietUser:!0});return}case"update":{or.current=!0,u({kind:"note",tone:"info",text:`Updating ${ft}\u2026 (don\u2019t close this window)`}),Sn(!0),(await Ro().finally(()=>Sn(!1))).ok?(u({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),Y("/exit"),us("")):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Co}`});return}case"screenshot":{let d=yi(h);if(d.mode==="list"){if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:ki(wi(e,d.scope),d.scope).join(`
339
+ `)});return}if(d.mode==="single"){let M=await $o(h);M.kind==="forward-to-agent"&&M.prompt&&await ie(M.prompt,{display:M.display,quietUser:!0});return}if(!ee(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=d.mode==="scope"?d.scope:void 0,b=eg(e,{scope:m}).map(M=>M.id);if(b.length===0){u({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let y=6,R=Zh(b,3),T=Vo(e,"standard");et.current=Date.now(),gt(0),N(!0);let z=new AbortController;Re.current=z,ne({verb:"Authoring",unit:"spec",total:R.length,done:0,active:[],rows:xn(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${b.length} screenshot spec${b.length===1?"":"s"} across ${R.length} partition${R.length===1?"":"s"} (\u2264${y} agents at once) on ${T.model}${T.forced?" (forced)":""}\u2026 (esc to stop)`});let q=!1;try{for await(let M of Bo({cwd:e,partitions:R,promptFor:Cl,concurrency:y,profileName:i,allowProdWrites:bt.current,model:T.model,signal:z.signal}))if(M.type==="partition_status")M.status==="running"?ne(v=>v&&{...v,active:[...v.active,M.label],rows:Fe(v.rows,M.label,"active"),lastAt:Date.now()}):ne(v=>v&&{...v,active:v.active.filter(E=>E!==M.label),done:v.done+1,rows:Fe(v.rows,M.label,M.status==="done"?"done":"failed"),lastAt:Date.now()});else if(M.type==="partition_event")ne(v=>{if(!v)return v;let E={...v,lastAt:Date.now()};return M.event.type==="tool"?E.tools=v.tools+1:M.event.type==="text"&&(E.chars=v.chars+M.event.delta.length),E});else if(M.type==="run_done"){St(X=>X+M.totalCostUsd),Tt(X=>X+M.results.reduce((Et,It)=>Et+It.outputTokens,0));let v=M.results.filter(X=>X.ok).length,E=M.aborted?"Stopped. ":"";q=!M.aborted&&d.setup;let H=M.aborted?"":q?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";u({kind:"note",tone:M.aborted?"warn":M.ok?"ok":"warn",text:`${E}Authored specs \u2014 ${v}/${M.results.length} batches ok.${H}`})}}catch(M){u({kind:"note",tone:"error",text:`Spec authoring failed: ${M.message}`})}finally{Re.current=null,ne(null),N(!1),Z(M=>M+1)}if(q){let M=await hn();M.kind==="forward-to-agent"&&M.prompt&&await ie(M.prompt,{display:M.display,quietUser:!0});let v=bi(e);v&&u({kind:"note",tone:"info",text:v.join(`
340
+ `)})}return}case"reset":{let d=ji(e);if(d.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}An.current={repoName:vn(e),targets:d,hadDevhints:$n(Fc(e))},u({kind:"note",tone:"warn",text:Ei(e,d).join(`
341
+ `)}),me(vn(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${s} \u2014 type /help.`})}},[e,r,i,qn,u,ke,ie,Un,dr,Ts]),Vn=V(l=>{let a=(l??D).trim();if(x(""),Dn(null),yt(0),a.startsWith("/")&&(Rn.current=!1,Be(),Yt(null),Ze(h=>Cc(h,a))),!a||(ds(!1),Ds(a))||Ss(a))return;Qo.current.push(a);let s=Sc(a,ps.current);if(a.startsWith("/"))u({kind:"user",text:a}),Bn(s);else if(dg(s)){u({kind:"user",text:a});let h=ug(s);if(!h)ie(s,{display:a,quietUser:!0});else{try{pg(e,{title:h,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ie(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${h}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${h}" and the article path(s) you wrote.`,{display:a,quietUser:!0})}}else ie(s,{display:a})},[D,Ds,Ss,Bn,ie]),js=V(l=>{if(l.length>1){if(l.includes("\x1B"))return;let a=Rc(l);if(Pc(a)){let s=Tc(++ad.current,a);ps.current.set(s,a),P(s)}else P(a);return}P(l)},[P]),At=Math.max(10,Ee-6),As=Zi(()=>Ho(w.text,At),[w.text,At]),fr=V(l=>k(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+l))})),[]),Gn=V(l=>k(a=>({...a,pos:jc(Ho(a.text,At),a.pos,l)})),[At]),nn=V(l=>k(a=>({...a,pos:Ac(Ho(a.text,At),a.pos,l)})),[At]),ud=["\x1B[H","\x1B[1~","\x1BOH"],pd=["\x1B[F","\x1B[4~","\x1BOF"],Es=V((l,a)=>a.leftArrow?(fr(-1),!0):a.rightArrow?(fr(1),!0):l&&ud.includes(l)?(nn("start"),!0):l&&pd.includes(l)?(nn("end"),!0):a.ctrl&&l==="a"?(nn("start"),!0):a.ctrl&&l==="e"?(nn("end"),!0):!1,[fr,nn]);return vh((l,a)=>{if(a.ctrl&&l==="c"){Ce.current?.close(),r();return}if(!O){if(S){if(a.escape){if(Re.current){if(!Re.current.signal.aborted){let s=(En?.verb??"work").toLowerCase(),h=En?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${s} run (finishing in-flight ${h}s)\u2026`}),Re.current.abort()}return}zt.current||(zt.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Ce.current?.interrupt());return}if(a.return){let s=D.trim();if(!s)return;st.current.push(s),Zo([...st.current]),x("");return}if(Es(l,a))return;if(a.upArrow){Gn(-1);return}if(a.downArrow){Gn(1);return}if(a.backspace||a.delete){C();return}l&&!a.ctrl&&!a.meta&&js(l);return}if(nt){if(a.upArrow){ot(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){ot(s=>s&&{...s,cursor:Math.min(Ne.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ne.length){ot(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Ne[nt.cursor];ot(null);let{lines:h,changed:d,effective:m}=fn(e,s.value??"default");for(let b of h)u({kind:"note",tone:b.startsWith("\u26A0")?"warn":b.startsWith("\u2713")?"ok":"info",text:b});d&&(bs(b=>b+1),Ce.current?.setModel(m));return}if(l==="s"){let s=Ne[nt.cursor];ot(null),Ce.current?.setModel(s.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${s.label} for this session only (your saved default is unchanged).`});return}if(a.escape){ot(null);return}return}if(Le){if(a.upArrow){xt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){xt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Le.rows.length){xt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return||l==="s"){let s=Le.rows[Le.cursor];xt(null),pr(s.name,a.return===!0);return}if(a.escape){xt(null);return}return}if(_n){if(a.escape){Xt(null);return}if(a.leftArrow||a.tab&&a.shift){Xt(s=>s&&{tab:(s.tab-1+Te.length)%Te.length});return}if(a.rightArrow||a.tab){Xt(s=>s&&{tab:(s.tab+1)%Te.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Te.length){Xt({tab:Number(l)-1});return}return}if(Oe){if(a.upArrow){$t(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){$t(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Oe.rows.length){$t(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Oe.rows[Oe.cursor].name;if($t(null),!$r(e,s).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${s}").`});let d=!1;try{let m=ht(s);d=!!m&&!(Qe(m)&&!m.refreshToken)}catch{d=!1}u({kind:"note",tone:"info",text:d?`Next: sign in to ${s} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${s}) and pick your project.`}),Y("/login"),Z(m=>m+1);return}if(a.escape){$t(null);return}return}if(pe){if(a.upArrow){vt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){vt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=pe.rows.length){vt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=pe.rows[pe.cursor],{profile:h,projectId:d}=pe;vt(null),Wn(h,d,s);return}if(a.escape){vt(null);return}return}if(ge){if(a.upArrow){rt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){rt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ge.rows.length){rt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=ge.rows[ge.cursor],{profile:h}=ge;rt(null),Hn(h,s);return}if(a.escape){rt(null);return}return}if(fe){if(a.upArrow){Pt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Pt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l===" "){Pt(s=>s&&{...s,rows:s.rows.map((h,d)=>d===s.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let s=fe.rows.filter(h=>h.checked).map(h=>h.path);if(Pt(null),s.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Or(e,s),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${s.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of s)u({kind:"note",tone:"info",text:` ${h}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){Pt(null);return}return}if(Me){if(a.upArrow){Rt(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Rt(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Me.rows.length){Rt(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=Me.rows[Me.cursor],h=Me.run;Rt(null),h(s.token);return}if(a.escape){Rt(null);return}return}if(He){if(a.upArrow){Ct(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){Ct(s=>s&&{...s,cursor:Math.min(s.rows.length-1,s.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=He.rows.length){Ct(s=>s&&{...s,cursor:Number(l)-1});return}if(a.return){let s=He.rows[He.cursor];Ct(null),s.kind==="article"?dr(s.paths[0]):Un(s.paths);return}if(a.escape){Ct(null);return}return}if(ye){if(a.escape){it(null);return}if(a.upArrow){it(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){it(s=>s&&{...s,cursor:Math.min(Math.max(0,On.length-1),s.cursor+1)});return}if(a.return){let s=On[ye.cursor];if(s){it(null);try{u({kind:"preview",name:vn(s),text:zc(es(ts(e,s),"utf8"))})}catch(h){u({kind:"note",tone:"error",text:`Could not read ${s}: ${h.message}`})}}return}if(a.backspace||a.delete){it(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){it(s=>s&&{...s,query:s.query+l,cursor:0});return}return}if(we){if(a.escape){at(null);return}if(a.upArrow){at(s=>s&&{...s,cursor:Math.max(0,s.cursor-1)});return}if(a.downArrow){at(s=>s&&{...s,cursor:Math.min(Math.max(0,Mn.length-1),s.cursor+1)});return}if(a.return){let s=Mn[we.cursor];if(s){at(null),ke(s.uuid),_e.current={uuid:s.uuid,firstPrompt:s.firstPrompt,titleFired:!0},tt(s.name),ns(s.uuid),kt.current=[];let h=Xi(e,s.uuid);for(let d of h)u(d);u({kind:"note",tone:"ok",text:h.length?`Resumed "${s.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${s.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){at(s=>s&&{...s,query:s.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){at(s=>s&&{...s,query:s.query+l,cursor:0});return}return}if(a.tab&&!D&&de){x(de),Be();return}if(!D&&Je.length>0&&!Ko&&l&&/^[1-9]$/.test(l)){let s=Je[Number(l)-1];if(s){x(mt(s));return}}if(!D&&(sr||Qt)&&l==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let s=sr!=null;ac(sr??Qt).then(d=>{u({kind:"note",tone:d?"ok":"warn",text:d?s?"\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.":s?"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."}),d&&s&&ar(null),d&&!s&&vs(!0)});return}if(!Es(l,a)){if(Rs){if(a.upArrow){yt(s=>Math.max(0,s-1));return}if(a.downArrow){yt(s=>Math.min(tn.length-1,s+1));return}if(a.tab){x("/"+(tn[Gt]?.name??"")+" "),yt(0);return}if(a.return){let s=tn[Gt];if(s){let h=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(gc(s.usage)&&!h){x("/"+s.name+" "),yt(0);return}Vn("/"+s.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(D!==""&&wt===null){Gn(-1);return}let s=Qo.current;if(!s.length)return;let h=wt===null?s.length-1:Math.max(0,wt-1);Dn(h),x(s[h]??"");return}if(a.downArrow){if(D!==""&&wt===null){Gn(1);return}let s=Qo.current;if(wt===null)return;let h=wt+1;h>=s.length?(Dn(null),x("")):(Dn(h),x(s[h]??""));return}}if(a.return){Vn();return}if(a.backspace||a.delete){C();return}if(a.escape){x(""),yt(0),Be(),Ze([]),Yt(null),Rn.current=!0;return}l&&!a.ctrl&&!a.meta&&js(l)}}}),ve(()=>{if(S||O)return;let l=st.current.shift();l!==void 0&&(Zo([...st.current]),Vn(l))},[S,O,Vn]),B(te,{flexDirection:"column",width:Ee,children:[cr!==null&&B(te,{marginTop:1,flexDirection:"column",children:[cr.truncated&&A(j,{dimColor:!0,children:"\u2026"}),A(j,{children:cr.text})]}),S&&(En?A($g,{p:En}):A(kg,{startTime:et.current,chars:sd})),!S&&gs?A(bg,{text:gs}):null,A(te,{borderStyle:"round",borderColor:Cs.prod?"yellow":F,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?As.map((l,a)=>{let s=w.text.slice(l.start,l.end),h=a===qo(As,w.pos),d=Math.min(w.pos,l.end)-l.start;return B(j,{children:[A(j,{color:F,children:a===0?"> ":" "}),h?B(Go,{children:[s.slice(0,d),A(qt,{ch:s[d]??" "}),s.slice(d+1)]}):s||" "]},`${a}-${l.start}`)}):B(j,{children:[A(j,{color:F,children:"> "}),er?A(qt,{ch:" "}):de&&!S&&Yo?B(Go,{children:[A(qt,{ch:Yo[0],dim:!0}),A(j,{color:"gray",children:Yo.slice(1)})]}):de&&!S?B(Go,{children:[A(qt,{ch:de[0],dim:!0}),A(j,{color:"gray",children:de.slice(1)}),A(j,{dimColor:!0,children:" (tab)"})]}):(lr.isSetup||!rd)&&!S?B(Go,{children:[A(qt,{ch:lr.text[0],dim:!0}),A(j,{color:"gray",children:lr.text.slice(1)})]}):A(qt,{ch:" "})]})}),hs.length>0&&A(te,{flexDirection:"column",paddingX:1,children:hs.map((l,a)=>A(j,{color:"gray",children:`\u29D7 queued: ${l}`},`${a}-${l.slice(0,24)}`))}),_n?A(wc,{tab:_n.tab,width:Ee}):nt?B(te,{flexDirection:"column",paddingX:1,children:[A(j,{color:F,bold:!0,children:"Select model"}),A(j,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ne.map((l,a)=>B(j,{color:a===nt.cursor?F:void 0,children:[a===nt.cursor?"\u276F ":" ",`${a+1}. ${l.label}${a===nt.current?" \u2714":""}`.padEnd(16),A(j,{color:"gray",children:l.desc})]},l.label)),A(j,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Le?B(te,{flexDirection:"column",paddingX:1,children:[A(j,{color:F,bold:!0,children:"Switch connection profile"}),Le.rows.map((l,a)=>B(j,{color:a===Le.cursor?F:void 0,children:[a===Le.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===Le.current?" \u2714":""}`.padEnd(20),A(j,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?A(j,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),A(j,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Oe?B(te,{flexDirection:"column",paddingX:1,children:[A(j,{color:F,bold:!0,children:"Pick your Document360 environment"}),Oe.rows.map((l,a)=>B(j,{color:a===Oe.cursor?F:void 0,children:[a===Oe.cursor?"\u276F ":" ",`${a+1}. ${l.name}`.padEnd(16),A(j,{color:"gray",children:l.apiUrl})]},l.name)),A(j,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):pe?B(te,{flexDirection:"column",paddingX:1,children:[A(j,{color:F,bold:!0,children:"Switch workspace"}),A(j,{dimColor:!0,children:`environment ${pe.environment} \xB7 project ${pe.projectName??`${pe.projectId.slice(0,8)}\u2026`}`}),pe.rows.map((l,a)=>B(j,{color:a===pe.cursor?F:void 0,children:[a===pe.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===pe.current?" \u2714":""}`.padEnd(30),A(j,{color:"gray",children:l.type??""})]},l.id)),A(j,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ge?B(te,{flexDirection:"column",paddingX:1,children:[A(j,{color:F,bold:!0,children:"Choose project"}),A(j,{dimColor:!0,children:`environment ${ge.environment}`}),ge.rows.map((l,a)=>B(j,{color:a===ge.cursor?F:void 0,children:[a===ge.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===ge.current?" \u2714":""}`.padEnd(30),A(j,{color:"gray",children:l.sub??""})]},l.id)),A(j,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?(()=>{let a=Math.min(Math.max(0,fe.cursor-Math.floor(7)),Math.max(0,fe.rows.length-14)),s=fe.rows.slice(a,a+14),h=fe.rows.filter(d=>d.checked).length;return B(te,{flexDirection:"column",paddingX:1,children:[A(j,{color:F,bold:!0,children:`Which folders back the user docs? (${h} selected of ${fe.rows.length})`}),a>0?A(j,{dimColor:!0,children:` \u2191 ${a} more`}):null,s.map((d,m)=>{let b=a+m;return B(j,{color:b===fe.cursor?F:void 0,children:[b===fe.cursor?"\u276F ":" ",d.checked?"\u25C9 ":"\u25CB ",d.path.padEnd(Math.min(48,Ee-34)),A(j,{color:"gray",children:ho(d)})]},d.path)}),a+14<fe.rows.length?A(j,{dimColor:!0,children:` \u2193 ${fe.rows.length-a-14} more`}):null,A(j,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Me?B(te,{flexDirection:"column",paddingX:1,children:[A(j,{color:F,bold:!0,children:"Which category? (pick one to scope to)"}),Me.rows.map((l,a)=>{let s=a===Me.cursor,h=`${a+1}.`.padEnd(3);return B(j,{color:s?F:void 0,children:[s?"\u276F ":" ",`${h} ${l.label} (${l.count})`.padEnd(Math.min(44,Math.max(20,Ee-24))),A(j,{color:"gray",children:` ${l.token}`})]},l.token)}),A(j,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):He?B(te,{flexDirection:"column",paddingX:1,children:[A(j,{color:F,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),He.rows.map((l,a)=>{let s=a===He.cursor,h=l.indent?" ":" ",d=`${a+1}.`.padEnd(3);return B(j,{color:s?F:void 0,bold:l.kind==="category"&&!s,children:[s?"\u276F ":" ",`${h}${d} ${l.label}`.padEnd(Math.min(56,Ee-24)),l.note?A(j,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),A(j,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ye?B(te,{flexDirection:"column",paddingX:1,children:[A(j,{color:F,bold:!0,children:`Preview article${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),On.length===0?A(j,{color:"gray",children:"no articles match"}):On.map((l,a)=>B(j,{color:a===ye.cursor?F:void 0,children:[a===ye.cursor?"\u276F ":" ",l]},l)),A(j,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):we?B(te,{flexDirection:"column",paddingX:1,children:[A(j,{color:F,bold:!0,children:`Resume session${we.query?` \u2014 filter: ${we.query}`:" (type to filter)"}`}),Mn.length===0?A(j,{color:"gray",children:"no sessions match"}):Mn.map((l,a)=>B(j,{color:a===we.cursor?F:void 0,children:[a===we.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),A(j,{color:a===we.cursor?F:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ee-40))})]},l.uuid)),A(j,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Rs?B(te,{flexDirection:"column",children:[tn.map((l,a)=>B(j,{color:a===Gt?F:void 0,children:[a===Gt?"\u276F ":" ",l.usage.padEnd(22)," ",A(j,{color:a===Gt?F:"gray",children:l.name==="model"&&tr?`${l.desc} (currently ${tr})`:l.desc})]},l.name)),A(j,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!S&&!D&&Je.length>0?B(te,{flexDirection:"column",paddingX:1,children:[ms?A(j,{color:F,children:ms}):null,Je.map((l,a)=>{let s=mt(l),h=s.slice(0,Math.max(20,Ee-5)),d=Ee-h.length-7,m=d>=12?(vc(l)??mc(s)).slice(0,d):"";return B(j,{children:[A(j,{color:F,children:a+1})," ",h,m?A(j,{dimColor:!0,children:` \u2014 ${m}`}):null]},s)}),A(j,{dimColor:!0,children:`press 1-${Je.length} to fill \xB7 esc cancel`})]}):A(te,{paddingX:1,children:B(j,{color:"gray",children:[Cs.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${tr??"model n/a"}${t.kind==="api"?ks>0?` \xB7 ${he(ks)}`:"":ws>0?` \xB7 ${Ke(ws)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}U();import{jsx as Pg}from"react/jsx-runtime";async function Qc(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Rg(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:i}=Cg(Pg(Xc,{cwd:e,auth:r,profileName:n,version:o}));await i(),process.stdout.write(`
342
+ `),process.exit(0)}U();import{writeCrashLog as Jc,isBenignTransportError as Tg}from"document360-engine";var Zc=!1;function ss(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function ed(e){if(Zc)return;Zc=!0;let t=(n,o)=>{if(Tg(o)){Jc({kind:n,level:"transport",message:ss(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=Jc({kind:n,level:"fatal",message:ss(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
343
+ `+$(`\u2717 d360-writer crashed: ${ss(o)}`)+`
344
344
  `),r&&process.stderr.write(f(` Crash details: ${r}`)+`
345
345
  `+f(" Run: d360-writer logs")+`
346
- `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var jg=Sg(import.meta.url),ed=jg("../package.json");Zc("d360-writer");var De=new Tg;function ss(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}De.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=>{ss(e),await Jn({profile:e.profile,manual:e.manual})});De.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{ss(e),await Bs({profile:e.profile})});De.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{ss(e),await qs({profile:e.profile})});var as=De.command("profile").description("Manage connection profiles for the current repo");as.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Zn(process.cwd()));as.command("use <name>").description("Set the default profile for this repo").action(e=>eo(process.cwd(),e));as.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>to(process.cwd(),e));var td=De.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");td.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>_t(process.cwd(),e.profile));td.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Ls(process.cwd(),e,t.profile)});var nd=De.command("project").description("Choose the Document360 project for this repo (active profile's identity)");nd.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Kn(process.cwd(),e.profile));nd.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Ms(process.cwd(),e,t.profile)});De.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(lo(),ya));await e()});De.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>zs());De.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(()=>(bo(),hl)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});De.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(ed.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(Dg.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 Ks(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 rc(e.cwd,e.auth,e.profile):await Xc(e.cwd,e.auth,e.profile,ed.version)});De.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
346
+ `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Ag=Dg(import.meta.url),td=Ag("../package.json");ed("d360-writer");var De=new Sg;function as(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}De.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=>{as(e),await Zn({profile:e.profile,manual:e.manual})});De.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{as(e),await Vs({profile:e.profile})});De.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{as(e),await Bs({profile:e.profile})});var ls=De.command("profile").description("Manage connection profiles for the current repo");ls.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>eo(process.cwd()));ls.command("use <name>").description("Set the default profile for this repo").action(e=>to(process.cwd(),e));ls.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>no(process.cwd(),e));var nd=De.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");nd.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>_t(process.cwd(),e.profile));nd.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Os(process.cwd(),e,t.profile)});var od=De.command("project").description("Choose the Document360 project for this repo (active profile's identity)");od.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Xn(process.cwd(),e.profile));od.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Us(process.cwd(),e,t.profile)});De.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(co(),wa));await e()});De.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>Ks());De.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(()=>(xo(),gl)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});De.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(td.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(jg.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 Xs(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 ic(e.cwd,e.auth,e.profile):await Qc(e.cwd,e.auth,e.profile,td.version)});De.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});