document360-writer 0.5.106 → 0.5.109

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 +39 -39
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var Gd=Object.defineProperty;var ao=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var ea=(e,t)=>{for(var n in t)Gd(e,n,{get:t[n],enumerable:!0})};import et from"picocolors";var q,Yd,zd,Kd,ta,wn,f,R,L,D,O,ae,ye,W=ao(()=>{"use strict";q="#7f56d9",[Yd,zd,Kd]=[127,86,217],ta=e=>et.isColorSupported?`\x1B[38;2;${Yd};${zd};${Kd}m${e}\x1B[39m`:e,wn=e=>et.bold(ta(e)),f=e=>et.dim(e),R=e=>et.red(e),L=e=>et.yellow(e),D=e=>et.green(e),O=ta,ae=e=>et.gray(e),ye=e=>et.bold(e)});import{existsSync as Gt,writeFileSync as nt,readFileSync as Iu,readdirSync as _u}from"node:fs";import{join as ka}from"node:path";import{devHintsGuidePath as yo,hintsDir as ba,hooksDir as va,architectureDir as Pa,messagesDir as Mr,creatorNotesPath as $a,devhintsStatePath as Sa,directivesPath as xa,DIRECTIVES_HEADER as Ou,roadmapPath as Ca,ROADMAP_HEADER as Lu,ensureDir as bn,writeMessage as Mu,listOpenForDev as Uu}from"document360-engine";function Ta(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var Gd=Object.defineProperty;var ao=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var ea=(e,t)=>{for(var n in t)Gd(e,n,{get:t[n],enumerable:!0})};import et from"picocolors";var q,Yd,zd,Kd,ta,wn,f,R,L,D,O,ae,ye,W=ao(()=>{"use strict";q="#7f56d9",[Yd,zd,Kd]=[127,86,217],ta=e=>et.isColorSupported?`\x1B[38;2;${Yd};${zd};${Kd}m${e}\x1B[39m`:e,wn=e=>et.bold(ta(e)),f=e=>et.dim(e),R=e=>et.red(e),L=e=>et.yellow(e),D=e=>et.green(e),O=ta,ae=e=>et.gray(e),ye=e=>et.bold(e)});import{existsSync as Gt,writeFileSync as nt,readFileSync as Iu,readdirSync as _u}from"node:fs";import{join as ka}from"node:path";import{devHintsGuidePath as yo,hintsDir as ba,hooksDir as va,architectureDir as Pa,messagesDir as Mr,creatorNotesPath as $a,devhintsStatePath as Ta,directivesPath as xa,DIRECTIVES_HEADER as Ou,roadmapPath as Ca,ROADMAP_HEADER as Lu,ensureDir as bn,writeMessage as Mu,listOpenForDev as Uu}from"document360-engine";function Sa(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
3
3
 
4
4
  <!-- devhints script v${le} \xB7 maintained by document360-writer (/devhints). -->
5
5
 
@@ -231,9 +231,9 @@ Anything only a human knows that would help document this product. For example:
231
231
 
232
232
  (Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
233
233
  `}function zt(e){bn(ba(e)),bn(Pa(e)),bn(Mr(e));for(let n of[ba(e),Mr(e)]){let o=ka(n,".gitkeep");Gt(o)||nt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
234
- `)}Gt($a(e))||nt($a(e),Fu()),Gt(xa(e))||nt(xa(e),Ou),Gt(Ca(e))||nt(Ca(e),Lu),nt(yo(e),Ta()),bn(va(e)),nt(ka(va(e),"open-questions.mjs"),Wu);let t=Ee(e);return ja(e,new Date().toISOString()),t}async function Da(e,t){for(let n of Kt(zt(t.cwd)))console.log(n);return{kind:"continue"}}function kt(){return[`This is document360-writer's dev hand-off setup (v${le}).`,'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 promptly and"," in full \u2014 an open docs question BLOCKS the documentation, and `[discovery]` questions define the"," whole product brief, so answer those in depth; 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. Wire the SESSION-START QUESTION NUDGE so open docs questions surface every session \u2014 a memory rule"," alone (step 3) is easy to forget. d360-writer already scaffolded a portable, dependency-free checker"," at `.d360-writer/hooks/open-questions.mjs` (prints a one-line nudge when open `from: docs` questions"," exist; silent otherwise). Register it with YOUR coding agent's session-start mechanism:"," \u2022 Claude Code (this repo has a `.claude/` dir): add a `SessionStart` hook to `.claude/settings.json`"," (create the file if absent) that runs `node .d360-writer/hooks/open-questions.mjs` \u2014 its stdout is"," added to your context at session start. MERGE into any existing hooks, do NOT clobber other"," settings, and skip if that exact hook is already there. Shape:",' {"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"node .d360-writer/hooks/open-questions.mjs"}]}]}}'," \u2022 Codex / other agents: no stdout-injecting session hook yet \u2014 rely on the step-3 memory rule, and"," optionally run `node .d360-writer/hooks/open-questions.mjs` yourself when starting a docs-touching"," session. Wire the same command once your agent gains a session-start trigger."," Commit the hook config (`.claude/settings.json` or the equivalent) with the rest. Idempotent \u2014 leave"," an existing hook alone.","5. Two-way messages (Part 3): check `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each IN FULL \u2014 an open docs question blocks the documentation,"," and `[discovery]`-tagged questions (what the product is, who it's for, its core mental model,"," misconceptions, positioning, terminology) define the whole product brief, so answer those in depth."," Fold durable facts into the architecture brief and drop a reply (`from: dev`, `kind: answer`,"," `re: <id>`) \u2014 then set the question's frontmatter `status: done`. If there are none, continue.","6. 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.",`7. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${le},`,' "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.","8. 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(`
235
- `)}function Ur(e){try{let t=Iu(Sa(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function ja(e,t){let o={...Ur(e)??{},emittedVersion:le,emittedAt:t};nt(Sa(e),`${JSON.stringify(o,null,2)}
236
- `)}function ze(e){try{return _u(Pa(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ee(e){let n=Ur(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<le?"stale":"current",completedVersion:n}}function ko(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:le};try{if(!Gt(yo(e)))return n;let o=Ur(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;le>r&&(bn(Mr(e)),nt(yo(e),Ta()),ja(e,t),n.guideRefreshed=!0),le>s&&(Uu(e).some(p=>p.kind==="request"&&p.subject.startsWith(Ra))||(Mu(e,{id:`onb${le}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Ra}${le})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${le}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",kt()].join(`
234
+ `)}Gt($a(e))||nt($a(e),Fu()),Gt(xa(e))||nt(xa(e),Ou),Gt(Ca(e))||nt(Ca(e),Lu),nt(yo(e),Sa()),bn(va(e)),nt(ka(va(e),"open-questions.mjs"),Wu);let t=Ee(e);return ja(e,new Date().toISOString()),t}async function Da(e,t){for(let n of Kt(zt(t.cwd)))console.log(n);return{kind:"continue"}}function kt(){return[`This is document360-writer's dev hand-off setup (v${le}).`,'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 promptly and"," in full \u2014 an open docs question BLOCKS the documentation, and `[discovery]` questions define the"," whole product brief, so answer those in depth; 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. Wire the SESSION-START QUESTION NUDGE so open docs questions surface every session \u2014 a memory rule"," alone (step 3) is easy to forget. d360-writer already scaffolded a portable, dependency-free checker"," at `.d360-writer/hooks/open-questions.mjs` (prints a one-line nudge when open `from: docs` questions"," exist; silent otherwise). Register it with YOUR coding agent's session-start mechanism:"," \u2022 Claude Code (this repo has a `.claude/` dir): add a `SessionStart` hook to `.claude/settings.json`"," (create the file if absent) that runs `node .d360-writer/hooks/open-questions.mjs` \u2014 its stdout is"," added to your context at session start. MERGE into any existing hooks, do NOT clobber other"," settings, and skip if that exact hook is already there. Shape:",' {"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"node .d360-writer/hooks/open-questions.mjs"}]}]}}'," \u2022 Codex / other agents: no stdout-injecting session hook yet \u2014 rely on the step-3 memory rule, and"," optionally run `node .d360-writer/hooks/open-questions.mjs` yourself when starting a docs-touching"," session. Wire the same command once your agent gains a session-start trigger."," Commit the hook config (`.claude/settings.json` or the equivalent) with the rest. Idempotent \u2014 leave"," an existing hook alone.","5. Two-way messages (Part 3): check `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each IN FULL \u2014 an open docs question blocks the documentation,"," and `[discovery]`-tagged questions (what the product is, who it's for, its core mental model,"," misconceptions, positioning, terminology) define the whole product brief, so answer those in depth."," Fold durable facts into the architecture brief and drop a reply (`from: dev`, `kind: answer`,"," `re: <id>`) \u2014 then set the question's frontmatter `status: done`. If there are none, continue.","6. 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.",`7. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${le},`,' "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.","8. 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(`
235
+ `)}function Ur(e){try{let t=Iu(Ta(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function ja(e,t){let o={...Ur(e)??{},emittedVersion:le,emittedAt:t};nt(Ta(e),`${JSON.stringify(o,null,2)}
236
+ `)}function ze(e){try{return _u(Pa(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ee(e){let n=Ur(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<le?"stale":"current",completedVersion:n}}function ko(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:le};try{if(!Gt(yo(e)))return n;let o=Ur(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;le>r&&(bn(Mr(e)),nt(yo(e),Sa()),ja(e,t),n.guideRefreshed=!0),le>s&&(Uu(e).some(p=>p.kind==="request"&&p.subject.startsWith(Ra))||(Mu(e,{id:`onb${le}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Ra}${le})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${le}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",kt()].join(`
237
237
  `)}),n.notifiedBuilder=!0))}catch{}return n}function bo(e){if(!Gt(yo(e)))return[];let t=Ee(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${le}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Yt,kt(),Yt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Wr(){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(`
238
238
  `)}function vo(){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):",Yt,Wr(),Yt]}function Kt(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${le}.`," 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):",Yt,kt(),Yt,"","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 Yt,le,Wu,Ra,ot=ao(()=>{"use strict";Yt="-".repeat(64),le=9,Wu=`#!/usr/bin/env node
239
239
  // d360-writer \u2014 session-start nudge for the builder ("John"). Surfaces open questions the docs agent
@@ -274,16 +274,16 @@ try {
274
274
  /* a session-start nudge must never break the session */
275
275
  }
276
276
  `;Ra="Re-run dev\u2194docs onboarding (protocol v"});var Wa={};ea(Wa,{initCommand:()=>Hr,scaffoldInit:()=>Fr});import{input as vn,confirm as Hu}from"@inquirer/prompts";import{basename as Aa,join as $o}from"node:path";import{existsSync as Xt,readFileSync as qu,readdirSync as Bu,writeFileSync as Vu}from"node:fs";import{writeProjectConfig as Ea,readProjectConfig as Gu,projectConfigPath as Na,writerDir as Yu,DEFAULT_DOCS_DIR as Ia,DEFAULT_CAPTURE_DIR as _a,DEFAULT_OUTPUT_DIR as Oa}from"document360-engine";function Fr(e,t="berlin"){let n=Na(e);if(Xt(n))return{created:!1,path:n,profileName:""};let o={projectId:Ma(e)??Aa(e),docsDir:Ia,captureDir:_a,outputDir:Oa,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Ua(e)};return Ea(o,e),La(e),{created:!0,path:n,profileName:t}}function La(e){let t=$o(Yu(e),".gitignore");Xt(t)||Vu(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
277
- `),"utf8")}async function Hr(){let e=process.cwd(),t=Na(e);if(Xt(t)&&!await Hu({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Ma(e)??Aa(e),o=await vn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await vn({message:"Capture directory (where document360-capture .spec.ts files live):",default:_a}),s=await vn({message:"Screenshot output directory:",default:Oa}),l=await vn({message:"Default connection profile name:",default:"berlin"}),p=await vn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),m={projectId:o,docsDir:Ia,captureDir:r,outputDir:s,profiles:{[l]:{connection:{environment:p},production:!1}},defaultProfile:l,authoritativeSourceFiles:Ua(e)},k=Gu(e);k?.terminologyGlossary&&(m.terminologyGlossary=k.terminologyGlossary),Ea(m,e),La(e);let g=zt(e);console.log(""),console.log(D(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${O(`d360-writer login --profile ${l}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let S of Kt(g))console.log(S);return console.log(""),console.log(`${f("Then ask:")} ${O('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Ma(e){let t=$o(e,"package.json");if(!Xt(t))return null;try{return JSON.parse(qu(t,"utf8")).name??null}catch{return null}}function Ua(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Xt($o(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=$o(e,n);Xt(o)&&!zu(o)&&t.push(n)}return t}function zu(e){try{return Bu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var xo=ao(()=>{"use strict";W();ot()});var ql={};ea(ql,{doctorCommand:()=>Dn,renderDoctorChecks:()=>Hl,runDoctorChecks:()=>Fl});import{existsSync as Wf}from"node:fs";import{d360GetAll as Ff,getAccessToken as Hf,isExpired as Os,loadProfileMap as qf,loadTokens as Bf,packageSkillsDir as Ul,ENGINE_VERSION as Vf,projectConfigPath as Gf,readProjectConfig as Yf,DEFAULT_DOCS_DIR as zf,fetchManifestSummary as Kf,resolveActiveProfile as Xf,classifyClaudeAuth as Qf,CLAUDE_CODE_SETUP_HINT as Wl,resolveModelSetting as Jf,probeModel as Zf,detectAppType as eh,playbookSkillName as th,D360AuthError as nh}from"document360-engine";async function Fl(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Vf}`});let o=Number(process.versions.node.split(".")[0]);n.push(o>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let r=Qf();r.state==="ready"?n.push({level:"ok",label:`Claude auth: ${r.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):r.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${Wl}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Wl});let s=Jf(e);if(n.push({level:"ok",label:`Model: ${s.model} (${s.source==="auto"?"auto \u2014 right-sized for docs; /model to change":s.source})`}),r.state==="ready"){let P=await Zf(e,s.model??void 0);P.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(P.latencyMs/1e3).toFixed(1)}s`}):P.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${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 l=Yf(e);if(!l)return n.push({level:"fail",label:`No ${Gf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${l.projectId}`});let p=(l.docsDir??zf).replace(/\/+$/,"");n.push(l.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 ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let m=l.authoritativeSourceFiles??[];n.push(m.length>0?{level:"ok",label:`Sources: docs grounded in ${m.length} path(s) (${m.slice(0,3).join(", ")}${m.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 k=l.appType??eh(e);if(k){let P=l.appType?"from config":"auto-detected",N=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${P})${N?` \u2192 ${th(k)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let g;try{g=Xf(e),n.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(P){return n.push({level:"fail",label:`Profile config: ${P.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let S=Bf(g.name);S?Os(S)&&!S.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Os(S)?n.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(S.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${g.name})`}),n.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let v=qf(e,g.name);v?v.projectId&&g.project.projectId&&v.projectId!==g.project.projectId?n.push({level:"fail",label:`Category map projectId (${v.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(v.articles).length} articles, ${Object.keys(v.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),n.push(Wf(Ul())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Ul()}`,fix:"Reinstall document360-writer (broken install)"});let _=Ee(e);if(_.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${le})`}):_.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${_.completedVersion}, current is v${le}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),S&&(!Os(S)||S.refreshToken)){let P={profile:g.name,connection:g.connection};try{await Hf(P);let T=await Ff(P,"/v3/projects");n.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${T.length} project(s) visible`})}catch(T){n.push({level:"fail",label:`API call failed: ${T.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=v?.projectId??g.project.projectId;if(N&&g.project.workspaceId)try{let T=await Kf(P,N,g.project.workspaceId);if(T){let M=(T.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${g.connection.name} (${T.languages?.length??0} language${(T.languages?.length??0)===1?"":"s"}) \xB7 hash ${M||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${g.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(T){T instanceof nh||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(T.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??N})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${T.message.slice(0,80)})`})}}return n}function Hl(e){let t=[""];for(let r of e){let s=r.level==="ok"?D("\u2713"):r.level==="warn"?L("\u26A0"):R("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${O(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?D(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):R(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Dn(e,t){console.log(f("Running checks\u2026"));for(let n of Hl(await Fl(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Lo=ao(()=>{"use strict";ot();W()});import{Command as vw}from"commander";import{createRequire as $w}from"node:module";import{AUTH_MODES as xw}from"document360-engine";import{input as cu}from"@inquirer/prompts";import{loginPkce as du,refreshTokens as uu,toStoredTokens as aa,clearTokens as pu,decodeJwtClaims as ia,isExpired as fu,loadTokens as hu,saveTokens as la,resolveActiveProfile as po,setProfileProject as mu,readProjectConfig as gu}from"document360-engine";W();import{select as Xd}from"@inquirer/prompts";import{resolveActiveProfile as Qd,setProfileProject as Jd,resolveProjectId as Zd,listWorkspaces as eu}from"document360-engine";async function yn(e,t){let n=Qd(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Zd(o);return{workspaces:await eu(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var na=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Nr(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 lo(e,t,n,o,r){Jd(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function oa(e,t,n){let o;try{o=await yn(e,n)}catch(s){return console.log(R(`Could not list workspaces: ${s.message}`)),1}let r=Nr(o.workspaces,t);return r?(lo(e,o.profile,o.projectId,r.id,r.name),console.log(D(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(R(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Vt(e,t){let n;try{n=await yn(e,t)}catch(k){console.log(R(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:l}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===l?O("\u25CF"):" "} ${na(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Xd({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${na(k)}${k.id===l?" (current)":""}`,value:k.id}))}),m=o.find(k=>k.id===p);lo(e,s,r,p,m?.name),console.log(D(`\u2713 Workspace set to "${m?.name??p}" for profile "${s}".`))}W();import{select as tu}from"@inquirer/prompts";import{resolveActiveProfile as nu,setProfileProject as ou,listProjects as ru}from"document360-engine";async function tt(e,t){let n=nu(e,t),o={profile:n.name,connection:n.connection};return{projects:await ru(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ra=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Ir(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 co(e,t,n,o){ou(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function sa(e,t,n){let o;try{o=await tt(e,n)}catch(s){return console.log(R(`Could not list projects: ${s.message}`)),1}let r=Ir(o.projects,t);return r?(co(e,o.profile,r.id,r.name),console.log(D(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(R(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function uo(e,t){let n;try{n=await tt(e,t)}catch(m){console.log(R(`Could not list projects: ${m.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let m of o)console.log(` ${m.id===s?O("\u25CF"):" "} ${ra(m)} ${f(m.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let l=await tu({message:"Select the Document360 project for this repo:",choices:o.map(m=>({name:`${ra(m)}${m.id===s?" (current)":""}`,value:m.id}))}),p=o.find(m=>m.id===l);co(e,r,l,p?.name),console.log(D(`\u2713 Project set to "${p?.name??l}" for profile "${r}". Next: pick a workspace.`))}W();import su from"picocolors";function iu(e=process.env){return e.FORCE_HYPERLINK==="0"||!su.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 au(e,t=e,n){return iu(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var lu=/https?:\/\/[^\s\x1b]+/g;function kn(e,t){return e.replace(lu,n=>au(n,n,t))}function ca(e){return{...ia(e.idToken)??{},...ia(e.accessToken)??{}}}function fo(e){let t=ca(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 ho(e){let t=po(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 du(n,{manual:e.manual,promptForRedirect:s=>cu({message:s})},s=>console.log(kn(s))),r=aa(t.name,o);if(la(r),await _r(r,t.name,s=>console.log(f(s))),console.log(""),console.log(D(`\u2713 Logged in to "${t.name}" as ${fo(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{gu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Vt(process.cwd(),t.name))}catch{}}async function _r(e,t,n){let r=ca(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(po(process.cwd(),t).project.projectId)return;let l;try{let{projects:p}=await tt(process.cwd(),t);l=p.find(m=>m.id===r)?.name}catch{}mu(process.cwd(),t,{projectId:r,projectName:l}),n(` Project "${l??r}" written to profile "${t}".`)}catch{}}async function da(e){let t=po(process.cwd(),e.profile),n=t.connection,o=hu(t.name);if(!o){console.log(R(`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 ${O(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${fo(o)}`),fu(o))if(o.refreshToken)try{let r=aa(t.name,await uu(n,o.refreshToken));la(r),console.log(D(`\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 ua(e){let t=po(process.cwd(),e.profile);pu(t.name)?console.log(D(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as pa,writeProjectConfig as wu,resolveActiveProfile as yu,loadTokens as ku,isExpired as bu}from"document360-engine";function mo(e){let t=pa(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(R("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?O("\u25CF "):" ",s=o.production?L(" \u26A0 PRODUCTION"):"",l=o.connection.environment??"(inline)",p=ku(n),m=p?bu(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${O(n)} \u2192 ${l}${s} [${m}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function go(e,t){let n=pa(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(R(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,wu(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(D(`\u2713 Default profile is now "${t}"${o}`))}function wo(e,t){try{let n=yu(e,t);console.log(""),console.log(`Profile ${O(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(R(n.message)),process.exitCode=1}}W();import{existsSync as vu,readdirSync as $u,statSync as fa}from"node:fs";import{join as ha}from"node:path";import{apiLogDir as xu}from"document360-engine";function ma(){let e=xu();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!vu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=$u(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(fa(ha(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(fa(ha(e,r)).size/1024).toFixed(1);console.log(` ${R(r)} ${f(`${s} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as Cu,resolveAuth as Ru,findByName as Pu,slugify as Su,touchSession as Tu,upsertSession as Du,resolveActiveProfile as ju}from"document360-engine";async function ga(e,t,n,o,r,s){let l=Ru(n);l.kind==="none"&&(console.error(""),console.error(R("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2)),l.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=ju(e,r)}catch(v){console.error(R(`Document360 profile error: ${v.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(R("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let m;if(o){let v=Pu(e,o);v||(console.error(R(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),m=v.uuid,console.error(f(`Resuming "${v.name}"`))}let k=Cu({cwd:e,resume:m,profileName:r,allowProdWrites:s===!0}),g=m??null,S=1;for await(let v of k.send(t))switch(v.type){case"session":if(!g){g=v.sessionId;let _=new Date().toISOString();Du({uuid:g,name:Su(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:_,updatedAt:_})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(ae(` \u2699 ${v.name}`));break;case"result":S=v.ok?0:1,console.error(f(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(R("agent finished with an error result"));break;case"error":console.error(""),console.error(R(`agent error: ${v.message}`)),process.exit(1)}g&&Tu(g),process.stdout.write(`
278
- `),process.exit(S)}import{createInterface as Dm}from"node:readline/promises";import{createSession as fi,resolveAuth as jm,getSession as Am,setTitle as Em,slugify as Nm,touchSession as Ec,upsertSession as Im,generateTitle as _m,resolveActiveProfile as Nc,resolveModelSetting as Om,readProjectConfig as Lm,resolveAndPersistAppType as Mm,decodeJwtClaims as Ac,isExpired as Um,loadTokens as Wm,isDirectiveMention as Fm,stripDirectiveMention as Hm,appendDirective as qm,reconcileUpgradeActions as Bm,stampArticles as Vm,listArticleFiles as Gm,CONTENT_CAP_VERSION as Ym}from"document360-engine";import{ENGINE_VERSION as Eu}from"document360-engine";var Ae=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --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:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"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:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function Au(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 wa(e){let n=[e?`document360-writer \u2014 help \xB7 v${e.version} \xB7 engine v${e.engineVersion}`:"document360-writer \u2014 help",""];for(let o of Ae){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(Au(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function Or(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:Eu}:void 0;for(let o of wa(n))console.log(o);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}W();import{getSession as Nu}from"document360-engine";async function ya(e,t){let n=t.currentUuid(),o=n?Nu(n):void 0;return console.log(o?f(`
277
+ `),"utf8")}async function Hr(){let e=process.cwd(),t=Na(e);if(Xt(t)&&!await Hu({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Ma(e)??Aa(e),o=await vn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await vn({message:"Capture directory (where document360-capture .spec.ts files live):",default:_a}),s=await vn({message:"Screenshot output directory:",default:Oa}),l=await vn({message:"Default connection profile name:",default:"berlin"}),p=await vn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),m={projectId:o,docsDir:Ia,captureDir:r,outputDir:s,profiles:{[l]:{connection:{environment:p},production:!1}},defaultProfile:l,authoritativeSourceFiles:Ua(e)},k=Gu(e);k?.terminologyGlossary&&(m.terminologyGlossary=k.terminologyGlossary),Ea(m,e),La(e);let g=zt(e);console.log(""),console.log(D(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${O(`d360-writer login --profile ${l}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let T of Kt(g))console.log(T);return console.log(""),console.log(`${f("Then ask:")} ${O('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Ma(e){let t=$o(e,"package.json");if(!Xt(t))return null;try{return JSON.parse(qu(t,"utf8")).name??null}catch{return null}}function Ua(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Xt($o(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=$o(e,n);Xt(o)&&!zu(o)&&t.push(n)}return t}function zu(e){try{return Bu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var xo=ao(()=>{"use strict";W();ot()});var ql={};ea(ql,{doctorCommand:()=>Dn,renderDoctorChecks:()=>Hl,runDoctorChecks:()=>Fl});import{existsSync as Wf}from"node:fs";import{d360GetAll as Ff,getAccessToken as Hf,isExpired as Os,loadProfileMap as qf,loadTokens as Bf,packageSkillsDir as Ul,ENGINE_VERSION as Vf,projectConfigPath as Gf,readProjectConfig as Yf,DEFAULT_DOCS_DIR as zf,fetchManifestSummary as Kf,resolveActiveProfile as Xf,classifyClaudeAuth as Qf,CLAUDE_CODE_SETUP_HINT as Wl,resolveModelSetting as Jf,probeModel as Zf,detectAppType as eh,playbookSkillName as th,D360AuthError as nh}from"document360-engine";async function Fl(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Vf}`});let o=Number(process.versions.node.split(".")[0]);n.push(o>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let r=Qf();r.state==="ready"?n.push({level:"ok",label:`Claude auth: ${r.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):r.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${Wl}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Wl});let s=Jf(e);if(n.push({level:"ok",label:`Model: ${s.model} (${s.source==="auto"?"auto \u2014 right-sized for docs; /model to change":s.source})`}),r.state==="ready"){let P=await Zf(e,s.model??void 0);P.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(P.latencyMs/1e3).toFixed(1)}s`}):P.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${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 l=Yf(e);if(!l)return n.push({level:"fail",label:`No ${Gf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${l.projectId}`});let p=(l.docsDir??zf).replace(/\/+$/,"");n.push(l.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 ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let m=l.authoritativeSourceFiles??[];n.push(m.length>0?{level:"ok",label:`Sources: docs grounded in ${m.length} path(s) (${m.slice(0,3).join(", ")}${m.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 k=l.appType??eh(e);if(k){let P=l.appType?"from config":"auto-detected",N=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${P})${N?` \u2192 ${th(k)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let g;try{g=Xf(e),n.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(P){return n.push({level:"fail",label:`Profile config: ${P.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let T=Bf(g.name);T?Os(T)&&!T.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Os(T)?n.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(T.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${g.name})`}),n.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let v=qf(e,g.name);v?v.projectId&&g.project.projectId&&v.projectId!==g.project.projectId?n.push({level:"fail",label:`Category map projectId (${v.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(v.articles).length} articles, ${Object.keys(v.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),n.push(Wf(Ul())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Ul()}`,fix:"Reinstall document360-writer (broken install)"});let _=Ee(e);if(_.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${le})`}):_.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${_.completedVersion}, current is v${le}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),T&&(!Os(T)||T.refreshToken)){let P={profile:g.name,connection:g.connection};try{await Hf(P);let S=await Ff(P,"/v3/projects");n.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${S.length} project(s) visible`})}catch(S){n.push({level:"fail",label:`API call failed: ${S.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=v?.projectId??g.project.projectId;if(N&&g.project.workspaceId)try{let S=await Kf(P,N,g.project.workspaceId);if(S){let M=(S.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${g.connection.name} (${S.languages?.length??0} language${(S.languages?.length??0)===1?"":"s"}) \xB7 hash ${M||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${g.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(S){S instanceof nh||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(S.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??N})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${S.message.slice(0,80)})`})}}return n}function Hl(e){let t=[""];for(let r of e){let s=r.level==="ok"?D("\u2713"):r.level==="warn"?L("\u26A0"):R("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${O(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?D(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):R(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Dn(e,t){console.log(f("Running checks\u2026"));for(let n of Hl(await Fl(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Lo=ao(()=>{"use strict";ot();W()});import{Command as vw}from"commander";import{createRequire as $w}from"node:module";import{AUTH_MODES as xw}from"document360-engine";import{input as cu}from"@inquirer/prompts";import{loginPkce as du,refreshTokens as uu,toStoredTokens as aa,clearTokens as pu,decodeJwtClaims as ia,isExpired as fu,loadTokens as hu,saveTokens as la,resolveActiveProfile as po,setProfileProject as mu,readProjectConfig as gu}from"document360-engine";W();import{select as Xd}from"@inquirer/prompts";import{resolveActiveProfile as Qd,setProfileProject as Jd,resolveProjectId as Zd,listWorkspaces as eu}from"document360-engine";async function yn(e,t){let n=Qd(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Zd(o);return{workspaces:await eu(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var na=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Nr(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 lo(e,t,n,o,r){Jd(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function oa(e,t,n){let o;try{o=await yn(e,n)}catch(s){return console.log(R(`Could not list workspaces: ${s.message}`)),1}let r=Nr(o.workspaces,t);return r?(lo(e,o.profile,o.projectId,r.id,r.name),console.log(D(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(R(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Vt(e,t){let n;try{n=await yn(e,t)}catch(k){console.log(R(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:l}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===l?O("\u25CF"):" "} ${na(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Xd({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${na(k)}${k.id===l?" (current)":""}`,value:k.id}))}),m=o.find(k=>k.id===p);lo(e,s,r,p,m?.name),console.log(D(`\u2713 Workspace set to "${m?.name??p}" for profile "${s}".`))}W();import{select as tu}from"@inquirer/prompts";import{resolveActiveProfile as nu,setProfileProject as ou,listProjects as ru}from"document360-engine";async function tt(e,t){let n=nu(e,t),o={profile:n.name,connection:n.connection};return{projects:await ru(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ra=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Ir(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 co(e,t,n,o){ou(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function sa(e,t,n){let o;try{o=await tt(e,n)}catch(s){return console.log(R(`Could not list projects: ${s.message}`)),1}let r=Ir(o.projects,t);return r?(co(e,o.profile,r.id,r.name),console.log(D(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(R(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function uo(e,t){let n;try{n=await tt(e,t)}catch(m){console.log(R(`Could not list projects: ${m.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let m of o)console.log(` ${m.id===s?O("\u25CF"):" "} ${ra(m)} ${f(m.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let l=await tu({message:"Select the Document360 project for this repo:",choices:o.map(m=>({name:`${ra(m)}${m.id===s?" (current)":""}`,value:m.id}))}),p=o.find(m=>m.id===l);co(e,r,l,p?.name),console.log(D(`\u2713 Project set to "${p?.name??l}" for profile "${r}". Next: pick a workspace.`))}W();import su from"picocolors";function iu(e=process.env){return e.FORCE_HYPERLINK==="0"||!su.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 au(e,t=e,n){return iu(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var lu=/https?:\/\/[^\s\x1b]+/g;function kn(e,t){return e.replace(lu,n=>au(n,n,t))}function ca(e){return{...ia(e.idToken)??{},...ia(e.accessToken)??{}}}function fo(e){let t=ca(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 ho(e){let t=po(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 du(n,{manual:e.manual,promptForRedirect:s=>cu({message:s})},s=>console.log(kn(s))),r=aa(t.name,o);if(la(r),await _r(r,t.name,s=>console.log(f(s))),console.log(""),console.log(D(`\u2713 Logged in to "${t.name}" as ${fo(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{gu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Vt(process.cwd(),t.name))}catch{}}async function _r(e,t,n){let r=ca(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(po(process.cwd(),t).project.projectId)return;let l;try{let{projects:p}=await tt(process.cwd(),t);l=p.find(m=>m.id===r)?.name}catch{}mu(process.cwd(),t,{projectId:r,projectName:l}),n(` Project "${l??r}" written to profile "${t}".`)}catch{}}async function da(e){let t=po(process.cwd(),e.profile),n=t.connection,o=hu(t.name);if(!o){console.log(R(`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 ${O(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${fo(o)}`),fu(o))if(o.refreshToken)try{let r=aa(t.name,await uu(n,o.refreshToken));la(r),console.log(D(`\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 ua(e){let t=po(process.cwd(),e.profile);pu(t.name)?console.log(D(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as pa,writeProjectConfig as wu,resolveActiveProfile as yu,loadTokens as ku,isExpired as bu}from"document360-engine";function mo(e){let t=pa(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(R("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?O("\u25CF "):" ",s=o.production?L(" \u26A0 PRODUCTION"):"",l=o.connection.environment??"(inline)",p=ku(n),m=p?bu(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${O(n)} \u2192 ${l}${s} [${m}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function go(e,t){let n=pa(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(R(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,wu(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(D(`\u2713 Default profile is now "${t}"${o}`))}function wo(e,t){try{let n=yu(e,t);console.log(""),console.log(`Profile ${O(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(R(n.message)),process.exitCode=1}}W();import{existsSync as vu,readdirSync as $u,statSync as fa}from"node:fs";import{join as ha}from"node:path";import{apiLogDir as xu}from"document360-engine";function ma(){let e=xu();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!vu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=$u(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(fa(ha(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(fa(ha(e,r)).size/1024).toFixed(1);console.log(` ${R(r)} ${f(`${s} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as Cu,resolveAuth as Ru,findByName as Pu,slugify as Tu,touchSession as Su,upsertSession as Du,resolveActiveProfile as ju}from"document360-engine";async function ga(e,t,n,o,r,s){let l=Ru(n);l.kind==="none"&&(console.error(""),console.error(R("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2)),l.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=ju(e,r)}catch(v){console.error(R(`Document360 profile error: ${v.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(R("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let m;if(o){let v=Pu(e,o);v||(console.error(R(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),m=v.uuid,console.error(f(`Resuming "${v.name}"`))}let k=Cu({cwd:e,resume:m,profileName:r,allowProdWrites:s===!0}),g=m??null,T=1;for await(let v of k.send(t))switch(v.type){case"session":if(!g){g=v.sessionId;let _=new Date().toISOString();Du({uuid:g,name:Tu(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:_,updatedAt:_})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(ae(` \u2699 ${v.name}`));break;case"result":T=v.ok?0:1,console.error(f(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(R("agent finished with an error result"));break;case"error":console.error(""),console.error(R(`agent error: ${v.message}`)),process.exit(1)}g&&Su(g),process.stdout.write(`
278
+ `),process.exit(T)}import{createInterface as Dm}from"node:readline/promises";import{createSession as fi,resolveAuth as jm,getSession as Am,setTitle as Em,slugify as Nm,touchSession as Ec,upsertSession as Im,generateTitle as _m,resolveActiveProfile as Nc,resolveModelSetting as Om,readProjectConfig as Lm,resolveAndPersistAppType as Mm,decodeJwtClaims as Ac,isExpired as Um,loadTokens as Wm,isDirectiveMention as Fm,stripDirectiveMention as Hm,appendDirective as qm,reconcileUpgradeActions as Bm,stampArticles as Vm,listArticleFiles as Gm,CONTENT_CAP_VERSION as Ym}from"document360-engine";import{ENGINE_VERSION as Eu}from"document360-engine";var Ae=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --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:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"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:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function Au(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 wa(e){let n=[e?`document360-writer \u2014 help \xB7 v${e.version} \xB7 engine v${e.engineVersion}`:"document360-writer \u2014 help",""];for(let o of Ae){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(Au(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function Or(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:Eu}:void 0;for(let o of wa(n))console.log(o);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}W();import{getSession as Nu}from"document360-engine";async function ya(e,t){let n=t.currentUuid(),o=n?Nu(n):void 0;return console.log(o?f(`
279
279
  (conversation reset \u2014 "${o.name}" is still available via /resume)
280
280
  `):f(`
281
281
  (conversation reset \u2014 agent will start fresh on the next prompt)
282
282
  `)),{kind:"clear"}}async function Lr(){return{kind:"exit"}}xo();W();import{readMcpConfig as qr,writeMcpConfig as Fa}from"document360-engine";async function Co(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Ku(),{kind:"continue"}):t==="add"?(Xu(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Qu(e.slice(1)),{kind:"continue"}):(console.log(R(`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 Ku(){let e=qr(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
283
283
  No MCP servers registered. Add one with /mcp add <name> <type> <ref>
284
284
  `));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(` ${O(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${O(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Xu(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(R("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(R(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=qr(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let l={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let m=o[++p],k=m?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(R(`-H expects key:value (no spaces). Got: ${m??"(nothing)"}`));return}l[k[1].trim()]=k[2].trim()}else{console.log(R(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(l).length>0?l:void 0}}r.servers[t]=s,Fa(r),console.log(""),console.log(D(`\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 Qu(e){let t=e[0];if(!t){console.log(R("Usage: /mcp remove <name>"));return}let n=qr();if(!n.servers[t]){console.log(R(`No server named "${t}".`));return}delete n.servers[t],Fa(n),console.log(D(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as fp}from"node:fs";import{join as hp}from"node:path";import{select as mp}from"@inquirer/prompts";import{computeSyncStatus as Ro,planPartitions as gp,relatedArticlePaths as wp,resolveModelForOperation as yp,runPartitioned as kp,loadProfileMap as bp,resolveActiveProfile as vp,resolveCrossLinks as $p,applyStructureOrder as Qa,orderSyncLine as Ja,applyRelatedArticles as Za,relatedSyncLine as el}from"document360-engine";import Z from"picocolors";import Ya from"wrap-ansi";import Kr from"string-width";W();import rt from"picocolors";import Br from"wrap-ansi";import Vr from"string-width";var Ha=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),qa=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Ba=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Ju(e){let t=e.replace(/\r/g,"").split(`
285
- `),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(Ha(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&qa(t[o+1])){let p=Ba(r);o+=2;let m=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)m.push(Ba(t[o++]));n.push({kind:"table",header:p,rows:m});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let m=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(m),text:m.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let l=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Ha(t[o])&&!(t[o].includes("|")&&o+1<t.length&&qa(t[o+1]));)l.push(t[o++]);n.push({kind:"para",text:l.join(" ")})}return n}function Gr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?rt.bold(t.slice(2,-2)):t.startsWith("`")?O(t.slice(1,-1)):rt.italic(t.slice(1,-1)))}var Zu=(e,t)=>e+" ".repeat(Math.max(0,t-Vr(e)));function ep(e,t,n){let o=e.length,r=e.map((P,N)=>Math.max(Vr(P),...t.map(T=>Vr(T[N]??"")))),s=Math.max(24,n),l=3*o+1,p=[...r],m=()=>p.reduce((P,N)=>P+N,0)+l,k=0;for(;m()>s&&k++<1e4;){let P=-1,N=6;for(let T=0;T<o;T++)p[T]>N&&(N=p[T],P=T);if(P===-1)break;p[P]-=1}let g=(P,N,T)=>rt.gray(P+p.map(M=>"\u2500".repeat(M+2)).join(N)+T),S=rt.gray("\u2502"),v=(P,N)=>{let T=p.map((V,Y)=>{let ne=P[Y]??"",_e=N?rt.bold(ne):Gr(ne);return Br(_e,V,{hard:!0}).split(`
286
- `)}),M=Math.max(...T.map(V=>V.length)),B=[];for(let V=0;V<M;V++)B.push(p.map((Y,ne)=>`${S} ${Zu(T[ne][V]??"",Y)} `).join("")+S);return B.join(`
285
+ `),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(Ha(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&qa(t[o+1])){let p=Ba(r);o+=2;let m=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)m.push(Ba(t[o++]));n.push({kind:"table",header:p,rows:m});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let m=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(m),text:m.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let l=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Ha(t[o])&&!(t[o].includes("|")&&o+1<t.length&&qa(t[o+1]));)l.push(t[o++]);n.push({kind:"para",text:l.join(" ")})}return n}function Gr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?rt.bold(t.slice(2,-2)):t.startsWith("`")?O(t.slice(1,-1)):rt.italic(t.slice(1,-1)))}var Zu=(e,t)=>e+" ".repeat(Math.max(0,t-Vr(e)));function ep(e,t,n){let o=e.length,r=e.map((P,N)=>Math.max(Vr(P),...t.map(S=>Vr(S[N]??"")))),s=Math.max(24,n),l=3*o+1,p=[...r],m=()=>p.reduce((P,N)=>P+N,0)+l,k=0;for(;m()>s&&k++<1e4;){let P=-1,N=6;for(let S=0;S<o;S++)p[S]>N&&(N=p[S],P=S);if(P===-1)break;p[P]-=1}let g=(P,N,S)=>rt.gray(P+p.map(M=>"\u2500".repeat(M+2)).join(N)+S),T=rt.gray("\u2502"),v=(P,N)=>{let S=p.map((V,Y)=>{let ne=P[Y]??"",_e=N?rt.bold(ne):Gr(ne);return Br(_e,V,{hard:!0}).split(`
286
+ `)}),M=Math.max(...S.map(V=>V.length)),B=[];for(let V=0;V<M;V++)B.push(p.map((Y,ne)=>`${T} ${Zu(S[ne][V]??"",Y)} `).join("")+T);return B.join(`
287
287
  `)},_=[g("\u250C","\u252C","\u2510"),v(e,!0)];return _.push(t.length===0?g("\u2514","\u2534","\u2518"):g("\u251C","\u253C","\u2524")),t.forEach((P,N)=>{_.push(v(P,!1)),_.push(N===t.length-1?g("\u2514","\u2534","\u2518"):g("\u251C","\u253C","\u2524"))}),_.join(`
288
288
  `)}function tp(e,t){switch(e.kind){case"heading":return rt.bold(e.text);case"hr":return rt.gray("\u2500".repeat(t));case"para":return Br(Gr(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",s=" ".repeat(2+r.length+1),[l="",...p]=Br(Gr(o.text),Math.max(10,t-s.length)).split(`
289
289
  `);return` ${r} ${l}`+p.map(m=>`
@@ -293,7 +293,7 @@ ${s}${m}`).join("")}).join(`
293
293
 
294
294
  `)}W();import np from"picocolors";var op=[127,86,217],rp=[22,38,43],Va={T:op,E:rp},$n=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],zr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,sp=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Ga(){if(!np.isColorSupported)return[];let e=$n[0].length,t=[];for(let n=0;n<$n.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Va[$n[n][r]],l=n+1<$n.length?Va[$n[n+1][r]]:void 0;s&&l?o+=`${zr(s)}${sp(l)}\u2580\x1B[49m\x1B[39m`:s?o+=`${zr(s)}\u2580\x1B[39m`:l?o+=`${zr(l)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function xn(e){let t=n=>n.toFixed(1).endsWith(".0")?n.toFixed(0):n.toFixed(1);return e<1e3?String(e):e<1e6?`${t(e/1e3)}k`:`${t(e/1e6)}M`}function Cn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function ke(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function st(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Qt=(e,t)=>` ${e.padEnd(13)}${t}`;function ip(e,t){let n=[wn("\u270E document360-writer")+Z.gray(` v${e.version} \xB7 engine v${e.engineVersion}`),Z.gray(" Reads your code, writes your docs."),"",Qt("Claude:",`${e.claude}${Z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Qt("Document360:",e.configured?e.loggedOut?Z.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?Z.gray(` (${e.sessionHint})`):""}`:Z.yellow("not set up \u2014 run /init")),Qt("Profile:",e.configured?`${e.profile}${Z.gray(` (${e.apiUrl})`)}${e.prod?Z.bold(Z.yellow(" \u26A0 PRODUCTION")):""}`:Z.gray("\u2014 (run /init)")),Qt("Project:",e.project),Qt("Mode:",Z.gray(e.mode)),Qt("cwd:",Z.gray(e.cwd))],o=Ga();if(o.length===0)return n.join(`
295
295
  `);let r=2,s=3,l=Kr(o[0]);if(!(t>=r+l+s+Math.max(...n.map(g=>Kr(g)))))return[...o.map(g=>" "+g),...n].join(`
296
- `);let m=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let g=0;g<Math.max(o.length+m,n.length);g++){let S=o[g-m]??" ".repeat(l);k.push((" ".repeat(r)+S+" ".repeat(s)+(n[g]??"")).trimEnd())}return k.join(`
296
+ `);let m=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let g=0;g<Math.max(o.length+m,n.length);g++){let T=o[g-m]??" ".repeat(l);k.push((" ".repeat(r)+T+" ".repeat(s)+(n[g]??"")).trimEnd())}return k.join(`
297
297
  `)}var ap={error:Z.red,warn:Z.yellow,ok:Z.green,info:Z.gray};function lp(e){return e.replace(/^([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1 ")}function Xr(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return ip(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),l=50,p=e.text.split(`
298
298
  `).flatMap(k=>Ya(k,s,{hard:!0}).split(`
299
299
  `)),m=Math.max(0,p.length-l);return m>0&&(p=[...p.slice(0,l),Z.dim(`\u2026 +${m} more lines`)]),`
@@ -310,54 +310,54 @@ ${s}${m}`).join("")}).join(`
310
310
  `+ap[e.tone](kn(lp(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${xn(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
311
311
  `+(e.ok?Z.magenta("\u2736 "):Z.red("\u2736 "))+Z.gray(`Cooked for ${Cn(e.seconds)} \xB7 ${xn(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${ke(e.costUsd)}`:""))}}}function za(e,t){return e.map(n=>Xr(n,t)).join(`
312
312
  `)}import{resolveActiveProfile as cp,loadTokens as dp,isExpired as up,decodeJwtClaims as Ka}from"document360-engine";function pp(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ne(e,t){try{let n=cp(e,t),o=dp(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(up(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let l={...Ka(o.idToken)??{},...Ka(o.accessToken)??{}}.doc360_project_id;if(typeof l=="string"&&l&&l!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${pp(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var Rn=3;function Qr(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(`
313
- `)}var Xa={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Jr(e){return e.filter(t=>t.path!==null&&t.status in Xa&&!t.link).map(t=>({path:t.path,label:Xa[t.status]}))}function Po(e){let t=Jr(e),n=new Set(e.filter(o=>o.status==="conflict"&&o.path).map(o=>o.path));return{clean:t.filter(o=>!n.has(o.path)),conflicts:t.filter(o=>n.has(o.path))}}function So(e){let t=e!==1;return`\u26A0 ${e} conflict${t?"s":""} NOT published (portal edit${t?"s":""} kept safe) \u2014 ${t?"these were":"it was"} edited both here and on the portal, so ${t?"they are":"it is"} left untouched. Settle ${t?"them":"it"}: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's).`}function To(e){return e.filter(t=>t.link).length}function Zr(e,t){try{let n=bp(e,vp(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=$p(fp(hp(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 xp(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 tl(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let s=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),l=o.get(s);l?l.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((l,p)=>l.path.localeCompare(p.path));n.push({kind:"category",label:`${xp(r)} (${s.length})`,paths:s.map(l=>l.path),indent:!1});for(let l of s){let p=l.path.replace(/\\/g,"/").split("/").pop()??l.path;n.push({kind:"article",label:p,paths:[l.path],indent:!0,note:l.label})}}for(let r of[...t].sort((s,l)=>s.path.localeCompare(l.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function Do(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(`
314
- `)}function es(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),s=e.filter(v=>!v.ok),l=e.reduce((v,_)=>v+o(_),0),p=r.reduce((v,_)=>v+o(_),0),m=n==="api"?`${ke(e.reduce((v,_)=>v+_.costUsd,0))} total`:st(e.reduce((v,_)=>v+_.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,g=v=>`${v} article${v===1?"":"s"}`,S=[];if(s.length===0)S.push(`Published ${g(l)} (${k}) successfully \xB7 ${m}.`),S.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{S.push(`Published ${p}/${g(l)} (${k}) \xB7 ${m}.`),S.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let v of s)S.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return S}async function bt(e,t){let{model:n}=yp(e.cwd,"standard"),o=async(r,s)=>{let l=gp(r);console.log(f(s?`Resolving cross-links in ${r.length} article${r.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${r.length} article${r.length===1?"":"s"} across ${l.length} partition${l.length===1?"":"s"} (\u2264${Rn} agents at once) on ${n}\u2026`)),s||console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let p=!1;for await(let m of kp({cwd:e.cwd,partitions:l,promptFor:k=>Do(k.paths),concurrency:Rn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(m.type==="partition_status")m.status==="running"?console.log(f(` \u25B8 ${m.label} \u2014 publishing\u2026`)):m.status==="done"?console.log(D(` \u2713 ${m.label}`)):console.log(R(` \u2717 ${m.label}`));else if(m.type==="run_done"){p=m.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let S of es(m.results,l,k))console.log(m.ok?D(S):L(S));let g=Zr(e.cwd,e.profileName);g&&console.log(f(g));try{let S=Ja(await Qa({cwd:e.cwd,profileName:e.profileName}));S&&console.log(f(S))}catch{}try{let S=el(await Za({cwd:e.cwd,profileName:e.profileName}));S&&console.log(f(S))}catch{}}return p};try{if(!await o(t,!1)){let s=await ts(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(R(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function jo(e,t,n){let o=wp(e,n);if(o.length===0)return[];let r=new Set(Jr((await Ro({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function ts(e,t,n){try{let o=new Set(n),r=await Ro({cwd:e,profileName:t});return Jr(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function nl(e,t){let n=Ne(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await jo(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(D("\u2713 All related articles are already published.")),{kind:"continue"}):await bt(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await Ro({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:l}=Po(r.entries),p=To(r.entries),m=e.includes("--force")&&l.length>0;p>0&&console.log(L(`\u26A0 ${p} 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.`)),l.length>0&&!m&&console.log(L(So(l.length)));let k=m?[...s,...l]:s;if(k.length===0){if(l.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(D(p>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let g=Ja(await Qa({cwd:t.cwd,profileName:t.profileName}));g&&console.log(f(g));let S=el(await Za({cwd:t.cwd,profileName:t.profileName}));S&&console.log(f(S))}catch{}return{kind:"continue"}}return t?await bt(t,k.map(g=>g.path)):{kind:"forward-to-agent",prompt:Do(k.map(g=>g.path)),display:"/publish --all"}}catch(r){return console.log(R(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let s=await Ro({cwd:t?.cwd??process.cwd()}),{clean:l,conflicts:p}=Po(s.entries);r=l;let m=To(s.entries);if(m>0&&console.log(L(`\u26A0 ${m} 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.`)),p.length>0&&console.log(L(So(p.length))),r.length===0&&p.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(R(`Could not compute sync status: ${s.message}`)),console.log(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(D("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(f(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${f(`(${s.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>mp({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await bt(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Qr(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(`
313
+ `)}var Xa={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Jr(e){return e.filter(t=>t.path!==null&&t.status in Xa&&!t.link).map(t=>({path:t.path,label:Xa[t.status]}))}function Po(e){let t=Jr(e),n=new Set(e.filter(o=>o.status==="conflict"&&o.path).map(o=>o.path));return{clean:t.filter(o=>!n.has(o.path)),conflicts:t.filter(o=>n.has(o.path))}}function To(e){let t=e!==1;return`\u26A0 ${e} conflict${t?"s":""} NOT published (portal edit${t?"s":""} kept safe) \u2014 ${t?"these were":"it was"} edited both here and on the portal, so ${t?"they are":"it is"} left untouched. Settle ${t?"them":"it"}: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's).`}function So(e){return e.filter(t=>t.link).length}function Zr(e,t){try{let n=bp(e,vp(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=$p(fp(hp(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 xp(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 tl(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let s=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),l=o.get(s);l?l.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((l,p)=>l.path.localeCompare(p.path));n.push({kind:"category",label:`${xp(r)} (${s.length})`,paths:s.map(l=>l.path),indent:!1});for(let l of s){let p=l.path.replace(/\\/g,"/").split("/").pop()??l.path;n.push({kind:"article",label:p,paths:[l.path],indent:!0,note:l.label})}}for(let r of[...t].sort((s,l)=>s.path.localeCompare(l.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function Do(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(`
314
+ `)}function es(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),s=e.filter(v=>!v.ok),l=e.reduce((v,_)=>v+o(_),0),p=r.reduce((v,_)=>v+o(_),0),m=n==="api"?`${ke(e.reduce((v,_)=>v+_.costUsd,0))} total`:st(e.reduce((v,_)=>v+_.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,g=v=>`${v} article${v===1?"":"s"}`,T=[];if(s.length===0)T.push(`Published ${g(l)} (${k}) successfully \xB7 ${m}.`),T.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{T.push(`Published ${p}/${g(l)} (${k}) \xB7 ${m}.`),T.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let v of s)T.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return T}async function bt(e,t){let{model:n}=yp(e.cwd,"standard"),o=async(r,s)=>{let l=gp(r);console.log(f(s?`Resolving cross-links in ${r.length} article${r.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${r.length} article${r.length===1?"":"s"} across ${l.length} partition${l.length===1?"":"s"} (\u2264${Rn} agents at once) on ${n}\u2026`)),s||console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let p=!1;for await(let m of kp({cwd:e.cwd,partitions:l,promptFor:k=>Do(k.paths),concurrency:Rn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(m.type==="partition_status")m.status==="running"?console.log(f(` \u25B8 ${m.label} \u2014 publishing\u2026`)):m.status==="done"?console.log(D(` \u2713 ${m.label}`)):console.log(R(` \u2717 ${m.label}`));else if(m.type==="run_done"){p=m.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let T of es(m.results,l,k))console.log(m.ok?D(T):L(T));let g=Zr(e.cwd,e.profileName);g&&console.log(f(g));try{let T=Ja(await Qa({cwd:e.cwd,profileName:e.profileName}));T&&console.log(f(T))}catch{}try{let T=el(await Za({cwd:e.cwd,profileName:e.profileName}));T&&console.log(f(T))}catch{}}return p};try{if(!await o(t,!1)){let s=await ts(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(R(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function jo(e,t,n){let o=wp(e,n);if(o.length===0)return[];let r=new Set(Jr((await Ro({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function ts(e,t,n){try{let o=new Set(n),r=await Ro({cwd:e,profileName:t});return Jr(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function nl(e,t){let n=Ne(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await jo(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(D("\u2713 All related articles are already published.")),{kind:"continue"}):await bt(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await Ro({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:l}=Po(r.entries),p=So(r.entries),m=e.includes("--force")&&l.length>0;p>0&&console.log(L(`\u26A0 ${p} 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.`)),l.length>0&&!m&&console.log(L(To(l.length)));let k=m?[...s,...l]:s;if(k.length===0){if(l.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(D(p>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let g=Ja(await Qa({cwd:t.cwd,profileName:t.profileName}));g&&console.log(f(g));let T=el(await Za({cwd:t.cwd,profileName:t.profileName}));T&&console.log(f(T))}catch{}return{kind:"continue"}}return t?await bt(t,k.map(g=>g.path)):{kind:"forward-to-agent",prompt:Do(k.map(g=>g.path)),display:"/publish --all"}}catch(r){return console.log(R(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let s=await Ro({cwd:t?.cwd??process.cwd()}),{clean:l,conflicts:p}=Po(s.entries);r=l;let m=So(s.entries);if(m>0&&console.log(L(`\u26A0 ${m} 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.`)),p.length>0&&console.log(L(To(p.length))),r.length===0&&p.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(R(`Could not compute sync status: ${s.message}`)),console.log(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(D("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(f(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${f(`(${s.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>mp({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await bt(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Qr(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(`
315
315
  `),display:"/audit"}}W();import{readProjectConfig as Cp}from"document360-engine";function ns(){return["Run the discover-product skill against this repo.","","Build (or continue refining) the product brief at `.d360-writer/product-brief.md` by interviewing the","source repo's coding agent (the builder):","1. Gather all grounding \u2014 the code surface (analyze-codebase pass), `.d360-writer/architecture/`"," (+ CREATOR-NOTES), any specs under `.d360-writer/input/`, existing docs, git log, and the current"," product brief if one exists.","2. Self-assess against the 8-point readiness rubric (identity, audience, core mental model,"," misconceptions, positioning, key concepts & terminology, critical journeys, boundaries/non-goals).","3. Write/update the brief \u2014 every claim cited to its grounding \u2014 and keep its frontmatter current"," (status, rounds, open_questions, last_updated).","4. For the dimensions you cannot yet ground confidently, ask the builder a focused batch (\u22646) of pointed",' questions via d360_ask_builder, with the subject prefixed "[discovery] ". Then END the turn \u2014 the'," builder answers async; /catch-up will ingest the answers and continue the loop.","","Set status: confident and hand off to propose-structure ONLY when every rubric dimension passes. If the","builder stays silent across a few rounds, degrade gracefully per the skill (best-effort brief, flagged","open questions) rather than blocking the docs. Do NOT write or publish any articles in this turn."].join(`
316
- `)}async function ol(e,t){let n=t?.cwd??process.cwd();return Cp(n)?{kind:"forward-to-agent",prompt:ns(),display:"/discover"}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{checkbox as Rp}from"@inquirer/prompts";import{inventoryRepo as Pp,readProjectConfig as rl,writeProjectConfig as Sp}from"document360-engine";function os(e,t){let n=rl(e);n&&(n.authoritativeSourceFiles=t,Sp(n,e))}function Ao(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 sl(e,t){let n=t?.cwd??process.cwd();if(!rl(n))return console.log(R("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Pp(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(O("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(Ao(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Rp({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Ao(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(f("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};os(n,r),console.log(D(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as Lp}from"@inquirer/prompts";import{applyPull as is,computeSyncStatus as hl,compareRemoteSources as Mp,planPull as ml,planImport as Up,applyImport as Wp,establishBaselines as Fp,rebaselineServerMeta as Hp,D360AuthError as qp}from"document360-engine";W();var il=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:R,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:O,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:R,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:R,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 Tp(e){return e.path?e.path:`${e.title??"(untitled)"} ${ae(`[${e.articleId}]`)}`}function Dp(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 Eo(e,t){let n=[],o=e.entries.filter(g=>g.link);if(o.length>0){n.push(""),n.push(ye("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let g of o)n.push(` ${L("~")} ${L(g.path??"")} ${ae(`\u2192 "${g.link.title}"`)}`)}for(let g of il){let S=e.entries.filter(v=>v.status===g.status&&!(g.status==="untracked-local"&&v.link));if(S.length!==0){n.push(""),n.push(ye(g.header));for(let v of S)n.push(` ${g.paint(g.mark)} ${g.paint(Tp(v))}${v.detail?ae(` (${v.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let l={"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,m=s===r?D("\u2713 everything up to date"):[r>0?D(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...il.map(g=>{let S=(e.counts[g.status]??0)-(g.status==="untracked-local"?p:0);return S>0?`${S} ${l[g.status]}`:null})].filter(Boolean).join(ae(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${Dp(t)}`:"";return n.push(m+ae(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as jp}from"diff";import al from"picocolors";var ll=80,Ap="\x1B[48;2;74;28;28m",Ep="\x1B[48;2;24;66;24m",cl="\x1B[49m",rs=e=>String(e).padStart(5);function dl(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function ul(e,t,n){if(n===void 0||n<t-4)return e.slice(0,t);let o=Math.max(0,n-12);return`\u2026${e.slice(o).slice(0,Math.max(8,t-1))}`}function Ke(e,t,n){let o=v=>{let _=v.replace(/\r\n/g,`
316
+ `)}async function ol(e,t){let n=t?.cwd??process.cwd();return Cp(n)?{kind:"forward-to-agent",prompt:ns(),display:"/discover"}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{checkbox as Rp}from"@inquirer/prompts";import{inventoryRepo as Pp,readProjectConfig as rl,writeProjectConfig as Tp}from"document360-engine";function os(e,t){let n=rl(e);n&&(n.authoritativeSourceFiles=t,Tp(n,e))}function Ao(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 sl(e,t){let n=t?.cwd??process.cwd();if(!rl(n))return console.log(R("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Pp(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(O("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(Ao(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Rp({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Ao(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(f("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};os(n,r),console.log(D(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as Lp}from"@inquirer/prompts";import{applyPull as is,computeSyncStatus as hl,compareRemoteSources as Mp,planPull as ml,planImport as Up,applyImport as Wp,establishBaselines as Fp,rebaselineServerMeta as Hp,D360AuthError as qp}from"document360-engine";W();var il=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:R,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:O,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:R,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:R,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 Sp(e){return e.path?e.path:`${e.title??"(untitled)"} ${ae(`[${e.articleId}]`)}`}function Dp(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 Eo(e,t){let n=[],o=e.entries.filter(g=>g.link);if(o.length>0){n.push(""),n.push(ye("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let g of o)n.push(` ${L("~")} ${L(g.path??"")} ${ae(`\u2192 "${g.link.title}"`)}`)}for(let g of il){let T=e.entries.filter(v=>v.status===g.status&&!(g.status==="untracked-local"&&v.link));if(T.length!==0){n.push(""),n.push(ye(g.header));for(let v of T)n.push(` ${g.paint(g.mark)} ${g.paint(Sp(v))}${v.detail?ae(` (${v.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let l={"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,m=s===r?D("\u2713 everything up to date"):[r>0?D(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...il.map(g=>{let T=(e.counts[g.status]??0)-(g.status==="untracked-local"?p:0);return T>0?`${T} ${l[g.status]}`:null})].filter(Boolean).join(ae(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${Dp(t)}`:"";return n.push(m+ae(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as jp}from"diff";import al from"picocolors";var ll=80,Ap="\x1B[48;2;74;28;28m",Ep="\x1B[48;2;24;66;24m",cl="\x1B[49m",rs=e=>String(e).padStart(5);function dl(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function ul(e,t,n){if(n===void 0||n<t-4)return e.slice(0,t);let o=Math.max(0,n-12);return`\u2026${e.slice(o).slice(0,Math.max(8,t-1))}`}function Ke(e,t,n){let o=v=>{let _=v.replace(/\r\n/g,`
317
317
  `);return _.endsWith(`
318
318
  `)||_===""?_:_+`
319
- `},r=o(e),s=o(t);if(r===s)return null;let l=Math.max(20,n-10),p=jp("a","b",r,s,"","",{context:3}),m=0,k=0,g=[];p.hunks.forEach((v,_)=>{_>0&&g.push(al.gray(" \u2026"));let P=v.oldStart,N=v.newStart,T=[],M=[],B=()=>{for(let V=0;V<T.length;V++){let Y=V<M.length?dl(T[V],M[V]):void 0;k++,g.push(`${Ap}${rs(P++)} - ${ul(T[V],l,Y)}${cl}`)}for(let V=0;V<M.length;V++){let Y=V<T.length?dl(T[V],M[V]):void 0;m++,g.push(`${Ep}${rs(N++)} + ${ul(M[V],l,Y)}${cl}`)}T=[],M=[]};for(let V of v.lines){let Y=V[0],ne=V.slice(1);Y==="-"?T.push(ne):Y==="+"?M.push(ne):(B(),g.push(al.gray(rs(N))+" "+ne.slice(0,l)),P++,N++)}B()});let S=g.slice(0,ll);return{added:m,removed:k,lines:S,hidden:Math.max(0,g.length-ll)}}W();import{select as Np}from"@inquirer/prompts";import{applyPull as Ip,computeSyncStatus as _p,planPull as Op}from"document360-engine";var pl=e=>e===1?"":"s";async function ss(e,t){console.log(""),console.log(`${O("\u25CF")} ${ye(t.title)} ${ae(`(${t.path})`)}`);for(let r of t.notes)console.log(L(` \u26A0 ${r}`));let n=Ke(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(ae(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${pl(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(f(` \u2026 +${n.hidden} more diff lines`))}else console.log(f(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>Np({message:`Conflict \u2014 ${t.path}`,choices:[{name:"Keep local (publish \u2014 overwrites the portal edit)",value:"local"},{name:"Take portal (overwrites your local edits)",value:"portal"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip");return o==="portal"?(Ip({cwd:e.cwd,profileName:e.profileName},t),console.log(D(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(f(" Skipped \u2014 still a conflict.")),"skipped")}async function fl(e,t){let n=Ne(t.cwd,t.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await _p({cwd:t.cwd,profileName:t.profileName})).entries.filter(p=>p.status==="conflict"&&p.path).map(p=>p.path);if(o){if(!s.includes(o))return console.log(D(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(D("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let l=[];for(let p of s){let m=await Op({cwd:t.cwd,profileName:t.profileName,relPath:p});await ss(t,m)==="keep-local"&&l.push(p)}if(l.length>0)return console.log(f(`Publishing ${l.length} kept-local article${pl(l.length)} over the portal\u2026`)),await bt(t,l)}catch(r){console.log(R(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function gl(e,t){let n=Ne(t.cwd,t.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Bp(t),{kind:"continue"};if(o==="--baseline")return await Vp(t,e.filter(l=>l!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Gp(t),{kind:"continue"};if(o)return console.log(R(`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 Yp(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await as({cwd:t.cwd,profileName:t.profileName});for(let l of ls(s))console.log(l.tone==="ok"?D(l.text):l.tone==="warn"?L(l.text):f(l.text));console.log("")}catch(r){r instanceof qp?console.log(R(r.message)):console.log(R(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function as(e){let t=await hl({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 ml({cwd:e.cwd,profileName:e.profileName,relPath:o.path});is({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 Up({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Wp({cwd:e.cwd,profileName:e.profileName},r),n.imported.push({title:r.title,path:r.path})}catch(r){n.failed.push({ref:o.title??o.articleId,error:r.message})}else o.status==="conflict"&&o.path?n.conflicts.push(o.path):(o.status==="local-ahead"||o.status==="untracked-local"&&!o.link)&&o.path&&n.toPublish++;return n}var No=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,vt=e=>e===1?"":"s";function ls(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${vt(e.pulled.length)} into local: ${No(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${vt(e.imported.length)}: ${No(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${vt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${vt(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's). (${No(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${vt(e.failed.length)} failed: ${No(e.failed.map(n=>n.ref))}`}),t.length===0&&t.push({tone:"ok",text:"\u2713 Already in sync with Document360 \u2014 nothing to pull."}),t}async function Bp(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await hl({cwd:e.cwd,profileName:e.profileName});for(let o of Eo(n,Date.now()-t))console.log(o);console.log("")}async function Vp(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 Fp({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Hp({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(D("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(D(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(D(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(L(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(f(` - ${s.path} (${s.reason})`))}}async function Gp(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Mp({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${ye(String(t.legacyCount))} \xB7 Manifest: ${ye(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(D("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(R(`\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 Yp(e,t){let n=t.replace(/\\/g,"/"),o=await ml({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await ss(e,o)==="keep-local"&&(console.log(f(`Publishing ${o.path} over the portal\u2026`)),await bt(e,[o.path]));return}console.log(""),console.log(`${O("\u25CF")} ${ye(o.title)} ${ae(`(${o.path})`)}`);for(let l of o.notes)console.log(L(` \u26A0 ${l}`));let r=Ke(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.")),is({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ae(` \u23BF Added ${r.added} line${vt(r.added)}, removed ${r.removed} line${vt(r.removed)}`));for(let l of r.lines)console.log(l);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Lp({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}is({cwd:e.cwd,profileName:e.profileName},o),console.log(D(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as zp}from"node:fs";import{resolve as Kp}from"node:path";import{estimateBulkCost as Xp,planPartitions as Qp,readProjectConfig as Jp,resolveModelForOperation as Zp,runPartitioned as ef,trackedArticlePaths as tf}from"document360-engine";var cs=3;function ds(e){let t,n=!1;for(let r=0;r<e.length;r++){let s=e[r];s==="--run"||s==="--yes"?n=!0:s==="--scope"?t=e[++r]:s?.startsWith("--scope=")&&(t=s.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function us(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function ps(e,t){return t.map(n=>{let o=0;try{o=zp(Kp(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function fs(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:
319
+ `},r=o(e),s=o(t);if(r===s)return null;let l=Math.max(20,n-10),p=jp("a","b",r,s,"","",{context:3}),m=0,k=0,g=[];p.hunks.forEach((v,_)=>{_>0&&g.push(al.gray(" \u2026"));let P=v.oldStart,N=v.newStart,S=[],M=[],B=()=>{for(let V=0;V<S.length;V++){let Y=V<M.length?dl(S[V],M[V]):void 0;k++,g.push(`${Ap}${rs(P++)} - ${ul(S[V],l,Y)}${cl}`)}for(let V=0;V<M.length;V++){let Y=V<S.length?dl(S[V],M[V]):void 0;m++,g.push(`${Ep}${rs(N++)} + ${ul(M[V],l,Y)}${cl}`)}S=[],M=[]};for(let V of v.lines){let Y=V[0],ne=V.slice(1);Y==="-"?S.push(ne):Y==="+"?M.push(ne):(B(),g.push(al.gray(rs(N))+" "+ne.slice(0,l)),P++,N++)}B()});let T=g.slice(0,ll);return{added:m,removed:k,lines:T,hidden:Math.max(0,g.length-ll)}}W();import{select as Np}from"@inquirer/prompts";import{applyPull as Ip,computeSyncStatus as _p,planPull as Op}from"document360-engine";var pl=e=>e===1?"":"s";async function ss(e,t){console.log(""),console.log(`${O("\u25CF")} ${ye(t.title)} ${ae(`(${t.path})`)}`);for(let r of t.notes)console.log(L(` \u26A0 ${r}`));let n=Ke(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(ae(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${pl(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(f(` \u2026 +${n.hidden} more diff lines`))}else console.log(f(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>Np({message:`Conflict \u2014 ${t.path}`,choices:[{name:"Keep local (publish \u2014 overwrites the portal edit)",value:"local"},{name:"Take portal (overwrites your local edits)",value:"portal"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip");return o==="portal"?(Ip({cwd:e.cwd,profileName:e.profileName},t),console.log(D(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(f(" Skipped \u2014 still a conflict.")),"skipped")}async function fl(e,t){let n=Ne(t.cwd,t.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await _p({cwd:t.cwd,profileName:t.profileName})).entries.filter(p=>p.status==="conflict"&&p.path).map(p=>p.path);if(o){if(!s.includes(o))return console.log(D(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(D("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let l=[];for(let p of s){let m=await Op({cwd:t.cwd,profileName:t.profileName,relPath:p});await ss(t,m)==="keep-local"&&l.push(p)}if(l.length>0)return console.log(f(`Publishing ${l.length} kept-local article${pl(l.length)} over the portal\u2026`)),await bt(t,l)}catch(r){console.log(R(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function gl(e,t){let n=Ne(t.cwd,t.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Bp(t),{kind:"continue"};if(o==="--baseline")return await Vp(t,e.filter(l=>l!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Gp(t),{kind:"continue"};if(o)return console.log(R(`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 Yp(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await as({cwd:t.cwd,profileName:t.profileName});for(let l of ls(s))console.log(l.tone==="ok"?D(l.text):l.tone==="warn"?L(l.text):f(l.text));console.log("")}catch(r){r instanceof qp?console.log(R(r.message)):console.log(R(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function as(e){let t=await hl({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 ml({cwd:e.cwd,profileName:e.profileName,relPath:o.path});is({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 Up({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Wp({cwd:e.cwd,profileName:e.profileName},r),n.imported.push({title:r.title,path:r.path})}catch(r){n.failed.push({ref:o.title??o.articleId,error:r.message})}else o.status==="conflict"&&o.path?n.conflicts.push(o.path):(o.status==="local-ahead"||o.status==="untracked-local"&&!o.link)&&o.path&&n.toPublish++;return n}var No=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,vt=e=>e===1?"":"s";function ls(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${vt(e.pulled.length)} into local: ${No(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${vt(e.imported.length)}: ${No(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${vt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${vt(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's). (${No(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${vt(e.failed.length)} failed: ${No(e.failed.map(n=>n.ref))}`}),t.length===0&&t.push({tone:"ok",text:"\u2713 Already in sync with Document360 \u2014 nothing to pull."}),t}async function Bp(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await hl({cwd:e.cwd,profileName:e.profileName});for(let o of Eo(n,Date.now()-t))console.log(o);console.log("")}async function Vp(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 Fp({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Hp({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(D("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(D(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(D(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(L(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(f(` - ${s.path} (${s.reason})`))}}async function Gp(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Mp({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${ye(String(t.legacyCount))} \xB7 Manifest: ${ye(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(D("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(R(`\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 Yp(e,t){let n=t.replace(/\\/g,"/"),o=await ml({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await ss(e,o)==="keep-local"&&(console.log(f(`Publishing ${o.path} over the portal\u2026`)),await bt(e,[o.path]));return}console.log(""),console.log(`${O("\u25CF")} ${ye(o.title)} ${ae(`(${o.path})`)}`);for(let l of o.notes)console.log(L(` \u26A0 ${l}`));let r=Ke(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.")),is({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ae(` \u23BF Added ${r.added} line${vt(r.added)}, removed ${r.removed} line${vt(r.removed)}`));for(let l of r.lines)console.log(l);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Lp({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}is({cwd:e.cwd,profileName:e.profileName},o),console.log(D(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as zp}from"node:fs";import{resolve as Kp}from"node:path";import{estimateBulkCost as Xp,planPartitions as Qp,readProjectConfig as Jp,resolveModelForOperation as Zp,runPartitioned as ef,trackedArticlePaths as tf}from"document360-engine";var cs=3;function ds(e){let t,n=!1;for(let r=0;r<e.length;r++){let s=e[r];s==="--run"||s==="--yes"?n=!0:s==="--scope"?t=e[++r]:s?.startsWith("--scope=")&&(t=s.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function us(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function ps(e,t){return t.map(n=>{let o=0;try{o=zp(Kp(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function fs(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:
320
320
  - 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.
321
321
  - 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.
322
322
  - 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.
323
323
  - Work only on these files:
324
324
  `+e.paths.map(t=>`- ${t}`).join(`
325
- `)}function hs(e,t,n){let o=e.reduce((p,m)=>p+m.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${ke(r)}\u2013${ke(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function ms(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),s=e.filter(P=>!P.ok),l=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),m=e.reduce((P,N)=>P+N.costUsd,0),k=e.reduce((P,N)=>P+N.outputTokens,0),g=n==="api"?`${ke(m)} total`:st(k),S=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=P=>`${P} article${P===1?"":"s"}`,_=[];if(s.length===0)_.push(`Converted ${v(l)} (${S}) successfully \xB7 ${g}.`);else{_.push(`Converted ${p}/${v(l)} (${S}) \xB7 ${g}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let P of s)_.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return _}async function wl(e,t){if(!Jp(t.cwd))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=ds(e),r=tf(t.cwd,t.profileName);if(r.length===0)return console.log(R("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=us(r,n);if(s.length===0)return console.log(R(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let l=Qp(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:m,forced:k}=Zp(t.cwd,"light");if(!o){let g=Xp({files:ps(t.cwd,s),op:"convert",model:m});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let S of hs(l,g,cs))console.log(S);return console.log(f(`Model: ${m}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${l.length} partitions (\u2264${cs} agents at once) on ${m}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let g of ef({cwd:t.cwd,partitions:l,promptFor:fs,concurrency:cs,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:m}))if(g.type==="partition_status")g.status==="running"?console.log(f(` \u25B8 ${g.label} \u2014 converting\u2026`)):g.status==="done"?console.log(D(` \u2713 ${g.label}`)):console.log(R(` \u2717 ${g.label}`));else if(g.type==="run_done"){console.log("");let S=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let v of ms(g.results,l,S))console.log(g.ok?D(v):L(v))}}catch(g){console.log(R(`Convert run failed: ${g.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as bl}from"node:fs";import{resolve as vl}from"node:path";import{estimateBulkCost as uf,lintDocs as pf,planPartitions as ff,readDocsPlan as hf,readProjectConfig as $l,DEFAULT_DOCS_DIR as mf,resolveModelForOperation as gf,runPartitioned as wf,stampArticles as yf,CONTENT_CAP_VERSION as kf}from"document360-engine";import{readProjectConfig as nf,loadProfileMap as of,resolveActiveProfile as rf,desiredCategoryOrder as sf,desiredArticleOrder as af,DEFAULT_DOCS_DIR as lf}from"document360-engine";var gs=e=>e.replace(/\\/g,"/"),cf=e=>gs(e).split("/").pop()??e;function df(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function Sn(e,t){try{let n=nf(e);if(!n)return[];let o=rf(e,t),r=of(e,o.name);if(!r)return[];let s=gs(n.docsDir??lf).replace(/\/+$/,""),l=new Map;for(let m of af(r))l.set(m.categoryPath,(l.get(m.categoryPath)??0)+1);let p=[];for(let m of sf(r)){let k=gs(m.path),g=k.startsWith(`${s}/`)?k.slice(s.length+1):k===s?"":k;g&&p.push({token:g,label:df(cf(k)),count:l.get(m.path)??0})}return p}catch{return[]}}function yl(e,t){let n=Sn(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 it(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function Jt(e,t,n,o){let r=Sn(e,o);if(r.length<=1)return[];let s=n.filter(k=>k.startsWith("--")).join(" "),l=s?` ${s}`:"",p=`/${t}${l} --all`.replace(/\s+/g," "),m=k=>t==="write"?`/write --scope ${k}${l}`:`/${t} ${k}${l}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((k,g)=>k+g.count,0)} articles). Pick a target:`,` ${p} (everything)`,...r.map(k=>` ${m(k.token)} (${k.label} \xB7 ${k.count} article${k.count===1?"":"s"})`)]}function Io(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function kl(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 bf=3,vf=8;function ws(e){return e===void 0||!Number.isFinite(e)?bf:Math.max(1,Math.min(Math.floor(e),vf))}function ys(e){let t,n,o=!1,r=!1,s,l=m=>{let k=Number(m);return m!==void 0&&Number.isFinite(k)?k:void 0};for(let m=0;m<e.length;m++){let k=e[m];if(k==="--preview"||k==="--dry-run")o=!0;else if(k==="--rewrite"||k==="--force")r=!0;else{if(k==="--run"||k==="--yes"||k==="--all")continue;k==="--scope"?t=e[++m]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?s=l(e[++m]):k?.startsWith("--concurrency=")?s=l(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=m=>m?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function $f(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function xf(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function ks(e,t,n){return n.filter(o=>{try{return bl(vl(e,t,o)).size===0}catch{return!0}})}function bs(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let l of o.get(r)?.sources??[])try{s+=bl(vl(e,l)).size}catch{}return{path:r,bytes:s}})}function vs(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.
325
+ `)}function hs(e,t,n){let o=e.reduce((p,m)=>p+m.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${ke(r)}\u2013${ke(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function ms(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),s=e.filter(P=>!P.ok),l=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),m=e.reduce((P,N)=>P+N.costUsd,0),k=e.reduce((P,N)=>P+N.outputTokens,0),g=n==="api"?`${ke(m)} total`:st(k),T=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=P=>`${P} article${P===1?"":"s"}`,_=[];if(s.length===0)_.push(`Converted ${v(l)} (${T}) successfully \xB7 ${g}.`);else{_.push(`Converted ${p}/${v(l)} (${T}) \xB7 ${g}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let P of s)_.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return _}async function wl(e,t){if(!Jp(t.cwd))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=ds(e),r=tf(t.cwd,t.profileName);if(r.length===0)return console.log(R("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=us(r,n);if(s.length===0)return console.log(R(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let l=Qp(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:m,forced:k}=Zp(t.cwd,"light");if(!o){let g=Xp({files:ps(t.cwd,s),op:"convert",model:m});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let T of hs(l,g,cs))console.log(T);return console.log(f(`Model: ${m}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${l.length} partitions (\u2264${cs} agents at once) on ${m}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let g of ef({cwd:t.cwd,partitions:l,promptFor:fs,concurrency:cs,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:m}))if(g.type==="partition_status")g.status==="running"?console.log(f(` \u25B8 ${g.label} \u2014 converting\u2026`)):g.status==="done"?console.log(D(` \u2713 ${g.label}`)):console.log(R(` \u2717 ${g.label}`));else if(g.type==="run_done"){console.log("");let T=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let v of ms(g.results,l,T))console.log(g.ok?D(v):L(v))}}catch(g){console.log(R(`Convert run failed: ${g.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as bl}from"node:fs";import{resolve as vl}from"node:path";import{estimateBulkCost as uf,lintDocs as pf,planPartitions as ff,readDocsPlan as hf,readProjectConfig as $l,DEFAULT_DOCS_DIR as mf,resolveModelForOperation as gf,runPartitioned as wf,stampArticles as yf,CONTENT_CAP_VERSION as kf}from"document360-engine";import{readProjectConfig as nf,loadProfileMap as of,resolveActiveProfile as rf,desiredCategoryOrder as sf,desiredArticleOrder as af,DEFAULT_DOCS_DIR as lf}from"document360-engine";var gs=e=>e.replace(/\\/g,"/"),cf=e=>gs(e).split("/").pop()??e;function df(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function Tn(e,t){try{let n=nf(e);if(!n)return[];let o=rf(e,t),r=of(e,o.name);if(!r)return[];let s=gs(n.docsDir??lf).replace(/\/+$/,""),l=new Map;for(let m of af(r))l.set(m.categoryPath,(l.get(m.categoryPath)??0)+1);let p=[];for(let m of sf(r)){let k=gs(m.path),g=k.startsWith(`${s}/`)?k.slice(s.length+1):k===s?"":k;g&&p.push({token:g,label:df(cf(k)),count:l.get(m.path)??0})}return p}catch{return[]}}function yl(e,t){let n=Tn(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 it(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function Jt(e,t,n,o){let r=Tn(e,o);if(r.length<=1)return[];let s=n.filter(k=>k.startsWith("--")).join(" "),l=s?` ${s}`:"",p=`/${t}${l} --all`.replace(/\s+/g," "),m=k=>t==="write"?`/write --scope ${k}${l}`:`/${t} ${k}${l}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((k,g)=>k+g.count,0)} articles). Pick a target:`,` ${p} (everything)`,...r.map(k=>` ${m(k.token)} (${k.label} \xB7 ${k.count} article${k.count===1?"":"s"})`)]}function Io(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function kl(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 bf=3,vf=8;function ws(e){return e===void 0||!Number.isFinite(e)?bf:Math.max(1,Math.min(Math.floor(e),vf))}function ys(e){let t,n,o=!1,r=!1,s,l=m=>{let k=Number(m);return m!==void 0&&Number.isFinite(k)?k:void 0};for(let m=0;m<e.length;m++){let k=e[m];if(k==="--preview"||k==="--dry-run")o=!0;else if(k==="--rewrite"||k==="--force")r=!0;else{if(k==="--run"||k==="--yes"||k==="--all")continue;k==="--scope"?t=e[++m]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?s=l(e[++m]):k?.startsWith("--concurrency=")?s=l(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=m=>m?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function $f(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function xf(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function ks(e,t,n){return n.filter(o=>{try{return bl(vl(e,t,o)).size===0}catch{return!0}})}function bs(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let l of o.get(r)?.sources??[])try{s+=bl(vl(e,l)).size}catch{}return{path:r,bytes:s}})}function vs(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.
326
326
  `:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
327
- - It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose, its \`type\` (concept | task | reference | faq; missing \u21D2 task), and the source files it draws from (AGENT-PLAN.md has the same table).
328
- - Use the skeleton for that \`type\` (see write-article): a \`concept\`/overview page opens with what the product IS + its mental model and takes NO Prerequisites/Steps; only a \`task\` page gets Steps.
327
+ - It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose, its \`type\` (concept | task | reference | faq | tutorial | troubleshooting | best-practices | use-case; missing \u21D2 task), and the source files it draws from (AGENT-PLAN.md has the same table).
328
+ - Use the skeleton for that \`type\` (see write-article): a \`concept\`/overview page opens with what the product IS + its mental model and takes NO Prerequisites/Steps; only a \`task\` or \`tutorial\` page gets numbered steps (a tutorial ends every stage with a visible checkpoint); a \`troubleshooting\` page is symptom \u2192 cause \u2192 fix. Titles follow the type grammar (task: "How to <verb> <object>"; concept: "Understanding <X>"; troubleshooting: the symptom the user sees).
329
329
  - 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.
330
330
  `+o+`- Write the finished article to ${t}/<path>, following the write-article structure and the project terminologyGlossary. Add the \`sources:\` frontmatter listing the files you actually read.
331
331
  - Emit \`<!-- SCREENSHOT -->\` placeholders where a visual helps, but do NOT author capture specs now.
332
332
  - 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.
333
333
  Articles:
334
334
  `+e.paths.map(r=>`- ${r}`).join(`
335
- `)}function $s(e,t,n){let o=e.reduce((l,p)=>l+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(l=>` \u2022 ${l.label} \u2014 ${l.paths.length} article${l.paths.length===1?"":"s"}`),"",`Estimated cost: ${ke(r)}\u2013${ke(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function xs(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),s=e.filter(P=>!P.ok),l=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),m=e.reduce((P,N)=>P+N.costUsd,0),k=e.reduce((P,N)=>P+N.outputTokens,0),g=n==="api"?`${ke(m)} total`:st(k),S=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=P=>`${P} article${P===1?"":"s"}`,_=[];if(s.length===0)_.push(`Wrote ${v(l)} (${S}) successfully \xB7 ${g}.`),_.push("Next \u2014 push them to Document360:"),_.push("/publish --all"),_.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{_.push(`Wrote ${p}/${v(l)} (${S}) \xB7 ${g}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let P of s)_.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return _}function Cs(e,t,n){try{let o=pf({cwd:e,paths:n.map(s=>`${t}/${s}`)});if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 /check --fix corrects them.`}catch{return null}}function Rs(e,t,n){let o=($l(e)?.docsDir??mf).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=$f(n.path,o);return r.includes(p)?{docsDir:o,targets:[p],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${p}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=xf(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let l=ks(e,o,s);if(l.length===0){let p=n.scope?` under "${n.scope}"`:"",m=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${m} --rewrite to regenerate them all.`}}return{docsDir:o,targets:l,planCount:r.length}}async function xl(e,t){if(!$l(t.cwd))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Io(e)){for(let M of yl(t.cwd,t.profileName))console.log(f(M));return{kind:"continue"}}if(it("write",e)){let M=Jt(t.cwd,"write",e,t.profileName);if(M.length>0){for(let B of M)console.log(f(B));return{kind:"continue"}}}let n=hf(t.cwd);if(n.length===0)return console.log(R("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:l,rewrite:p}=ys(e),{docsDir:m,targets:k,reason:g,rewriting:S}=Rs(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(g?L(g):L("Nothing to write.")),{kind:"continue"};S&&console.log(L(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let v=ff(k),_=ws(l),{model:P,forced:N}=gf(t.cwd,"standard"),T=!!r;if(s&&!T){let M=uf({files:bs(t.cwd,n,k),op:"write",model:P});o&&console.log(f(`Scope: ${o} (${k.length} pending).`));for(let B of $s(v,M,_))console.log(B);return console.log(f(`Model: ${P}${N?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${k.length} article${k.length===1?"":"s"} across ${v.length} partition${v.length===1?"":"s"} (\u2264${_} agents at once) on ${P}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let M of wf({cwd:t.cwd,partitions:v,promptFor:B=>vs(B,m,{rewrite:S||T}),concurrency:_,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:P}))if(M.type==="partition_status")M.status==="running"?console.log(f(` \u25B8 ${M.label} \u2014 writing\u2026`)):M.status==="done"?console.log(D(` \u2713 ${M.label}`)):console.log(R(` \u2717 ${M.label}`));else if(M.type==="run_done"){console.log("");let B=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let Y of xs(M.results,v,B))console.log(M.ok?D(Y):L(Y));if(M.ok)try{yf(t.cwd,k.map(Y=>`${m}/${Y}`),{writtenCap:kf})}catch{}let V=Cs(t.cwd,m,k);V&&console.log(L(V))}}catch(M){console.log(R(`Write run failed: ${M.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as Cf,readdirSync as Cl,statSync as Rl}from"node:fs";import{join as Pl}from"node:path";import{inputDir as Rf,readProjectConfig as Pf}from"document360-engine";var Sl=/\.(md|markdown|pdf|txt)$/i;function Ps(e){let t=Rf(e);if(!Cf(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Cl(t)){let s=Pl(t,r),l=!1;try{l=Rl(s).isDirectory()}catch{continue}if(l){if(r.startsWith("."))continue;let p=Sf(s);p>0&&n.push({name:r,docCount:p})}else Sl.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Sf(e){let t=0;for(let n of Cl(e))try{Rl(Pl(e,n)).isFile()&&Sl.test(n)&&t++}catch{}return t}function Ss(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 _o(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(`
336
- `)}var Ts="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(!Pf(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Ps(n);if(o.length===0&&r===0)return console.log(f(Ts)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let m of o)console.log(` ${m.name} ${f(`(${m.docCount} doc${m.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:_o(p),display:p?`/draft ${p}`:"/draft"}}let l=Ss(o,s);return{kind:"forward-to-agent",prompt:_o(l??"",l?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as Tf,readProjectConfig as Df}from"document360-engine";function Ds(e){try{return Tf(e).filter(t=>t.kind==="request").length}catch{return 0}}function js(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function As(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(`
337
- `)}var Es="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 Dl(e,t){let n=t?.cwd??process.cwd();if(!Df(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=js(e);if(!r&&Ds(n)===0)return console.log(f(Es)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:As(r,o),display:s}}W();import{search as jf}from"@inquirer/prompts";import{findByName as Af,getSession as Ef,listSessions as Nf,relativeTime as Al}from"document360-engine";async function El(e,t){let n=Nf(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=Af(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(R(`No session matches "${o}".`)),jl(n),{kind:"continue"})}if(!process.stdin.isTTY)return jl(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>jf({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let l=(s??"").toLowerCase();return n.filter(p=>!l||p.name.toLowerCase().includes(l)||p.firstPrompt.toLowerCase().includes(l)).map(p=>({name:`${p.name} ${Al(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Ef(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function jl(e){console.log("");for(let t of e.slice(0,15))console.log(` ${O(t.name)} ${f(Al(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as If}from"document360-engine";function Ns(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 Nl(e,t){let n=Ns(e.join(" "));if(!n)return console.log(R("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(If(o,n)?console.log(D(`\u2713 Session renamed to "${n}"`)):console.log(R("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(D(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Il,readProjectConfig as _f,writeProjectConfig as Of}from"document360-engine";W();function Is(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=_f(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 Il().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Of(o,e),null):`Unknown environment "${r}". Known: ${Il().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function _l(e,t){let n=e[0];if(!n)return mo(t.cwd),{kind:"continue"};if(n==="add"){let o=Is(t.cwd,e[1],e[2]);return o?(console.log(R(o)),{kind:"continue"}):(console.log(D(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${O(`/profile ${e[1]}`)} then ${O("/login")}`),{kind:"continue"})}return go(t.cwd,n),wo(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Lf}from"@inquirer/prompts";import{readProjectConfig as Mf,readUserConfig as Ol,resolveModelSetting as _s,writeUserConfig as Ll}from"document360-engine";var We=[{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 Oo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=We.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Uf(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 Tn(e,t){let n=()=>_s(e).model;if(t==="default"){let s=Ol();return s.defaultModel?(delete s.defaultModel,Ll(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${_s(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}}Ll({...Ol(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Mf(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 Ml(e,t){let n=e[0]?.trim();if(!n){let l=_s(t.cwd);if(!process.stdin.isTTY)return console.log(`${ye("Model:")} ${O(l.model)}${l.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${Uf(l)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Oo(l),m;try{m=await t.withPausedInput(()=>Lf({message:`Select model (current: ${l.model}${l.source==="auto"?" \xB7 auto":""})`,default:We[p].value,choices:We.map((v,_)=>({name:`${v.label}${_===p?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:g,effective:S}=Tn(t.cwd,m??"default");for(let v of k)console.log(v.startsWith("\u26A0")?L(v):v.startsWith("\u2713")?D(v):f(v));return g&&await t.setModel(S),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Tn(t.cwd,n);for(let l of o)console.log(l.startsWith("\u26A0")?L(l):l.startsWith("\u2713")?D(l):f(l));return r&&await t.setModel(s),{kind:"continue"}}Lo();async function Bl(e,t){return await t.withPausedInput(()=>Vt(t.cwd)),{kind:"clear"}}async function Vl(e,t){return await t.withPausedInput(()=>uo(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as oh}from"document360-engine";async function Gl(e,t){let n=!1;try{n=oh(t.cwd).production}catch{}return n?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var Yl=async(e,t)=>{try{await t.withPausedInput(()=>ho({}))}catch(n){console.log(R(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as rh,clearTokens as sh,clearProfileProject as ih}from"document360-engine";async function zl(e,t){let n;try{n=rh(t.cwd,t.profileName).name}catch(r){return console.log(R(r.message)),{kind:"continue"}}let o=sh(n);return ih(t.cwd,n),console.log(o?D(`\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 Kl}from"node:fs";import{isAbsolute as ah,join as lh,resolve as ch}from"node:path";import{readProjectConfig as dh,screenshotPlaceholderIds as uh,DEFAULT_CAPTURE_DIR as ph,DEFAULT_OUTPUT_DIR as fh}from"document360-engine";var Xl=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ls(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Xl(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Xl(o),setup:t}:{mode:"single",id:o}}function Ms(e,t){let n=dh(e),o=n?.captureDir??ph,r=n?.outputDir??fh,s=(l,p)=>ah(l)?lh(l,p):ch(e,l,p);return uh(e,{scope:t}).map(({id:l,file:p})=>{let m=Kl(s(r,`${l}.png`))?"captured":Kl(s(o,`${l}.spec.ts`))?"spec":"placeholder";return{id:l,file:p,state:m}})}var hh={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},mh={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Us(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(s=>s.file))].sort(),o=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of n){r.push(s);for(let l of e.filter(p=>p.file===s))r.push(` ${hh[l.state]} ${l.id.padEnd(34)} ${mh[l.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Ql(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(`
335
+ `)}function $s(e,t,n){let o=e.reduce((l,p)=>l+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(l=>` \u2022 ${l.label} \u2014 ${l.paths.length} article${l.paths.length===1?"":"s"}`),"",`Estimated cost: ${ke(r)}\u2013${ke(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function xs(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),s=e.filter(P=>!P.ok),l=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),m=e.reduce((P,N)=>P+N.costUsd,0),k=e.reduce((P,N)=>P+N.outputTokens,0),g=n==="api"?`${ke(m)} total`:st(k),T=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=P=>`${P} article${P===1?"":"s"}`,_=[];if(s.length===0)_.push(`Wrote ${v(l)} (${T}) successfully \xB7 ${g}.`),_.push("Next \u2014 push them to Document360:"),_.push("/publish --all"),_.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{_.push(`Wrote ${p}/${v(l)} (${T}) \xB7 ${g}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let P of s)_.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return _}function Cs(e,t,n){try{let o=pf({cwd:e,paths:n.map(s=>`${t}/${s}`)});if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 /check --fix corrects them.`}catch{return null}}function Rs(e,t,n){let o=($l(e)?.docsDir??mf).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=$f(n.path,o);return r.includes(p)?{docsDir:o,targets:[p],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${p}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=xf(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let l=ks(e,o,s);if(l.length===0){let p=n.scope?` under "${n.scope}"`:"",m=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${m} --rewrite to regenerate them all.`}}return{docsDir:o,targets:l,planCount:r.length}}async function xl(e,t){if(!$l(t.cwd))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Io(e)){for(let M of yl(t.cwd,t.profileName))console.log(f(M));return{kind:"continue"}}if(it("write",e)){let M=Jt(t.cwd,"write",e,t.profileName);if(M.length>0){for(let B of M)console.log(f(B));return{kind:"continue"}}}let n=hf(t.cwd);if(n.length===0)return console.log(R("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:l,rewrite:p}=ys(e),{docsDir:m,targets:k,reason:g,rewriting:T}=Rs(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(g?L(g):L("Nothing to write.")),{kind:"continue"};T&&console.log(L(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let v=ff(k),_=ws(l),{model:P,forced:N}=gf(t.cwd,"standard"),S=!!r;if(s&&!S){let M=uf({files:bs(t.cwd,n,k),op:"write",model:P});o&&console.log(f(`Scope: ${o} (${k.length} pending).`));for(let B of $s(v,M,_))console.log(B);return console.log(f(`Model: ${P}${N?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${k.length} article${k.length===1?"":"s"} across ${v.length} partition${v.length===1?"":"s"} (\u2264${_} agents at once) on ${P}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let M of wf({cwd:t.cwd,partitions:v,promptFor:B=>vs(B,m,{rewrite:T||S}),concurrency:_,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:P}))if(M.type==="partition_status")M.status==="running"?console.log(f(` \u25B8 ${M.label} \u2014 writing\u2026`)):M.status==="done"?console.log(D(` \u2713 ${M.label}`)):console.log(R(` \u2717 ${M.label}`));else if(M.type==="run_done"){console.log("");let B=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let Y of xs(M.results,v,B))console.log(M.ok?D(Y):L(Y));if(M.ok)try{yf(t.cwd,k.map(Y=>`${m}/${Y}`),{writtenCap:kf})}catch{}let V=Cs(t.cwd,m,k);V&&console.log(L(V))}}catch(M){console.log(R(`Write run failed: ${M.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as Cf,readdirSync as Cl,statSync as Rl}from"node:fs";import{join as Pl}from"node:path";import{inputDir as Rf,readProjectConfig as Pf}from"document360-engine";var Tl=/\.(md|markdown|pdf|txt)$/i;function Ps(e){let t=Rf(e);if(!Cf(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Cl(t)){let s=Pl(t,r),l=!1;try{l=Rl(s).isDirectory()}catch{continue}if(l){if(r.startsWith("."))continue;let p=Tf(s);p>0&&n.push({name:r,docCount:p})}else Tl.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Tf(e){let t=0;for(let n of Cl(e))try{Rl(Pl(e,n)).isFile()&&Tl.test(n)&&t++}catch{}return t}function Ts(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 _o(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(`
336
+ `)}var Ss="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Sl(e,t){let n=t?.cwd??process.cwd();if(!Pf(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Ps(n);if(o.length===0&&r===0)return console.log(f(Ss)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let m of o)console.log(` ${m.name} ${f(`(${m.docCount} doc${m.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:_o(p),display:p?`/draft ${p}`:"/draft"}}let l=Ts(o,s);return{kind:"forward-to-agent",prompt:_o(l??"",l?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as Sf,readProjectConfig as Df}from"document360-engine";function Ds(e){try{return Sf(e).filter(t=>t.kind==="request").length}catch{return 0}}function js(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function As(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(`
337
+ `)}var Es="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 Dl(e,t){let n=t?.cwd??process.cwd();if(!Df(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=js(e);if(!r&&Ds(n)===0)return console.log(f(Es)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:As(r,o),display:s}}W();import{search as jf}from"@inquirer/prompts";import{findByName as Af,getSession as Ef,listSessions as Nf,relativeTime as Al}from"document360-engine";async function El(e,t){let n=Nf(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=Af(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(R(`No session matches "${o}".`)),jl(n),{kind:"continue"})}if(!process.stdin.isTTY)return jl(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>jf({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let l=(s??"").toLowerCase();return n.filter(p=>!l||p.name.toLowerCase().includes(l)||p.firstPrompt.toLowerCase().includes(l)).map(p=>({name:`${p.name} ${Al(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Ef(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function jl(e){console.log("");for(let t of e.slice(0,15))console.log(` ${O(t.name)} ${f(Al(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as If}from"document360-engine";function Ns(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 Nl(e,t){let n=Ns(e.join(" "));if(!n)return console.log(R("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(If(o,n)?console.log(D(`\u2713 Session renamed to "${n}"`)):console.log(R("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(D(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Il,readProjectConfig as _f,writeProjectConfig as Of}from"document360-engine";W();function Is(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=_f(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 Il().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Of(o,e),null):`Unknown environment "${r}". Known: ${Il().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function _l(e,t){let n=e[0];if(!n)return mo(t.cwd),{kind:"continue"};if(n==="add"){let o=Is(t.cwd,e[1],e[2]);return o?(console.log(R(o)),{kind:"continue"}):(console.log(D(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${O(`/profile ${e[1]}`)} then ${O("/login")}`),{kind:"continue"})}return go(t.cwd,n),wo(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Lf}from"@inquirer/prompts";import{readProjectConfig as Mf,readUserConfig as Ol,resolveModelSetting as _s,writeUserConfig as Ll}from"document360-engine";var We=[{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 Oo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=We.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Uf(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 Sn(e,t){let n=()=>_s(e).model;if(t==="default"){let s=Ol();return s.defaultModel?(delete s.defaultModel,Ll(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${_s(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}}Ll({...Ol(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Mf(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 Ml(e,t){let n=e[0]?.trim();if(!n){let l=_s(t.cwd);if(!process.stdin.isTTY)return console.log(`${ye("Model:")} ${O(l.model)}${l.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${Uf(l)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Oo(l),m;try{m=await t.withPausedInput(()=>Lf({message:`Select model (current: ${l.model}${l.source==="auto"?" \xB7 auto":""})`,default:We[p].value,choices:We.map((v,_)=>({name:`${v.label}${_===p?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:g,effective:T}=Sn(t.cwd,m??"default");for(let v of k)console.log(v.startsWith("\u26A0")?L(v):v.startsWith("\u2713")?D(v):f(v));return g&&await t.setModel(T),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Sn(t.cwd,n);for(let l of o)console.log(l.startsWith("\u26A0")?L(l):l.startsWith("\u2713")?D(l):f(l));return r&&await t.setModel(s),{kind:"continue"}}Lo();async function Bl(e,t){return await t.withPausedInput(()=>Vt(t.cwd)),{kind:"clear"}}async function Vl(e,t){return await t.withPausedInput(()=>uo(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as oh}from"document360-engine";async function Gl(e,t){let n=!1;try{n=oh(t.cwd).production}catch{}return n?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var Yl=async(e,t)=>{try{await t.withPausedInput(()=>ho({}))}catch(n){console.log(R(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as rh,clearTokens as sh,clearProfileProject as ih}from"document360-engine";async function zl(e,t){let n;try{n=rh(t.cwd,t.profileName).name}catch(r){return console.log(R(r.message)),{kind:"continue"}}let o=sh(n);return ih(t.cwd,n),console.log(o?D(`\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 Kl}from"node:fs";import{isAbsolute as ah,join as lh,resolve as ch}from"node:path";import{readProjectConfig as dh,screenshotPlaceholderIds as uh,DEFAULT_CAPTURE_DIR as ph,DEFAULT_OUTPUT_DIR as fh}from"document360-engine";var Xl=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ls(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Xl(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Xl(o),setup:t}:{mode:"single",id:o}}function Ms(e,t){let n=dh(e),o=n?.captureDir??ph,r=n?.outputDir??fh,s=(l,p)=>ah(l)?lh(l,p):ch(e,l,p);return uh(e,{scope:t}).map(({id:l,file:p})=>{let m=Kl(s(r,`${l}.png`))?"captured":Kl(s(o,`${l}.spec.ts`))?"spec":"placeholder";return{id:l,file:p,state:m}})}var hh={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},mh={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Us(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(s=>s.file))].sort(),o=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of n){r.push(s);for(let l of e.filter(p=>p.file===s))r.push(` ${hh[l.state]} ${l.id.padEnd(34)} ${mh[l.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Ql(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(`
338
338
  `),"","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(`
339
339
  `)}async function Mo(e,t){let n=Ls(e);if(n.mode==="list"){let l=t?.cwd??process.cwd();for(let p of Us(Ms(l,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(`
340
340
  `),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(`
341
341
  `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as gh,readFileSync as wh}from"node:fs";import{isAbsolute as yh,join as kh,resolve as bh}from"node:path";import{readProjectConfig as vh,DEFAULT_CAPTURE_DIR as $h}from"document360-engine";async function jn(){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(`
342
- `),display:"/capture-setup"}}var Jl="-".repeat(64);function Ws(e){let t=$h;try{let g=vh(e);g?.captureDir&&(t=g.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=yh(t)?kh(t,"CAPTURE-TESTID-REQUESTS.json"):bh(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!gh(n))return null;let o;try{let g=JSON.parse(wh(n,"utf8").replace(/^/,""));o=Array.isArray(g?.requests)?g.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(g=>g.file).filter(Boolean)).size,s=o.length,l=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,m=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${l} 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.","",Jl,`Read ${m} and ${k}. They list ${l} 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.",Jl]}ot();W();import{listOpenForDocs as xh,readProjectConfig as Ch}from"document360-engine";function Fs(e){try{return xh(e).length}catch{return 0}}function Hs(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape.",' \u2022 answer to a [discovery]-tagged question (subject starts "[discovery] ") \u2192 this is product-discovery,'," not an article edit: fold the fact into `.d360-writer/product-brief.md` (updating the cited grounding,"," clearing the matching OPEN marker), then RE-RUN the discover-product readiness assessment \u2014 set the"," brief's frontmatter status to `confident` and offer propose-structure if every rubric dimension now"," passes, else ask the next focused batch via d360_ask_builder. Do not touch articles for these."," \u2022 answer (a reply to any other question you asked; `re` = your question id) \u2192 fold the fact into the"," affected article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only \u2014 do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
343
- `)}async function Zl(e,t){let n=t?.cwd??process.cwd();return Ch(n)?Fs(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:Hs(),display:"/inbox"}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as Rh,listOpenForDocs as Ph,listOpenDirectives as Sh,readProjectConfig as Th,computeSyncStatus as Dh,planPull as jh,applyPull as Ah,planImport as Eh,applyImport as Nh}from"document360-engine";function An(e){let t=0,n=0,o=0,r=0;try{t=Rh(e).length}catch{}try{let s=Ph(e);n=s.filter(l=>l.kind==="request").length,o=s.filter(l=>l.kind==="answer").length}catch{}try{r=Sh(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function En(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 Bs(e){return{publish:e.includes("--publish")}}function Vs({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page" \u2014 .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and \u2014 if it already exists \u2014 RE-ASSERTS and VERIFIES that the category is hidden). If the result has `hiddenConfirmed: false` or a `warning`, SURFACE that warning to the user PROMINENTLY at the end of your summary (\u26A0 the internal feedback control zone may be public on their KB \u2014 they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY \u2014 triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.",'4. Decide the right doc actions across ALL of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief \u2014 EXCEPT an answer to a [discovery]-tagged question (subject starts "[discovery] "), which is product discovery: fold it into `.d360-writer/product-brief.md`, then re-run the discover-product readiness assessment (flip the brief to `confident` if every rubric dimension now passes and offer propose-structure, else leave a follow-up [discovery] question) \u2014 address each feedback item (improve the doc it points at \u2014 as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts \u2014 following the active doc-type playbook).',"5. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the loop:"," \u2022 stamp consumed hints, and mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done), 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(`
344
- `)}var Ih={status:Dh,plan:jh,apply:Ah,planImport:Eh,applyImport:Nh};async function Gs(e,t=Ih){let n={pulled:[],imported:[],conflicts:[],failed:[]},o;try{o=await t.status({cwd:e.cwd,profileName:e.profileName})}catch(r){return n.error=r.message,n}for(let r of o.entries)if(r.status==="conflict"&&r.path)n.conflicts.push(r.path);else if(r.status==="untracked-remote"&&r.articleId)try{let s=await t.planImport({cwd:e.cwd,profileName:e.profileName,articleId:r.articleId});t.applyImport({cwd:e.cwd,profileName:e.profileName},s),n.imported.push(s.path)}catch(s){n.failed.push({path:r.title??r.articleId,error:s.message})}else if(r.status==="remote-ahead"&&r.path)try{let s=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},s),n.pulled.push(r.path)}catch(s){n.failed.push({path:r.path,error:s.message})}return n}var qs=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Uo=e=>e===1?"":"s";function Ys(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${Uo(e.pulled.length)} into local: ${qs(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Uo(e.imported.length)} into local drafts: ${qs(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Uo(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${qs(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${Uo(e.failed.length)} failed \u2014 left for /pull.`),t}async function ec(e,t){let n=t?.cwd??process.cwd();if(!Th(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ne(n,t?.profileName);if(!o.ok)return console.log(R(o.reason)),{kind:"continue"};let{publish:r}=Bs(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await Gs({cwd:n,profileName:t?.profileName});for(let p of Ys(s))console.log(p.startsWith("\u2713")?D(p):p.startsWith("\u2139")?f(p):L(p));let l=En(An(n));return console.log(f(l?`Catching up on ${l}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Vs({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as _h}from"node:child_process";var $t="document360-writer",Wo=`npm i -g ${$t}@latest`;async function Fo(){let e=process.platform==="win32";return new Promise(t=>{try{let n=_h(`npm i -g ${$t}@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 tc(){return console.log(f(`Updating ${$t}\u2026`)),(await Fo()).ok?console.log(D("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(R(`Update failed \u2014 run manually: ${Wo}`)),{kind:"continue"}}W();ot();import{existsSync as zs,rmSync as Oh}from"node:fs";import{basename as nc,resolve as Ks}from"node:path";import{execFileSync as Lh}from"node:child_process";import{input as Mh}from"@inquirer/prompts";import{readProjectConfig as Uh,devHintsGuidePath as Wh}from"document360-engine";var Fh=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Hh=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Ho=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),oc=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function rc(e){let t=Ho(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:oc(t)?!0:Hh.has(t)}function Xs(e){let t=null;try{t=Uh(e)}catch{t=null}let n=new Set(Fh);for(let o of[Ho(t?.docsDir),Ho(t?.captureDir),Ho(t?.outputDir)])o&&oc(o)&&n.add(o);return[...n].filter(o=>rc(o)&&zs(Ks(e,o)))}function Qs(e,t){let n=[],o=[];for(let r of t){if(!rc(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Oh(Ks(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function sc(e,t){try{return Lh("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
342
+ `),display:"/capture-setup"}}var Jl="-".repeat(64);function Ws(e){let t=$h;try{let g=vh(e);g?.captureDir&&(t=g.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=yh(t)?kh(t,"CAPTURE-TESTID-REQUESTS.json"):bh(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!gh(n))return null;let o;try{let g=JSON.parse(wh(n,"utf8").replace(/^/,""));o=Array.isArray(g?.requests)?g.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(g=>g.file).filter(Boolean)).size,s=o.length,l=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,m=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${l} 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.","",Jl,`Read ${m} and ${k}. They list ${l} 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.",Jl]}ot();W();import{listOpenForDocs as xh,readProjectConfig as Ch}from"document360-engine";function Fs(e){try{return xh(e).length}catch{return 0}}function Hs(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape.",' \u2022 answer to a [discovery]-tagged question (subject starts "[discovery] ") \u2192 this is product-discovery,'," not an article edit: fold the fact into `.d360-writer/product-brief.md` (updating the cited grounding,"," clearing the matching OPEN marker), then RE-RUN the discover-product readiness assessment \u2014 set the"," brief's frontmatter status to `confident` and offer propose-structure if every rubric dimension now"," passes, else ask the next focused batch via d360_ask_builder. Do not touch articles for these.",' \u2022 answer to a [depth]-tagged question (subject starts "[depth] ") \u2192 this is per-feature depth-mining,'," not the brief and not an article edit: fold it into the DOCS PLAN per propose-structure's"," depth-reconcile \u2014 adjust that feature's article palette in plan.json/AGENT-PLAN.md (add rows citing"," the answer's .d360-writer/messages/ file in `sources`, never renumber existing rows), decrement"," open_depth_questions in AGENT-PLAN.md's frontmatter, and flip status to `pinned` at zero."," \u2022 answer (a reply to any other question you asked; `re` = your question id) \u2192 fold the fact into the"," affected article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only \u2014 do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
343
+ `)}async function Zl(e,t){let n=t?.cwd??process.cwd();return Ch(n)?Fs(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:Hs(),display:"/inbox"}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as Rh,listOpenForDocs as Ph,listOpenDirectives as Th,readProjectConfig as Sh,computeSyncStatus as Dh,planPull as jh,applyPull as Ah,planImport as Eh,applyImport as Nh}from"document360-engine";function An(e){let t=0,n=0,o=0,r=0;try{t=Rh(e).length}catch{}try{let s=Ph(e);n=s.filter(l=>l.kind==="request").length,o=s.filter(l=>l.kind==="answer").length}catch{}try{r=Th(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function En(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 Bs(e){return{publish:e.includes("--publish")}}function Vs({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page" \u2014 .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and \u2014 if it already exists \u2014 RE-ASSERTS and VERIFIES that the category is hidden). If the result has `hiddenConfirmed: false` or a `warning`, SURFACE that warning to the user PROMINENTLY at the end of your summary (\u26A0 the internal feedback control zone may be public on their KB \u2014 they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY \u2014 triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","4. Decide the right doc actions across ALL of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief \u2014 EXCEPT an answer to a [discovery]-tagged question (subject starts \"[discovery] \"), which is product discovery: fold it into `.d360-writer/product-brief.md`, then re-run the discover-product readiness assessment (flip the brief to `confident` if every rubric dimension now passes and offer propose-structure, else leave a follow-up [discovery] question), and EXCEPT an answer to a [depth]-tagged question (subject starts \"[depth] \"), which is per-feature depth-mining: fold it into the DOCS PLAN per propose-structure's depth-reconcile (adjust that feature's article palette in plan.json/AGENT-PLAN.md, cite the answer's messages/ file in new rows' `sources`, never renumber existing rows, decrement AGENT-PLAN.md's open_depth_questions and flip status to `pinned` at zero) \u2014 address each feedback item (improve the doc it points at \u2014 as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts \u2014 following the active doc-type playbook).","5. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the loop:"," \u2022 stamp consumed hints, and mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done), 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(`
344
+ `)}var Ih={status:Dh,plan:jh,apply:Ah,planImport:Eh,applyImport:Nh};async function Gs(e,t=Ih){let n={pulled:[],imported:[],conflicts:[],failed:[]},o;try{o=await t.status({cwd:e.cwd,profileName:e.profileName})}catch(r){return n.error=r.message,n}for(let r of o.entries)if(r.status==="conflict"&&r.path)n.conflicts.push(r.path);else if(r.status==="untracked-remote"&&r.articleId)try{let s=await t.planImport({cwd:e.cwd,profileName:e.profileName,articleId:r.articleId});t.applyImport({cwd:e.cwd,profileName:e.profileName},s),n.imported.push(s.path)}catch(s){n.failed.push({path:r.title??r.articleId,error:s.message})}else if(r.status==="remote-ahead"&&r.path)try{let s=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},s),n.pulled.push(r.path)}catch(s){n.failed.push({path:r.path,error:s.message})}return n}var qs=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Uo=e=>e===1?"":"s";function Ys(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${Uo(e.pulled.length)} into local: ${qs(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Uo(e.imported.length)} into local drafts: ${qs(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Uo(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${qs(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${Uo(e.failed.length)} failed \u2014 left for /pull.`),t}async function ec(e,t){let n=t?.cwd??process.cwd();if(!Sh(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ne(n,t?.profileName);if(!o.ok)return console.log(R(o.reason)),{kind:"continue"};let{publish:r}=Bs(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await Gs({cwd:n,profileName:t?.profileName});for(let p of Ys(s))console.log(p.startsWith("\u2713")?D(p):p.startsWith("\u2139")?f(p):L(p));let l=En(An(n));return console.log(f(l?`Catching up on ${l}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Vs({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as _h}from"node:child_process";var $t="document360-writer",Wo=`npm i -g ${$t}@latest`;async function Fo(){let e=process.platform==="win32";return new Promise(t=>{try{let n=_h(`npm i -g ${$t}@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 tc(){return console.log(f(`Updating ${$t}\u2026`)),(await Fo()).ok?console.log(D("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(R(`Update failed \u2014 run manually: ${Wo}`)),{kind:"continue"}}W();ot();import{existsSync as zs,rmSync as Oh}from"node:fs";import{basename as nc,resolve as Ks}from"node:path";import{execFileSync as Lh}from"node:child_process";import{input as Mh}from"@inquirer/prompts";import{readProjectConfig as Uh,devHintsGuidePath as Wh}from"document360-engine";var Fh=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Hh=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Ho=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),oc=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function rc(e){let t=Ho(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:oc(t)?!0:Hh.has(t)}function Xs(e){let t=null;try{t=Uh(e)}catch{t=null}let n=new Set(Fh);for(let o of[Ho(t?.docsDir),Ho(t?.captureDir),Ho(t?.outputDir)])o&&oc(o)&&n.add(o);return[...n].filter(o=>rc(o)&&zs(Ks(e,o)))}function Qs(e,t){let n=[],o=[];for(let r of t){if(!rc(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Oh(Ks(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function sc(e,t){try{return Lh("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
345
345
  `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function qh(e){return sc(e,".d360-writer/hints")}function Bh(e){return sc(e,".d360-writer/messages")}function Js(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=qh(e),o=Bh(e),r=zs(Ks(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(s=>` \u2022 ${s}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o>0?[`\u26A0 ${o} message(s) under .d360-writer/messages/ are not committed \u2014 commit them first or they're gone.`]:[],...r?["Note: a repo-root user-docs/ is NOT touched (only .d360-writer/ is removed)."]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${nc(e)}`]}async function ic(e,t){let n=Xs(t.cwd);for(let m of Js(t.cwd,n))console.log(n.length===0?f(m):m);if(n.length===0)return{kind:"continue"};let o=nc(t.cwd);if((await t.withPausedInput(()=>Mh({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=zs(Wh(t.cwd)),{removed:l,failed:p}=Qs(t.cwd,n);console.log(D(`\u2713 Reset complete \u2014 removed ${l.length} item${l.length===1?"":"s"}. The repo is back to its original state.`));for(let m of p)console.log(R(` \u2717 ${m.path}: ${m.error}`));if(s){for(let m of vo())console.log(m);console.log(f("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}W();import{lintDocs as Vh}from"document360-engine";function qo(e){if(e.length===0)return["\u2713 No issues found \u2014 no leaked internals, unknown commands, stale version facts, or AI-tells in the docs."];let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}let n=[`\u26A0 ${e.length} doc issue${e.length===1?"":"s"} in ${t.size} article${t.size===1?"":"s"} (leaked internals / unknown commands / stale facts / AI-tells):`];for(let[o,r]of t){n.push(` ${o}`);for(let s of r)n.push(` L${s.line}: "${s.term}" \u2014 ${s.message}`)}return n}function Zs(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(s=>` - L${s.line} [${s.kind}]: "${s.term}" \u2014 ${s.message}`)].join(`
346
346
  `)).join(`
347
347
  `)].join(`
348
348
  `)}async function ac(e,t){let n=e.includes("--fix"),o=e.find(l=>!l.startsWith("--")),r=o?` ${o}`:"",s=Vh({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(D("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:Zs(s),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let l of qo(s))console.log(s.length===0?D(l):L(l));return s.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}W();import{lintDocs as Qh,loadStyleGuide as Jh,buildReviewPrompt as Zh,readProjectConfig as em,DEFAULT_DOCS_DIR as tm}from"document360-engine";W();import{readProjectConfig as Gh,loadProfileMap as Yh,resolveActiveProfile as zh,desiredCategoryOrder as Kh,desiredArticleOrder as Xh}from"document360-engine";function lc(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var cc=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Nn(e,t){try{if(!Gh(e))return[];let n=zh(e,t),o=Yh(e,n.name);if(!o)return[];let r=new Map;for(let l of Xh(o)){let p=r.get(l.categoryPath);p?p.push(l):r.set(l.categoryPath,[l])}let s=[];for(let l of Kh(o)){s.push(lc(cc(l.path)));for(let p of(r.get(l.path)??[]).sort((m,k)=>m.order-k.order))s.push(` ${lc(cc(p.path))}`)}return s}catch{return[]}}async function dc(e,t){let n=Nn(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(O("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function ei(e,t){let n=em(e);if(!n)return null;let o=(n.docsDir??tm).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(g=>!g.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),l=Qh({cwd:e}),p=s?l.filter(g=>g.path===`${o}/${s}`||g.path.startsWith(`${o}/${s}/`)):l,m=s?"":Nn(e).join(`
349
349
  `);return{prompt:Zh({docsRoot:o,scope:s,styleGuide:Jh(e),deterministicFindings:p,fix:r,structure:m||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function uc(e,t){if(it("review",e)){let o=Jt(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=ei(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as nm}from"document360-engine";function ti(e,t){if(!nm(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.",n?"":"If the CATEGORY order itself reads wrong too, fix that first with the d360_reorder_categories tool (folder paths under one parent, in the desired order).","Do not rename files or folders or edit the map by hand; the tools handle it. Report the new order, and","remind me it reaches Document360 on the next /publish."].filter(Boolean).join(`
350
- `),display:`/reorder${n?` ${n}`:""}`}}async function pc(e,t){if(it("reorder",e)){let o=Jt(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=ti(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as om,writeProjectConfig as fc,isAppType as rm,playbookSkillName as sm,detectAppType as hc}from"document360-engine";var mc=["web","cli","service","library"],im=new Set(["web","cli"]);function ni(e){return im.has(e)?`${sm(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Bo(e,t){let n=t.cwd,o=om(n);if(!o)return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??hc(n);if(s){let l=o.appType?"set in config":"auto-detected";console.log(`${O("Genre:")} ${s} (${l}) \u2014 ${ni(s)}`)}else console.log(L("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${mc.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:s,...l}=o;fc(l,n);let p=hc(n);return console.log(D(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${ni(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return rm(r)?(fc({...o,appType:r},n),console.log(D(`\u2713 Genre set to ${r} \u2014 ${ni(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(R(`Unknown genre "${r}". Choose one of: ${mc.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}W();import{listRoadmap as gc,roadmapProgress as wc,stampRoadmapDone as am}from"document360-engine";function oi(e){let t=gc(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=wc(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 ri(e,t){if(!t.trim())return{ok:!1,line:"Usage: /roadmap done <step title>"};if(!am(e,t,{doneAt:new Date().toISOString()})){let r=gc(e).filter(s=>s.status==="open");return{ok:!1,line:r.length?`No open step titled "${t}". Open steps: ${r.map(s=>`"${s.title}"`).join(", ")}`:`No open step titled "${t}" \u2014 the roadmap has no open steps.`}}let o=wc(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 yc(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=ri(n,e.slice(1).join(" ").trim());return console.log(r.ok?D(r.line):L(r.line)),{kind:"continue"}}let o=oi(n);console.log(O(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?f(r):r);return{kind:"continue"}}var kc={help:Or,"?":Or,clear:ya,exit:Lr,quit:Lr,init:Hr,mcp:Co,publish:nl,audit:Pn,discover:ol,scope:sl,pull:gl,resolve:fl,convert:wl,write:xl,draft:Tl,document:Dl,resume:El,rename:Nl,profile:_l,model:Ml,doctor:Dn,workspace:Bl,project:Vl,"allow-prod":Gl,login:Yl,logout:zl,screenshot:Mo,"capture-setup":jn,devhints:Da,inbox:Zl,"catch-up":ec,update:tc,reset:ic,check:ac,review:uc,reorder:pc,structure:dc,genre:Bo,roadmap:yc};function bc(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}ot();var lm="Or just tell me what to write or update.",cm='\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 fe(e){return e===1?"":"s"}function Vo(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function In(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var dm={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 um(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:dm,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.discovery&&e.discovery.status!=="confident"){let n=e.discovery.openQuestions;t.push(e.discovery.status==="pending"?{key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/publish steps)."}:n>0?{key:"discovery",bullet:`product discovery is waiting on ${n} answer${fe(n)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}:{key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${fe(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${fe(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${fe(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
350
+ `),display:`/reorder${n?` ${n}`:""}`}}async function pc(e,t){if(it("reorder",e)){let o=Jt(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=ti(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as om,writeProjectConfig as fc,isAppType as rm,playbookSkillName as sm,detectAppType as hc}from"document360-engine";var mc=["web","cli","service","library"],im=new Set(["web","cli"]);function ni(e){return im.has(e)?`${sm(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Bo(e,t){let n=t.cwd,o=om(n);if(!o)return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??hc(n);if(s){let l=o.appType?"set in config":"auto-detected";console.log(`${O("Genre:")} ${s} (${l}) \u2014 ${ni(s)}`)}else console.log(L("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${mc.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:s,...l}=o;fc(l,n);let p=hc(n);return console.log(D(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${ni(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return rm(r)?(fc({...o,appType:r},n),console.log(D(`\u2713 Genre set to ${r} \u2014 ${ni(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(R(`Unknown genre "${r}". Choose one of: ${mc.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}W();import{listRoadmap as gc,roadmapProgress as wc,stampRoadmapDone as am}from"document360-engine";function oi(e){let t=gc(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=wc(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 ri(e,t){if(!t.trim())return{ok:!1,line:"Usage: /roadmap done <step title>"};if(!am(e,t,{doneAt:new Date().toISOString()})){let r=gc(e).filter(s=>s.status==="open");return{ok:!1,line:r.length?`No open step titled "${t}". Open steps: ${r.map(s=>`"${s.title}"`).join(", ")}`:`No open step titled "${t}" \u2014 the roadmap has no open steps.`}}let o=wc(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 yc(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=ri(n,e.slice(1).join(" ").trim());return console.log(r.ok?D(r.line):L(r.line)),{kind:"continue"}}let o=oi(n);console.log(O(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?f(r):r);return{kind:"continue"}}var kc={help:Or,"?":Or,clear:ya,exit:Lr,quit:Lr,init:Hr,mcp:Co,publish:nl,audit:Pn,discover:ol,scope:sl,pull:gl,resolve:fl,convert:wl,write:xl,draft:Sl,document:Dl,resume:El,rename:Nl,profile:_l,model:Ml,doctor:Dn,workspace:Bl,project:Vl,"allow-prod":Gl,login:Yl,logout:zl,screenshot:Mo,"capture-setup":jn,devhints:Da,inbox:Zl,"catch-up":ec,update:tc,reset:ic,check:ac,review:uc,reorder:pc,structure:dc,genre:Bo,roadmap:yc};function bc(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}ot();var lm="Or just tell me what to write or update.",cm='\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 fe(e){return e===1?"":"s"}function Vo(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function In(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var dm={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 um(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:dm,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.discovery&&e.discovery.status!=="confident"){let n=e.discovery.openQuestions;t.push(e.discovery.status==="pending"?{key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/publish steps)."}:n>0?{key:"discovery",bullet:`product discovery is waiting on ${n} answer${fe(n)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}:{key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${fe(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${fe(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${fe(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
351
351
  \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${fe(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${fe(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${fe(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${fe(n)} changed both here and on Document360 (conflicts) \u2014 /publish skips these`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each conflict \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${n} conflict${fe(n)} (keep yours / take the portal's / skip).`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${fe(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${fe(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${fe(n)}.`})}return t}function vc(e){return e.find(t=>t.lead||t.picker)??null}function si(e,t){let n=t.filter(l=>l.bullet).map(l=>` \u2022 ${l.bullet}`),o=vc(t),r=[];o?.lead?r.push(In(o.lead)):o?.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let l of t.filter(p=>p!==o).slice(0,2))l.follow&&r.push(l.follow);let s=[[e,...n].join(`
352
352
  `)];return r.length&&s.push(r.join(" ")),s.push(lm),s.join(`
353
353
 
354
- `)}function _n(e){if(!e.ready)return{kind:"idle"};let t=um(e);if(!e.hasDocs){let s=vc(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:si("\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",t),tone:s.tone??"info",lead:s.lead,picker:s.picker}}:{kind:"recommend",rec:{note:cm,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 s=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${fe(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${fe(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${s}`,tone:"info",lead:null,picker:null}}}let n=t.filter(s=>s.lead||s.picker),o=n[0]??null;return o?(o.key==="audit"||o.key==="roadmap"&&n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${fe(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:si("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:si("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as ii,readdirSync as li}from"node:fs";import{spawnSync as pm}from"node:child_process";import{join as Go}from"node:path";import{readProjectConfig as xc,resolveActiveProfile as Cc,loadTokens as fm,isExpired as hm,loadProfileMap as Rc,localAheadPaths as mm,loadKnownConflicts as gm,readDocsPlan as wm,devHintsGuidePath as ym,DEFAULT_DOCS_DIR as ai,roadmapProgress as km,listRoadmap as bm,readProductBriefState as vm}from"document360-engine";ot();function $c(e){try{return li(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ci(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>$c(Go(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&$c(Go(e,o)))}function di(e,t){try{let n=xc(e);if(!n)return!1;let o=Cc(e,t),r=Rc(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Go(e,(n.docsDir??ai).replace(/\/+$/,""));return!!(ii(s)&&li(s).length>0||ii(ym(e)))}catch{return!1}}function On(e,t,n){try{let o=xc(e);if(!o)return null;let r=Cc(e,t),s=fm(r.name),l=!!s&&(!hm(s)||!!s.refreshToken),p=di(e,t)||!ci(e,o.authoritativeSourceFiles),m=Rc(e,r.name),k=m?Object.keys(m.articles).length:0,g=Go(e,(o.docsDir??ai).replace(/\/+$/,"")),S=!1;try{S=ii(g)&&li(g).length>0}catch{}let v=0;if(m?.lastAnalyzedCommit)try{let Te=pm("git",["rev-list","--count",`${m.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});Te.status===0&&(v=parseInt((Te.stdout||"").trim(),10)||0)}catch{}let _=0;try{let Te=wm(e);if(Te.length>0){let be=(o.docsDir??ai).replace(/\/+$/,"");_=ks(e,be,Te.map(He=>He.path)).length}}catch{}let P=An(e),N=En({...P,directives:0}),T=mm(e,t),M=new Set(gm(e,r.name)),B=T.filter(Te=>M.has(Te)).length,V=T.length-B,Y=Ee(e),ne=km(e),_e=vm(e),Fe=_e?{status:_e.status,openQuestions:_e.openQuestions}:null;return!Fe&&S&&bm(e).some(be=>be.status==="open"&&(be.run??"").trim()==="/discover")&&(Fe={status:"pending",openQuestions:0}),{ready:l&&p&&!n.claudeMissing,hasDocs:S,tracked:k,pendingText:N,directives:P.directives,behind:v,pendingWrites:_,localAhead:V,conflicts:B,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:Y.status,devhintsCompletedVersion:Y.completedVersion,devhintsToVersion:le,builderStarted:ze(e),genreUnknown:n.genreUnknown,roadmap:ne,discovery:Fe}}catch{return null}}function Pc(e,t){let n=[],o="";for(let r of e.split(/\s+/).filter(Boolean))for(o.length?o.length+1+r.length<=t?o+=` ${r}`:(n.push(o),o=r):o=r;o.length>t;)n.push(o.slice(0,t)),o=o.slice(t);return o&&n.push(o),n}function Yo(e){if(e.length===0)return[];let t=(s,l)=>`${s}${"\u2500".repeat(78)}${l}`,n=(s="")=>`\u2502 ${s.padEnd(76)} \u2502`,o=[`\u2B06 d360-writer upgraded \u2014 ${e.length===1?"one improvement affects":`${e.length} improvements affect`} the docs you've already written:`,"",t("\u250C","\u2510")];e.forEach((s,l)=>{l>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let p of Pc(`${l+1}. ${s.feature}`,76))o.push(n(p));o.push(n());for(let p of Pc(s.why,73))o.push(n(` ${p}`));o.push(n())}),o.push(t("\u2514","\u2518")),o.push("");let r=e.length>1;return o.push(`\u2713 ${r?"These are":"This is"} now on your docs roadmap \u2014 each launch shows your next step below (/roadmap shows the full campaign).`),o}W();var $m={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"},Tc=160,pi=200,Dc=40;function Re(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Sc(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}: ${Re(typeof r=="string"?r:JSON.stringify(r),Dc)}`);return t.length>4&&n.push("\u2026"),Re(n.join(", "),Tc)}var at=e=>typeof e=="string"&&e?e:null,ui=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function xm(e){let t=at(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function Cm(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=at(t.title);if(!o)return null;let r=xm(t.local_path);return n("Create article",`"${Re(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=at(t.title),r=ui(t.article_id);return n("Update article",o?`"${Re(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",ui(t.article_id)?`id ${ui(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",at(t.name)?`"${Re(at(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=at(t.file_path);return n("Upload image",o?Re(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function zo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),l=s.join("__");if(r==="document360"){let k=Cm(l,t);if(k)return k}let p=l.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Sc(t)}}let n=$m[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:Re(o,Tc)}:{title:e,sep:"",arg:Sc(t)}}function Rm(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 Pm(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Rm).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Re(r,pi))]}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}: ${Re(String(r),Dc)}`);return n.length>0?[Re(n.join(" \xB7 "),pi)]:null}return null}function Sm(e){let t=at(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Tm(e,t,n){switch(e){case"d360_create_article":{let o=Sm(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=at(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 ${Re(o[0],120)}`:""}`]}default:return null}}function Ko(e,t=4,n,o){let r=e.replace(/\r\n/g,`
355
- `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let l=Tm(n.slice(18),o,r);if(l)return{lines:l,hidden:0}}let s=Pm(r)??r.split(`
356
- `);return{lines:s.slice(0,t).map(l=>Re(l,pi)),hidden:Math.max(0,s.length-t)}}function Xo(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Qo(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 jc(e,t){try{let n=JSON.parse(e),r=(Array.isArray(n)?n[0]:n)?.[t];return typeof r=="string"&&/^https?:\/\//.test(r)?r:null}catch{return null}}function Jo(e){return jc(e,"url")}function Zo(e){return jc(e,"preview_url")}var zm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Km(e,t,n,o){if(zm.test(e))try{let r=Nc(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,l=Qo(t,n),p=Jo(n);e.endsWith("publish_article")&&p&&console.log(O(` \u2B95 Live: ${p}`));let m=Zo(n);m?console.log(O(` \u2B95 Preview: ${m}`)):l&&s&&console.log(O(` \u2B95 Preview: ${Xo(r.connection.portalUrl,s,l,r.project.languageCode??"en")}`))}catch{}}async function Ic(e=process.cwd(),t="auto",n,o){let r=jm(t);r.kind==="none"&&(console.error(""),console.error(R("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${O("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${O('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Xm(e,n),r.kind==="subscription"&&(r.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 s=!1,l=fi({cwd:e,profileName:n,allowProdWrites:s}),p={uuid:null,firstPrompt:null,titleFired:!1},m=Dm({input:process.stdin,output:process.stdout}),k=[],g=null,S=!1;m.on("line",P=>{if(g){let N=g;g=null,N(P)}else k.push(P)}),m.on("close",()=>{if(S=!0,g){let P=g;g=null,P(null)}});function v(){return k.length>0?Promise.resolve(k.shift()):S?Promise.resolve(null):(process.stdout.write(O("> ")),new Promise(P=>{g=P}))}let _={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{l.close(),l=fi({cwd:e,profileName:n,allowProdWrites:s}),p={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>p.uuid,setPendingName:P=>{p.pendingName=P},setModel:async P=>l.setModel(P),withPausedInput:async P=>{m.pause();try{return await P()}finally{m.resume()}}};try{for(;;){let P=await v();if(P===null)break;let N=P.trim();if(N){if(N.startsWith("/")){let T=bc(N);if(!T)continue;let M=kc[T.name];if(!M){console.log(R(`Unknown command: /${T.name}`)),console.log(f("Type /help for the list."));continue}let B=await M(T.args,_);if(B.kind==="exit")break;if(B.kind==="clear"){_.restartAgent();continue}if(B.kind==="allow-prod"){s=!0,_.restartAgent(),console.log(D("\u2713 Production writes authorized for this session.")),console.log("");continue}if(B.kind==="resume"){l.close(),l=fi({cwd:e,resume:B.uuid,profileName:n,allowProdWrites:s});let V=Am(B.uuid);p={uuid:B.uuid,firstPrompt:V?.firstPrompt??null,titleFired:!0},Ec(B.uuid),console.log(D(`\u2713 Resumed "${B.name}"`)),console.log("");continue}if(B.kind==="forward-to-agent"){p.firstPrompt||(p.firstPrompt=B.display??B.prompt);let V=(B.display??"").trim().split(/\s+/),Y=(V[0]==="/check"||V[0]==="/review")&&V.includes("--fix"),ne=V.slice(1).find(Fe=>!Fe.startsWith("--")),_e=Y?Gm(e,ne):[];if(await hi(l,B.prompt,r,p,e),Y)try{Vm(e,_e,{reviewedCap:Ym})}catch{}}else Qm(e,n);continue}if(Fm(N)){let T=Hm(N);if(T){try{qm(e,{title:T,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}p.firstPrompt||(p.firstPrompt=N),await hi(l,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${T}". 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 "${T}" and the article path(s) you wrote.`,r,p,e);continue}}p.firstPrompt||(p.firstPrompt=N),await hi(l,N,r,p,e)}}}finally{l.close(),m.close()}}function Xm(e,t){console.log(""),console.log(wn("document360-writer")),console.log(f(` cwd: ${e}`));let n=Om(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Jm(e,t)),!Lm(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(ko(e),!ze(e))for(let r of bo(e))console.log(L(` ${r}`))}catch{}try{let r=Mm(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=Bm(e);for(let s of Yo(r.applied))console.log(L(` ${s}`))}catch{}try{let r=On(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?_n(r):null;if(s?.kind==="recommend"&&s.rec.note){let l=s.rec.tone==="warn"?L:f;for(let p of s.rec.note.split(`
354
+ `)}function _n(e){if(!e.ready)return{kind:"idle"};let t=um(e);if(!e.hasDocs){let s=vc(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:si("\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",t),tone:s.tone??"info",lead:s.lead,picker:s.picker}}:{kind:"recommend",rec:{note:cm,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 s=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${fe(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${fe(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${s}`,tone:"info",lead:null,picker:null}}}let n=t.filter(s=>s.lead||s.picker),o=n[0]??null;return o?(o.key==="audit"||o.key==="roadmap"&&n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${fe(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:si("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:si("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as ii,readdirSync as li}from"node:fs";import{spawnSync as pm}from"node:child_process";import{join as Go}from"node:path";import{readProjectConfig as xc,resolveActiveProfile as Cc,loadTokens as fm,isExpired as hm,loadProfileMap as Rc,localAheadPaths as mm,loadKnownConflicts as gm,readDocsPlan as wm,devHintsGuidePath as ym,DEFAULT_DOCS_DIR as ai,roadmapProgress as km,listRoadmap as bm,readProductBriefState as vm}from"document360-engine";ot();function $c(e){try{return li(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ci(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>$c(Go(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&$c(Go(e,o)))}function di(e,t){try{let n=xc(e);if(!n)return!1;let o=Cc(e,t),r=Rc(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Go(e,(n.docsDir??ai).replace(/\/+$/,""));return!!(ii(s)&&li(s).length>0||ii(ym(e)))}catch{return!1}}function On(e,t,n){try{let o=xc(e);if(!o)return null;let r=Cc(e,t),s=fm(r.name),l=!!s&&(!hm(s)||!!s.refreshToken),p=di(e,t)||!ci(e,o.authoritativeSourceFiles),m=Rc(e,r.name),k=m?Object.keys(m.articles).length:0,g=Go(e,(o.docsDir??ai).replace(/\/+$/,"")),T=!1;try{T=ii(g)&&li(g).length>0}catch{}let v=0;if(m?.lastAnalyzedCommit)try{let Se=pm("git",["rev-list","--count",`${m.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});Se.status===0&&(v=parseInt((Se.stdout||"").trim(),10)||0)}catch{}let _=0;try{let Se=wm(e);if(Se.length>0){let be=(o.docsDir??ai).replace(/\/+$/,"");_=ks(e,be,Se.map(He=>He.path)).length}}catch{}let P=An(e),N=En({...P,directives:0}),S=mm(e,t),M=new Set(gm(e,r.name)),B=S.filter(Se=>M.has(Se)).length,V=S.length-B,Y=Ee(e),ne=km(e),_e=vm(e),Fe=_e?{status:_e.status,openQuestions:_e.openQuestions}:null;return!Fe&&T&&bm(e).some(be=>be.status==="open"&&(be.run??"").trim()==="/discover")&&(Fe={status:"pending",openQuestions:0}),{ready:l&&p&&!n.claudeMissing,hasDocs:T,tracked:k,pendingText:N,directives:P.directives,behind:v,pendingWrites:_,localAhead:V,conflicts:B,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:Y.status,devhintsCompletedVersion:Y.completedVersion,devhintsToVersion:le,builderStarted:ze(e),genreUnknown:n.genreUnknown,roadmap:ne,discovery:Fe}}catch{return null}}function Pc(e,t){let n=[],o="";for(let r of e.split(/\s+/).filter(Boolean))for(o.length?o.length+1+r.length<=t?o+=` ${r}`:(n.push(o),o=r):o=r;o.length>t;)n.push(o.slice(0,t)),o=o.slice(t);return o&&n.push(o),n}function Yo(e){if(e.length===0)return[];let t=(s,l)=>`${s}${"\u2500".repeat(78)}${l}`,n=(s="")=>`\u2502 ${s.padEnd(76)} \u2502`,o=[`\u2B06 d360-writer upgraded \u2014 ${e.length===1?"one improvement affects":`${e.length} improvements affect`} the docs you've already written:`,"",t("\u250C","\u2510")];e.forEach((s,l)=>{l>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let p of Pc(`${l+1}. ${s.feature}`,76))o.push(n(p));o.push(n());for(let p of Pc(s.why,73))o.push(n(` ${p}`));o.push(n())}),o.push(t("\u2514","\u2518")),o.push("");let r=e.length>1;return o.push(`\u2713 ${r?"These are":"This is"} now on your docs roadmap \u2014 each launch shows your next step below (/roadmap shows the full campaign).`),o}W();var $m={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"},Sc=160,pi=200,Dc=40;function Re(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Tc(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}: ${Re(typeof r=="string"?r:JSON.stringify(r),Dc)}`);return t.length>4&&n.push("\u2026"),Re(n.join(", "),Sc)}var at=e=>typeof e=="string"&&e?e:null,ui=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function xm(e){let t=at(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function Cm(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=at(t.title);if(!o)return null;let r=xm(t.local_path);return n("Create article",`"${Re(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=at(t.title),r=ui(t.article_id);return n("Update article",o?`"${Re(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",ui(t.article_id)?`id ${ui(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",at(t.name)?`"${Re(at(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=at(t.file_path);return n("Upload image",o?Re(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function zo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),l=s.join("__");if(r==="document360"){let k=Cm(l,t);if(k)return k}let p=l.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Tc(t)}}let n=$m[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:Re(o,Sc)}:{title:e,sep:"",arg:Tc(t)}}function Rm(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 Pm(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Rm).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Re(r,pi))]}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}: ${Re(String(r),Dc)}`);return n.length>0?[Re(n.join(" \xB7 "),pi)]:null}return null}function Tm(e){let t=at(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Sm(e,t,n){switch(e){case"d360_create_article":{let o=Tm(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=at(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 ${Re(o[0],120)}`:""}`]}default:return null}}function Ko(e,t=4,n,o){let r=e.replace(/\r\n/g,`
355
+ `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let l=Sm(n.slice(18),o,r);if(l)return{lines:l,hidden:0}}let s=Pm(r)??r.split(`
356
+ `);return{lines:s.slice(0,t).map(l=>Re(l,pi)),hidden:Math.max(0,s.length-t)}}function Xo(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Qo(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 jc(e,t){try{let n=JSON.parse(e),r=(Array.isArray(n)?n[0]:n)?.[t];return typeof r=="string"&&/^https?:\/\//.test(r)?r:null}catch{return null}}function Jo(e){return jc(e,"url")}function Zo(e){return jc(e,"preview_url")}var zm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Km(e,t,n,o){if(zm.test(e))try{let r=Nc(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,l=Qo(t,n),p=Jo(n);e.endsWith("publish_article")&&p&&console.log(O(` \u2B95 Live: ${p}`));let m=Zo(n);m?console.log(O(` \u2B95 Preview: ${m}`)):l&&s&&console.log(O(` \u2B95 Preview: ${Xo(r.connection.portalUrl,s,l,r.project.languageCode??"en")}`))}catch{}}async function Ic(e=process.cwd(),t="auto",n,o){let r=jm(t);r.kind==="none"&&(console.error(""),console.error(R("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${O("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${O('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Xm(e,n),r.kind==="subscription"&&(r.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 s=!1,l=fi({cwd:e,profileName:n,allowProdWrites:s}),p={uuid:null,firstPrompt:null,titleFired:!1},m=Dm({input:process.stdin,output:process.stdout}),k=[],g=null,T=!1;m.on("line",P=>{if(g){let N=g;g=null,N(P)}else k.push(P)}),m.on("close",()=>{if(T=!0,g){let P=g;g=null,P(null)}});function v(){return k.length>0?Promise.resolve(k.shift()):T?Promise.resolve(null):(process.stdout.write(O("> ")),new Promise(P=>{g=P}))}let _={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{l.close(),l=fi({cwd:e,profileName:n,allowProdWrites:s}),p={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>p.uuid,setPendingName:P=>{p.pendingName=P},setModel:async P=>l.setModel(P),withPausedInput:async P=>{m.pause();try{return await P()}finally{m.resume()}}};try{for(;;){let P=await v();if(P===null)break;let N=P.trim();if(N){if(N.startsWith("/")){let S=bc(N);if(!S)continue;let M=kc[S.name];if(!M){console.log(R(`Unknown command: /${S.name}`)),console.log(f("Type /help for the list."));continue}let B=await M(S.args,_);if(B.kind==="exit")break;if(B.kind==="clear"){_.restartAgent();continue}if(B.kind==="allow-prod"){s=!0,_.restartAgent(),console.log(D("\u2713 Production writes authorized for this session.")),console.log("");continue}if(B.kind==="resume"){l.close(),l=fi({cwd:e,resume:B.uuid,profileName:n,allowProdWrites:s});let V=Am(B.uuid);p={uuid:B.uuid,firstPrompt:V?.firstPrompt??null,titleFired:!0},Ec(B.uuid),console.log(D(`\u2713 Resumed "${B.name}"`)),console.log("");continue}if(B.kind==="forward-to-agent"){p.firstPrompt||(p.firstPrompt=B.display??B.prompt);let V=(B.display??"").trim().split(/\s+/),Y=(V[0]==="/check"||V[0]==="/review")&&V.includes("--fix"),ne=V.slice(1).find(Fe=>!Fe.startsWith("--")),_e=Y?Gm(e,ne):[];if(await hi(l,B.prompt,r,p,e),Y)try{Vm(e,_e,{reviewedCap:Ym})}catch{}}else Qm(e,n);continue}if(Fm(N)){let S=Hm(N);if(S){try{qm(e,{title:S,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}p.firstPrompt||(p.firstPrompt=N),await hi(l,`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.`,r,p,e);continue}}p.firstPrompt||(p.firstPrompt=N),await hi(l,N,r,p,e)}}}finally{l.close(),m.close()}}function Xm(e,t){console.log(""),console.log(wn("document360-writer")),console.log(f(` cwd: ${e}`));let n=Om(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Jm(e,t)),!Lm(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(ko(e),!ze(e))for(let r of bo(e))console.log(L(` ${r}`))}catch{}try{let r=Mm(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=Bm(e);for(let s of Yo(r.applied))console.log(L(` ${s}`))}catch{}try{let r=On(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?_n(r):null;if(s?.kind==="recommend"&&s.rec.note){let l=s.rec.tone==="warn"?L:f;for(let p of s.rec.note.split(`
357
357
  `))console.log(l(` ${p}`));s.rec.picker&&console.log(O(` Pick one: ${s.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 Qm(e,t){try{let n=On(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?_n(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(f(` Next: ${In(o.rec.lead)}`))}catch{}}function Jm(e,t){try{let n=Nc(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=Wm(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Ac(r.idToken)??{},...Ac(r.accessToken)??{}},l=s.email??s.preferred_username??"signed in";return Um(r)&&!r.refreshToken?L(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${l} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function Zm(){console.error(""),console.error(`Sign in with your Claude subscription: run ${O("claude")} once, then retry.`),console.error(` (No Claude Code? ${O("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${O("https://console.anthropic.com/settings/keys")}`)}function eg(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Im({uuid:t,name:r??Nm(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function tg(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||_m(o,t).then(r=>{r&&Em(n,r)}).catch(()=>{})}async function hi(e,t,n,o,r){let s=new Map;for await(let l of e.send(t))ng(l,o,r,n,s)}function ng(e,t,n,o,r){switch(e.type){case"session":t.uuid||eg(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=zo(e.name,e.input);s&&(process.stdout.write(`
358
358
 
359
359
  `),console.log(`${D("\u25CF")} ${ye(s.title)}${s.arg!==null?ae(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=Ke(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let l=p=>p===1?"":"s";console.log(ae(` \u23BF Added ${s.added} line${l(s.added)}, removed ${s.removed} line${l(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(f(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let l=Ko(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?R:ae;l.lines.forEach((m,k)=>console.log(p((k===0?" \u23BF ":" ")+m))),l.hidden>0&&console.log(f(` \u2026 +${l.hidden} lines`)),e.isError||Km(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
360
- `);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(f(` (${xn(s)}\u2192${xn(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Ec(t.uuid),t.titleFired||tg(t,n));break}case"error":console.error(""),console.error(R(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Zm();break}}import{render as ww}from"ink";import{resolveAuth as yw}from"document360-engine";import{useCallback as z,useEffect as Se,useMemo as bi,useRef as ee,useState as F}from"react";import{Box as oe,Text as j,useApp as wg,useInput as yg,useStdout as kg}from"ink";import{existsSync as en,readFileSync as lr,readdirSync as bg}from"node:fs";import{basename as Mn,isAbsolute as vg,join as vi}from"node:path";import{createSession as cd,classifyClaudeAuth as Si,CLAUDE_CODE_SETUP_HINT as $g,loginPkce as xg,toStoredTokens as Cg,saveTokens as Rg,getAccessToken as Pg,resolveActiveProfile as Pe,resolveProjectId as Sg,getArticle as Tg,decodeJwtClaims as nn,isExpired as lt,loadTokens as Ct,clearTokens as Dg,clearProfileProject as jg,setTitle as Ag,slugify as Eg,touchSession as $i,upsertSession as Ng,generateTitle as dd,findByName as Ig,listSessions as _g,renameSession as Og,suggestNextAction as Lg,readProjectConfig as te,writeProjectConfig as ud,resolveAndPersistAppType as Mg,detectAppType as Ug,resolveModelSetting as Ti,loadProfileMap as pd,applyPull as fd,computeSyncStatus as xi,lintDocs as hd,compareRemoteSources as Wg,planPull as md,establishBaselines as Fg,rebaselineServerMeta as Hg,inventoryRepo as qg,knownEnvironments as Bg,resolveEnvironment as Vg,planPartitions as Ci,partitionEvenly as Gg,screenshotPlaceholderIds as Yg,trackedArticlePaths as zg,runPartitioned as cr,estimateBulkCost as gd,resolveModelForOperation as dr,readDocsPlan as Kg,checkForUpdate as Xg,detectInstallKind as Qg,isSelfUpdatable as Jg,devHintsGuidePath as wd,toolFeedbackPath as yd,reconcileToolFeedback as Zg,reconcileUpgradeActions as ew,stampArticles as Ri,listArticleFiles as kd,CONTENT_CAP_VERSION as Pi,ENGINE_VERSION as Sd,DEFAULT_DOCS_DIR as Td,setProfileProject as tw,writeCrashLog as nw,applyStructureOrder as bd,orderSyncLine as vd,applyRelatedArticles as $d,relatedSyncLine as xd}from"document360-engine";ot();import{spawn as _c}from"node:child_process";function og(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function rg(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?_c([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):_c(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",l=>o(l===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function mi(e){for(let[t,n]of og())if(await rg(t,n,e))return!0;return!1}var sg=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function gi(e,t){if(t.closed)return e;let n=e.split(`
360
+ `);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(f(` (${xn(s)}\u2192${xn(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Ec(t.uuid),t.titleFired||tg(t,n));break}case"error":console.error(""),console.error(R(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Zm();break}}import{render as ww}from"ink";import{resolveAuth as yw}from"document360-engine";import{useCallback as z,useEffect as Te,useMemo as bi,useRef as ee,useState as F}from"react";import{Box as oe,Text as j,useApp as wg,useInput as yg,useStdout as kg}from"ink";import{existsSync as en,readFileSync as lr,readdirSync as bg}from"node:fs";import{basename as Mn,isAbsolute as vg,join as vi}from"node:path";import{createSession as cd,classifyClaudeAuth as Ti,CLAUDE_CODE_SETUP_HINT as $g,loginPkce as xg,toStoredTokens as Cg,saveTokens as Rg,getAccessToken as Pg,resolveActiveProfile as Pe,resolveProjectId as Tg,getArticle as Sg,decodeJwtClaims as nn,isExpired as lt,loadTokens as Ct,clearTokens as Dg,clearProfileProject as jg,setTitle as Ag,slugify as Eg,touchSession as $i,upsertSession as Ng,generateTitle as dd,findByName as Ig,listSessions as _g,renameSession as Og,suggestNextAction as Lg,readProjectConfig as te,writeProjectConfig as ud,resolveAndPersistAppType as Mg,detectAppType as Ug,resolveModelSetting as Si,loadProfileMap as pd,applyPull as fd,computeSyncStatus as xi,lintDocs as hd,compareRemoteSources as Wg,planPull as md,establishBaselines as Fg,rebaselineServerMeta as Hg,inventoryRepo as qg,knownEnvironments as Bg,resolveEnvironment as Vg,planPartitions as Ci,partitionEvenly as Gg,screenshotPlaceholderIds as Yg,trackedArticlePaths as zg,runPartitioned as cr,estimateBulkCost as gd,resolveModelForOperation as dr,readDocsPlan as Kg,checkForUpdate as Xg,detectInstallKind as Qg,isSelfUpdatable as Jg,devHintsGuidePath as wd,toolFeedbackPath as yd,reconcileToolFeedback as Zg,reconcileUpgradeActions as ew,stampArticles as Ri,listArticleFiles as kd,CONTENT_CAP_VERSION as Pi,ENGINE_VERSION as Td,DEFAULT_DOCS_DIR as Sd,setProfileProject as tw,writeCrashLog as nw,applyStructureOrder as bd,orderSyncLine as vd,applyRelatedArticles as $d,relatedSyncLine as xd}from"document360-engine";ot();import{spawn as _c}from"node:child_process";function og(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function rg(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?_c([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):_c(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",l=>o(l===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function mi(e){for(let[t,n]of og())if(await rg(t,n,e))return!0;return!1}var sg=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function gi(e,t){if(t.closed)return e;let n=e.split(`
361
361
  `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){sg.test(s)&&(t.cueSeen=!0);continue}let l=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);l?(n[r]=`${l[1]}${++t.num}. ${l[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
362
362
  `)}import{existsSync as ig,mkdirSync as ag,readFileSync as lg,writeFileSync as cg}from"node:fs";import{join as Oc}from"node:path";import{writerDir as dg}from"document360-engine";function Lc(e){return Oc(dg(e),".sessions")}function Mc(e,t){return Oc(Lc(e),`${t}.json`)}function Uc(e,t,n){try{ag(Lc(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");cg(Mc(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function wi(e,t){try{let n=Mc(e,t);if(!ig(n))return[];let o=JSON.parse(lg(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var ug=e=>`\x1B]0;${e}\x07`,pg=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Wc(e){process.stdout.isTTY&&process.stdout.write(e)}function Zt(e){Wc(ug(e))}function er(e){Wc(pg(e))}var tr=["\xB7 "," \xB7"],nr="\u{1F7E3}";Lo();xo();var or=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--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> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"roadmap",usage:"/roadmap [done <step>]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done <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:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (publish), take portal (pull), or skip \u2014 for each. Bare: walk them all",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],Fc={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function Hc(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Fc[n])return Fc[n];let o=or.find(r=>r.name===t);return o?o.desc:""}function qc(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return or.filter(n=>n.name.startsWith(t))}function Bc(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as Vc,Text as de}from"ink";import{jsx as ue,jsxs as rr}from"react/jsx-runtime";function fg({row:e}){switch(e.t){case"head":return ue(de,{color:q,bold:!0,children:e.s});case"text":return ue(de,{children:e.s});case"dim":return ue(de,{dimColor:!0,children:e.s});case"sub":return ue(de,{bold:!0,dimColor:!0,children:e.s});case"good":return ue(de,{color:"green",children:e.s});case"step":return rr(de,{children:[ue(de,{color:q,children:`${e.n}. `}),e.s]});case"cmd":return rr(de,{children:[" ",ue(de,{color:q,children:e.name.padEnd(20)}),ue(de,{dimColor:!0,children:e.s})]});case"gap":return ue(de,{children:" "})}}function Gc({tab:e,width:t,version:n,engineVersion:o}){let r=Ae[e]??Ae[0],s=6+Ae.reduce((p,m)=>p+m.label.length+4,0),l="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return rr(Vc,{flexDirection:"column",paddingX:1,children:[rr(de,{children:[ue(de,{color:q,bold:!0,children:"Help "}),Ae.map((p,m)=>m===e?ue(de,{color:"white",backgroundColor:q,bold:!0,children:` ${p.label} `},p.key):ue(de,{dimColor:!0,children:` ${p.label} `},p.key))]}),ue(de,{color:q,children:l}),ue(Vc,{flexDirection:"column",marginTop:1,children:r.rows.map((p,m)=>ue(fg,{row:p},m))}),ue(de,{dimColor:!0,children:`
363
363
  \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var hg=/^(?:\d+[.)]|[-*•])\s+/;function Yc(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
@@ -370,29 +370,29 @@ Articles:
370
370
  `),truncated:l>0||m>0}}}return{text:e,truncated:!1}}function ad(e,t){if(t||e.length===0||/\s$/.test(e))return{head:e,keep:""};let n=e.search(/\s\S*$/);return n<0?{head:"",keep:e}:{head:e.slice(0,n),keep:e.slice(n)}}function ld(e){let t=!1,n=0,o=0;for(let r of e.split(`
371
371
  `)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as ur,jsx as E,jsxs as K}from"react/jsx-runtime";var iw={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},Cd=` 1. /init \u2014 pick your Document360 environment & scaffold config
372
372
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
373
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function aw(e,t,n,o){let r=Si(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",l=Ti(e),p=te(e),m=(p?.docsDir??Td).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${m}/ + config`,g={version:t,engineVersion:Sd,claude:s,model:l.model,modelSource:iw[l.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:k};if(p===null)return g;try{let S=Pe(e,o);g.profile=S.name,g.apiUrl=S.connection.apiUrl,g.prod=S.production,g.project=S.project.projectName??S.project.projectId??"(chosen at login)";let v=Ct(S.name);if(v){let _={...nn(v.idToken)??{},...nn(v.accessToken)??{}},P=_.email??_.preferred_username??"signed in";lt(v)?v.refreshToken&&(g.who=P,g.loggedOut=!1,g.sessionHint="session expired \u2014 refreshing\u2026"):(g.who=P,g.loggedOut=!1,g.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return g}function lw(e,t){try{let n=Pe(e,t),o=Ct(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...nn(o.idToken)??{},...nn(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return lt(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var Rd=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],on=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],cw="Ask me to write or update an article\u2026";function tn({ch:e,dim:t}){let[n,o]=F(!0);return Se(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),E(j,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var dw=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Pd(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var uw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function pw({startTime:e,chars:t}){let[n,o]=F(0);Se(()=>{let m=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(m)},[]);let r=on[n%on.length],s=Rd[Math.floor(n/16)%Rd.length],l=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return K(oe,{children:[E(j,{color:q,children:` ${r} ${s}\u2026 `}),E(j,{color:"gray",children:`(${Cn(l)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function fw({text:e}){let[t,n]=F(0);return Se(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),E(oe,{paddingX:1,children:E(j,{color:q,children:`${on[t%on.length]} ${e}`})})}var hw=12e4;function mw({p:e}){let[t,n]=F(0);Se(()=>{let T=setInterval(()=>n(M=>M+1),150);return()=>clearInterval(T)},[]);let o=on[t%on.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),l=Math.round(e.chars/4),p=Date.now()-e.lastAt>=hw,m=e.verb??"Converting",k=e.unit??"article",g=e.rows.reduce((T,M)=>T+M.items,0),S=m.toLowerCase(),v=e.rows,_=0;if(v.length>sr){let T=v.findIndex(B=>B.status==="active"||B.status==="pending"),M=Math.max(0,Math.min(T-2,v.length-sr));_=v.slice(0,M).filter(B=>B.status==="done").length,v=v.slice(M,M+sr)}let P=Math.min(40,Math.max(...v.map(T=>yi(T.label).length),0)),N=T=>T==="failed"?"red":T==="active"?q:void 0;return K(oe,{flexDirection:"column",children:[K(oe,{children:[E(j,{color:q,children:` ${o} ${m} ${g} ${k}${g===1?"":"s"} `}),E(j,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${l} tokens \xB7 ${Cn(r)} \xB7 esc to stop`})]}),_>0&&E(j,{dimColor:!0,children:` \u2714 +${_} done`}),v.map(T=>K(j,{color:N(T.status),dimColor:T.status==="done"||T.status==="pending",children:[` ${Xc[T.status]} ${yi(T.label).padEnd(P)}`,T.status==="active"&&T.itemsDone!==void 0?` (${T.itemsDone}/${T.items} ${k}${T.items===1?"":"s"})`:T.status!=="pending"?` (${T.items} ${k}${T.items===1?"":"s"})`:"",T.status==="active"?` \u2190 ${S}\u2026`:""]},T.label)),p&&E(j,{color:"yellow",children:` \u26A0 no activity for ${Cn(s)} \u2014 press esc to stop if it's wedged`})]})}var gw=10800*1e3;function Dd({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=wg(),[s,l]=F(n),[p,m]=F(null),[k,g]=F({text:"",pos:0}),S=k.text,v=z(c=>{g(a=>{let i=typeof c=="function"?c(a.text):c;return{text:i,pos:i.length}})},[]),_=z(c=>{g(a=>({text:a.text.slice(0,a.pos)+c+a.text.slice(a.pos),pos:a.pos+c.length}))},[]),P=z(()=>{g(c=>{if(c.pos===0)return c;let a=c.text.slice(0,c.pos),i=od(a)??a.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[N,T]=F(!1),[M,B]=F(!1),[V,Y]=F(0),[ne,_e]=F(null),[Fe,Te]=F(null),[be,He]=F([]),Un=ee(!1),fr=ee(!1),[hr,Ei]=F(!1),Wn=ee(0),[Od,Fn]=F(!1),[Ld,Hn]=F(!1),[mr,Ni]=F(null),[Md,Rt]=F(0),ct=ee(0),[rn,Pt]=F(0),[St,qn]=F(null),Ii=ee(new Map),Ud=ee(0),Tt=ee([]),De=ee(null);De.current===null&&(De.current=cd({cwd:e,profileName:s,allowProdWrites:!1}));let qe=ee({uuid:null,firstPrompt:null,titleFired:!1}),Bn=ee(new Map),Dt=ee(!1),gr=ee([]),ce=ee([]),jt=ee([]),Vn=ee(null),[_i,dt]=F(null),wr=ee(null),[ut,pt]=F(null),[Be,At]=F(null),[Ve,Et]=F(null),[he,Nt]=F(null),[ve,ft]=F(null),[Qe,It]=F(null),[Ge,ht]=F(null),[Oi,sn]=F(null),[$e,mt]=F(null),[ge,_t]=F(null),[Li,yr]=F([]),gt=ee([]),an=ee(!1),je=ee(null),[Gn,re]=F(null),[Mi,Ui]=F(null),Yn=ee(!1),ln=ee(null),cn=ee(null),[xe,wt]=F(null),[zn,dn]=F(null),kr=!!(Ve||he||ve||Qe||Ge||$e||ge||xe||zn),[Wi,Ot]=F(0),[Fi,Lt]=F(0),[Wd,Hi]=F(0),br=bi(()=>{try{let c=Ti(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,Wd]),{stdout:Oe}=kg(),[,Fd]=F(0),qi=ee(`${Oe.columns??80}x${Oe.rows??24}`),Je=z(()=>Math.max(20,(Oe.columns??80)-1),[Oe]),d=z(c=>{Tt.current.push(c),console.log(Xr(c,Je()))},[Je]),me=z((c,a)=>{Wn.current++,_e(c),Te(a??null)},[]),Le=z(()=>{Wn.current++,_e(null),Te(null)},[]),Q=z(c=>me(c,Vo({kind:"cmd",cmd:c,reason:""})),[me]),Kn=z((c,a)=>{!a?.silent&&c.note&&d({kind:"note",tone:c.tone,text:c.note}),c.picker&&(He(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),sn(c.picker.title)),c.lead&&me(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,Vo(c.lead))},[d,me]),Mt=z((c,a,i="info")=>{c&&d({kind:"note",tone:i,text:c}),a&&me(a.kind==="cmd"?a.cmd:a.text,Vo(a))},[d,me]),[un,vr]=F(null),[Hd,Bi]=F(!1),Ut=z(c=>{vr(c),Bi(!1),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),$r=ee(!1),xr=z(async()=>{try{if($r.current||!Jg(Qg())||te(e)?.mode==="engineer")return;let c=await Xg({pkg:$t,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;$r.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${$t} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),Hn(!0),(await Fo().finally(()=>Hn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),Q("/exit"),Ni(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${Wo}`})}catch{}},[e,o,d,Q]),Xn=z(c=>{let a=Ne(e,s);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),cn.current=c,Q("/login"),!1)},[e,s,d,Q]),[Qn,Cr]=F(null),yt=z(c=>{let a=On(e,s,{claudeMissing:Si(t).state==="missing",allowAutoAudit:c,genreUnknown:fr.current});return a?_n(a):{kind:"idle"}},[e,s,t]),pn=ee(!0),Wt=ee(!1),Jn=ee(0),fn=ee(0);Se(()=>{let c=setInterval(()=>{if(pn.current){Jn.current=0,fn.current=0;return}if(!N)try{if(!en(wd(e)))return;if(Ee(e).status==="current"){pn.current=!0,Jn.current=0,fn.current=0;let i=yt(!1),h=i.kind==="recommend"?i.rec:null,u=Wt.current?`\u2713 Your builder finished the protocol update (v${le}) \u2014 the dev\u2194docs hand-off is current again.`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs.";d({kind:"note",tone:"ok",text:`${u}${h?.lead?` ${In(h.lead)}`:""}`}),vr(null),h&&(h.lead||h.picker)?Kn(h,{silent:!0}):Wt.current||me("write the docs for this repo"),Y(y=>y+1);return}if(Wt.current)return;Jn.current+=1;let a=Jn.current;if((a===4||a%15===0)&&fn.current<3){fn.current+=1;let i=fn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:ze(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${i}`:`\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.${i}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,N,d,yt,Kn,me]),Se(()=>{let c=_i??Mn(e);if(!N){er(0),Zt(`${nr} ${c}`);return}er(3);let a=0;Zt(`${tr[0]} ${c}`);let i=setInterval(()=>{a=(a+1)%tr.length,Zt(`${tr[a]} ${c}`)},400);return()=>clearInterval(i)},[N,e,_i]),Se(()=>()=>er(0),[]),Se(()=>{let c=performance.now(),a=[],i=(w,$)=>{let x=performance.now();try{return $()}finally{let G=Math.round(performance.now()-x);G>=80&&a.push(`${w}: ${G}ms`)}};d({kind:"banner",info:i("banner",()=>aw(e,o,t,s))});let h=Si(t).state==="missing";if(h&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
373
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function aw(e,t,n,o){let r=Ti(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",l=Si(e),p=te(e),m=(p?.docsDir??Sd).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${m}/ + config`,g={version:t,engineVersion:Td,claude:s,model:l.model,modelSource:iw[l.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:k};if(p===null)return g;try{let T=Pe(e,o);g.profile=T.name,g.apiUrl=T.connection.apiUrl,g.prod=T.production,g.project=T.project.projectName??T.project.projectId??"(chosen at login)";let v=Ct(T.name);if(v){let _={...nn(v.idToken)??{},...nn(v.accessToken)??{}},P=_.email??_.preferred_username??"signed in";lt(v)?v.refreshToken&&(g.who=P,g.loggedOut=!1,g.sessionHint="session expired \u2014 refreshing\u2026"):(g.who=P,g.loggedOut=!1,g.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return g}function lw(e,t){try{let n=Pe(e,t),o=Ct(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...nn(o.idToken)??{},...nn(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return lt(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var Rd=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],on=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],cw="Ask me to write or update an article\u2026";function tn({ch:e,dim:t}){let[n,o]=F(!0);return Te(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),E(j,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var dw=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Pd(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var uw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function pw({startTime:e,chars:t}){let[n,o]=F(0);Te(()=>{let m=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(m)},[]);let r=on[n%on.length],s=Rd[Math.floor(n/16)%Rd.length],l=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return K(oe,{children:[E(j,{color:q,children:` ${r} ${s}\u2026 `}),E(j,{color:"gray",children:`(${Cn(l)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function fw({text:e}){let[t,n]=F(0);return Te(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),E(oe,{paddingX:1,children:E(j,{color:q,children:`${on[t%on.length]} ${e}`})})}var hw=12e4;function mw({p:e}){let[t,n]=F(0);Te(()=>{let S=setInterval(()=>n(M=>M+1),150);return()=>clearInterval(S)},[]);let o=on[t%on.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),l=Math.round(e.chars/4),p=Date.now()-e.lastAt>=hw,m=e.verb??"Converting",k=e.unit??"article",g=e.rows.reduce((S,M)=>S+M.items,0),T=m.toLowerCase(),v=e.rows,_=0;if(v.length>sr){let S=v.findIndex(B=>B.status==="active"||B.status==="pending"),M=Math.max(0,Math.min(S-2,v.length-sr));_=v.slice(0,M).filter(B=>B.status==="done").length,v=v.slice(M,M+sr)}let P=Math.min(40,Math.max(...v.map(S=>yi(S.label).length),0)),N=S=>S==="failed"?"red":S==="active"?q:void 0;return K(oe,{flexDirection:"column",children:[K(oe,{children:[E(j,{color:q,children:` ${o} ${m} ${g} ${k}${g===1?"":"s"} `}),E(j,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${l} tokens \xB7 ${Cn(r)} \xB7 esc to stop`})]}),_>0&&E(j,{dimColor:!0,children:` \u2714 +${_} done`}),v.map(S=>K(j,{color:N(S.status),dimColor:S.status==="done"||S.status==="pending",children:[` ${Xc[S.status]} ${yi(S.label).padEnd(P)}`,S.status==="active"&&S.itemsDone!==void 0?` (${S.itemsDone}/${S.items} ${k}${S.items===1?"":"s"})`:S.status!=="pending"?` (${S.items} ${k}${S.items===1?"":"s"})`:"",S.status==="active"?` \u2190 ${T}\u2026`:""]},S.label)),p&&E(j,{color:"yellow",children:` \u26A0 no activity for ${Cn(s)} \u2014 press esc to stop if it's wedged`})]})}var gw=10800*1e3;function Dd({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=wg(),[s,l]=F(n),[p,m]=F(null),[k,g]=F({text:"",pos:0}),T=k.text,v=z(c=>{g(a=>{let i=typeof c=="function"?c(a.text):c;return{text:i,pos:i.length}})},[]),_=z(c=>{g(a=>({text:a.text.slice(0,a.pos)+c+a.text.slice(a.pos),pos:a.pos+c.length}))},[]),P=z(()=>{g(c=>{if(c.pos===0)return c;let a=c.text.slice(0,c.pos),i=od(a)??a.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[N,S]=F(!1),[M,B]=F(!1),[V,Y]=F(0),[ne,_e]=F(null),[Fe,Se]=F(null),[be,He]=F([]),Un=ee(!1),fr=ee(!1),[hr,Ei]=F(!1),Wn=ee(0),[Od,Fn]=F(!1),[Ld,Hn]=F(!1),[mr,Ni]=F(null),[Md,Rt]=F(0),ct=ee(0),[rn,Pt]=F(0),[Tt,qn]=F(null),Ii=ee(new Map),Ud=ee(0),St=ee([]),De=ee(null);De.current===null&&(De.current=cd({cwd:e,profileName:s,allowProdWrites:!1}));let qe=ee({uuid:null,firstPrompt:null,titleFired:!1}),Bn=ee(new Map),Dt=ee(!1),gr=ee([]),ce=ee([]),jt=ee([]),Vn=ee(null),[_i,dt]=F(null),wr=ee(null),[ut,pt]=F(null),[Be,At]=F(null),[Ve,Et]=F(null),[he,Nt]=F(null),[ve,ft]=F(null),[Qe,It]=F(null),[Ge,ht]=F(null),[Oi,sn]=F(null),[$e,mt]=F(null),[ge,_t]=F(null),[Li,yr]=F([]),gt=ee([]),an=ee(!1),je=ee(null),[Gn,re]=F(null),[Mi,Ui]=F(null),Yn=ee(!1),ln=ee(null),cn=ee(null),[xe,wt]=F(null),[zn,dn]=F(null),kr=!!(Ve||he||ve||Qe||Ge||$e||ge||xe||zn),[Wi,Ot]=F(0),[Fi,Lt]=F(0),[Wd,Hi]=F(0),br=bi(()=>{try{let c=Si(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,Wd]),{stdout:Oe}=kg(),[,Fd]=F(0),qi=ee(`${Oe.columns??80}x${Oe.rows??24}`),Je=z(()=>Math.max(20,(Oe.columns??80)-1),[Oe]),d=z(c=>{St.current.push(c),console.log(Xr(c,Je()))},[Je]),me=z((c,a)=>{Wn.current++,_e(c),Se(a??null)},[]),Le=z(()=>{Wn.current++,_e(null),Se(null)},[]),Q=z(c=>me(c,Vo({kind:"cmd",cmd:c,reason:""})),[me]),Kn=z((c,a)=>{!a?.silent&&c.note&&d({kind:"note",tone:c.tone,text:c.note}),c.picker&&(He(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),sn(c.picker.title)),c.lead&&me(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,Vo(c.lead))},[d,me]),Mt=z((c,a,i="info")=>{c&&d({kind:"note",tone:i,text:c}),a&&me(a.kind==="cmd"?a.cmd:a.text,Vo(a))},[d,me]),[un,vr]=F(null),[Hd,Bi]=F(!1),Ut=z(c=>{vr(c),Bi(!1),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),$r=ee(!1),xr=z(async()=>{try{if($r.current||!Jg(Qg())||te(e)?.mode==="engineer")return;let c=await Xg({pkg:$t,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;$r.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${$t} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),Hn(!0),(await Fo().finally(()=>Hn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),Q("/exit"),Ni(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${Wo}`})}catch{}},[e,o,d,Q]),Xn=z(c=>{let a=Ne(e,s);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),cn.current=c,Q("/login"),!1)},[e,s,d,Q]),[Qn,Cr]=F(null),yt=z(c=>{let a=On(e,s,{claudeMissing:Ti(t).state==="missing",allowAutoAudit:c,genreUnknown:fr.current});return a?_n(a):{kind:"idle"}},[e,s,t]),pn=ee(!0),Wt=ee(!1),Jn=ee(0),fn=ee(0);Te(()=>{let c=setInterval(()=>{if(pn.current){Jn.current=0,fn.current=0;return}if(!N)try{if(!en(wd(e)))return;if(Ee(e).status==="current"){pn.current=!0,Jn.current=0,fn.current=0;let i=yt(!1),h=i.kind==="recommend"?i.rec:null,u=Wt.current?`\u2713 Your builder finished the protocol update (v${le}) \u2014 the dev\u2194docs hand-off is current again.`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs.";d({kind:"note",tone:"ok",text:`${u}${h?.lead?` ${In(h.lead)}`:""}`}),vr(null),h&&(h.lead||h.picker)?Kn(h,{silent:!0}):Wt.current||me("write the docs for this repo"),Y(y=>y+1);return}if(Wt.current)return;Jn.current+=1;let a=Jn.current;if((a===4||a%15===0)&&fn.current<3){fn.current+=1;let i=fn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:ze(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${i}`:`\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.${i}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,N,d,yt,Kn,me]),Te(()=>{let c=_i??Mn(e);if(!N){er(0),Zt(`${nr} ${c}`);return}er(3);let a=0;Zt(`${tr[0]} ${c}`);let i=setInterval(()=>{a=(a+1)%tr.length,Zt(`${tr[a]} ${c}`)},400);return()=>clearInterval(i)},[N,e,_i]),Te(()=>()=>er(0),[]),Te(()=>{let c=performance.now(),a=[],i=(w,$)=>{let x=performance.now();try{return $()}finally{let G=Math.round(performance.now()-x);G>=80&&a.push(`${w}: ${G}ms`)}};d({kind:"banner",info:i("banner",()=>aw(e,o,t,s))});let h=Ti(t).state==="missing";if(h&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
374
374
  ${$g}
375
375
  Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!te(e)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
376
376
  ${Cd}`}),Q(h?"/doctor":"/init");return}h&&Q("/doctor");try{let w=Pe(e,s),$=Ct(w.name);$&&lt($)&&$.refreshToken?Pg({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),Y(x=>x+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Q("/login")}):(!$||lt($))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 sign in with /login.`}),Q("/login"))}catch{}try{let w=te(e),$=Pe(e,s),x=Ct($.name);w&&x&&!lt(x)&&ci(e,w.authoritativeSourceFiles)&&!di(e,s)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),Q("/scope"))}catch{}try{let w=i("resolve-genre",()=>Mg(e));w.persisted&&w.appType?d({kind:"note",tone:"ok",text:`\u2713 Detected a ${w.appType} app \u2014 enabled the ${w.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):w.source==="unknown"&&te(e)&&(fr.current=!0)}catch{}let u=Ee(e);try{if(i("reconcile-devhints",()=>ko(e)),u.status!=="current"&&!ze(e)){let w=bo(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
377
377
  `)}),Ut(kt()),pn.current=!1,Wt.current=!1)}}catch{}try{let w=i("reconcile-feedback",()=>Zg(e));w.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}try{let w=i("upgrade-actions",()=>ew(e));w.applied.length>0&&d({kind:"note",tone:"warn",text:Yo(w.applied).join(`
378
378
  `)})}catch{}let y=i("ready-decision",()=>yt(!0));y.kind==="autoAudit"?(d({kind:"note",tone:"info",text:y.note}),Pn().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&se(w.prompt,{display:w.display,quietUser:!0})})):y.kind==="recommend"&&Kn(y.rec);let b=Math.round(performance.now()-c);b>=800&&nw({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(`
379
379
  `):"no single phase \u226580ms"}
380
- cwd: ${e}`}),xr()},[]),Se(()=>{let c=setInterval(()=>{xr()},gw);return()=>clearInterval(c)},[xr]),Se(()=>{if(N||hr||Un.current||ne!==null||be.length>0||S!==""||un!==null||ce.current.length>0||Vn.current||kr)return;let c=yt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&Kn(c.rec,{silent:!0})},[N,ne,be,S,un,kr,V,yt,hr]),Se(()=>{let c=null,a=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let h=`${Oe.columns??80}x${Oe.rows??24}`;h!==qi.current&&(qi.current=h,Fd(u=>u+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+za(Tt.current,Je())+"\x1B[?2026l")},80))},400)};return Oe.on("resize",i),()=>{c&&clearTimeout(c),a&&clearTimeout(a),Oe.off("resize",i)}},[Oe,Je]);let Me=Math.max(20,(Oe.columns??80)-1),Vi=bi(()=>lw(e,s),[e,s,V]),Rr=(()=>{if(Ld)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(mr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${mr?` v${mr}`:""}\u2026`,isSetup:!0};if(Qn)return{text:"\u{1F6E0} press c to copy the d360-writer feedback \u2014 then send it to the team (Teams / Slack / email)\u2026",isSetup:!0};if(un)return Hd?{text:"\u2713 copied \u2014 paste it into your coding agent \xB7 I\u2019ll pick up automatically when it finishes\u2026",isSetup:!0}:{text:"\u2328 press c to copy the prompt above \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(ce.current.length>0)return ce.current[0].mode==="conflict"?{text:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let c=te(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let a=vi(e,(c.docsDir??Td).replace(/\/+$/,"")),i=(()=>{try{return en(a)&&bg(a).length>0}catch{return!1}})();try{let h=Pe(e,s),u=Ct(h.name);if(!(!!u&&!(lt(u)&&!u.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&&!i)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return i?{text:cw,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),hn=qc(S),Gi=hn.length>0&&!N,Pr=p!==null?id(p,8,Me):null,Zn=$e?$e.paths.filter(c=>!$e.query||c.toLowerCase().includes($e.query.toLowerCase())).slice(0,8):[],eo=xe?xe.sessions.filter(c=>{let a=xe.query.toLowerCase();return!a||c.name.toLowerCase().includes(a)||c.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],Ce=z((c,a)=>{De.current?.close(),De.current=cd({cwd:e,resume:c,profileName:a??s,allowProdWrites:Dt.current}),c||(qe.current={uuid:null,firstPrompt:null,titleFired:!1},dt(null)),Ot(0),Lt(0)},[e,s]),Yi=z((c,a,i)=>{if(dw.test(c))try{let h=Pe(e,s),u=typeof a.project_id=="string"&&a.project_id||h.project.projectId,y=Qo(a,i),b=[],w=Jo(i);c.endsWith("publish_article")&&w&&b.push(`Live: ${w}`);let $=Zo(i);$?b.push(`Preview: ${$}`):y&&u&&b.push(`Preview: ${Xo(h.connection.portalUrl,u,y,h.project.languageCode??"en")}`),b.length>0&&d({kind:"link",lines:b})}catch{}},[e,s,d]),se=z(async(c,a)=>{Fn(!0),Un.current=!1,Le(),He([]),sn(null),vr(null);let i=Wn.current;a?.quietUser||d({kind:"user",text:a?.echoDisplay&&a.display?a.display:c});let h=qe.current;h.firstPrompt||(h.firstPrompt=a?.display??c),ct.current=Date.now(),Rt(0),T(!0),Bn.current.clear();let u="",y=!1,b=!1,w="",$={num:0,closed:!1,cueSeen:!1},x=null,G=()=>{x||(x=setTimeout(()=>{x=null,m(w.length>0?w:null)},60))},H=()=>{x&&clearTimeout(x),x=null,m(null)},I=(C=!1)=>{let{head:A,keep:U}=ad(w,C);A.trim()&&d({kind:"assistant",text:gi(A.trimEnd(),$)}),w=U,H()};try{for await(let C of De.current.send(c))if(C.type==="session"){if(!h.uuid){h.uuid=C.sessionId;let A=new Date().toISOString(),U=wr.current,J=U??Eg(h.firstPrompt??"session");Ng({uuid:C.sessionId,name:J,renamed:!!U,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:A,updatedAt:A}),dt(J),wr.current=null}}else if(C.type==="text"){w+=C.delta,u+=C.delta;let A=ld(w);if(A>0){let U=w.slice(0,A).trimEnd();U&&d({kind:"assistant",text:gi(U,$)}),w=w.slice(A)}G(),Rt(U=>U+C.delta.length)}else if(C.type==="tool"){y=!0;let A=zo(C.name,C.input);A&&(I(),d({kind:"tool",title:A.title,sep:A.sep,arg:A.arg}),Bn.current.set(C.id,{name:C.name,input:C.input}))}else if(C.type==="article_diff"){let A=Ke(C.oldContent,C.newContent,Je());A&&(I(),d({kind:"diff",added:A.added,removed:A.removed,lines:A.lines,hidden:A.hidden}))}else if(C.type==="tool_result"){C.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(C.output)&&(Yn.current=!0);let A=Bn.current.get(C.id);if(A){Bn.current.delete(C.id),I();let U=Ko(C.output,4,C.isError?void 0:A.name,A.input);d({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:C.isError}),C.isError||Yi(A.name,A.input,C.output)}}else if(C.type==="result"){I(!0),Ot(U=>U+C.outputTokens),Lt(U=>U+C.costUsd);let A=C.inputTokens+C.cacheReadTokens+C.cacheCreationTokens;if(d({kind:"done",seconds:Math.round((Date.now()-ct.current)/1e3),tokens:C.outputTokens,costUsd:C.costUsd,ok:C.ok,...A>0?{inTokens:A,cachedPct:Math.round(C.cacheReadTokens/A*100)}:{}}),!b&&!y&&!u.trim()&&!an.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),C.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let U=yd(e);if(en(U)){let J=lr(U,"utf8").trim();J&&(Cr(J),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(C.ok&&$.cueSeen)Ei(!0),He([]);else{let U=C.ok?Yc(u,or.map(J=>J.name)):[];if(U.length>0)Q(U[0]);else if(C.ok&&u.trim()){let J=yt(!1);J.kind==="recommend"&&(J.rec.lead||J.rec.picker)||Lg(c,u,e).then(we=>{we&&Wn.current===i&&me(we)}).catch(()=>{})}}if(h.uuid&&($i(h.uuid),!h.titleFired)){h.titleFired=!0;let U=h.uuid,J=h.firstPrompt;J&&dd(J,e).then(we=>{we&&(Ag(U,we),dt(we))}).catch(()=>{})}}else C.type==="error"&&(I(!0),b=!0,C.kind==="auth"&&(Yn.current=!0),d({kind:"note",text:`agent error: ${C.message}`,tone:"error"}))}finally{T(!1),H(),Y(C=>C+1),qe.current.uuid&&Uc(e,qe.current.uuid,Tt.current),Yn.current?(Yn.current=!1,ln.current=a?.display??c,me("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):ln.current=null,an.current&&(an.current=!1,gt.current.length>0&&(d({kind:"note",tone:"info",text:`(${gt.current.length} queued message(s) discarded)`}),gt.current=[],yr([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Yi,Je,me,Q,Le,yt]),Ft=z(async c=>{let a=dr(e,"standard");ct.current=Date.now(),Rt(0),T(!0);let i=new AbortController;je.current=i;let h=async(u,y)=>{let b=Ci(u);re({verb:"Publishing",total:b.length,done:0,active:[],rows:Ln(b),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:y?`Resolving cross-links in ${u.length} article${u.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${u.length} article${u.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${Rn} agents at once) on ${a.model}\u2026 (esc to stop)`});let w=!1;for await(let $ of cr({cwd:e,partitions:b,promptFor:x=>Do(x.paths),concurrency:Rn,profileName:s,allowProdWrites:Dt.current,model:a.model,signal:i.signal}))if($.type==="partition_status")$.status==="running"?re(x=>x&&{...x,active:[...x.active,$.label],rows:Xe(x.rows,$.label,"active"),lastAt:Date.now()}):re(x=>x&&{...x,active:x.active.filter(G=>G!==$.label),done:x.done+1,rows:Xe(x.rows,$.label,$.status==="done"?"done":"failed"),lastAt:Date.now()});else if($.type==="partition_event")re(x=>{if(!x)return x;let G={...x,lastAt:Date.now()};return $.event.type==="tool"?G.tools=x.tools+1:$.event.type==="text"&&(G.chars=x.chars+$.event.delta.length),G});else if($.type==="run_done"){w=$.aborted,Lt(I=>I+$.totalCostUsd),Ot(I=>I+$.results.reduce((C,A)=>C+A.outputTokens,0));let x=$.aborted?"Stopped. ":"",G=t.kind==="api"?"api":"subscription";d({kind:"note",tone:$.aborted?"warn":$.ok?"ok":"warn",text:x+es($.results,b,G).join(`
381
- `)});let H=Zr(e,s);if(H&&d({kind:"note",tone:"info",text:H}),!$.aborted){try{let I=await bd({cwd:e,profileName:s}),C=vd(I);C?d({kind:"note",tone:"info",text:C}):I.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${I.skipped}`})}catch(I){d({kind:"note",tone:"warn",text:`Order sync failed: ${I.message}`})}try{let I=xd(await $d({cwd:e,profileName:s}));I&&d({kind:"note",tone:"info",text:I})}catch(I){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${I.message}`})}}}return w};try{if(!await h(c,!1)){let y=await ts(e,s,c);y.length>0&&await h(y,!0)}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{je.current=null,re(null),T(!1),Y(u=>u+1)}},[e,s,d,t]),Sr=z(async c=>{await se(Qr(c),{display:`/publish ${c}`,quietUser:!0});try{let a=await jo(e,s,c.replace(/\\/g,"/"));a.length>0&&(sn(`Related articles not yet published (${a.length}):`),He([`/publish --related ${c}`,...a.map(i=>`/publish ${i}`)]))}catch{}},[e,s,se]),Tr=z(c=>{let a=Ct(c);if(!a||lt(a)&&!a.refreshToken)return null;let i={...nn(a.idToken)??{},...nn(a.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),Dr=z((c,a)=>{if(a){let i=te(e);i&&(i.defaultProfile=c,ud(i,e))}l(c),Ce(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Tr(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),Q("/login")),Y(i=>i+1)},[e,d,Ce,Tr,Q]),to=z((c,a,i)=>{lo(e,c,a,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Ce(),pd(e,c)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:Kt(zt(e)).join(`
380
+ cwd: ${e}`}),xr()},[]),Te(()=>{let c=setInterval(()=>{xr()},gw);return()=>clearInterval(c)},[xr]),Te(()=>{if(N||hr||Un.current||ne!==null||be.length>0||T!==""||un!==null||ce.current.length>0||Vn.current||kr)return;let c=yt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&Kn(c.rec,{silent:!0})},[N,ne,be,T,un,kr,V,yt,hr]),Te(()=>{let c=null,a=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let h=`${Oe.columns??80}x${Oe.rows??24}`;h!==qi.current&&(qi.current=h,Fd(u=>u+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+za(St.current,Je())+"\x1B[?2026l")},80))},400)};return Oe.on("resize",i),()=>{c&&clearTimeout(c),a&&clearTimeout(a),Oe.off("resize",i)}},[Oe,Je]);let Me=Math.max(20,(Oe.columns??80)-1),Vi=bi(()=>lw(e,s),[e,s,V]),Rr=(()=>{if(Ld)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(mr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${mr?` v${mr}`:""}\u2026`,isSetup:!0};if(Qn)return{text:"\u{1F6E0} press c to copy the d360-writer feedback \u2014 then send it to the team (Teams / Slack / email)\u2026",isSetup:!0};if(un)return Hd?{text:"\u2713 copied \u2014 paste it into your coding agent \xB7 I\u2019ll pick up automatically when it finishes\u2026",isSetup:!0}:{text:"\u2328 press c to copy the prompt above \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(ce.current.length>0)return ce.current[0].mode==="conflict"?{text:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let c=te(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let a=vi(e,(c.docsDir??Sd).replace(/\/+$/,"")),i=(()=>{try{return en(a)&&bg(a).length>0}catch{return!1}})();try{let h=Pe(e,s),u=Ct(h.name);if(!(!!u&&!(lt(u)&&!u.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&&!i)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return i?{text:cw,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),hn=qc(T),Gi=hn.length>0&&!N,Pr=p!==null?id(p,8,Me):null,Zn=$e?$e.paths.filter(c=>!$e.query||c.toLowerCase().includes($e.query.toLowerCase())).slice(0,8):[],eo=xe?xe.sessions.filter(c=>{let a=xe.query.toLowerCase();return!a||c.name.toLowerCase().includes(a)||c.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],Ce=z((c,a)=>{De.current?.close(),De.current=cd({cwd:e,resume:c,profileName:a??s,allowProdWrites:Dt.current}),c||(qe.current={uuid:null,firstPrompt:null,titleFired:!1},dt(null)),Ot(0),Lt(0)},[e,s]),Yi=z((c,a,i)=>{if(dw.test(c))try{let h=Pe(e,s),u=typeof a.project_id=="string"&&a.project_id||h.project.projectId,y=Qo(a,i),b=[],w=Jo(i);c.endsWith("publish_article")&&w&&b.push(`Live: ${w}`);let $=Zo(i);$?b.push(`Preview: ${$}`):y&&u&&b.push(`Preview: ${Xo(h.connection.portalUrl,u,y,h.project.languageCode??"en")}`),b.length>0&&d({kind:"link",lines:b})}catch{}},[e,s,d]),se=z(async(c,a)=>{Fn(!0),Un.current=!1,Le(),He([]),sn(null),vr(null);let i=Wn.current;a?.quietUser||d({kind:"user",text:a?.echoDisplay&&a.display?a.display:c});let h=qe.current;h.firstPrompt||(h.firstPrompt=a?.display??c),ct.current=Date.now(),Rt(0),S(!0),Bn.current.clear();let u="",y=!1,b=!1,w="",$={num:0,closed:!1,cueSeen:!1},x=null,G=()=>{x||(x=setTimeout(()=>{x=null,m(w.length>0?w:null)},60))},H=()=>{x&&clearTimeout(x),x=null,m(null)},I=(C=!1)=>{let{head:A,keep:U}=ad(w,C);A.trim()&&d({kind:"assistant",text:gi(A.trimEnd(),$)}),w=U,H()};try{for await(let C of De.current.send(c))if(C.type==="session"){if(!h.uuid){h.uuid=C.sessionId;let A=new Date().toISOString(),U=wr.current,J=U??Eg(h.firstPrompt??"session");Ng({uuid:C.sessionId,name:J,renamed:!!U,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:A,updatedAt:A}),dt(J),wr.current=null}}else if(C.type==="text"){w+=C.delta,u+=C.delta;let A=ld(w);if(A>0){let U=w.slice(0,A).trimEnd();U&&d({kind:"assistant",text:gi(U,$)}),w=w.slice(A)}G(),Rt(U=>U+C.delta.length)}else if(C.type==="tool"){y=!0;let A=zo(C.name,C.input);A&&(I(),d({kind:"tool",title:A.title,sep:A.sep,arg:A.arg}),Bn.current.set(C.id,{name:C.name,input:C.input}))}else if(C.type==="article_diff"){let A=Ke(C.oldContent,C.newContent,Je());A&&(I(),d({kind:"diff",added:A.added,removed:A.removed,lines:A.lines,hidden:A.hidden}))}else if(C.type==="tool_result"){C.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(C.output)&&(Yn.current=!0);let A=Bn.current.get(C.id);if(A){Bn.current.delete(C.id),I();let U=Ko(C.output,4,C.isError?void 0:A.name,A.input);d({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:C.isError}),C.isError||Yi(A.name,A.input,C.output)}}else if(C.type==="result"){I(!0),Ot(U=>U+C.outputTokens),Lt(U=>U+C.costUsd);let A=C.inputTokens+C.cacheReadTokens+C.cacheCreationTokens;if(d({kind:"done",seconds:Math.round((Date.now()-ct.current)/1e3),tokens:C.outputTokens,costUsd:C.costUsd,ok:C.ok,...A>0?{inTokens:A,cachedPct:Math.round(C.cacheReadTokens/A*100)}:{}}),!b&&!y&&!u.trim()&&!an.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),C.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let U=yd(e);if(en(U)){let J=lr(U,"utf8").trim();J&&(Cr(J),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(C.ok&&$.cueSeen)Ei(!0),He([]);else{let U=C.ok?Yc(u,or.map(J=>J.name)):[];if(U.length>0)Q(U[0]);else if(C.ok&&u.trim()){let J=yt(!1);J.kind==="recommend"&&(J.rec.lead||J.rec.picker)||Lg(c,u,e).then(we=>{we&&Wn.current===i&&me(we)}).catch(()=>{})}}if(h.uuid&&($i(h.uuid),!h.titleFired)){h.titleFired=!0;let U=h.uuid,J=h.firstPrompt;J&&dd(J,e).then(we=>{we&&(Ag(U,we),dt(we))}).catch(()=>{})}}else C.type==="error"&&(I(!0),b=!0,C.kind==="auth"&&(Yn.current=!0),d({kind:"note",text:`agent error: ${C.message}`,tone:"error"}))}finally{S(!1),H(),Y(C=>C+1),qe.current.uuid&&Uc(e,qe.current.uuid,St.current),Yn.current?(Yn.current=!1,ln.current=a?.display??c,me("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):ln.current=null,an.current&&(an.current=!1,gt.current.length>0&&(d({kind:"note",tone:"info",text:`(${gt.current.length} queued message(s) discarded)`}),gt.current=[],yr([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Yi,Je,me,Q,Le,yt]),Ft=z(async c=>{let a=dr(e,"standard");ct.current=Date.now(),Rt(0),S(!0);let i=new AbortController;je.current=i;let h=async(u,y)=>{let b=Ci(u);re({verb:"Publishing",total:b.length,done:0,active:[],rows:Ln(b),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:y?`Resolving cross-links in ${u.length} article${u.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${u.length} article${u.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${Rn} agents at once) on ${a.model}\u2026 (esc to stop)`});let w=!1;for await(let $ of cr({cwd:e,partitions:b,promptFor:x=>Do(x.paths),concurrency:Rn,profileName:s,allowProdWrites:Dt.current,model:a.model,signal:i.signal}))if($.type==="partition_status")$.status==="running"?re(x=>x&&{...x,active:[...x.active,$.label],rows:Xe(x.rows,$.label,"active"),lastAt:Date.now()}):re(x=>x&&{...x,active:x.active.filter(G=>G!==$.label),done:x.done+1,rows:Xe(x.rows,$.label,$.status==="done"?"done":"failed"),lastAt:Date.now()});else if($.type==="partition_event")re(x=>{if(!x)return x;let G={...x,lastAt:Date.now()};return $.event.type==="tool"?G.tools=x.tools+1:$.event.type==="text"&&(G.chars=x.chars+$.event.delta.length),G});else if($.type==="run_done"){w=$.aborted,Lt(I=>I+$.totalCostUsd),Ot(I=>I+$.results.reduce((C,A)=>C+A.outputTokens,0));let x=$.aborted?"Stopped. ":"",G=t.kind==="api"?"api":"subscription";d({kind:"note",tone:$.aborted?"warn":$.ok?"ok":"warn",text:x+es($.results,b,G).join(`
381
+ `)});let H=Zr(e,s);if(H&&d({kind:"note",tone:"info",text:H}),!$.aborted){try{let I=await bd({cwd:e,profileName:s}),C=vd(I);C?d({kind:"note",tone:"info",text:C}):I.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${I.skipped}`})}catch(I){d({kind:"note",tone:"warn",text:`Order sync failed: ${I.message}`})}try{let I=xd(await $d({cwd:e,profileName:s}));I&&d({kind:"note",tone:"info",text:I})}catch(I){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${I.message}`})}}}return w};try{if(!await h(c,!1)){let y=await ts(e,s,c);y.length>0&&await h(y,!0)}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{je.current=null,re(null),S(!1),Y(u=>u+1)}},[e,s,d,t]),Tr=z(async c=>{await se(Qr(c),{display:`/publish ${c}`,quietUser:!0});try{let a=await jo(e,s,c.replace(/\\/g,"/"));a.length>0&&(sn(`Related articles not yet published (${a.length}):`),He([`/publish --related ${c}`,...a.map(i=>`/publish ${i}`)]))}catch{}},[e,s,se]),Sr=z(c=>{let a=Ct(c);if(!a||lt(a)&&!a.refreshToken)return null;let i={...nn(a.idToken)??{},...nn(a.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),Dr=z((c,a)=>{if(a){let i=te(e);i&&(i.defaultProfile=c,ud(i,e))}l(c),Ce(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Sr(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),Q("/login")),Y(i=>i+1)},[e,d,Ce,Sr,Q]),to=z((c,a,i)=>{lo(e,c,a,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Ce(),pd(e,c)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:Kt(zt(e)).join(`
382
382
  `)}),Ut(kt()),pn.current=Ee(e).status==="current",Wt.current=ze(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,Ce,Ut]),no=z(async c=>{let a;try{a=await yn(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Q("/workspace");return}if(a.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=a.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),h=i.length>0?i:a.workspaces;if(h.length===1){let u=h[0],y=a.workspaces.length-h.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${y>0?" (skipped the API-documentation workspace)":""}.`}),to(a.profile,a.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),Q("/workspace")},[e,d,to,Q]),oo=z((c,a)=>{co(e,c,a.id,a.name),d({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),Ce(),no(c)},[e,d,Ce,no]),zi=z(async c=>{let a;try{a=Pe(e,c)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:i}=await tt(e,a.name),h=i.find(u=>u.id===a.project.projectId);h?.name&&tw(e,a.name,{projectName:h.name})}catch{}await no(a.name);return}try{let{projects:i}=await tt(e,a.name);if(i.length===1){let h=i[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${h.name??h.id}".`}),oo(a.name,{id:h.id,name:h.name});return}if(i.length>1){let h=i.map(u=>({id:u.id,name:u.name??u.id,sub:u.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),ft({cursor:0,current:-1,rows:h,profile:a.name,environment:a.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Q("/project")}},[e,d,no,oo,Q]),Ht=z(()=>{let c=ce.current[0];if(!c)return;Le();let{plan:a,mode:i}=c;d({kind:"note",tone:"info",text:`\u25CF ${a.title} (${a.path})`});for(let u of a.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${u}`});a.overwritesLocalChanges&&i==="pull"&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let h=Ke(a.oldContent,a.newContent,Je());d(h?{kind:"diff",added:h.added,removed:h.removed,lines:h.lines,hidden:h.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),i==="conflict"?(d({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),d({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):d({kind:"note",tone:"info",text:`Write ${a.path}? (y/n \u2014 anything else cancels)`})},[d,Je,Le]),jr=z(()=>{if(ce.current.length>0){Ht();return}let c=jt.current;jt.current=[],c.length>0?(d({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),Ft(c)):Q("/pull")},[Ht,d,Ft,Q]),Ki=z(c=>{if(ce.current.length===0)return!1;let a=c.trim().toLowerCase(),i=ce.current[0];if(i.mode==="conflict"){if(a==="l"||a==="local")ce.current.shift(),jt.current.push(i.plan.path),d({kind:"note",tone:"info",text:`Keeping local ${i.plan.path} \u2014 will publish over the portal.`});else if(a==="p"||a==="portal"){ce.current.shift();try{fd({cwd:e,profileName:s},i.plan),d({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(h){d({kind:"note",tone:"error",text:`Take-portal failed: ${h.message}`})}}else if(a==="s"||a==="skip"||a==="n")ce.current.shift(),d({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let h=ce.current.length;return ce.current=[],jt.current=[],d({kind:"note",tone:"info",text:`Resolve cancelled (${h} conflict${h===1?"":"s"} left untouched).`}),!0}return jr(),!0}if(a==="y"||a==="yes"){let h=ce.current.shift().plan;try{fd({cwd:e,profileName:s},h),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${h.path} (sync base advanced).`})}catch(u){d({kind:"note",tone:"error",text:`Pull failed: ${u.message}`})}}else if(a==="n"||a==="no"){let h=ce.current.shift().plan;d({kind:"note",tone:"info",text:`Skipped ${h.path}.`})}else{let h=ce.current.length;return ce.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${h} article(s) left untouched).`}),!0}return jr(),!0},[e,s,jr,d]),Ar=z(async c=>{d({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let a=await xi({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),h=a.entries.filter(y=>y.status==="conflict"&&y.path).map(y=>y.path);if(i){if(!h.includes(i)){d({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}h=[i]}if(h.length===0){d({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let u=[];for(let y of h)try{u.push({plan:await md({cwd:e,profileName:s,relPath:y}),mode:"conflict"})}catch(b){d({kind:"note",tone:"error",text:`Could not load ${y} from Document360: ${b.message}`})}if(u.length===0)return;d({kind:"note",tone:"info",text:`Resolving ${u.length} conflict${u.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),ce.current=u,jt.current=[],Ht()}catch(a){d({kind:"note",tone:"error",text:`Could not compute sync status: ${a.message}`})}},[e,s,d,Ht]),Xi=z(c=>{let a=Vn.current;if(!a)return!1;if(Vn.current=null,Le(),c.trim()!==a.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:h}=Qs(e,a.targets);d({kind:"note",tone:h.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`});for(let u of h)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return a.hadDevhints&&(d({kind:"note",tone:"warn",text:vo().join(`
383
383
  `)}),Ut(Wr())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
384
- ${Cd}`}),Q("/init"),Fn(!1),!0},[e,d,Ut,Le,Q]),mn=z(async c=>{let a=c.slice(1).trim().split(/\s+/),i=(a[0]??"").toLowerCase(),h=a.slice(1);if(Fn(!0),Io(h)&&["write","check","review","reorder"].includes(i)){let u=Sn(e,s);if(u.length===0){d({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let y=b=>i==="write"?`/write ${kl(h,b).join(" ")}`.trim():`/${i} ${[b,...h.filter(w=>w!=="--scope")].join(" ")}`.trim();if(u.length===1){mn(y(u[0].token));return}ht({cursor:0,rows:u,run:b=>{mn(y(b))}});return}if(it(i,h)){let u=Sn(e,s);if(u.length>1){let y=h.filter(x=>x.startsWith("--")).join(" "),b=x=>`/${i}${x?` ${i==="write"?`--scope ${x}`:x}`:""}${y?` ${y}`:""} ${x?"":"--all"}`.replace(/\s+/g," ").trim(),w=u.reduce((x,G)=>x+G.count,0),$={token:"",label:i==="review"?`Everything \u2014 all ${w} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${u.length} categories`:`Everything \u2014 rewrite all ${w} planned articles`,count:w};ht({cursor:0,rows:[$,...u],run:x=>{mn(b(x))}});return}}switch(i){case"help":dn({tab:0});return;case"exit":case"quit":De.current?.close(),r();return;case"clear":Ce(),Tt.current=[],Fn(!1),Le(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=Pe(e,s)}catch(y){d({kind:"note",tone:"error",text:y.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),B(!0);try{let y=await xg(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},w=>d({kind:"note",tone:"info",text:w})),b=Cg(u.name,y);if(Rg(b),await _r(b,u.name,w=>d({kind:"note",tone:"info",text:w})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${fo(b)}`}),await zi(s),cn.current){let w=cn.current;cn.current=null;let $=Ne(e,s);$.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${w}.`}),Q(w)):(d({kind:"note",tone:"warn",text:`${$.reason} (then ${w}.)`}),Q("/login"),cn.current=w)}else ln.current&&(me(ln.current,"\u21E5 tab to re-send your last prompt\u2026"),ln.current=null)}catch(y){d({kind:"note",tone:"error",text:`Login failed: ${y.message}`})}finally{B(!1),Y(y=>y+1)}return}case"allow-prod":{let u=!1;try{u=Pe(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Dt.current=!0,Ce(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Ns(h.join(" ")),y=qe.current.uuid;if(!y){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}wr.current=u,dt(u),Zt(`${nr} ${u}`),d({kind:"note",tone:"ok",text:`Session will be named "${u}" once it starts.`});return}if(!u){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let b=qe.current.firstPrompt??"";dd(b,e).then(w=>{w?(me(`/rename ${w}`),d({kind:"note",tone:"info",text:`Suggestion: "${w}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Og(y,u),dt(u),Zt(`${nr} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=h[0],y=te(e);if(!u){let b=Object.entries(y?.profiles??{});if(b.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let w=b.map(([G,H])=>({name:G,env:H.connection?.environment??"custom",prod:H.production===!0,who:Tr(G)})),$=s??y?.defaultProfile,x=Math.max(0,w.findIndex(G=>G.name===$));At({cursor:x,current:x,rows:w});return}if(u==="add"){let b=Is(e,h[1],h[2]);if(b){d({kind:"note",tone:"error",text:b});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),Dr(h[1],!1);return}if(!y?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}Dr(u,!0);return}case"doctor":await Dn(h,{cwd:e,version:o});return;case"genre":{await Bo(h,{cwd:e});try{fr.current=!(te(e)?.appType??Ug(e))}catch{}Y(u=>u+1);return}case"roadmap":{if(h[0]?.toLowerCase()==="done"){let u=ri(e,h.slice(1).join(" ").trim());d({kind:"note",tone:u.ok?"ok":"warn",text:u.line}),Y(y=>y+1);return}d({kind:"note",tone:"info",text:oi(e).join(`
385
- `)});return}case"mcp":await Co(h);return;case"init":{if(te(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let u=Bg().map(y=>({name:y,apiUrl:Vg(y).apiUrl}));Et({cursor:0,rows:u});return}case"resume":{let u=h.join(" ").trim(),y=_g(e).filter($=>$.uuid!==qe.current.uuid);if(!u){if(!y.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}wt({query:"",cursor:0,sessions:y});return}let b=Ig(e,u);if(!b){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}Ce(b.uuid),qe.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},dt(b.name),$i(b.uuid),Tt.current=[];let w=wi(e,b.uuid);for(let $ of w)d($);d({kind:"note",tone:"ok",text:w.length?`Resumed "${b.name}" \u2014 restored ${w.length} message(s); continue where you left off.`:`Resumed "${b.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=h.join(" ").trim(),y;try{y=await yn(e,s)}catch(w){d({kind:"note",tone:"error",text:`Could not list workspaces: ${w.message}`});return}if(!u){let w=y.workspaces.map(x=>({id:x.id,name:x.name??x.id,type:x.workspace_type}));if(w.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let $=Math.max(0,w.findIndex(x=>x.id===y.current));Nt({cursor:$,current:$,rows:w,profile:y.profile,projectId:y.projectId,projectName:y.projectName,environment:y.environment});return}let b=Nr(y.workspaces,u);if(!b){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}to(y.profile,y.projectId,b);return}case"project":{let u=h.join(" ").trim(),y;try{y=await tt(e,s)}catch(w){d({kind:"note",tone:"error",text:`Could not list projects: ${w.message} (signed in? try /login)`});return}if(!u){let w=y.projects.map(x=>({id:x.id,name:x.name??x.id,sub:x.sub_domain}));if(w.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let $=w.findIndex(x=>x.id===y.current);ft({cursor:Math.max(0,$),current:$,rows:w,profile:y.profile,environment:y.environment});return}let b=Ir(y.projects,u);if(!b){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${y.projects.map(w=>w.name??w.id).join(", ")}`});return}oo(y.profile,b);return}case"logout":{let u;try{u=Pe(e,s).name}catch(b){d({kind:"note",tone:"error",text:b.message});return}let y=Dg(u);jg(e,u),Ce(),Y(b=>b+1),d({kind:"note",tone:y?"ok":"info",text:y?`\u2713 Signed out of "${u}" and cleared its project/workspace selection.`:`Profile "${u}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Q("/login");return}case"publish":{if(!Xn(c.trim()))return;if(h[0]==="--related"&&h[1]){let w=await jo(e,s,h[1].replace(/\\/g,"/"));if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Ft(w);return}let u=h.filter(w=>!w.startsWith("--"));if(u[0]){await Sr(u[0]);return}let y=h.includes("--all"),b=h.includes("--force");d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let w=await xi({cwd:e,profileName:s}),{clean:$,conflicts:x}=Po(w.entries),G=y&&b&&x.length>0,H=To(w.entries);if(H>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${H} article${H===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.`}),x.length>0&&!G&&d({kind:"note",tone:"warn",text:So(x.length)}),$.length===0&&!G){if(x.length>0){Q("/resolve");return}d({kind:"note",tone:"ok",text:H>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let I=w.counts["unknown-base"]??0;I>0&&d({kind:"note",tone:"info",text:`(${I} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Ui("Reconciling structure on Document360 (order + related articles)\u2026");try{let C=await bd({cwd:e,profileName:s}),A=xd(await $d({cwd:e,profileName:s})),U=vd(C);U?d({kind:"note",tone:"info",text:U}):C.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${C.skipped}`}),A&&d({kind:"note",tone:"info",text:A}),d({kind:"note",tone:"ok",text:U||A?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(U||A)&&Q("/structure")}catch(C){d({kind:"note",tone:"warn",text:`Structure sync failed: ${C.message}`})}finally{Ui(null)}return}if(y){let I=(G?[...$,...x]:$).map(C=>C.path);await Ft(I),x.length>0&&!G&&Q("/resolve");return}It({cursor:0,rows:tl($,x)})}catch(w){d({kind:"note",tone:"error",text:`Could not compute sync status: ${w.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!Xn(c.trim()))return;await Ar(h.find(u=>!u.startsWith("--")));return}case"preview":{let u=h.join(" ").trim();if(!u){let b=[];try{b=Object.keys(pd(e,Pe(e,s).name)?.articles??{})}catch{}if(b.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}mt({query:"",cursor:0,paths:b});return}let y=vg(u)?u:vi(e,u);if(en(y)){try{d({kind:"preview",name:Mn(y),text:Pd(lr(y,"utf8"))})}catch(b){d({kind:"note",tone:"error",text:`Could not read ${y}: ${b.message}`})}return}if(uw.test(u)){try{let b=Pe(e,s),w={profile:b.name,connection:b.connection},$=b.project.projectId??Sg(w),x=await Tg(w,$,u);d({kind:"preview",name:x.title??u,text:x.content??"*(article has no content)*"})}catch(b){d({kind:"note",tone:"error",text:`Could not fetch article: ${b.message}`})}return}d({kind:"note",tone:"error",text:`"${u}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let u=h[0]?.trim();if(!u){let $=Oo(Ti(e));pt({cursor:$,current:$});return}let{lines:y,changed:b,effective:w}=Tn(e,u);for(let $ of y)d({kind:"note",tone:$.startsWith("\u26A0")?"warn":$.startsWith("\u2713")?"ok":"info",text:$});b&&(Hi($=>$+1),De.current?.setModel(w));return}case"convert":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:y}=ds(h),b=zg(e,s);if(b.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let w=us(b,u);if(w.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${b.length} are tracked overall.)`});return}let $=Ci(w),x=3,G=`/convert${u?` --scope ${u}`:""} --run`,H=dr(e,"light");if(!y){let C=gd({files:ps(e,w),op:"convert",model:H.model}),A=u?`Scope: ${u} (${w.length} of ${b.length} tracked)
384
+ ${Cd}`}),Q("/init"),Fn(!1),!0},[e,d,Ut,Le,Q]),mn=z(async c=>{let a=c.slice(1).trim().split(/\s+/),i=(a[0]??"").toLowerCase(),h=a.slice(1);if(Fn(!0),Io(h)&&["write","check","review","reorder"].includes(i)){let u=Tn(e,s);if(u.length===0){d({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let y=b=>i==="write"?`/write ${kl(h,b).join(" ")}`.trim():`/${i} ${[b,...h.filter(w=>w!=="--scope")].join(" ")}`.trim();if(u.length===1){mn(y(u[0].token));return}ht({cursor:0,rows:u,run:b=>{mn(y(b))}});return}if(it(i,h)){let u=Tn(e,s);if(u.length>1){let y=h.filter(x=>x.startsWith("--")).join(" "),b=x=>`/${i}${x?` ${i==="write"?`--scope ${x}`:x}`:""}${y?` ${y}`:""} ${x?"":"--all"}`.replace(/\s+/g," ").trim(),w=u.reduce((x,G)=>x+G.count,0),$={token:"",label:i==="review"?`Everything \u2014 all ${w} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${u.length} categories`:`Everything \u2014 rewrite all ${w} planned articles`,count:w};ht({cursor:0,rows:[$,...u],run:x=>{mn(b(x))}});return}}switch(i){case"help":dn({tab:0});return;case"exit":case"quit":De.current?.close(),r();return;case"clear":Ce(),St.current=[],Fn(!1),Le(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=Pe(e,s)}catch(y){d({kind:"note",tone:"error",text:y.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),B(!0);try{let y=await xg(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},w=>d({kind:"note",tone:"info",text:w})),b=Cg(u.name,y);if(Rg(b),await _r(b,u.name,w=>d({kind:"note",tone:"info",text:w})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${fo(b)}`}),await zi(s),cn.current){let w=cn.current;cn.current=null;let $=Ne(e,s);$.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${w}.`}),Q(w)):(d({kind:"note",tone:"warn",text:`${$.reason} (then ${w}.)`}),Q("/login"),cn.current=w)}else ln.current&&(me(ln.current,"\u21E5 tab to re-send your last prompt\u2026"),ln.current=null)}catch(y){d({kind:"note",tone:"error",text:`Login failed: ${y.message}`})}finally{B(!1),Y(y=>y+1)}return}case"allow-prod":{let u=!1;try{u=Pe(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Dt.current=!0,Ce(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Ns(h.join(" ")),y=qe.current.uuid;if(!y){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}wr.current=u,dt(u),Zt(`${nr} ${u}`),d({kind:"note",tone:"ok",text:`Session will be named "${u}" once it starts.`});return}if(!u){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let b=qe.current.firstPrompt??"";dd(b,e).then(w=>{w?(me(`/rename ${w}`),d({kind:"note",tone:"info",text:`Suggestion: "${w}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Og(y,u),dt(u),Zt(`${nr} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=h[0],y=te(e);if(!u){let b=Object.entries(y?.profiles??{});if(b.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let w=b.map(([G,H])=>({name:G,env:H.connection?.environment??"custom",prod:H.production===!0,who:Sr(G)})),$=s??y?.defaultProfile,x=Math.max(0,w.findIndex(G=>G.name===$));At({cursor:x,current:x,rows:w});return}if(u==="add"){let b=Is(e,h[1],h[2]);if(b){d({kind:"note",tone:"error",text:b});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),Dr(h[1],!1);return}if(!y?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}Dr(u,!0);return}case"doctor":await Dn(h,{cwd:e,version:o});return;case"genre":{await Bo(h,{cwd:e});try{fr.current=!(te(e)?.appType??Ug(e))}catch{}Y(u=>u+1);return}case"roadmap":{if(h[0]?.toLowerCase()==="done"){let u=ri(e,h.slice(1).join(" ").trim());d({kind:"note",tone:u.ok?"ok":"warn",text:u.line}),Y(y=>y+1);return}d({kind:"note",tone:"info",text:oi(e).join(`
385
+ `)});return}case"mcp":await Co(h);return;case"init":{if(te(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let u=Bg().map(y=>({name:y,apiUrl:Vg(y).apiUrl}));Et({cursor:0,rows:u});return}case"resume":{let u=h.join(" ").trim(),y=_g(e).filter($=>$.uuid!==qe.current.uuid);if(!u){if(!y.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}wt({query:"",cursor:0,sessions:y});return}let b=Ig(e,u);if(!b){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}Ce(b.uuid),qe.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},dt(b.name),$i(b.uuid),St.current=[];let w=wi(e,b.uuid);for(let $ of w)d($);d({kind:"note",tone:"ok",text:w.length?`Resumed "${b.name}" \u2014 restored ${w.length} message(s); continue where you left off.`:`Resumed "${b.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=h.join(" ").trim(),y;try{y=await yn(e,s)}catch(w){d({kind:"note",tone:"error",text:`Could not list workspaces: ${w.message}`});return}if(!u){let w=y.workspaces.map(x=>({id:x.id,name:x.name??x.id,type:x.workspace_type}));if(w.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let $=Math.max(0,w.findIndex(x=>x.id===y.current));Nt({cursor:$,current:$,rows:w,profile:y.profile,projectId:y.projectId,projectName:y.projectName,environment:y.environment});return}let b=Nr(y.workspaces,u);if(!b){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}to(y.profile,y.projectId,b);return}case"project":{let u=h.join(" ").trim(),y;try{y=await tt(e,s)}catch(w){d({kind:"note",tone:"error",text:`Could not list projects: ${w.message} (signed in? try /login)`});return}if(!u){let w=y.projects.map(x=>({id:x.id,name:x.name??x.id,sub:x.sub_domain}));if(w.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let $=w.findIndex(x=>x.id===y.current);ft({cursor:Math.max(0,$),current:$,rows:w,profile:y.profile,environment:y.environment});return}let b=Ir(y.projects,u);if(!b){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${y.projects.map(w=>w.name??w.id).join(", ")}`});return}oo(y.profile,b);return}case"logout":{let u;try{u=Pe(e,s).name}catch(b){d({kind:"note",tone:"error",text:b.message});return}let y=Dg(u);jg(e,u),Ce(),Y(b=>b+1),d({kind:"note",tone:y?"ok":"info",text:y?`\u2713 Signed out of "${u}" and cleared its project/workspace selection.`:`Profile "${u}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Q("/login");return}case"publish":{if(!Xn(c.trim()))return;if(h[0]==="--related"&&h[1]){let w=await jo(e,s,h[1].replace(/\\/g,"/"));if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Ft(w);return}let u=h.filter(w=>!w.startsWith("--"));if(u[0]){await Tr(u[0]);return}let y=h.includes("--all"),b=h.includes("--force");d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let w=await xi({cwd:e,profileName:s}),{clean:$,conflicts:x}=Po(w.entries),G=y&&b&&x.length>0,H=So(w.entries);if(H>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${H} article${H===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.`}),x.length>0&&!G&&d({kind:"note",tone:"warn",text:To(x.length)}),$.length===0&&!G){if(x.length>0){Q("/resolve");return}d({kind:"note",tone:"ok",text:H>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let I=w.counts["unknown-base"]??0;I>0&&d({kind:"note",tone:"info",text:`(${I} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Ui("Reconciling structure on Document360 (order + related articles)\u2026");try{let C=await bd({cwd:e,profileName:s}),A=xd(await $d({cwd:e,profileName:s})),U=vd(C);U?d({kind:"note",tone:"info",text:U}):C.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${C.skipped}`}),A&&d({kind:"note",tone:"info",text:A}),d({kind:"note",tone:"ok",text:U||A?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(U||A)&&Q("/structure")}catch(C){d({kind:"note",tone:"warn",text:`Structure sync failed: ${C.message}`})}finally{Ui(null)}return}if(y){let I=(G?[...$,...x]:$).map(C=>C.path);await Ft(I),x.length>0&&!G&&Q("/resolve");return}It({cursor:0,rows:tl($,x)})}catch(w){d({kind:"note",tone:"error",text:`Could not compute sync status: ${w.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!Xn(c.trim()))return;await Ar(h.find(u=>!u.startsWith("--")));return}case"preview":{let u=h.join(" ").trim();if(!u){let b=[];try{b=Object.keys(pd(e,Pe(e,s).name)?.articles??{})}catch{}if(b.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}mt({query:"",cursor:0,paths:b});return}let y=vg(u)?u:vi(e,u);if(en(y)){try{d({kind:"preview",name:Mn(y),text:Pd(lr(y,"utf8"))})}catch(b){d({kind:"note",tone:"error",text:`Could not read ${y}: ${b.message}`})}return}if(uw.test(u)){try{let b=Pe(e,s),w={profile:b.name,connection:b.connection},$=b.project.projectId??Tg(w),x=await Sg(w,$,u);d({kind:"preview",name:x.title??u,text:x.content??"*(article has no content)*"})}catch(b){d({kind:"note",tone:"error",text:`Could not fetch article: ${b.message}`})}return}d({kind:"note",tone:"error",text:`"${u}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let u=h[0]?.trim();if(!u){let $=Oo(Si(e));pt({cursor:$,current:$});return}let{lines:y,changed:b,effective:w}=Sn(e,u);for(let $ of y)d({kind:"note",tone:$.startsWith("\u26A0")?"warn":$.startsWith("\u2713")?"ok":"info",text:$});b&&(Hi($=>$+1),De.current?.setModel(w));return}case"convert":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:y}=ds(h),b=zg(e,s);if(b.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let w=us(b,u);if(w.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${b.length} are tracked overall.)`});return}let $=Ci(w),x=3,G=`/convert${u?` --scope ${u}`:""} --run`,H=dr(e,"light");if(!y){let C=gd({files:ps(e,w),op:"convert",model:H.model}),A=u?`Scope: ${u} (${w.length} of ${b.length} tracked)
386
386
  `:"",U=`
387
387
  Model: ${H.model}${H.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:A+hs($,C,x).join(`
388
- `)+U}),Q(G);return}ct.current=Date.now(),Rt(0),T(!0);let I=new AbortController;je.current=I,re({verb:"Converting",total:$.length,done:0,active:[],rows:Ln($),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${w.length} articles across ${$.length} partitions (\u2264${x} agents at once) on ${H.model}\u2026 (esc to stop)`});try{for await(let C of cr({cwd:e,partitions:$,promptFor:fs,concurrency:x,profileName:s,allowProdWrites:Dt.current,model:H.model,signal:I.signal}))if(C.type==="partition_status")C.status==="running"?re(A=>A&&{...A,active:[...A.active,C.label],rows:Xe(A.rows,C.label,"active"),lastAt:Date.now()}):re(A=>A&&{...A,active:A.active.filter(U=>U!==C.label),done:A.done+1,rows:Xe(A.rows,C.label,C.status==="done"?"done":"failed"),lastAt:Date.now()});else if(C.type==="partition_event")re(A=>{if(!A)return A;let U={...A,lastAt:Date.now()};return C.event.type==="tool"?U.tools=A.tools+1:C.event.type==="text"&&(U.chars=A.chars+C.event.delta.length),U});else if(C.type==="run_done"){Lt(J=>J+C.totalCostUsd),Ot(J=>J+C.results.reduce((we,Bt)=>we+Bt.outputTokens,0));let A=C.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";d({kind:"note",tone:C.aborted?"warn":C.ok?"ok":"warn",text:A+ms(C.results,$,U).join(`
389
- `)})}}catch(C){d({kind:"note",tone:"error",text:`Convert run failed: ${C.message}`})}finally{je.current=null,re(null),T(!1),Y(C=>C+1)}return}case"write":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Kg(e);if(u.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:y,path:b,preview:w,concurrency:$,rewrite:x}=ys(h),{docsDir:G,targets:H,reason:I,rewriting:C}=Rs(e,u,{scope:y,path:b,rewrite:x});if(H.length===0){d({kind:"note",tone:"warn",text:I??"Nothing to write."});return}C&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${H.length} already-written article${H.length===1?"":"s"} (overwrites them; git has your baseline).`});let A=Ci(H),U=ws($),J=dr(e,"standard"),we=!!b;if(w&&!we){let X=gd({files:bs(e,u,H),op:"write",model:J.model}),ie=y?`Scope: ${y} (${H.length} pending)
388
+ `)+U}),Q(G);return}ct.current=Date.now(),Rt(0),S(!0);let I=new AbortController;je.current=I,re({verb:"Converting",total:$.length,done:0,active:[],rows:Ln($),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${w.length} articles across ${$.length} partitions (\u2264${x} agents at once) on ${H.model}\u2026 (esc to stop)`});try{for await(let C of cr({cwd:e,partitions:$,promptFor:fs,concurrency:x,profileName:s,allowProdWrites:Dt.current,model:H.model,signal:I.signal}))if(C.type==="partition_status")C.status==="running"?re(A=>A&&{...A,active:[...A.active,C.label],rows:Xe(A.rows,C.label,"active"),lastAt:Date.now()}):re(A=>A&&{...A,active:A.active.filter(U=>U!==C.label),done:A.done+1,rows:Xe(A.rows,C.label,C.status==="done"?"done":"failed"),lastAt:Date.now()});else if(C.type==="partition_event")re(A=>{if(!A)return A;let U={...A,lastAt:Date.now()};return C.event.type==="tool"?U.tools=A.tools+1:C.event.type==="text"&&(U.chars=A.chars+C.event.delta.length),U});else if(C.type==="run_done"){Lt(J=>J+C.totalCostUsd),Ot(J=>J+C.results.reduce((we,Bt)=>we+Bt.outputTokens,0));let A=C.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";d({kind:"note",tone:C.aborted?"warn":C.ok?"ok":"warn",text:A+ms(C.results,$,U).join(`
389
+ `)})}}catch(C){d({kind:"note",tone:"error",text:`Convert run failed: ${C.message}`})}finally{je.current=null,re(null),S(!1),Y(C=>C+1)}return}case"write":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Kg(e);if(u.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:y,path:b,preview:w,concurrency:$,rewrite:x}=ys(h),{docsDir:G,targets:H,reason:I,rewriting:C}=Rs(e,u,{scope:y,path:b,rewrite:x});if(H.length===0){d({kind:"note",tone:"warn",text:I??"Nothing to write."});return}C&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${H.length} already-written article${H.length===1?"":"s"} (overwrites them; git has your baseline).`});let A=Ci(H),U=ws($),J=dr(e,"standard"),we=!!b;if(w&&!we){let X=gd({files:bs(e,u,H),op:"write",model:J.model}),ie=y?`Scope: ${y} (${H.length} pending)
390
390
  `:"",pe=`
391
391
  Model: ${J.model}${J.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:ie+$s(A,X,U).join(`
392
- `)+pe}),Q(`/write${y?` --scope ${y}`:""}`);return}ct.current=Date.now(),Rt(0),T(!0);let Bt=new AbortController;je.current=Bt,re({verb:"Writing",total:A.length,done:0,active:[],rows:Ln(A),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${H.length} article${H.length===1?"":"s"} across ${A.length} partition${A.length===1?"":"s"} (\u2264${U} agents at once) on ${J.model}${J.forced?" (forced)":""}\u2026 (esc to stop)`});let io=new Set;try{for await(let X of cr({cwd:e,partitions:A,promptFor:ie=>vs(ie,G,{rewrite:C||we}),concurrency:U,profileName:s,allowProdWrites:Dt.current,model:J.model,signal:Bt.signal}))if(X.type==="partition_status")X.status==="running"?re(ie=>ie&&{...ie,active:[...ie.active,X.label],rows:Xe(ie.rows,X.label,"active"),lastAt:Date.now()}):re(ie=>ie&&{...ie,active:ie.active.filter(pe=>pe!==X.label),done:ie.done+1,rows:Xe(ie.rows,X.label,X.status==="done"?"done":"failed"),lastAt:Date.now()});else if(X.type==="partition_event"){let ie=null;if(X.event.type==="tool"){let pe=Kc(X.event.name,X.event.input,A[X.index]?.paths??[]);pe&&!io.has(pe)&&(io.add(pe),ie=X.label)}re(pe=>{if(!pe)return pe;let Ue={...pe,lastAt:Date.now()};return X.event.type==="tool"?Ue.tools=pe.tools+1:X.event.type==="text"&&(Ue.chars=pe.chars+X.event.delta.length),ie&&(Ue.rows=zc(Ue.rows,ie)),Ue})}else if(X.type==="run_done"){Lt(Ze=>Ze+X.totalCostUsd),Ot(Ze=>Ze+X.results.reduce((Ye,Vd)=>Ye+Vd.outputTokens,0));let ie=X.aborted?"Stopped. ":"",pe=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:X.aborted?"warn":X.ok?"ok":"warn",text:ie+xs(X.results,A,pe).join(`
393
- `)}),!X.aborted&&X.ok)try{let Ze=(io.size>0?[...io]:H).map(Ye=>`${G}/${Ye}`);Ri(e,Ze,{writtenCap:Pi})}catch{}let Ue=X.aborted?null:Cs(e,G,H);if(Ue&&d({kind:"note",tone:"warn",text:Ue}),!X.aborted&&X.ok){let Ze=y??b??"",Ye=Ze?` ${Ze}`:"";Mt(Ue?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${Ye} --fix, then /review${Ye} --fix for editorial quality, then /publish --all (add /screenshot --all first if you want images).`:`Written. I\u2019d run /review${Ye} --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:Ue?`/check${Ye} --fix`:`/review${Ye} --fix`,reason:""})}}}catch(X){d({kind:"note",tone:"error",text:`Write run failed: ${X.message}`})}finally{je.current=null,re(null),T(!1),Y(X=>X+1)}return}case"draft":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:y}=Ps(e);if(u.length===0&&y===0){d({kind:"note",tone:"info",text:Ts});return}let b=h.join(" ").trim();if(!b&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
392
+ `)+pe}),Q(`/write${y?` --scope ${y}`:""}`);return}ct.current=Date.now(),Rt(0),S(!0);let Bt=new AbortController;je.current=Bt,re({verb:"Writing",total:A.length,done:0,active:[],rows:Ln(A),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${H.length} article${H.length===1?"":"s"} across ${A.length} partition${A.length===1?"":"s"} (\u2264${U} agents at once) on ${J.model}${J.forced?" (forced)":""}\u2026 (esc to stop)`});let io=new Set;try{for await(let X of cr({cwd:e,partitions:A,promptFor:ie=>vs(ie,G,{rewrite:C||we}),concurrency:U,profileName:s,allowProdWrites:Dt.current,model:J.model,signal:Bt.signal}))if(X.type==="partition_status")X.status==="running"?re(ie=>ie&&{...ie,active:[...ie.active,X.label],rows:Xe(ie.rows,X.label,"active"),lastAt:Date.now()}):re(ie=>ie&&{...ie,active:ie.active.filter(pe=>pe!==X.label),done:ie.done+1,rows:Xe(ie.rows,X.label,X.status==="done"?"done":"failed"),lastAt:Date.now()});else if(X.type==="partition_event"){let ie=null;if(X.event.type==="tool"){let pe=Kc(X.event.name,X.event.input,A[X.index]?.paths??[]);pe&&!io.has(pe)&&(io.add(pe),ie=X.label)}re(pe=>{if(!pe)return pe;let Ue={...pe,lastAt:Date.now()};return X.event.type==="tool"?Ue.tools=pe.tools+1:X.event.type==="text"&&(Ue.chars=pe.chars+X.event.delta.length),ie&&(Ue.rows=zc(Ue.rows,ie)),Ue})}else if(X.type==="run_done"){Lt(Ze=>Ze+X.totalCostUsd),Ot(Ze=>Ze+X.results.reduce((Ye,Vd)=>Ye+Vd.outputTokens,0));let ie=X.aborted?"Stopped. ":"",pe=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:X.aborted?"warn":X.ok?"ok":"warn",text:ie+xs(X.results,A,pe).join(`
393
+ `)}),!X.aborted&&X.ok)try{let Ze=(io.size>0?[...io]:H).map(Ye=>`${G}/${Ye}`);Ri(e,Ze,{writtenCap:Pi})}catch{}let Ue=X.aborted?null:Cs(e,G,H);if(Ue&&d({kind:"note",tone:"warn",text:Ue}),!X.aborted&&X.ok){let Ze=y??b??"",Ye=Ze?` ${Ze}`:"";Mt(Ue?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${Ye} --fix, then /review${Ye} --fix for editorial quality, then /publish --all (add /screenshot --all first if you want images).`:`Written. I\u2019d run /review${Ye} --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:Ue?`/check${Ye} --fix`:`/review${Ye} --fix`,reason:""})}}}catch(X){d({kind:"note",tone:"error",text:`Write run failed: ${X.message}`})}finally{je.current=null,re(null),S(!1),Y(X=>X+1)}return}case"draft":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:y}=Ps(e);if(u.length===0&&y===0){d({kind:"note",tone:"info",text:Ss});return}let b=h.join(" ").trim();if(!b&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
394
394
  ${u.map(x=>` \u2022 ${x.name} (${x.docCount} doc${x.docCount===1?"":"s"})`).join(`
395
- `)}`}),He(u.map(x=>`/draft ${x.name}`));return}let w="",$;if(b){let x=Ss(u,b);x?w=x:$=b}else w=u[0]?.name??"";await se(_o(w,$),{display:b?`/draft ${b}`:"/draft",quietUser:!0});return}case"pull":{if(!Xn(c.trim()))return;let u=h.find(y=>y.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let w=Date.now(),$=await xi({cwd:e,profileName:s});d({kind:"note",tone:"info",text:Eo($,Date.now()-w).join(`
395
+ `)}`}),He(u.map(x=>`/draft ${x.name}`));return}let w="",$;if(b){let x=Ts(u,b);x?w=x:$=b}else w=u[0]?.name??"";await se(_o(w,$),{display:b?`/draft ${b}`:"/draft",quietUser:!0});return}case"pull":{if(!Xn(c.trim()))return;let u=h.find(y=>y.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let w=Date.now(),$=await xi({cwd:e,profileName:s});d({kind:"note",tone:"info",text:Eo($,Date.now()-w).join(`
396
396
  `)});return}if(u==="--baseline"){let w=h.find(H=>!H.startsWith("--")),$=w?w.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:$?`Setting the sync baseline for ${$}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let x=await Fg({cwd:e,profileName:s,relPaths:$?[$]:void 0}),G=$?{rebaselined:[],skipped:[]}:await Hg({cwd:e,profileName:s});if(x.baselined.length===0&&x.skipped.length===0&&G.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}x.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${x.baselined.length} article${x.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),G.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${G.rebaselined.length} article${G.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),x.skipped.length>0&&d({kind:"note",tone:"warn",text:`${x.skipped.length} skipped:
397
397
  ${x.skipped.map(H=>` - ${H.path} (${H.reason})`).join(`
398
398
  `)}`}),Y(H=>H+1);return}if(u==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let w=await Wg({cwd:e,profileName:s}),$=w.onlyInLegacy.length===0&&w.onlyInManifest.length===0&&w.mappedMissingFromManifest.length===0,x=[`Legacy listing: ${w.legacyCount} \xB7 Manifest: ${w.manifestCount} \xB7 in both: ${w.inBoth}`];$?x.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(w.mappedMissingFromManifest.length&&x.push(`\u2717 ${w.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${w.mappedMissingFromManifest.slice(0,5).join(", ")}`),w.onlyInLegacy.length&&x.push(`\u26A0 ${w.onlyInLegacy.length} only in the legacy listing: ${w.onlyInLegacy.slice(0,5).join(", ")}`),w.onlyInManifest.length&&x.push(`\u26A0 ${w.onlyInManifest.length} only in the manifest: ${w.onlyInManifest.slice(0,5).join(", ")}`),x.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:$?"ok":"warn",text:x.join(`
@@ -402,9 +402,9 @@ ${x.skipped.map(H=>` - ${H.path} (${H.reason})`).join(`
402
402
  `)});return}case"reorder":{let u=ti(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await se(u.prompt,{display:u.display,quietUser:!0}),Mt("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let u=ei(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=h.includes("--fix"),b=h.find($=>!$.startsWith("--")),w=y?kd(e,b):[];if(await se(u.prompt,{display:u.display,quietUser:!0}),y)try{Ri(e,w,{reviewedCap:Pi})}catch{}if(y)Mt("\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 $=h.filter(x=>x!=="--fix").join(" ");Mt(`The review listed issues above. /review${$?` ${$}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${$?` ${$}`:""} --fix`,reason:""})}return}case"capture-setup":{let u=await jn();u.kind==="forward-to-agent"&&u.prompt&&await se(u.prompt,{display:u.display,quietUser:!0});let y=Ws(e);y&&d({kind:"note",tone:"info",text:y.join(`
403
403
  `)});return}case"devhints":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Kt(zt(e)).join(`
404
404
  `)}),Ut(kt()),pn.current=Ee(e).status==="current",Wt.current=ze(e);return}case"discover":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await se(ns(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Fs(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await se(Hs(),{display:"/inbox",quietUser:!0});return}case"feedback":{let u=yd(e),y="";try{y=en(u)?lr(u,"utf8"):""}catch{y=""}if(!/^## /m.test(y)){d({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let b=await mi(y.trim());d({kind:"note",tone:b?"ok":"warn",text:b?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${u} and copy it manually.`}),b&&Cr(null);return}case"document":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:y}=js(h);if(!y&&Ds(e)===0){d({kind:"note",tone:"info",text:Es});return}let b=`/document${y?` ${y}`:""}${u?" --publish":""}`;await se(As(y,u),{display:b,quietUser:!0});return}case"catch-up":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Xn(c.trim()))return;let{publish:u}=Bs(h);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let y=await Gs({cwd:e,profileName:s});for(let w of Ys(y))d({kind:"note",tone:w.startsWith("\u2713")?"ok":w.startsWith("\u2139")?"info":"warn",text:w});let b=En(An(e));d({kind:"note",tone:"info",text:b?`Catching up on ${b}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await se(Vs({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{$r.current=!0,d({kind:"note",tone:"info",text:`Updating ${$t}\u2026 (don\u2019t close this window)`}),Hn(!0),(await Fo().finally(()=>Hn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),Q("/exit"),Ni("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Wo}`});return}case"screenshot":{let u=Ls(h);if(u.mode==="list"){if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Us(Ms(e,u.scope),u.scope).join(`
405
- `)});return}if(u.mode==="single"){let I=await Mo(h);I.kind==="forward-to-agent"&&I.prompt&&await se(I.prompt,{display:I.display,quietUser:!0});return}if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=u.mode==="scope"?u.scope:void 0,b=Yg(e,{scope:y}).map(I=>I.id);if(b.length===0){d({kind:"note",tone:"info",text:y?`No screenshot placeholders under ${y}.`:"No screenshot placeholders found in the docs."});return}let w=6,$=Gg(b,3),x=dr(e,"standard");ct.current=Date.now(),Rt(0),T(!0);let G=new AbortController;je.current=G,re({verb:"Authoring",unit:"spec",total:$.length,done:0,active:[],rows:Ln($),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${b.length} screenshot spec${b.length===1?"":"s"} across ${$.length} partition${$.length===1?"":"s"} (\u2264${w} agents at once) on ${x.model}${x.forced?" (forced)":""}\u2026 (esc to stop)`});let H=!1;try{for await(let I of cr({cwd:e,partitions:$,promptFor:Ql,concurrency:w,profileName:s,allowProdWrites:Dt.current,model:x.model,signal:G.signal}))if(I.type==="partition_status")I.status==="running"?re(C=>C&&{...C,active:[...C.active,I.label],rows:Xe(C.rows,I.label,"active"),lastAt:Date.now()}):re(C=>C&&{...C,active:C.active.filter(A=>A!==I.label),done:C.done+1,rows:Xe(C.rows,I.label,I.status==="done"?"done":"failed"),lastAt:Date.now()});else if(I.type==="partition_event")re(C=>{if(!C)return C;let A={...C,lastAt:Date.now()};return I.event.type==="tool"?A.tools=C.tools+1:I.event.type==="text"&&(A.chars=C.chars+I.event.delta.length),A});else if(I.type==="run_done"){Lt(J=>J+I.totalCostUsd),Ot(J=>J+I.results.reduce((we,Bt)=>we+Bt.outputTokens,0));let C=I.results.filter(J=>J.ok).length,A=I.aborted?"Stopped. ":"";H=!I.aborted&&u.setup;let U=I.aborted?"":H?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:I.aborted?"warn":I.ok?"ok":"warn",text:`${A}Authored specs \u2014 ${C}/${I.results.length} batches ok.${U}`})}}catch(I){d({kind:"note",tone:"error",text:`Spec authoring failed: ${I.message}`})}finally{je.current=null,re(null),T(!1),Y(I=>I+1)}if(H){let I=await jn();I.kind==="forward-to-agent"&&I.prompt&&await se(I.prompt,{display:I.display,quietUser:!0});let C=Ws(e);C&&d({kind:"note",tone:"info",text:C.join(`
405
+ `)});return}if(u.mode==="single"){let I=await Mo(h);I.kind==="forward-to-agent"&&I.prompt&&await se(I.prompt,{display:I.display,quietUser:!0});return}if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=u.mode==="scope"?u.scope:void 0,b=Yg(e,{scope:y}).map(I=>I.id);if(b.length===0){d({kind:"note",tone:"info",text:y?`No screenshot placeholders under ${y}.`:"No screenshot placeholders found in the docs."});return}let w=6,$=Gg(b,3),x=dr(e,"standard");ct.current=Date.now(),Rt(0),S(!0);let G=new AbortController;je.current=G,re({verb:"Authoring",unit:"spec",total:$.length,done:0,active:[],rows:Ln($),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${b.length} screenshot spec${b.length===1?"":"s"} across ${$.length} partition${$.length===1?"":"s"} (\u2264${w} agents at once) on ${x.model}${x.forced?" (forced)":""}\u2026 (esc to stop)`});let H=!1;try{for await(let I of cr({cwd:e,partitions:$,promptFor:Ql,concurrency:w,profileName:s,allowProdWrites:Dt.current,model:x.model,signal:G.signal}))if(I.type==="partition_status")I.status==="running"?re(C=>C&&{...C,active:[...C.active,I.label],rows:Xe(C.rows,I.label,"active"),lastAt:Date.now()}):re(C=>C&&{...C,active:C.active.filter(A=>A!==I.label),done:C.done+1,rows:Xe(C.rows,I.label,I.status==="done"?"done":"failed"),lastAt:Date.now()});else if(I.type==="partition_event")re(C=>{if(!C)return C;let A={...C,lastAt:Date.now()};return I.event.type==="tool"?A.tools=C.tools+1:I.event.type==="text"&&(A.chars=C.chars+I.event.delta.length),A});else if(I.type==="run_done"){Lt(J=>J+I.totalCostUsd),Ot(J=>J+I.results.reduce((we,Bt)=>we+Bt.outputTokens,0));let C=I.results.filter(J=>J.ok).length,A=I.aborted?"Stopped. ":"";H=!I.aborted&&u.setup;let U=I.aborted?"":H?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:I.aborted?"warn":I.ok?"ok":"warn",text:`${A}Authored specs \u2014 ${C}/${I.results.length} batches ok.${U}`})}}catch(I){d({kind:"note",tone:"error",text:`Spec authoring failed: ${I.message}`})}finally{je.current=null,re(null),S(!1),Y(I=>I+1)}if(H){let I=await jn();I.kind==="forward-to-agent"&&I.prompt&&await se(I.prompt,{display:I.display,quietUser:!0});let C=Ws(e);C&&d({kind:"note",tone:"info",text:C.join(`
406
406
  `)})}return}case"reset":{let u=Xs(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Vn.current={repoName:Mn(e),targets:u,hadDevhints:en(wd(e))},d({kind:"note",tone:"warn",text:Js(e,u).join(`
407
- `)}),me(Mn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Ht,Ar,d,Ce,se,Ft,Sr,zi]),ro=z(c=>{let a=(c??S).trim();if(v(""),qn(null),Pt(0),a.startsWith("/")&&(Un.current=!1,Le(),sn(null),He(h=>Jc(h,a))),!a||(Ei(!1),Xi(a))||Ki(a))return;gr.current.push(a);let i=nd(a,Ii.current);if(a.startsWith("/"))d({kind:"user",text:a}),mn(i);else if(ow(i)){d({kind:"user",text:a});let h=rw(i);if(!h)se(i,{display:a,quietUser:!0});else{try{sw(e,{title:h,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}se(`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 se(i,{display:a})},[S,Xi,Ki,mn,se]),Qi=z(c=>{if(c.length>1){if(c.includes("\x1B"))return;let a=Zc(c);if(ed(a)){let i=td(++Ud.current,a);Ii.current.set(i,a),_(i)}else _(a);return}_(c)},[_]),qt=Math.max(10,Me-6),Ji=bi(()=>ir(k.text,qt),[k.text,qt]),Er=z(c=>g(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+c))})),[]),so=z(c=>g(a=>({...a,pos:rd(ir(a.text,qt),a.pos,c)})),[qt]),gn=z(c=>g(a=>({...a,pos:sd(ir(a.text,qt),a.pos,c)})),[qt]),qd=["\x1B[H","\x1B[1~","\x1BOH"],Bd=["\x1B[F","\x1B[4~","\x1BOF"],Zi=z((c,a)=>a.leftArrow?(Er(-1),!0):a.rightArrow?(Er(1),!0):c&&qd.includes(c)?(gn("start"),!0):c&&Bd.includes(c)?(gn("end"),!0):a.ctrl&&c==="a"?(gn("start"),!0):a.ctrl&&c==="e"?(gn("end"),!0):!1,[Er,gn]);return yg((c,a)=>{if(a.ctrl&&c==="c"){De.current?.close(),r();return}if(!M){if(N){if(a.escape){if(je.current){if(!je.current.signal.aborted){let i=(Gn?.verb??"work").toLowerCase(),h=Gn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${h}s)\u2026`}),je.current.abort()}return}an.current||(an.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),De.current?.interrupt());return}if(a.return){let i=S.trim();if(!i)return;gt.current.push(i),yr([...gt.current]),v("");return}if(Zi(c,a))return;if(a.upArrow){so(-1);return}if(a.downArrow){so(1);return}if(a.backspace||a.delete){P();return}c&&!a.ctrl&&!a.meta&&Qi(c);return}if(ut){if(a.upArrow){pt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){pt(i=>i&&{...i,cursor:Math.min(We.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=We.length){pt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=We[ut.cursor];pt(null);let{lines:h,changed:u,effective:y}=Tn(e,i.value??"default");for(let b of h)d({kind:"note",tone:b.startsWith("\u26A0")?"warn":b.startsWith("\u2713")?"ok":"info",text:b});u&&(Hi(b=>b+1),De.current?.setModel(y));return}if(c==="s"){let i=We[ut.cursor];pt(null),De.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){pt(null);return}return}if(Be){if(a.upArrow){At(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){At(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Be.rows.length){At(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return||c==="s"){let i=Be.rows[Be.cursor];At(null),Dr(i.name,a.return===!0);return}if(a.escape){At(null);return}return}if(zn){if(a.escape){dn(null);return}if(a.leftArrow||a.tab&&a.shift){dn(i=>i&&{tab:(i.tab-1+Ae.length)%Ae.length});return}if(a.rightArrow||a.tab){dn(i=>i&&{tab:(i.tab+1)%Ae.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ae.length){dn({tab:Number(c)-1});return}return}if(Ve){if(a.upArrow){Et(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Et(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ve.rows.length){Et(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Ve.rows[Ve.cursor].name;if(Et(null),!Fr(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let u=!1;try{let y=Ct(i);u=!!y&&!(lt(y)&&!y.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${i} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${i}) and pick your project.`}),Q("/login"),Y(y=>y+1);return}if(a.escape){Et(null);return}return}if(he){if(a.upArrow){Nt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Nt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=he.rows.length){Nt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=he.rows[he.cursor],{profile:h,projectId:u}=he;Nt(null),to(h,u,i);return}if(a.escape){Nt(null);return}return}if(ve){if(a.upArrow){ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ft(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ve.rows.length){ft(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=ve.rows[ve.cursor],{profile:h}=ve;ft(null),oo(h,i);return}if(a.escape){ft(null);return}return}if(ge){if(a.upArrow){_t(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){_t(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){_t(i=>i&&{...i,rows:i.rows.map((h,u)=>u===i.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let i=ge.rows.filter(h=>h.checked).map(h=>h.path);if(_t(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}os(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of i)d({kind:"note",tone:"info",text:` ${h}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){_t(null);return}return}if(Ge){if(a.upArrow){ht(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ht(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ge.rows.length){ht(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Ge.rows[Ge.cursor],h=Ge.run;ht(null),h(i.token);return}if(a.escape){ht(null);return}return}if(Qe){if(a.upArrow){It(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){It(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Qe.rows.length){It(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Qe.rows[Qe.cursor];It(null),i.conflict?Ar(i.paths[0]):i.kind==="article"?Sr(i.paths[0]):Ft(i.paths);return}if(a.escape){It(null);return}return}if($e){if(a.escape){mt(null);return}if(a.upArrow){mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){mt(i=>i&&{...i,cursor:Math.min(Math.max(0,Zn.length-1),i.cursor+1)});return}if(a.return){let i=Zn[$e.cursor];if(i){mt(null);try{d({kind:"preview",name:Mn(i),text:Pd(lr(vi(e,i),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${i}: ${h.message}`})}}return}if(a.backspace||a.delete){mt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){mt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(xe){if(a.escape){wt(null);return}if(a.upArrow){wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){wt(i=>i&&{...i,cursor:Math.min(Math.max(0,eo.length-1),i.cursor+1)});return}if(a.return){let i=eo[xe.cursor];if(i){wt(null),Ce(i.uuid),qe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},dt(i.name),$i(i.uuid),Tt.current=[];let h=wi(e,i.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${i.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){wt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){wt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(a.tab&&!S&&ne){v(ne),Le();return}if(!S&&be.length>0&&!hr&&c&&/^[1-9]$/.test(c)){let i=be[Number(c)-1];if(i){v(xt(i));return}}if(!S&&(Qn||un)&&c==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let i=Qn!=null;mi(Qn??un).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?i?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":i?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&i&&Cr(null),u&&!i&&Bi(!0)});return}if(!Zi(c,a)){if(Gi){if(a.upArrow){Pt(i=>Math.max(0,i-1));return}if(a.downArrow){Pt(i=>Math.min(hn.length-1,i+1));return}if(a.tab){v("/"+(hn[rn]?.name??"")+" "),Pt(0);return}if(a.return){let i=hn[rn];if(i){let h=S.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Bc(i.usage)&&!h){v("/"+i.name+" "),Pt(0);return}ro("/"+i.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(S!==""&&St===null){so(-1);return}let i=gr.current;if(!i.length)return;let h=St===null?i.length-1:Math.max(0,St-1);qn(h),v(i[h]??"");return}if(a.downArrow){if(S!==""&&St===null){so(1);return}let i=gr.current;if(St===null)return;let h=St+1;h>=i.length?(qn(null),v("")):(qn(h),v(i[h]??""));return}}if(a.return){ro();return}if(a.backspace||a.delete){P();return}if(a.escape){v(""),Pt(0),Le(),He([]),sn(null),Un.current=!0;return}c&&!a.ctrl&&!a.meta&&Qi(c)}}}),Se(()=>{if(N||M)return;let c=gt.current.shift();c!==void 0&&(yr([...gt.current]),ro(c))},[N,M,ro]),K(oe,{flexDirection:"column",width:Me,children:[Pr!==null&&K(oe,{marginTop:1,flexDirection:"column",children:[Pr.truncated&&E(j,{dimColor:!0,children:"\u2026"}),E(j,{children:Pr.text})]}),N&&(Gn?E(mw,{p:Gn}):E(pw,{startTime:ct.current,chars:Md})),!N&&Mi?E(fw,{text:Mi}):null,E(oe,{borderStyle:"round",borderColor:Vi.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:S?Ji.map((c,a)=>{let i=k.text.slice(c.start,c.end),h=a===ar(Ji,k.pos),u=Math.min(k.pos,c.end)-c.start;return K(j,{children:[E(j,{color:q,children:a===0?"> ":" "}),h?K(ur,{children:[i.slice(0,u),E(tn,{ch:i[u]??" "}),i.slice(u+1)]}):i||" "]},`${a}-${c.start}`)}):K(j,{children:[E(j,{color:q,children:"> "}),kr?E(tn,{ch:" "}):ne&&!N&&Fe?K(ur,{children:[E(tn,{ch:Fe[0],dim:!0}),E(j,{color:"gray",children:Fe.slice(1)})]}):ne&&!N?K(ur,{children:[E(tn,{ch:ne[0],dim:!0}),E(j,{color:"gray",children:ne.slice(1)}),E(j,{dimColor:!0,children:" (tab)"})]}):(Rr.isSetup||!Od)&&!N?K(ur,{children:[E(tn,{ch:Rr.text[0],dim:!0}),E(j,{color:"gray",children:Rr.text.slice(1)})]}):E(tn,{ch:" "})]})}),Li.length>0&&E(oe,{flexDirection:"column",paddingX:1,children:Li.map((c,a)=>E(j,{color:"gray",children:`\u29D7 queued: ${c}`},`${a}-${c.slice(0,24)}`))}),zn?E(Gc,{tab:zn.tab,width:Me,version:o,engineVersion:Sd}):ut?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,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)."}),We.map((c,a)=>K(j,{color:a===ut.cursor?q:void 0,children:[a===ut.cursor?"\u276F ":" ",`${a+1}. ${c.label}${a===ut.current?" \u2714":""}`.padEnd(16),E(j,{color:"gray",children:c.desc})]},c.label)),E(j,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Be?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Switch connection profile"}),Be.rows.map((c,a)=>K(j,{color:a===Be.cursor?q:void 0,children:[a===Be.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===Be.current?" \u2714":""}`.padEnd(20),E(j,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?E(j,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),E(j,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ve?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Pick your Document360 environment"}),Ve.rows.map((c,a)=>K(j,{color:a===Ve.cursor?q:void 0,children:[a===Ve.cursor?"\u276F ":" ",`${a+1}. ${c.name}`.padEnd(16),E(j,{color:"gray",children:c.apiUrl})]},c.name)),E(j,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):he?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Switch workspace"}),E(j,{dimColor:!0,children:`environment ${he.environment} \xB7 project ${he.projectName??`${he.projectId.slice(0,8)}\u2026`}`}),he.rows.map((c,a)=>K(j,{color:a===he.cursor?q:void 0,children:[a===he.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===he.current?" \u2714":""}`.padEnd(30),E(j,{color:"gray",children:c.type??""})]},c.id)),E(j,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ve?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Choose project"}),E(j,{dimColor:!0,children:`environment ${ve.environment}`}),ve.rows.map((c,a)=>K(j,{color:a===ve.cursor?q:void 0,children:[a===ve.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===ve.current?" \u2714":""}`.padEnd(30),E(j,{color:"gray",children:c.sub??""})]},c.id)),E(j,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ge?(()=>{let a=Math.min(Math.max(0,ge.cursor-Math.floor(7)),Math.max(0,ge.rows.length-14)),i=ge.rows.slice(a,a+14),h=ge.rows.filter(u=>u.checked).length;return K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Which folders back the user docs? (${h} selected of ${ge.rows.length})`}),a>0?E(j,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((u,y)=>{let b=a+y;return K(j,{color:b===ge.cursor?q:void 0,children:[b===ge.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Me-34)),E(j,{color:"gray",children:Ao(u)})]},u.path)}),a+14<ge.rows.length?E(j,{dimColor:!0,children:` \u2193 ${ge.rows.length-a-14} more`}):null,E(j,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Ge?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Which category? (pick one to scope to)"}),Ge.rows.map((c,a)=>{let i=a===Ge.cursor,h=`${a+1}.`.padEnd(3);return K(j,{color:i?q:void 0,children:[i?"\u276F ":" ",`${h} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Me-24))),E(j,{color:"gray",children:` ${c.token}`})]},c.token)}),E(j,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Qe?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Qe.rows.map((c,a)=>{let i=a===Qe.cursor,h=c.indent?" ":" ",u=`${a+1}.`.padEnd(3);return K(j,{color:i?q:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${h}${u} ${c.label}`.padEnd(Math.min(56,Me-24)),c.note?E(j,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),E(j,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):$e?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Preview article${$e.query?` \u2014 filter: ${$e.query}`:" (type to filter)"}`}),Zn.length===0?E(j,{color:"gray",children:"no articles match"}):Zn.map((c,a)=>K(j,{color:a===$e.cursor?q:void 0,children:[a===$e.cursor?"\u276F ":" ",c]},c)),E(j,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):xe?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Resume session${xe.query?` \u2014 filter: ${xe.query}`:" (type to filter)"}`}),eo.length===0?E(j,{color:"gray",children:"no sessions match"}):eo.map((c,a)=>K(j,{color:a===xe.cursor?q:void 0,children:[a===xe.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),E(j,{color:a===xe.cursor?q:"gray",children:c.firstPrompt.slice(0,Math.max(10,Me-40))})]},c.uuid)),E(j,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Gi?K(oe,{flexDirection:"column",children:[hn.map((c,a)=>K(j,{color:a===rn?q:void 0,children:[a===rn?"\u276F ":" ",c.usage.padEnd(22)," ",E(j,{color:a===rn?q:"gray",children:c.name==="model"&&br?`${c.desc} (currently ${br})`:c.desc})]},c.name)),E(j,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!S&&be.length>0?K(oe,{flexDirection:"column",paddingX:1,children:[Oi?E(j,{color:q,children:Oi}):null,be.map((c,a)=>{let i=xt(c),h=i.slice(0,Math.max(20,Me-5)),u=Me-h.length-7,y=u>=12?(Qc(c)??Hc(i)).slice(0,u):"";return K(j,{children:[E(j,{color:q,children:a+1})," ",h,y?E(j,{dimColor:!0,children:` \u2014 ${y}`}):null]},i)}),E(j,{dimColor:!0,children:`press 1-${be.length} to fill \xB7 esc cancel`})]}):E(oe,{paddingX:1,children:K(j,{color:"gray",children:[Vi.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${br??"model n/a"}${t.kind==="api"?Fi>0?` \xB7 ${ke(Fi)}`:"":Wi>0?` \xB7 ${st(Wi)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as kw}from"react/jsx-runtime";async function jd(e=process.cwd(),t="auto",n,o="0.0.0"){let r=yw(t);r.kind==="none"&&(console.error(""),console.error(R("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=ww(kw(Dd,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
407
+ `)}),me(Mn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Ht,Ar,d,Ce,se,Ft,Tr,zi]),ro=z(c=>{let a=(c??T).trim();if(v(""),qn(null),Pt(0),a.startsWith("/")&&(Un.current=!1,Le(),sn(null),He(h=>Jc(h,a))),!a||(Ei(!1),Xi(a))||Ki(a))return;gr.current.push(a);let i=nd(a,Ii.current);if(a.startsWith("/"))d({kind:"user",text:a}),mn(i);else if(ow(i)){d({kind:"user",text:a});let h=rw(i);if(!h)se(i,{display:a,quietUser:!0});else{try{sw(e,{title:h,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}se(`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 se(i,{display:a})},[T,Xi,Ki,mn,se]),Qi=z(c=>{if(c.length>1){if(c.includes("\x1B"))return;let a=Zc(c);if(ed(a)){let i=td(++Ud.current,a);Ii.current.set(i,a),_(i)}else _(a);return}_(c)},[_]),qt=Math.max(10,Me-6),Ji=bi(()=>ir(k.text,qt),[k.text,qt]),Er=z(c=>g(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+c))})),[]),so=z(c=>g(a=>({...a,pos:rd(ir(a.text,qt),a.pos,c)})),[qt]),gn=z(c=>g(a=>({...a,pos:sd(ir(a.text,qt),a.pos,c)})),[qt]),qd=["\x1B[H","\x1B[1~","\x1BOH"],Bd=["\x1B[F","\x1B[4~","\x1BOF"],Zi=z((c,a)=>a.leftArrow?(Er(-1),!0):a.rightArrow?(Er(1),!0):c&&qd.includes(c)?(gn("start"),!0):c&&Bd.includes(c)?(gn("end"),!0):a.ctrl&&c==="a"?(gn("start"),!0):a.ctrl&&c==="e"?(gn("end"),!0):!1,[Er,gn]);return yg((c,a)=>{if(a.ctrl&&c==="c"){De.current?.close(),r();return}if(!M){if(N){if(a.escape){if(je.current){if(!je.current.signal.aborted){let i=(Gn?.verb??"work").toLowerCase(),h=Gn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${h}s)\u2026`}),je.current.abort()}return}an.current||(an.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),De.current?.interrupt());return}if(a.return){let i=T.trim();if(!i)return;gt.current.push(i),yr([...gt.current]),v("");return}if(Zi(c,a))return;if(a.upArrow){so(-1);return}if(a.downArrow){so(1);return}if(a.backspace||a.delete){P();return}c&&!a.ctrl&&!a.meta&&Qi(c);return}if(ut){if(a.upArrow){pt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){pt(i=>i&&{...i,cursor:Math.min(We.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=We.length){pt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=We[ut.cursor];pt(null);let{lines:h,changed:u,effective:y}=Sn(e,i.value??"default");for(let b of h)d({kind:"note",tone:b.startsWith("\u26A0")?"warn":b.startsWith("\u2713")?"ok":"info",text:b});u&&(Hi(b=>b+1),De.current?.setModel(y));return}if(c==="s"){let i=We[ut.cursor];pt(null),De.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){pt(null);return}return}if(Be){if(a.upArrow){At(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){At(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Be.rows.length){At(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return||c==="s"){let i=Be.rows[Be.cursor];At(null),Dr(i.name,a.return===!0);return}if(a.escape){At(null);return}return}if(zn){if(a.escape){dn(null);return}if(a.leftArrow||a.tab&&a.shift){dn(i=>i&&{tab:(i.tab-1+Ae.length)%Ae.length});return}if(a.rightArrow||a.tab){dn(i=>i&&{tab:(i.tab+1)%Ae.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ae.length){dn({tab:Number(c)-1});return}return}if(Ve){if(a.upArrow){Et(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Et(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ve.rows.length){Et(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Ve.rows[Ve.cursor].name;if(Et(null),!Fr(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let u=!1;try{let y=Ct(i);u=!!y&&!(lt(y)&&!y.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${i} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${i}) and pick your project.`}),Q("/login"),Y(y=>y+1);return}if(a.escape){Et(null);return}return}if(he){if(a.upArrow){Nt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Nt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=he.rows.length){Nt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=he.rows[he.cursor],{profile:h,projectId:u}=he;Nt(null),to(h,u,i);return}if(a.escape){Nt(null);return}return}if(ve){if(a.upArrow){ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ft(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ve.rows.length){ft(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=ve.rows[ve.cursor],{profile:h}=ve;ft(null),oo(h,i);return}if(a.escape){ft(null);return}return}if(ge){if(a.upArrow){_t(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){_t(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){_t(i=>i&&{...i,rows:i.rows.map((h,u)=>u===i.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let i=ge.rows.filter(h=>h.checked).map(h=>h.path);if(_t(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}os(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of i)d({kind:"note",tone:"info",text:` ${h}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){_t(null);return}return}if(Ge){if(a.upArrow){ht(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ht(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ge.rows.length){ht(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Ge.rows[Ge.cursor],h=Ge.run;ht(null),h(i.token);return}if(a.escape){ht(null);return}return}if(Qe){if(a.upArrow){It(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){It(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Qe.rows.length){It(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Qe.rows[Qe.cursor];It(null),i.conflict?Ar(i.paths[0]):i.kind==="article"?Tr(i.paths[0]):Ft(i.paths);return}if(a.escape){It(null);return}return}if($e){if(a.escape){mt(null);return}if(a.upArrow){mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){mt(i=>i&&{...i,cursor:Math.min(Math.max(0,Zn.length-1),i.cursor+1)});return}if(a.return){let i=Zn[$e.cursor];if(i){mt(null);try{d({kind:"preview",name:Mn(i),text:Pd(lr(vi(e,i),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${i}: ${h.message}`})}}return}if(a.backspace||a.delete){mt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){mt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(xe){if(a.escape){wt(null);return}if(a.upArrow){wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){wt(i=>i&&{...i,cursor:Math.min(Math.max(0,eo.length-1),i.cursor+1)});return}if(a.return){let i=eo[xe.cursor];if(i){wt(null),Ce(i.uuid),qe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},dt(i.name),$i(i.uuid),St.current=[];let h=wi(e,i.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${i.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){wt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){wt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(a.tab&&!T&&ne){v(ne),Le();return}if(!T&&be.length>0&&!hr&&c&&/^[1-9]$/.test(c)){let i=be[Number(c)-1];if(i){v(xt(i));return}}if(!T&&(Qn||un)&&c==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let i=Qn!=null;mi(Qn??un).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?i?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":i?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&i&&Cr(null),u&&!i&&Bi(!0)});return}if(!Zi(c,a)){if(Gi){if(a.upArrow){Pt(i=>Math.max(0,i-1));return}if(a.downArrow){Pt(i=>Math.min(hn.length-1,i+1));return}if(a.tab){v("/"+(hn[rn]?.name??"")+" "),Pt(0);return}if(a.return){let i=hn[rn];if(i){let h=T.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Bc(i.usage)&&!h){v("/"+i.name+" "),Pt(0);return}ro("/"+i.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(T!==""&&Tt===null){so(-1);return}let i=gr.current;if(!i.length)return;let h=Tt===null?i.length-1:Math.max(0,Tt-1);qn(h),v(i[h]??"");return}if(a.downArrow){if(T!==""&&Tt===null){so(1);return}let i=gr.current;if(Tt===null)return;let h=Tt+1;h>=i.length?(qn(null),v("")):(qn(h),v(i[h]??""));return}}if(a.return){ro();return}if(a.backspace||a.delete){P();return}if(a.escape){v(""),Pt(0),Le(),He([]),sn(null),Un.current=!0;return}c&&!a.ctrl&&!a.meta&&Qi(c)}}}),Te(()=>{if(N||M)return;let c=gt.current.shift();c!==void 0&&(yr([...gt.current]),ro(c))},[N,M,ro]),K(oe,{flexDirection:"column",width:Me,children:[Pr!==null&&K(oe,{marginTop:1,flexDirection:"column",children:[Pr.truncated&&E(j,{dimColor:!0,children:"\u2026"}),E(j,{children:Pr.text})]}),N&&(Gn?E(mw,{p:Gn}):E(pw,{startTime:ct.current,chars:Md})),!N&&Mi?E(fw,{text:Mi}):null,E(oe,{borderStyle:"round",borderColor:Vi.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:T?Ji.map((c,a)=>{let i=k.text.slice(c.start,c.end),h=a===ar(Ji,k.pos),u=Math.min(k.pos,c.end)-c.start;return K(j,{children:[E(j,{color:q,children:a===0?"> ":" "}),h?K(ur,{children:[i.slice(0,u),E(tn,{ch:i[u]??" "}),i.slice(u+1)]}):i||" "]},`${a}-${c.start}`)}):K(j,{children:[E(j,{color:q,children:"> "}),kr?E(tn,{ch:" "}):ne&&!N&&Fe?K(ur,{children:[E(tn,{ch:Fe[0],dim:!0}),E(j,{color:"gray",children:Fe.slice(1)})]}):ne&&!N?K(ur,{children:[E(tn,{ch:ne[0],dim:!0}),E(j,{color:"gray",children:ne.slice(1)}),E(j,{dimColor:!0,children:" (tab)"})]}):(Rr.isSetup||!Od)&&!N?K(ur,{children:[E(tn,{ch:Rr.text[0],dim:!0}),E(j,{color:"gray",children:Rr.text.slice(1)})]}):E(tn,{ch:" "})]})}),Li.length>0&&E(oe,{flexDirection:"column",paddingX:1,children:Li.map((c,a)=>E(j,{color:"gray",children:`\u29D7 queued: ${c}`},`${a}-${c.slice(0,24)}`))}),zn?E(Gc,{tab:zn.tab,width:Me,version:o,engineVersion:Td}):ut?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,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)."}),We.map((c,a)=>K(j,{color:a===ut.cursor?q:void 0,children:[a===ut.cursor?"\u276F ":" ",`${a+1}. ${c.label}${a===ut.current?" \u2714":""}`.padEnd(16),E(j,{color:"gray",children:c.desc})]},c.label)),E(j,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Be?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Switch connection profile"}),Be.rows.map((c,a)=>K(j,{color:a===Be.cursor?q:void 0,children:[a===Be.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===Be.current?" \u2714":""}`.padEnd(20),E(j,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?E(j,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),E(j,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ve?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Pick your Document360 environment"}),Ve.rows.map((c,a)=>K(j,{color:a===Ve.cursor?q:void 0,children:[a===Ve.cursor?"\u276F ":" ",`${a+1}. ${c.name}`.padEnd(16),E(j,{color:"gray",children:c.apiUrl})]},c.name)),E(j,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):he?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Switch workspace"}),E(j,{dimColor:!0,children:`environment ${he.environment} \xB7 project ${he.projectName??`${he.projectId.slice(0,8)}\u2026`}`}),he.rows.map((c,a)=>K(j,{color:a===he.cursor?q:void 0,children:[a===he.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===he.current?" \u2714":""}`.padEnd(30),E(j,{color:"gray",children:c.type??""})]},c.id)),E(j,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ve?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Choose project"}),E(j,{dimColor:!0,children:`environment ${ve.environment}`}),ve.rows.map((c,a)=>K(j,{color:a===ve.cursor?q:void 0,children:[a===ve.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===ve.current?" \u2714":""}`.padEnd(30),E(j,{color:"gray",children:c.sub??""})]},c.id)),E(j,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ge?(()=>{let a=Math.min(Math.max(0,ge.cursor-Math.floor(7)),Math.max(0,ge.rows.length-14)),i=ge.rows.slice(a,a+14),h=ge.rows.filter(u=>u.checked).length;return K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Which folders back the user docs? (${h} selected of ${ge.rows.length})`}),a>0?E(j,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((u,y)=>{let b=a+y;return K(j,{color:b===ge.cursor?q:void 0,children:[b===ge.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Me-34)),E(j,{color:"gray",children:Ao(u)})]},u.path)}),a+14<ge.rows.length?E(j,{dimColor:!0,children:` \u2193 ${ge.rows.length-a-14} more`}):null,E(j,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Ge?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Which category? (pick one to scope to)"}),Ge.rows.map((c,a)=>{let i=a===Ge.cursor,h=`${a+1}.`.padEnd(3);return K(j,{color:i?q:void 0,children:[i?"\u276F ":" ",`${h} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Me-24))),E(j,{color:"gray",children:` ${c.token}`})]},c.token)}),E(j,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Qe?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Qe.rows.map((c,a)=>{let i=a===Qe.cursor,h=c.indent?" ":" ",u=`${a+1}.`.padEnd(3);return K(j,{color:i?q:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${h}${u} ${c.label}`.padEnd(Math.min(56,Me-24)),c.note?E(j,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),E(j,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):$e?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Preview article${$e.query?` \u2014 filter: ${$e.query}`:" (type to filter)"}`}),Zn.length===0?E(j,{color:"gray",children:"no articles match"}):Zn.map((c,a)=>K(j,{color:a===$e.cursor?q:void 0,children:[a===$e.cursor?"\u276F ":" ",c]},c)),E(j,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):xe?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Resume session${xe.query?` \u2014 filter: ${xe.query}`:" (type to filter)"}`}),eo.length===0?E(j,{color:"gray",children:"no sessions match"}):eo.map((c,a)=>K(j,{color:a===xe.cursor?q:void 0,children:[a===xe.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),E(j,{color:a===xe.cursor?q:"gray",children:c.firstPrompt.slice(0,Math.max(10,Me-40))})]},c.uuid)),E(j,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Gi?K(oe,{flexDirection:"column",children:[hn.map((c,a)=>K(j,{color:a===rn?q:void 0,children:[a===rn?"\u276F ":" ",c.usage.padEnd(22)," ",E(j,{color:a===rn?q:"gray",children:c.name==="model"&&br?`${c.desc} (currently ${br})`:c.desc})]},c.name)),E(j,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!T&&be.length>0?K(oe,{flexDirection:"column",paddingX:1,children:[Oi?E(j,{color:q,children:Oi}):null,be.map((c,a)=>{let i=xt(c),h=i.slice(0,Math.max(20,Me-5)),u=Me-h.length-7,y=u>=12?(Qc(c)??Hc(i)).slice(0,u):"";return K(j,{children:[E(j,{color:q,children:a+1})," ",h,y?E(j,{dimColor:!0,children:` \u2014 ${y}`}):null]},i)}),E(j,{dimColor:!0,children:`press 1-${be.length} to fill \xB7 esc cancel`})]}):E(oe,{paddingX:1,children:K(j,{color:"gray",children:[Vi.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${br??"model n/a"}${t.kind==="api"?Fi>0?` \xB7 ${ke(Fi)}`:"":Wi>0?` \xB7 ${st(Wi)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as kw}from"react/jsx-runtime";async function jd(e=process.cwd(),t="auto",n,o="0.0.0"){let r=yw(t);r.kind==="none"&&(console.error(""),console.error(R("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=ww(kw(Dd,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
408
408
  `),process.exit(0)}W();import{writeCrashLog as Ad,isBenignTransportError as bw}from"document360-engine";var Ed=!1;function Di(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Nd(e){if(Ed)return;Ed=!0;let t=(n,o)=>{if(bw(o)){Ad({kind:n,level:"transport",message:Di(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=Ad({kind:n,level:"fatal",message:Di(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
409
409
  `+R(`\u2717 d360-writer crashed: ${Di(o)}`)+`
410
410
  `),r&&process.stderr.write(f(` Crash details: ${r}`)+`