document360-writer 0.5.141 → 0.5.142

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 +121 -121
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var Ud=Object.defineProperty;var $o=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Na=(e,t)=>{for(var n in t)Ud(e,n,{get:t[n],enumerable:!0})};import ot from"picocolors";var V,Wd,Fd,qd,Ia,Cn,g,C,M,E,L,ae,xe,H=$o(()=>{"use strict";V="#7f56d9",[Wd,Fd,qd]=[127,86,217],Ia=e=>ot.isColorSupported?`\x1B[38;2;${Wd};${Fd};${qd}m${e}\x1B[39m`:e,Cn=e=>ot.bold(Ia(e)),g=e=>ot.dim(e),C=e=>ot.red(e),M=e=>ot.yellow(e),E=e=>ot.green(e),L=Ia,ae=e=>ot.gray(e),xe=e=>ot.bold(e)});import{existsSync as Xt,writeFileSync as st,readFileSync as Pp,readdirSync as Tp}from"node:fs";import{join as Ja}from"node:path";import{devHintsGuidePath as Eo,hintsDir as Za,hooksDir as el,architectureDir as sl,messagesDir as ns,creatorNotesPath as tl,devhintsStatePath as il,directivesPath as nl,DIRECTIVES_HEADER as Dp,roadmapPath as ol,ROADMAP_HEADER as Ap,ensureDir as Pn,writeMessage as jp,listOpenForDev as Ep}from"document360-engine";function al(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var Hd=Object.defineProperty;var Cn=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var _a=(e,t)=>{for(var n in t)Hd(e,n,{get:t[n],enumerable:!0})};import ot from"picocolors";var V,Bd,Vd,Gd,La,Rn,g,C,M,N,L,ae,$e,H=Cn(()=>{"use strict";V="#7f56d9",[Bd,Vd,Gd]=[127,86,217],La=e=>ot.isColorSupported?`\x1B[38;2;${Bd};${Vd};${Gd}m${e}\x1B[39m`:e,Rn=e=>ot.bold(La(e)),g=e=>ot.dim(e),C=e=>ot.red(e),M=e=>ot.yellow(e),N=e=>ot.green(e),L=La,ae=e=>ot.gray(e),$e=e=>ot.bold(e)});import{existsSync as Xt,writeFileSync as st,readFileSync as jp,readdirSync as Ep}from"node:fs";import{join as el}from"node:path";import{devHintsGuidePath as Eo,hintsDir as tl,hooksDir as nl,architectureDir as al,messagesDir as os,creatorNotesPath as ol,devhintsStatePath as ll,directivesPath as rl,DIRECTIVES_HEADER as Np,roadmapPath as sl,ROADMAP_HEADER as Ip,ensureDir as Tn,writeMessage as _p,listOpenForDev as Lp}from"document360-engine";function cl(){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
 
@@ -218,7 +218,7 @@ do it**:
218
218
  **Do NOT write or action the documentation yourself** \u2014 same boundary as Part 2. Writing the article is the
219
219
  docs agent's job; it actions open directives on its next \`/catch-up\` (as drafts) and flips each to \`[done]\`
220
220
  with the article it wrote. You are only the relay so the ask is captured durably and travels via git.
221
- `}function Ip(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
221
+ `}function Mp(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
222
222
 
223
223
  <!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
224
224
  The builder agent reads this FIRST and treats it as authoritative when writing the architecture
@@ -232,12 +232,12 @@ Anything only a human knows that would help document this product. For example:
232
232
  - Gotchas or non-obvious behavior.
233
233
 
234
234
  (Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
235
- `}function Jt(e){Pn(Za(e)),Pn(sl(e)),Pn(ns(e));for(let n of[Za(e),ns(e)]){let o=Ja(n,".gitkeep");Xt(o)||st(o,`# Keeps this document360-writer inbox tracked in git even when empty.
236
- `)}Xt(tl(e))||st(tl(e),Ip()),Xt(nl(e))||st(nl(e),Dp),Xt(ol(e))||st(ol(e),Ap),st(Eo(e),al()),Pn(el(e)),st(Ja(el(e),"open-questions.mjs"),Np);let t=Ne(e);return cl(e,new Date().toISOString()),t}async function ll(e,t){for(let n of Zt(Jt(t.cwd)))console.log(n);return{kind:"continue"}}function Pt(){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(`
237
- `)}function os(e){try{let t=Pp(il(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function cl(e,t){let o={...os(e)??{},emittedVersion:le,emittedAt:t};st(il(e),`${JSON.stringify(o,null,2)}
238
- `)}function Xe(e){try{return Tp(sl(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ne(e){let n=os(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<le?"stale":"current",completedVersion:n}}function No(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:le};try{if(!Xt(Eo(e)))return n;let o=os(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;le>r&&(Pn(ns(e)),st(Eo(e),al()),cl(e,t),n.guideRefreshed=!0),le>s&&(Ep(e).some(d=>d.kind==="request"&&d.subject.startsWith(rl))||(jp(e,{id:`onb${le}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${rl}${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:","",Pt()].join(`
239
- `)}),n.notifiedBuilder=!0))}catch{}return n}function Io(e){if(!Xt(Eo(e)))return[];let t=Ne(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}`,Qt,Pt(),Qt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function rs(){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(`
240
- `)}function _o(){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):",Qt,rs(),Qt]}function Zt(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):",Qt,Pt(),Qt,"","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 Qt,le,Np,rl,it=$o(()=>{"use strict";Qt="-".repeat(64),le=10,Np=`#!/usr/bin/env node
235
+ `}function Jt(e){Tn(tl(e)),Tn(al(e)),Tn(os(e));for(let n of[tl(e),os(e)]){let o=el(n,".gitkeep");Xt(o)||st(o,`# Keeps this document360-writer inbox tracked in git even when empty.
236
+ `)}Xt(ol(e))||st(ol(e),Mp()),Xt(rl(e))||st(rl(e),Np),Xt(sl(e))||st(sl(e),Ip),st(Eo(e),cl()),Tn(nl(e)),st(el(nl(e),"open-questions.mjs"),Op);let t=Ne(e);return dl(e,new Date().toISOString()),t}async function ul(e,t){for(let n of Zt(Jt(t.cwd)))console.log(n);return{kind:"continue"}}function Pt(){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(`
237
+ `)}function rs(e){try{let t=jp(ll(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function dl(e,t){let o={...rs(e)??{},emittedVersion:le,emittedAt:t};st(ll(e),`${JSON.stringify(o,null,2)}
238
+ `)}function Xe(e){try{return Ep(al(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ne(e){let n=rs(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<le?"stale":"current",completedVersion:n}}function No(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:le};try{if(!Xt(Eo(e)))return n;let o=rs(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;le>r&&(Tn(os(e)),st(Eo(e),cl()),dl(e,t),n.guideRefreshed=!0),le>s&&(Lp(e).some(d=>d.kind==="request"&&d.subject.startsWith(il))||(_p(e,{id:`onb${le}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${il}${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:","",Pt()].join(`
239
+ `)}),n.notifiedBuilder=!0))}catch{}return n}function Io(e){if(!Xt(Eo(e)))return[];let t=Ne(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}`,Qt,Pt(),Qt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function ss(){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(`
240
+ `)}function _o(){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):",Qt,ss(),Qt]}function Zt(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):",Qt,Pt(),Qt,"","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 Qt,le,Op,il,it=Cn(()=>{"use strict";Qt="-".repeat(64),le=10,Op=`#!/usr/bin/env node
241
241
  // d360-writer \u2014 session-start nudge for the builder ("John"). Surfaces open questions the docs agent
242
242
  // ("Julie") left in .d360-writer/messages/ so they get answered, not forgotten. Self-contained (no deps);
243
243
  // wired into your coding agent's session-start trigger by /devhints. See .d360-writer/DEV-HINTS-GUIDE.md.
@@ -275,60 +275,60 @@ try {
275
275
  } catch {
276
276
  /* a session-start nudge must never break the session */
277
277
  }
278
- `;rl="Re-run dev\u2194docs onboarding (protocol v"});var kl={};Na(kl,{initCommand:()=>is,scaffoldInit:()=>ss});import{input as Tn,confirm as _p}from"@inquirer/prompts";import{basename as ul,join as Lo}from"node:path";import{existsSync as en,readFileSync as Lp,readdirSync as Op,writeFileSync as Mp}from"node:fs";import{writeProjectConfig as dl,readProjectConfig as Up,projectConfigPath as pl,writerDir as Wp,DEFAULT_DOCS_DIR as hl,DEFAULT_CAPTURE_DIR as fl,DEFAULT_OUTPUT_DIR as ml}from"document360-engine";function ss(e,t="berlin"){let n=pl(e);if(en(n))return{created:!1,path:n,profileName:""};let o={projectId:wl(e)??ul(e),docsDir:hl,captureDir:fl,outputDir:ml,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:yl(e)};return dl(o,e),gl(e),{created:!0,path:n,profileName:t}}function gl(e){let t=Lo(Wp(e),".gitignore");en(t)||Mp(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
279
- `),"utf8")}async function is(){let e=process.cwd(),t=pl(e);if(en(t)&&!await _p({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(g("init cancelled.")),{kind:"continue"};let n=wl(e)??ul(e),o=await Tn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Tn({message:"Capture directory (where document360-capture .spec.ts files live):",default:fl}),s=await Tn({message:"Screenshot output directory:",default:ml}),l=await Tn({message:"Default connection profile name:",default:"berlin"}),d=await Tn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),m={projectId:o,docsDir:hl,captureDir:r,outputDir:s,profiles:{[l]:{connection:{environment:d},production:!1}},defaultProfile:l,authoritativeSourceFiles:yl(e)},k=Up(e);k?.terminologyGlossary&&(m.terminologyGlossary=k.terminologyGlossary),dl(m,e),gl(e);let y=Jt(e);console.log(""),console.log(E(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${L(`d360-writer login --profile ${l}`)} ${g("(sign in; project & workspace auto-selected)")}`),console.log("");for(let v of Zt(y))console.log(v);return console.log(""),console.log(`${g("Then ask:")} ${L('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function wl(e){let t=Lo(e,"package.json");if(!en(t))return null;try{return JSON.parse(Lp(t,"utf8")).name??null}catch{return null}}function yl(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])en(Lo(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Lo(e,n);en(o)&&!Fp(o)&&t.push(n)}return t}function Fp(e){try{return Op(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Oo=$o(()=>{"use strict";H();it()});var Nc={};Na(Nc,{doctorCommand:()=>Mn,renderDoctorChecks:()=>Ec,runDoctorChecks:()=>jc});import{existsSync as Mf}from"node:fs";import{d360GetAll as Uf,getAccessToken as Wf,isExpired as li,loadProfileMap as Ff,loadTokens as qf,packageSkillsDir as Dc,ENGINE_VERSION as Hf,projectConfigPath as Bf,readProjectConfig as Vf,DEFAULT_DOCS_DIR as Gf,fetchManifestSummary as Yf,resolveActiveProfile as zf,classifyClaudeAuth as Kf,CLAUDE_CODE_SETUP_HINT as Ac,resolveModelSetting as Xf,probeModel as Qf,detectAppType as Jf,playbookSkillName as Zf,D360AuthError as em}from"document360-engine";async function jc(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Hf}`});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=Kf();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. ${Ac}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Ac});let s=Xf(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 R=await Qf(e,s.model??void 0);R.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(R.latencyMs/1e3).toFixed(1)}s`}):R.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 ${R.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=Vf(e);if(!l)return n.push({level:"fail",label:`No ${Bf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${l.projectId}`});let d=(l.docsDir??Gf).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 ${d}/ 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??Jf(e);if(k){let R=l.appType?"from config":"auto-detected",N=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${R})${N?` \u2192 ${Zf(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 y;try{y=zf(e),n.push({level:"ok",label:`Profile: ${y.name} (${y.connection.name})${y.production?" \u26A0 PRODUCTION":""}`})}catch(R){return n.push({level:"fail",label:`Profile config: ${R.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let v=qf(y.name);v?li(v)&&!v.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):li(v)?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(v.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${y.name})`}),n.push(y.project.workspaceId?{level:"ok",label:`Workspace: ${y.project.workspaceName??y.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let $=Ff(e,y.name);$?$.projectId&&y.project.projectId&&$.projectId!==y.project.projectId?n.push({level:"fail",label:`Category map projectId (${$.projectId}) \u2260 profile projectId (${y.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($.articles).length} articles, ${Object.keys($.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${y.name}" (created on first /publish)`}),n.push(Mf(Dc())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Dc()}`,fix:"Reinstall document360-writer (broken install)"});let _=Ne(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)"}),v&&(!li(v)||v.refreshToken)){let R={profile:y.name,connection:y.connection};try{await Wf(R);let T=await Uf(R,"/v3/projects");n.push({level:"ok",label:`API reachable (${y.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=$?.projectId??y.project.projectId;if(N&&y.project.workspaceId)try{let T=await Yf(R,N,y.project.workspaceId);if(T){let F=(T.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${y.connection.name} (${T.languages?.length??0} language${(T.languages?.length??0)===1?"":"s"}) \xB7 hash ${F||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${y.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 em||/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 (${y.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 Ec(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?M("\u26A0"):C("\u2717");t.push(` ${s} ${r.label}${r.detail?g(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${g("fix:")} ${L(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?E(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):C(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Mn(e,t){console.log(g("Running checks\u2026"));for(let n of Ec(await jc(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var er=$o(()=>{"use strict";it();H()});import{Command as $y}from"commander";import{createRequire as vy}from"node:module";import{AUTH_MODES as Cy}from"document360-engine";import{input as np}from"@inquirer/prompts";import{loginPkce as op,refreshTokens as rp,toStoredTokens as Wa,clearTokens as sp,decodeJwtClaims as Ua,isExpired as ip,loadTokens as ap,saveTokens as Fa,resolveActiveProfile as So,setProfileProject as lp,readProjectConfig as cp}from"document360-engine";H();import{select as Hd}from"@inquirer/prompts";import{resolveActiveProfile as Bd,setProfileProject as Vd,resolveProjectId as Gd,listWorkspaces as Yd}from"document360-engine";async function Rn(e,t){let n=Bd(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Gd(o);return{workspaces:await Yd(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var _a=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Qr(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function vo(e,t,n,o,r){Vd(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function La(e,t,n){let o;try{o=await Rn(e,n)}catch(s){return console.log(C(`Could not list workspaces: ${s.message}`)),1}let r=Qr(o.workspaces,t);return r?(vo(e,o.profile,o.projectId,r.id,r.name),console.log(E(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(C(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Kt(e,t){let n;try{n=await Rn(e,t)}catch(k){console.log(C(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:l}=n;if(o.length===0){console.log(g("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===l?L("\u25CF"):" "} ${_a(k)} ${g(k.id)}`);console.log(g("Run: d360-writer workspace use <name>"));return}let d=await Hd({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${_a(k)}${k.id===l?" (current)":""}`,value:k.id}))}),m=o.find(k=>k.id===d);vo(e,s,r,d,m?.name),console.log(E(`\u2713 Workspace set to "${m?.name??d}" for profile "${s}".`))}H();import{select as zd}from"@inquirer/prompts";import{resolveActiveProfile as Kd,setProfileProject as Xd,listProjects as Qd}from"document360-engine";async function rt(e,t){let n=Kd(e,t),o={profile:n.name,connection:n.connection};return{projects:await Qd(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Oa=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Jr(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){Xd(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Ma(e,t,n){let o;try{o=await rt(e,n)}catch(s){return console.log(C(`Could not list projects: ${s.message}`)),1}let r=Jr(o.projects,t);return r?(Co(e,o.profile,r.id,r.name),console.log(E(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(C(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Ro(e,t){let n;try{n=await rt(e,t)}catch(m){console.log(C(`Could not list projects: ${m.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(g("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let m of o)console.log(` ${m.id===s?L("\u25CF"):" "} ${Oa(m)} ${g(m.id)}`);console.log(g("Run: d360-writer project use <name>"));return}let l=await zd({message:"Select the Document360 project for this repo:",choices:o.map(m=>({name:`${Oa(m)}${m.id===s?" (current)":""}`,value:m.id}))}),d=o.find(m=>m.id===l);Co(e,r,l,d?.name),console.log(E(`\u2713 Project set to "${d?.name??l}" for profile "${r}". Next: pick a workspace.`))}H();import Jd from"picocolors";function Zd(e=process.env){return e.FORCE_HYPERLINK==="0"||!Jd.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 ep(e,t=e,n){return Zd(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var tp=/https?:\/\/[^\s\x1b]+/g;function Sn(e,t){return e.replace(tp,n=>ep(n,n,t))}function qa(e){return{...Ua(e.idToken)??{},...Ua(e.accessToken)??{}}}function Po(e){let t=qa(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 To(e){let t=So(process.cwd(),e.profile),n=t.connection;console.log(g(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await op(n,{manual:e.manual,promptForRedirect:s=>np({message:s})},s=>console.log(Sn(s))),r=Wa(t.name,o);if(Fa(r),await Zr(r,t.name,s=>console.log(g(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${Po(r)}`)),console.log(g(` access token expires: ${r.expiresAt}`)),console.log(g(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{cp(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Kt(process.cwd(),t.name))}catch{}}async function Zr(e,t,n){let r=qa(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(So(process.cwd(),t).project.projectId)return;let l;try{let{projects:d}=await rt(process.cwd(),t);l=d.find(m=>m.id===r)?.name}catch{}lp(process.cwd(),t,{projectId:r,projectName:l}),n(` Project "${l??r}" written to profile "${t}".`)}catch{}}async function Ha(e){let t=So(process.cwd(),e.profile),n=t.connection,o=ap(t.name);if(!o){console.log(C(`Not logged in to Document360 (profile "${t.name}").`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${L(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Po(o)}`),ip(o))if(o.refreshToken)try{let r=Wa(t.name,await rp(n,o.refreshToken));Fa(r),console.log(E(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(M(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(M("Session expired (no refresh token).")),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(g(` expires: ${o.expiresAt}`))}async function Ba(e){let t=So(process.cwd(),e.profile);sp(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(g(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}H();import{readProjectConfig as Va,writeProjectConfig as up,resolveActiveProfile as dp,loadTokens as pp,isExpired as hp}from"document360-engine";function Do(e){let t=Va(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(C("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?L("\u25CF "):" ",s=o.production?M(" \u26A0 PRODUCTION"):"",l=o.connection.environment??"(inline)",d=pp(n),m=d?hp(d)&&!d.refreshToken?M("expired"):g("logged in"):g("not logged in");console.log(`${r}${L(n)} \u2192 ${l}${s} [${m}]`)}console.log(""),console.log(g("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Ao(e,t){let n=Va(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(C(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,up(n,e);let o=n.profiles[t].production?M(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function jo(e,t){try{let n=dp(e,t);console.log(""),console.log(`Profile ${L(n.name)}${n.production?M(" \u26A0 PRODUCTION"):""}`),console.log(g(` api: ${n.connection.apiUrl}`)),console.log(g(` identity: ${n.connection.authorizationUrl}`)),console.log(g(` clientId: ${n.connection.clientId}`)),console.log(g(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(g(` project: ${n.project.projectId??"(set at login)"}`)),console.log(g(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(C(n.message)),process.exitCode=1}}H();import{existsSync as fp,readdirSync as mp,statSync as Ga}from"node:fs";import{join as Ya}from"node:path";import{apiLogDir as gp}from"document360-engine";function za(){let e=gp();if(console.log(""),console.log(`Document360 API logs: ${L(e)}`),!fp(e)){console.log(g(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=mp(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(g(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Ga(Ya(e,r)).size/1024).toFixed(1);console.log(` ${r} ${g(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${g("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Ga(Ya(e,r)).size/1024).toFixed(1);console.log(` ${C(r)} ${g(`${s} KB`)}`)}}console.log(""),console.log(g("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(g("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}H();import{createSession as wp,resolveAuth as yp,findByName as kp,slugify as bp,touchSession as xp,upsertSession as $p,resolveActiveProfile as vp}from"document360-engine";async function Ka(e,t,n,o,r,s){let l=yp(n);l.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),process.exit(2)),l.kind==="subscription"&&console.error(g("Using your Claude subscription (no API key set)."));let d=null;try{d=vp(e,r)}catch($){console.error(C(`Document360 profile error: ${$.message}`)),process.exit(2)}d.production&&(console.error(M(`\u26A0 Profile "${d.name}" is PRODUCTION.`)),s||(console.error(C("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(g(" --yes given \u2014 proceeding against production.")));let m;if(o){let $=kp(e,o);$||(console.error(C(`No saved session matches "${o}" in this repo.`)),console.error(g("List sessions inside the REPL with /resume.")),process.exit(2)),m=$.uuid,console.error(g(`Resuming "${$.name}"`))}let k=wp({cwd:e,resume:m,profileName:r,allowProdWrites:s===!0}),y=m??null,v=1;for await(let $ of k.send(t))switch($.type){case"session":if(!y){y=$.sessionId;let _=new Date().toISOString();$p({uuid:y,name:bp(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:_,updatedAt:_})}break;case"text":process.stdout.write($.delta);break;case"tool":console.error(ae(` \u2699 ${$.name}`));break;case"result":v=$.ok?0:1,console.error(g(`(${$.inputTokens}\u2192${$.outputTokens} tokens`+($.costUsd>0?`, $${$.costUsd<.01?$.costUsd.toFixed(4):$.costUsd.toFixed(2)}`:"")+")")),$.ok||console.error(C("agent finished with an error result"));break;case"error":console.error(""),console.error(C(`agent error: ${$.message}`)),process.exit(1)}y&&xp(y),process.stdout.write(`
280
- `),process.exit(v)}import{createInterface as Ag}from"node:readline/promises";import{createSession as Vi,resolveAuth as jg,getSession as Eg,setTitle as Ng,slugify as Ig,touchSession as Du,upsertSession as _g,generateTitle as Lg,resolveActiveProfile as Au,resolveModelSetting as Og,readProjectConfig as Mg,resolveAndPersistAppType as Ug,decodeJwtClaims as Tu,isExpired as Wg,loadTokens as Fg,isDirectiveMention as qg,stripDirectiveMention as Hg,appendDirective as Bg,reconcileUpgradeActions as Vg,stampArticles as Gg,listArticleFiles as Yg,CONTENT_CAP_VERSION as zg}from"document360-engine";import{ENGINE_VERSION as Rp}from"document360-engine";var Ee=[{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 author --all to write the 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 /screenshot capture \u2014 the writer drives a real browser that signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Run /publish --screenshots \u2014 it re-saves the articles with captured shots so the images embed on Document360."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Bare: pick what to do next (author or capture, per shot)."},{t:"cmd",name:"/screenshot author",s:"Write capture specs (<id>, a path, or --all)."},{t:"cmd",name:"/screenshot capture",s:"Take the screenshots (<id>, a path, or --all; bare = pick ready specs)."},{t:"cmd",name:"/screenshot checklist",s:"What to stage + dev test-id requests (a report; auto-runs after bulk authoring)."},{t:"cmd",name:"/screenshot list",s:"Read-only status of every shot (\u25CB placeholder \xB7 \u25D0 spec \xB7 \u25CF captured)."},{t:"gap"},{t:"dim",s:"One-time setup in the app repo: npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth (real login, once per machine)."}]},{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 (`done` marks the next step finished)."},{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:"The screenshot pipeline: bare = pick; author / capture / checklist / 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 Cp(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 Xa(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 Ee){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(Cp(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function es(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:Rp}:void 0;for(let o of Xa(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"}}H();import{getSession as Sp}from"document360-engine";async function Qa(e,t){let n=t.currentUuid(),o=n?Sp(n):void 0;return console.log(o?g(`
278
+ `;il="Re-run dev\u2194docs onboarding (protocol v"});var $l={};_a($l,{initCommand:()=>as,scaffoldInit:()=>is});import{input as Dn,confirm as Up}from"@inquirer/prompts";import{basename as pl,join as Lo}from"node:path";import{existsSync as en,readFileSync as Wp,readdirSync as Fp,writeFileSync as qp}from"node:fs";import{writeProjectConfig as hl,readProjectConfig as Hp,projectConfigPath as fl,writerDir as Bp,DEFAULT_DOCS_DIR as ml,DEFAULT_CAPTURE_DIR as gl,DEFAULT_OUTPUT_DIR as wl}from"document360-engine";function is(e,t="berlin"){let n=fl(e);if(en(n))return{created:!1,path:n,profileName:""};let o={projectId:kl(e)??pl(e),docsDir:ml,captureDir:gl,outputDir:wl,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:bl(e)};return hl(o,e),yl(e),{created:!0,path:n,profileName:t}}function yl(e){let t=Lo(Bp(e),".gitignore");en(t)||qp(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
279
+ `),"utf8")}async function as(){let e=process.cwd(),t=fl(e);if(en(t)&&!await Up({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(g("init cancelled.")),{kind:"continue"};let n=kl(e)??pl(e),o=await Dn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Dn({message:"Capture directory (where document360-capture .spec.ts files live):",default:gl}),s=await Dn({message:"Screenshot output directory:",default:wl}),l=await Dn({message:"Default connection profile name:",default:"berlin"}),d=await Dn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),m={projectId:o,docsDir:ml,captureDir:r,outputDir:s,profiles:{[l]:{connection:{environment:d},production:!1}},defaultProfile:l,authoritativeSourceFiles:bl(e)},y=Hp(e);y?.terminologyGlossary&&(m.terminologyGlossary=y.terminologyGlossary),hl(m,e),yl(e);let b=Jt(e);console.log(""),console.log(N(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${L(`d360-writer login --profile ${l}`)} ${g("(sign in; project & workspace auto-selected)")}`),console.log("");for(let v of Zt(b))console.log(v);return console.log(""),console.log(`${g("Then ask:")} ${L('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function kl(e){let t=Lo(e,"package.json");if(!en(t))return null;try{return JSON.parse(Wp(t,"utf8")).name??null}catch{return null}}function bl(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])en(Lo(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Lo(e,n);en(o)&&!Vp(o)&&t.push(n)}return t}function Vp(e){try{return Fp(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Oo=Cn(()=>{"use strict";H();it()});import{createRequire as qf}from"node:module";import{existsSync as Hf,readFileSync as Bf}from"node:fs";import{dirname as jc,join as Ec}from"node:path";function er(){let e;try{e=Vf.resolve("document360-capture/helpers")}catch{return null}let t=jc(e);for(let n=0;n<5&&!Hf(Ec(t,"package.json"));n++)t=jc(t);try{let n=JSON.parse(Bf(Ec(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var Vf,ci=Cn(()=>{"use strict";Vf=qf(import.meta.url)});var Oc={};_a(Oc,{doctorCommand:()=>Un,renderDoctorChecks:()=>Lc,runDoctorChecks:()=>_c});import{existsSync as Gf}from"node:fs";import{d360GetAll as Yf,getAccessToken as zf,isExpired as ui,loadProfileMap as Kf,loadTokens as Xf,packageSkillsDir as Nc,ENGINE_VERSION as Qf,projectConfigPath as Jf,readProjectConfig as Zf,DEFAULT_DOCS_DIR as em,fetchManifestSummary as tm,resolveActiveProfile as nm,classifyClaudeAuth as om,CLAUDE_CODE_SETUP_HINT as Ic,resolveModelSetting as rm,probeModel as sm,detectAppType as im,playbookSkillName as am,D360AuthError as lm}from"document360-engine";async function _c(e,t){let n=[],o=er();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Qf}${o?` \xB7 capture v${o}`:" \xB7 capture not installed"}`});let r=Number(process.versions.node.split(".")[0]);n.push(r>=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 s=om();s.state==="ready"?n.push({level:"ok",label:`Claude auth: ${s.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):s.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. ${Ic}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Ic});let l=rm(e);if(n.push({level:"ok",label:`Model: ${l.model} (${l.source==="auto"?"auto \u2014 right-sized for docs; /model to change":l.source})`}),s.state==="ready"){let j=await sm(e,l.model??void 0);j.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(j.latencyMs/1e3).toFixed(1)}s`}):j.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 ${j.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 d=Zf(e);if(!d)return n.push({level:"fail",label:`No ${Jf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${d.projectId}`});let m=(d.docsDir??em).replace(/\/+$/,"");n.push(d.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 ${m}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let y=d.authoritativeSourceFiles??[];n.push(y.length>0?{level:"ok",label:`Sources: docs grounded in ${y.length} path(s) (${y.slice(0,3).join(", ")}${y.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 b=d.appType??im(e);if(b){let j=d.appType?"from config":"auto-detected",D=b==="web"||b==="cli";n.push({level:"ok",label:`Genre: ${b} (${j})${D?` \u2192 ${am(b)} 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 v;try{v=nm(e),n.push({level:"ok",label:`Profile: ${v.name} (${v.connection.name})${v.production?" \u26A0 PRODUCTION":""}`})}catch(j){return n.push({level:"fail",label:`Profile config: ${j.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let x=Xf(v.name);x?ui(x)&&!x.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):ui(x)?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(x.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${v.name})`}),n.push(v.project.workspaceId?{level:"ok",label:`Workspace: ${v.project.workspaceName??v.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let I=Kf(e,v.name);I?I.projectId&&v.project.projectId&&I.projectId!==v.project.projectId?n.push({level:"fail",label:`Category map projectId (${I.projectId}) \u2260 profile projectId (${v.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(I.articles).length} articles, ${Object.keys(I.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${v.name}" (created on first /publish)`}),n.push(Gf(Nc())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Nc()}`,fix:"Reinstall document360-writer (broken install)"});let P=Ne(e);if(P.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${le})`}):P.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${P.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)"}),x&&(!ui(x)||x.refreshToken)){let j={profile:v.name,connection:v.connection};try{await zf(j);let U=await Yf(j,"/v3/projects");n.push({level:"ok",label:`API reachable (${v.connection.apiUrl}) \u2014 ${U.length} project(s) visible`})}catch(U){n.push({level:"fail",label:`API call failed: ${U.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let D=I?.projectId??v.project.projectId;if(D&&v.project.workspaceId)try{let U=await tm(j,D,v.project.workspaceId);if(U){let G=(U.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${v.connection.name} (${U.languages?.length??0} language${(U.languages?.length??0)===1?"":"s"}) \xB7 hash ${G||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${v.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(U){U instanceof lm||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(U.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${v.project.projectName??D})`,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 (${U.message.slice(0,80)})`})}}return n}function Lc(e){let t=[""];for(let r of e){let s=r.level==="ok"?N("\u2713"):r.level==="warn"?M("\u26A0"):C("\u2717");t.push(` ${s} ${r.label}${r.detail?g(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${g("fix:")} ${L(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?N(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):C(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Un(e,t){console.log(g("Running checks\u2026"));for(let n of Lc(await _c(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var tr=Cn(()=>{"use strict";it();H();ci()});import{Command as Ay}from"commander";import{createRequire as jy}from"node:module";import{AUTH_MODES as Ey}from"document360-engine";import{input as ip}from"@inquirer/prompts";import{loginPkce as ap,refreshTokens as lp,toStoredTokens as qa,clearTokens as cp,decodeJwtClaims as Fa,isExpired as up,loadTokens as dp,saveTokens as Ha,resolveActiveProfile as So,setProfileProject as pp,readProjectConfig as hp}from"document360-engine";H();import{select as Yd}from"@inquirer/prompts";import{resolveActiveProfile as zd,setProfileProject as Kd,resolveProjectId as Xd,listWorkspaces as Qd}from"document360-engine";async function Sn(e,t){let n=zd(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Xd(o);return{workspaces:await Qd(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Oa=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Jr(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function vo(e,t,n,o,r){Kd(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Ma(e,t,n){let o;try{o=await Sn(e,n)}catch(s){return console.log(C(`Could not list workspaces: ${s.message}`)),1}let r=Jr(o.workspaces,t);return r?(vo(e,o.profile,o.projectId,r.id,r.name),console.log(N(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(C(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Kt(e,t){let n;try{n=await Sn(e,t)}catch(y){console.log(C(`Could not list workspaces: ${y.message}`));return}let{workspaces:o,projectId:r,profile:s,current:l}=n;if(o.length===0){console.log(g("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let y of o)console.log(` ${y.id===l?L("\u25CF"):" "} ${Oa(y)} ${g(y.id)}`);console.log(g("Run: d360-writer workspace use <name>"));return}let d=await Yd({message:"Select the Document360 workspace for this repo:",choices:o.map(y=>({name:`${Oa(y)}${y.id===l?" (current)":""}`,value:y.id}))}),m=o.find(y=>y.id===d);vo(e,s,r,d,m?.name),console.log(N(`\u2713 Workspace set to "${m?.name??d}" for profile "${s}".`))}H();import{select as Jd}from"@inquirer/prompts";import{resolveActiveProfile as Zd,setProfileProject as ep,listProjects as tp}from"document360-engine";async function rt(e,t){let n=Zd(e,t),o={profile:n.name,connection:n.connection};return{projects:await tp(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Ua=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Zr(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){ep(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Wa(e,t,n){let o;try{o=await rt(e,n)}catch(s){return console.log(C(`Could not list projects: ${s.message}`)),1}let r=Zr(o.projects,t);return r?(Co(e,o.profile,r.id,r.name),console.log(N(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(C(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Ro(e,t){let n;try{n=await rt(e,t)}catch(m){console.log(C(`Could not list projects: ${m.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(g("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let m of o)console.log(` ${m.id===s?L("\u25CF"):" "} ${Ua(m)} ${g(m.id)}`);console.log(g("Run: d360-writer project use <name>"));return}let l=await Jd({message:"Select the Document360 project for this repo:",choices:o.map(m=>({name:`${Ua(m)}${m.id===s?" (current)":""}`,value:m.id}))}),d=o.find(m=>m.id===l);Co(e,r,l,d?.name),console.log(N(`\u2713 Project set to "${d?.name??l}" for profile "${r}". Next: pick a workspace.`))}H();import np from"picocolors";function op(e=process.env){return e.FORCE_HYPERLINK==="0"||!np.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 rp(e,t=e,n){return op(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var sp=/https?:\/\/[^\s\x1b]+/g;function Pn(e,t){return e.replace(sp,n=>rp(n,n,t))}function Ba(e){return{...Fa(e.idToken)??{},...Fa(e.accessToken)??{}}}function Po(e){let t=Ba(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 To(e){let t=So(process.cwd(),e.profile),n=t.connection;console.log(g(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await ap(n,{manual:e.manual,promptForRedirect:s=>ip({message:s})},s=>console.log(Pn(s))),r=qa(t.name,o);if(Ha(r),await es(r,t.name,s=>console.log(g(s))),console.log(""),console.log(N(`\u2713 Logged in to "${t.name}" as ${Po(r)}`)),console.log(g(` access token expires: ${r.expiresAt}`)),console.log(g(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{hp(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Kt(process.cwd(),t.name))}catch{}}async function es(e,t,n){let r=Ba(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(So(process.cwd(),t).project.projectId)return;let l;try{let{projects:d}=await rt(process.cwd(),t);l=d.find(m=>m.id===r)?.name}catch{}pp(process.cwd(),t,{projectId:r,projectName:l}),n(` Project "${l??r}" written to profile "${t}".`)}catch{}}async function Va(e){let t=So(process.cwd(),e.profile),n=t.connection,o=dp(t.name);if(!o){console.log(C(`Not logged in to Document360 (profile "${t.name}").`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${L(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Po(o)}`),up(o))if(o.refreshToken)try{let r=qa(t.name,await lp(n,o.refreshToken));Ha(r),console.log(N(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(M(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(M("Session expired (no refresh token).")),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(g(` expires: ${o.expiresAt}`))}async function Ga(e){let t=So(process.cwd(),e.profile);cp(t.name)?console.log(N(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(g(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}H();import{readProjectConfig as Ya,writeProjectConfig as fp,resolveActiveProfile as mp,loadTokens as gp,isExpired as wp}from"document360-engine";function Do(e){let t=Ya(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(C("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?L("\u25CF "):" ",s=o.production?M(" \u26A0 PRODUCTION"):"",l=o.connection.environment??"(inline)",d=gp(n),m=d?wp(d)&&!d.refreshToken?M("expired"):g("logged in"):g("not logged in");console.log(`${r}${L(n)} \u2192 ${l}${s} [${m}]`)}console.log(""),console.log(g("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Ao(e,t){let n=Ya(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(C(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,fp(n,e);let o=n.profiles[t].production?M(" \u26A0 PRODUCTION"):"";console.log(N(`\u2713 Default profile is now "${t}"${o}`))}function jo(e,t){try{let n=mp(e,t);console.log(""),console.log(`Profile ${L(n.name)}${n.production?M(" \u26A0 PRODUCTION"):""}`),console.log(g(` api: ${n.connection.apiUrl}`)),console.log(g(` identity: ${n.connection.authorizationUrl}`)),console.log(g(` clientId: ${n.connection.clientId}`)),console.log(g(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(g(` project: ${n.project.projectId??"(set at login)"}`)),console.log(g(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(C(n.message)),process.exitCode=1}}H();import{existsSync as yp,readdirSync as kp,statSync as za}from"node:fs";import{join as Ka}from"node:path";import{apiLogDir as bp}from"document360-engine";function Xa(){let e=bp();if(console.log(""),console.log(`Document360 API logs: ${L(e)}`),!yp(e)){console.log(g(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=kp(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(g(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(za(Ka(e,r)).size/1024).toFixed(1);console.log(` ${r} ${g(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${g("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(za(Ka(e,r)).size/1024).toFixed(1);console.log(` ${C(r)} ${g(`${s} KB`)}`)}}console.log(""),console.log(g("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(g("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}H();import{createSession as $p,resolveAuth as xp,findByName as vp,slugify as Cp,touchSession as Rp,upsertSession as Sp,resolveActiveProfile as Pp}from"document360-engine";async function Qa(e,t,n,o,r,s){let l=xp(n);l.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),process.exit(2)),l.kind==="subscription"&&console.error(g("Using your Claude subscription (no API key set)."));let d=null;try{d=Pp(e,r)}catch(x){console.error(C(`Document360 profile error: ${x.message}`)),process.exit(2)}d.production&&(console.error(M(`\u26A0 Profile "${d.name}" is PRODUCTION.`)),s||(console.error(C("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(g(" --yes given \u2014 proceeding against production.")));let m;if(o){let x=vp(e,o);x||(console.error(C(`No saved session matches "${o}" in this repo.`)),console.error(g("List sessions inside the REPL with /resume.")),process.exit(2)),m=x.uuid,console.error(g(`Resuming "${x.name}"`))}let y=$p({cwd:e,resume:m,profileName:r,allowProdWrites:s===!0}),b=m??null,v=1;for await(let x of y.send(t))switch(x.type){case"session":if(!b){b=x.sessionId;let I=new Date().toISOString();Sp({uuid:b,name:Cp(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:I,updatedAt:I})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(ae(` \u2699 ${x.name}`));break;case"result":v=x.ok?0:1,console.error(g(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error(C("agent finished with an error result"));break;case"error":console.error(""),console.error(C(`agent error: ${x.message}`)),process.exit(1)}b&&Rp(b),process.stdout.write(`
280
+ `),process.exit(v)}import{createInterface as Mg}from"node:readline/promises";import{createSession as Yi,resolveAuth as Ug,getSession as Wg,setTitle as Fg,slugify as qg,touchSession as Nu,upsertSession as Hg,generateTitle as Bg,resolveActiveProfile as Iu,resolveModelSetting as Vg,readProjectConfig as Gg,resolveAndPersistAppType as Yg,decodeJwtClaims as Eu,isExpired as zg,loadTokens as Kg,isDirectiveMention as Xg,stripDirectiveMention as Qg,appendDirective as Jg,reconcileUpgradeActions as Zg,stampArticles as ew,listArticleFiles as tw,CONTENT_CAP_VERSION as nw}from"document360-engine";import{ENGINE_VERSION as Dp}from"document360-engine";var Ee=[{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 author --all to write the 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 /screenshot capture \u2014 the writer drives a real browser that signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Run /publish --screenshots \u2014 it re-saves the articles with captured shots so the images embed on Document360."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Bare: pick what to do next (author or capture, per shot)."},{t:"cmd",name:"/screenshot author",s:"Write capture specs (<id>, a path, or --all)."},{t:"cmd",name:"/screenshot capture",s:"Take the screenshots (<id>, a path, or --all; bare = pick ready specs)."},{t:"cmd",name:"/screenshot checklist",s:"What to stage + dev test-id requests (a report; auto-runs after bulk authoring)."},{t:"cmd",name:"/screenshot list",s:"Read-only status of every shot (\u25CB placeholder \xB7 \u25D0 spec \xB7 \u25CF captured)."},{t:"gap"},{t:"dim",s:"One-time setup in the app repo: npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth (real login, once per machine)."}]},{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 (`done` marks the next step finished)."},{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:"The screenshot pipeline: bare = pick; author / capture / checklist / 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 Tp(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 Ja(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 Ee){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(Tp(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function ts(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:Dp}:void 0;for(let o of Ja(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"}}H();import{getSession as Ap}from"document360-engine";async function Za(e,t){let n=t.currentUuid(),o=n?Ap(n):void 0;return console.log(o?g(`
281
281
  (conversation reset \u2014 "${o.name}" is still available via /resume)
282
282
  `):g(`
283
283
  (conversation reset \u2014 agent will start fresh on the next prompt)
284
- `)),{kind:"clear"}}async function ts(){return{kind:"exit"}}Oo();H();import{readMcpConfig as as,writeMcpConfig as bl}from"document360-engine";async function Mo(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(qp(),{kind:"continue"}):t==="add"?(Hp(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Bp(e.slice(1)),{kind:"continue"}):(console.log(C(`Unknown /mcp subcommand: ${t}`)),console.log(g("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function qp(){let e=as(),t=Object.keys(e.servers);if(t.length===0){console.log(g(`
284
+ `)),{kind:"clear"}}async function ns(){return{kind:"exit"}}Oo();H();import{readMcpConfig as ls,writeMcpConfig as xl}from"document360-engine";async function Mo(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Gp(),{kind:"continue"}):t==="add"?(Yp(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(zp(e.slice(1)),{kind:"continue"}):(console.log(C(`Unknown /mcp subcommand: ${t}`)),console.log(g("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Gp(){let e=ls(),t=Object.keys(e.servers);if(t.length===0){console.log(g(`
285
285
  No MCP servers registered. Add one with /mcp add <name> <type> <ref>
286
- `));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(` ${L(n)} ${g("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?g(` [headers: ${r.join(", ")}]`):"";console.log(` ${L(n)} ${g(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Hp(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(C("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(C(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=as(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let l={};for(let d=1;d<o.length;d++)if(o[d]==="-H"||o[d]==="--header"){let m=o[++d],k=m?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(C(`-H expects key:value (no spaces). Got: ${m??"(nothing)"}`));return}l[k[1].trim()]=k[2].trim()}else{console.log(C(`Unexpected argument: ${o[d]}. 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,bl(r),console.log(""),console.log(E(`\u2713 Registered "${t}" (${n})`)),console.log(M(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(g(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Bp(e){let t=e[0];if(!t){console.log(C("Usage: /mcp remove <name>"));return}let n=as();if(!n.servers[t]){console.log(C(`No server named "${t}".`));return}delete n.servers[t],bl(n),console.log(E(`\u2713 Removed "${t}".`)),console.log(g(" Run /clear to drop it from the current session immediately."))}H();import{readFileSync as dh}from"node:fs";import{join as ph}from"node:path";import{select as hh}from"@inquirer/prompts";import{computeSyncStatus as Ho,planPartitions as fh,relatedArticlePaths as mh,resolveModelForOperation as gh,runPartitioned as wh,loadProfileMap as yh,resolveActiveProfile as kh,resolveCrossLinks as bh,applyStructureOrder as Fl,orderSyncLine as ql,applyRelatedArticles as Hl,relatedSyncLine as Bl}from"document360-engine";import Z from"picocolors";import jl from"wrap-ansi";import hs from"string-width";H();import at from"picocolors";import ls from"wrap-ansi";import cs from"string-width";var tn=[{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 [author|capture|checklist|list] [id|path|--all]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots; checklist: what to stage + dev test-id requests; list: status",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|--screenshots]",desc:"Publish to Document360 (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed)",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` marks the next open step finished (add words from a title to pick another)",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 \u2014 and d360-capture when installed \u2014 to the latest versions (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"}],xl={"/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":"work the screenshot pipeline (author specs, take shots)","/doctor":"run a health check"};function $l(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(xl[n])return xl[n];let o=tn.find(r=>r.name===t);return o?o.desc:""}function vl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return tn.filter(n=>n.name.startsWith(t))}function Cl(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Vp=new RegExp(`^\\s*/(?:${tn.map(e=>e.name).join("|")})(?:\\s|$)`),Rl=e=>Vp.test(e),Sl=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Pl=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Tl=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Gp(e){let t=e.replace(/\r/g,"").split(`
287
- `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let d=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)d.push(t[o++]);o++,n.push({kind:"code",lines:d});continue}if(Sl(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Pl(t[o+1])){let d=Tl(r);o+=2;let m=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)m.push(Tl(t[o++]));n.push({kind:"table",header:d,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 d=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let m=t[o++];d.push({ordered:/^\s*\d+\.\s+/.test(m),text:m.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:d});continue}if(r.trim()===""){o++;continue}if(Rl(r)){n.push({kind:"para",text: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])&&!Rl(t[o])&&!Sl(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Pl(t[o+1]));)l.push(t[o++]);n.push({kind:"para",text:l.join(" ")})}return n}function us(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?at.bold(t.slice(2,-2)):t.startsWith("`")?L(t.slice(1,-1)):at.italic(t.slice(1,-1)))}var Yp=(e,t)=>e+" ".repeat(Math.max(0,t-cs(e)));function zp(e,t,n){let o=e.length,r=e.map((R,N)=>Math.max(cs(R),...t.map(T=>cs(T[N]??"")))),s=Math.max(24,n),l=3*o+1,d=[...r],m=()=>d.reduce((R,N)=>R+N,0)+l,k=0;for(;m()>s&&k++<1e4;){let R=-1,N=6;for(let T=0;T<o;T++)d[T]>N&&(N=d[T],R=T);if(R===-1)break;d[R]-=1}let y=(R,N,T)=>at.gray(R+d.map(F=>"\u2500".repeat(F+2)).join(N)+T),v=at.gray("\u2502"),$=(R,N)=>{let T=d.map((K,X)=>{let he=R[X]??"",Je=N?at.bold(he):us(he);return ls(Je,K,{hard:!0}).split(`
288
- `)}),F=Math.max(...T.map(K=>K.length)),z=[];for(let K=0;K<F;K++)z.push(d.map((X,he)=>`${v} ${Yp(T[he][K]??"",X)} `).join("")+v);return z.join(`
289
- `)},_=[y("\u250C","\u252C","\u2510"),$(e,!0)];return _.push(t.length===0?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524")),t.forEach((R,N)=>{_.push($(R,!1)),_.push(N===t.length-1?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524"))}),_.join(`
290
- `)}function Kp(e,t){switch(e.kind){case"heading":return at.bold(e.text);case"hr":return at.gray("\u2500".repeat(t));case"para":return ls(us(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="",...d]=ls(us(o.text),Math.max(10,t-s.length)).split(`
286
+ `));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(` ${L(n)} ${g("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?g(` [headers: ${r.join(", ")}]`):"";console.log(` ${L(n)} ${g(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Yp(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(C("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(C(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=ls(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let l={};for(let d=1;d<o.length;d++)if(o[d]==="-H"||o[d]==="--header"){let m=o[++d],y=m?.match(/^([^:=]+)[:=](.+)$/);if(!y){console.log(C(`-H expects key:value (no spaces). Got: ${m??"(nothing)"}`));return}l[y[1].trim()]=y[2].trim()}else{console.log(C(`Unexpected argument: ${o[d]}. 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,xl(r),console.log(""),console.log(N(`\u2713 Registered "${t}" (${n})`)),console.log(M(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(g(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function zp(e){let t=e[0];if(!t){console.log(C("Usage: /mcp remove <name>"));return}let n=ls();if(!n.servers[t]){console.log(C(`No server named "${t}".`));return}delete n.servers[t],xl(n),console.log(N(`\u2713 Removed "${t}".`)),console.log(g(" Run /clear to drop it from the current session immediately."))}H();import{readFileSync as mh}from"node:fs";import{join as gh}from"node:path";import{select as wh}from"@inquirer/prompts";import{computeSyncStatus as Ho,planPartitions as yh,relatedArticlePaths as kh,resolveModelForOperation as bh,runPartitioned as $h,loadProfileMap as xh,resolveActiveProfile as vh,resolveCrossLinks as Ch,applyStructureOrder as Hl,orderSyncLine as Bl,applyRelatedArticles as Vl,relatedSyncLine as Gl}from"document360-engine";import Z from"picocolors";import Nl from"wrap-ansi";import fs from"string-width";H();import at from"picocolors";import cs from"wrap-ansi";import us from"string-width";var tn=[{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 [author|capture|checklist|list] [id|path|--all]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots; checklist: what to stage + dev test-id requests; list: status",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|--screenshots]",desc:"Publish to Document360 (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed)",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` marks the next open step finished (add words from a title to pick another)",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 \u2014 and d360-capture when installed \u2014 to the latest versions (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"}],vl={"/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":"work the screenshot pipeline (author specs, take shots)","/doctor":"run a health check"};function Cl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(vl[n])return vl[n];let o=tn.find(r=>r.name===t);return o?o.desc:""}function Rl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return tn.filter(n=>n.name.startsWith(t))}function Sl(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Kp=new RegExp(`^\\s*/(?:${tn.map(e=>e.name).join("|")})(?:\\s|$)`),Pl=e=>Kp.test(e),Tl=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Dl=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Al=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Xp(e){let t=e.replace(/\r/g,"").split(`
287
+ `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let d=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)d.push(t[o++]);o++,n.push({kind:"code",lines:d});continue}if(Tl(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Dl(t[o+1])){let d=Al(r);o+=2;let m=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)m.push(Al(t[o++]));n.push({kind:"table",header:d,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 d=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let m=t[o++];d.push({ordered:/^\s*\d+\.\s+/.test(m),text:m.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:d});continue}if(r.trim()===""){o++;continue}if(Pl(r)){n.push({kind:"para",text: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])&&!Pl(t[o])&&!Tl(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Dl(t[o+1]));)l.push(t[o++]);n.push({kind:"para",text:l.join(" ")})}return n}function ds(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?at.bold(t.slice(2,-2)):t.startsWith("`")?L(t.slice(1,-1)):at.italic(t.slice(1,-1)))}var Qp=(e,t)=>e+" ".repeat(Math.max(0,t-us(e)));function Jp(e,t,n){let o=e.length,r=e.map((P,j)=>Math.max(us(P),...t.map(D=>us(D[j]??"")))),s=Math.max(24,n),l=3*o+1,d=[...r],m=()=>d.reduce((P,j)=>P+j,0)+l,y=0;for(;m()>s&&y++<1e4;){let P=-1,j=6;for(let D=0;D<o;D++)d[D]>j&&(j=d[D],P=D);if(P===-1)break;d[P]-=1}let b=(P,j,D)=>at.gray(P+d.map(U=>"\u2500".repeat(U+2)).join(j)+D),v=at.gray("\u2502"),x=(P,j)=>{let D=d.map((K,X)=>{let he=P[X]??"",Je=j?at.bold(he):ds(he);return cs(Je,K,{hard:!0}).split(`
288
+ `)}),U=Math.max(...D.map(K=>K.length)),G=[];for(let K=0;K<U;K++)G.push(d.map((X,he)=>`${v} ${Qp(D[he][K]??"",X)} `).join("")+v);return G.join(`
289
+ `)},I=[b("\u250C","\u252C","\u2510"),x(e,!0)];return I.push(t.length===0?b("\u2514","\u2534","\u2518"):b("\u251C","\u253C","\u2524")),t.forEach((P,j)=>{I.push(x(P,!1)),I.push(j===t.length-1?b("\u2514","\u2534","\u2518"):b("\u251C","\u253C","\u2524"))}),I.join(`
290
+ `)}function Zp(e,t){switch(e.kind){case"heading":return at.bold(e.text);case"hr":return at.gray("\u2500".repeat(t));case"para":return cs(ds(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="",...d]=cs(ds(o.text),Math.max(10,t-s.length)).split(`
291
291
  `);return` ${r} ${l}`+d.map(m=>`
292
292
  ${s}${m}`).join("")}).join(`
293
293
  `)}case"code":return e.lines.map(n=>at.gray(" "+n)).join(`
294
- `);case"table":return zp(e.header,e.rows,t)}}function ds(e,t){let n=Math.max(20,t);return Gp(e).map(o=>Kp(o,n)).join(`
294
+ `);case"table":return Jp(e.header,e.rows,t)}}function ps(e,t){let n=Math.max(20,t);return Xp(e).map(o=>Zp(o,n)).join(`
295
295
 
296
- `)}H();import Xp from"picocolors";var Qp=[127,86,217],Jp=[22,38,43],Dl={T:Qp,E:Jp},Dn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],ps=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Zp=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Al(){if(!Xp.isColorSupported)return[];let e=Dn[0].length,t=[];for(let n=0;n<Dn.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Dl[Dn[n][r]],l=n+1<Dn.length?Dl[Dn[n+1][r]]:void 0;s&&l?o+=`${ps(s)}${Zp(l)}\u2580\x1B[49m\x1B[39m`:s?o+=`${ps(s)}\u2580\x1B[39m`:l?o+=`${ps(l)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function An(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 jn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function $e(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function lt(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var nn=(e,t)=>` ${e.padEnd(13)}${t}`;function eh(e,t){let n=[Cn("\u270E document360-writer")+Z.gray(` v${e.version} \xB7 engine v${e.engineVersion}`),Z.gray(" Reads your code, writes your docs."),"",nn("Claude:",`${e.claude}${Z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),nn("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")),nn("Profile:",e.configured?`${e.profile}${Z.gray(` (${e.apiUrl})`)}${e.prod?Z.bold(Z.yellow(" \u26A0 PRODUCTION")):""}`:Z.gray("\u2014 (run /init)")),nn("Project:",e.project),nn("Mode:",Z.gray(e.mode)),nn("cwd:",Z.gray(e.cwd))],o=Al();if(o.length===0)return n.join(`
297
- `);let r=2,s=3,l=hs(o[0]);if(!(t>=r+l+s+Math.max(...n.map(y=>hs(y)))))return[...o.map(y=>" "+y),...n].join(`
298
- `);let m=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let y=0;y<Math.max(o.length+m,n.length);y++){let v=o[y-m]??" ".repeat(l);k.push((" ".repeat(r)+v+" ".repeat(s)+(n[y]??"")).trimEnd())}return k.join(`
299
- `)}var th={error:Z.red,warn:Z.yellow,ok:Z.green,info:Z.gray};function fs(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1$2 ")}function ms(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return eh(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),l=50,d=e.text.split(`
300
- `).flatMap(k=>jl(k,s,{hard:!0}).split(`
296
+ `)}H();import eh from"picocolors";var th=[127,86,217],nh=[22,38,43],jl={T:th,E:nh},An=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],hs=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,oh=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function El(){if(!eh.isColorSupported)return[];let e=An[0].length,t=[];for(let n=0;n<An.length;n+=2){let o="";for(let r=0;r<e;r++){let s=jl[An[n][r]],l=n+1<An.length?jl[An[n+1][r]]:void 0;s&&l?o+=`${hs(s)}${oh(l)}\u2580\x1B[49m\x1B[39m`:s?o+=`${hs(s)}\u2580\x1B[39m`:l?o+=`${hs(l)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function jn(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 En(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function xe(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function lt(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var nn=(e,t)=>` ${e.padEnd(13)}${t}`;function rh(e,t){let n=[Rn("\u270E document360-writer")+Z.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),Z.gray(" Reads your code, writes your docs."),"",nn("Claude:",`${e.claude}${Z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),nn("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")),nn("Profile:",e.configured?`${e.profile}${Z.gray(` (${e.apiUrl})`)}${e.prod?Z.bold(Z.yellow(" \u26A0 PRODUCTION")):""}`:Z.gray("\u2014 (run /init)")),nn("Project:",e.project),nn("Mode:",Z.gray(e.mode)),nn("cwd:",Z.gray(e.cwd))],o=El();if(o.length===0)return n.join(`
297
+ `);let r=2,s=3,l=fs(o[0]);if(!(t>=r+l+s+Math.max(...n.map(b=>fs(b)))))return[...o.map(b=>" "+b),...n].join(`
298
+ `);let m=Math.max(0,Math.floor((n.length-o.length)/2)),y=[];for(let b=0;b<Math.max(o.length+m,n.length);b++){let v=o[b-m]??" ".repeat(l);y.push((" ".repeat(r)+v+" ".repeat(s)+(n[b]??"")).trimEnd())}return y.join(`
299
+ `)}var sh={error:Z.red,warn:Z.yellow,ok:Z.green,info:Z.gray};function ms(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1$2 ")}function gs(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return rh(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),l=50,d=e.text.split(`
300
+ `).flatMap(y=>Nl(y,s,{hard:!0}).split(`
301
301
  `)),m=Math.max(0,d.length-l);return m>0&&(d=[...d.slice(0,l),Z.dim(`\u2026 +${m} more lines`)]),`
302
- `+d.map((k,y)=>o+(y===0?L(" \u276F "):" ")+k+" ".repeat(Math.max(0,s-hs(k))+1)+r).join(`
302
+ `+d.map((y,b)=>o+(b===0?L(" \u276F "):" ")+y+" ".repeat(Math.max(0,s-fs(y))+1)+r).join(`
303
303
  `)}case"assistant":return`
304
- `+ds(e.text,n);case"tool":{let o=e.arg!==null?Z.gray(`${e.sep}(${e.arg})`):"";return`
305
- `+jl(Z.green("\u25CF ")+Z.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?Z.red:Z.gray,r=e.lines.map((s,l)=>o((l===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(Z.dim(` \u2026 +${e.hidden} lines`)),r.join(`
304
+ `+ps(e.text,n);case"tool":{let o=e.arg!==null?Z.gray(`${e.sep}(${e.arg})`):"";return`
305
+ `+Nl(Z.green("\u25CF ")+Z.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?Z.red:Z.gray,r=e.lines.map((s,l)=>o((l===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(Z.dim(` \u2026 +${e.hidden} lines`)),r.join(`
306
306
  `)}case"diff":{let o=l=>l===1?"":"s",s=[Z.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(Z.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
307
- `)}case"link":return e.lines.map(o=>L(Sn(` \u2B95 ${o}`))).join(`
307
+ `)}case"link":return e.lines.map(o=>L(Pn(` \u2B95 ${o}`))).join(`
308
308
  `);case"preview":return`
309
- `+Cn(`\u25A3 Preview \u2014 ${e.name}`)+`
309
+ `+Rn(`\u25A3 Preview \u2014 ${e.name}`)+`
310
310
 
311
- `+ds(e.text,n);case"note":return`
312
- `+th[e.tone](Sn(fs(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${An(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
313
- `+(e.ok?Z.magenta("\u2736 "):Z.red("\u2736 "))+Z.gray(`Cooked for ${jn(e.seconds)} \xB7 ${An(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${$e(e.costUsd)}`:""))}}}function El(e,t){return e.map(n=>ms(n,t)).join(`
314
- `)}import{resolveActiveProfile as nh,loadTokens as oh,isExpired as rh,decodeJwtClaims as Nl}from"document360-engine";function sh(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ie(e,t){try{let n=nh(e,t),o=oh(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(rh(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={...Nl(o.idToken)??{},...Nl(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 ${sh(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}import{existsSync as ws,readFileSync as Il}from"node:fs";import{isAbsolute as ys,join as ks,resolve as bs}from"node:path";import{readProjectConfig as xs,screenshotPlaceholderIds as ih,DEFAULT_CAPTURE_DIR as $s,DEFAULT_OUTPUT_DIR as ah}from"document360-engine";var gs=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function En(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="checklist"||t==="setup")return{mode:"checklist"};if(t==="list")return{mode:"list",scope:e[1]?gs(e[1]):void 0};t==="author"&&(e=e.slice(1));let n=!e.includes("--no-setup"),o=e.filter(s=>s!=="--no-setup");if(o[0]==="--list")return{mode:"list",scope:o[1]?gs(o[1]):void 0};let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:gs(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function qe(e,t){let n=xs(e),o=n?.captureDir??$s,r=n?.outputDir??ah,s=(l,d)=>ys(l)?ks(l,d):bs(e,l,d);return ih(e,{scope:t}).map(({id:l,file:d})=>{let m=s(o,`${l}.spec.ts`),k=ws(m),y=ws(s(r,`${l}.png`))?"captured":k?"spec":"placeholder",v;if(k)try{v=Ll(Il(m,"utf8")).mutates}catch{}return{id:l,file:d,state:y,...v!==void 0?{mutates:v}:{}}})}function _l(e,t){let n=xs(e)?.captureDir??$s;return ws(ys(n)?ks(n,`${t}.spec.ts`):bs(e,n,`${t}.spec.ts`))}function Ll(e){let t=/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/im.exec(e);if(t)return{mutates:t[1].toLowerCase()==="mutates",declared:!0,what:t[2]?.trim()||void 0};let n=/setInputFiles/.test(e),o=/\{\s*name:\s*['"][^'"]*\b(create|import|save|apply|confirm|delete|submit|send|mint)\b[^'"]*['"][^}]*\}\s*\)\s*\.click\(/i.test(e),r=/\.fill\(/.test(e);return{mutates:n||r&&o,declared:!1}}function Ol(e,t){let n=xs(e)?.captureDir??$s,o=ys(n)?ks(n,`${t}.spec.ts`):bs(e,n,`${t}.spec.ts`);try{return Ll(Il(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}function Wo(e){return[...new Set(e.filter(t=>t.state==="captured").map(t=>t.file))].sort()}var lh={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},ch={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Fo(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(d=>d.file===s))r.push(` ${lh[l.state]} ${l.id.padEnd(34)} ${ch[l.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function uh(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function Uo(e,t,n){let o=new Map;for(let s of t){let{category:l,article:d}=uh(s.file),m=o.get(l)??new Map;o.set(l,m);let k=m.get(d)??[];m.set(d,k),k.push(s)}let r=s=>n==="author"||!s.mutates;for(let s of[...o.keys()].sort()){let l=o.get(s),d=[...l.values()].flat().filter(r).map(m=>m.id);d.length>0&&e.push({kind:"category",action:n,label:`${s} (${d.length})`,ids:d,depth:1});for(let m of[...l.keys()].sort()){let k=l.get(m),y=k.filter(r).map(v=>v.id);y.length>0&&e.push({kind:"article",action:n,label:`${m} (${y.length})`,ids:y,depth:2});for(let v of k){let $=n==="capture"&&v.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:v.id,ids:[v.id],depth:3,...$?{note:$}:{}})}}}}function Ml(e){let t=e.filter(s=>s.state==="placeholder"),n=e.filter(s=>s.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(s=>s.id),depth:0}),Uo(o,t,"author");let r=n.filter(s=>!s.mutates);return r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),Uo(o,n,"capture"),o}function Ul(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(`
311
+ `+ps(e.text,n);case"note":return`
312
+ `+sh[e.tone](Pn(ms(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${jn(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
313
+ `+(e.ok?Z.magenta("\u2736 "):Z.red("\u2736 "))+Z.gray(`Cooked for ${En(e.seconds)} \xB7 ${jn(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${xe(e.costUsd)}`:""))}}}function Il(e,t){return e.map(n=>gs(n,t)).join(`
314
+ `)}import{resolveActiveProfile as ih,loadTokens as ah,isExpired as lh,decodeJwtClaims as _l}from"document360-engine";function ch(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ie(e,t){try{let n=ih(e,t),o=ah(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(lh(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={..._l(o.idToken)??{},..._l(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 ${ch(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}import{existsSync as ys,readFileSync as Ll}from"node:fs";import{isAbsolute as ks,join as bs,resolve as $s}from"node:path";import{readProjectConfig as xs,screenshotPlaceholderIds as uh,DEFAULT_CAPTURE_DIR as vs,DEFAULT_OUTPUT_DIR as dh}from"document360-engine";var ws=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Nn(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="checklist"||t==="setup")return{mode:"checklist"};if(t==="list")return{mode:"list",scope:e[1]?ws(e[1]):void 0};t==="author"&&(e=e.slice(1));let n=!e.includes("--no-setup"),o=e.filter(s=>s!=="--no-setup");if(o[0]==="--list")return{mode:"list",scope:o[1]?ws(o[1]):void 0};let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:ws(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function qe(e,t){let n=xs(e),o=n?.captureDir??vs,r=n?.outputDir??dh,s=(l,d)=>ks(l)?bs(l,d):$s(e,l,d);return uh(e,{scope:t}).map(({id:l,file:d})=>{let m=s(o,`${l}.spec.ts`),y=ys(m),b=ys(s(r,`${l}.png`))?"captured":y?"spec":"placeholder",v;if(y)try{v=Ml(Ll(m,"utf8")).mutates}catch{}return{id:l,file:d,state:b,...v!==void 0?{mutates:v}:{}}})}function Ol(e,t){let n=xs(e)?.captureDir??vs;return ys(ks(n)?bs(n,`${t}.spec.ts`):$s(e,n,`${t}.spec.ts`))}function Ml(e){let t=/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/im.exec(e);if(t)return{mutates:t[1].toLowerCase()==="mutates",declared:!0,what:t[2]?.trim()||void 0};let n=/setInputFiles/.test(e),o=/\{\s*name:\s*['"][^'"]*\b(create|import|save|apply|confirm|delete|submit|send|mint)\b[^'"]*['"][^}]*\}\s*\)\s*\.click\(/i.test(e),r=/\.fill\(/.test(e);return{mutates:n||r&&o,declared:!1}}function Ul(e,t){let n=xs(e)?.captureDir??vs,o=ks(n)?bs(n,`${t}.spec.ts`):$s(e,n,`${t}.spec.ts`);try{return Ml(Ll(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}function Wo(e){return[...new Set(e.filter(t=>t.state==="captured").map(t=>t.file))].sort()}var ph={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},hh={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Fo(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(d=>d.file===s))r.push(` ${ph[l.state]} ${l.id.padEnd(34)} ${hh[l.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function fh(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function Uo(e,t,n){let o=new Map;for(let s of t){let{category:l,article:d}=fh(s.file),m=o.get(l)??new Map;o.set(l,m);let y=m.get(d)??[];m.set(d,y),y.push(s)}let r=s=>n==="author"||!s.mutates;for(let s of[...o.keys()].sort()){let l=o.get(s),d=[...l.values()].flat().filter(r).map(m=>m.id);d.length>0&&e.push({kind:"category",action:n,label:`${s} (${d.length})`,ids:d,depth:1});for(let m of[...l.keys()].sort()){let y=l.get(m),b=y.filter(r).map(v=>v.id);b.length>0&&e.push({kind:"article",action:n,label:`${m} (${b.length})`,ids:b,depth:2});for(let v of y){let x=n==="capture"&&v.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:v.id,ids:[v.id],depth:3,...x?{note:x}:{}})}}}}function Wl(e){let t=e.filter(s=>s.state==="placeholder"),n=e.filter(s=>s.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(s=>s.id),depth:0}),Uo(o,t,"author");let r=n.filter(s=>!s.mutates);return r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),Uo(o,n,"capture"),o}function Fl(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(`
315
315
  `),"","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(`
316
- `)}async function qo(e,t){let n=En(e);if(n.mode==="list"){let l=t?.cwd??process.cwd(),d=qe(l,n.scope);for(let k of Fo(d,n.scope))console.log(k);let m=d.filter(k=>k.state==="placeholder").length;return m>0&&(console.log(""),console.log(`Author specs: /screenshot author <id> (one shot) \xB7 /screenshot author <path> (a folder) \xB7 /screenshot author --all (all ${m} unauthored)`)),{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 per the skill's writer-facing format \u2014 spec path, data to`,"stage, dev requests only if any, and the capture command; no grounding narration."].join(`
316
+ `)}async function qo(e,t){let n=Nn(e);if(n.mode==="list"){let l=t?.cwd??process.cwd(),d=qe(l,n.scope);for(let y of Fo(d,n.scope))console.log(y);let m=d.filter(y=>y.state==="placeholder").length;return m>0&&(console.log(""),console.log(`Author specs: /screenshot author <id> (one shot) \xB7 /screenshot author <path> (a folder) \xB7 /screenshot author --all (all ${m} unauthored)`)),{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 per the skill's writer-facing format \u2014 spec path, data to`,"stage, dev requests only if any, and the capture command; no grounding narration."].join(`
317
317
  `),display:`/screenshot ${n.id}`};if(n.mode==="capture"||n.mode==="checklist")return{kind:"continue"};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(`
318
- `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}var Nn=3;function vs(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, normalize cross-article links). For each <!-- SCREENSHOT ... --> block, read its id BEFORE stripping the block: when <outputDir>/<id>.png exists (the annotated capture), upload it (d360_search_drive first to reuse, else d360_upload_drive_file) and replace the visible [Screenshot: ...] line with the image markdown; only when no PNG exists does the visible line stay as text.","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(`
319
- `)}var Wl={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Cs(e){return e.filter(t=>t.path!==null&&t.status in Wl&&!t.link).map(t=>({path:t.path,label:Wl[t.status]}))}function Bo(e){let t=Cs(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 Vo(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 Go(e){return e.filter(t=>t.link).length}function Rs(e,t){try{let n=yh(e,kh(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=bh(dh(ph(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 xh(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 Vl(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,d)=>l.path.localeCompare(d.path));n.push({kind:"category",label:`${xh(r)} (${s.length})`,paths:s.map(l=>l.path),indent:!1});for(let l of s){let d=l.path.replace(/\\/g,"/").split("/").pop()??l.path;n.push({kind:"article",label:d,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 In(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). Compute each publish form IN MEMORY and pass it straight to the tool \u2014 NEVER write it to disk (no *.publish.md siblings, no temp copies anywhere in the docs tree; the local .md files stay untouched). 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(`
320
- `)}function Ss(e,t,n){let o=$=>t[$.index]?.paths.length??0,r=e.filter($=>$.ok),s=e.filter($=>!$.ok),l=e.reduce(($,_)=>$+o(_),0),d=r.reduce(($,_)=>$+o(_),0),m=n==="api"?`${$e(e.reduce(($,_)=>$+_.costUsd,0))} total`:lt(e.reduce(($,_)=>$+_.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,y=$=>`${$} article${$===1?"":"s"}`,v=[];if(s.length===0)v.push(`Published ${y(l)} (${k}) successfully \xB7 ${m}.`),v.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{v.push(`Published ${d}/${y(l)} (${k}) \xB7 ${m}.`),v.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 $ of s)v.push(` \u2717 ${$.label}${$.error?` \u2014 ${$.error}`:""}`)}return v}async function ct(e,t){let{model:n}=gh(e.cwd,"standard"),o=async(r,s)=>{let l=fh(r);console.log(g(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${Nn} agents at once) on ${n}\u2026`)),s||console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let d=!1;for await(let m of wh({cwd:e.cwd,partitions:l,promptFor:k=>In(k.paths),concurrency:Nn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(m.type==="partition_status")m.status==="running"?console.log(g(` \u25B8 ${m.label} \u2014 publishing\u2026`)):m.status==="done"?console.log(E(` \u2713 ${m.label}`)):console.log(C(` \u2717 ${m.label}`));else if(m.type==="run_done"){d=m.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let v of Ss(m.results,l,k))console.log(m.ok?E(v):M(v));let y=Rs(e.cwd,e.profileName);y&&console.log(g(y));try{let v=ql(await Fl({cwd:e.cwd,profileName:e.profileName}));v&&console.log(g(v))}catch{}try{let v=Bl(await Hl({cwd:e.cwd,profileName:e.profileName}));v&&console.log(g(v))}catch{}}return d};try{if(!await o(t,!1)){let s=await Ps(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(C(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Yo(e,t,n){let o=mh(e,n);if(o.length===0)return[];let r=new Set(Cs((await Ho({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Ps(e,t,n){try{let o=new Set(n),r=await Ho({cwd:e,profileName:t});return Cs(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function Gl(e,t){let n=Ie(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let r=t?.cwd??process.cwd(),s=Wo(qe(r));return s.length===0?(console.log(g("No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}):t?await ct(t,s):{kind:"forward-to-agent",prompt:In(s),display:"/publish --screenshots"}}if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Yo(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(E("\u2713 All related articles are already published.")),{kind:"continue"}):await ct(t,r)}if(o==="--all"){console.log(g("Checking what needs publishing\u2026"));try{let r=await Ho({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:l}=Bo(r.entries),d=Go(r.entries),m=e.includes("--force")&&l.length>0;d>0&&console.log(M(`\u26A0 ${d} 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(M(Vo(l.length)));let k=m?[...s,...l]:s;if(k.length===0){if(l.length>0)return console.log(g("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(E(d>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let y=ql(await Fl({cwd:t.cwd,profileName:t.profileName}));y&&console.log(g(y));let v=Bl(await Hl({cwd:t.cwd,profileName:t.profileName}));v&&console.log(g(v))}catch{}return{kind:"continue"}}return t?await ct(t,k.map(y=>y.path)):{kind:"forward-to-agent",prompt:In(k.map(y=>y.path)),display:"/publish --all"}}catch(r){return console.log(C(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(g("Checking what needs publishing\u2026"));let r;try{let s=await Ho({cwd:t?.cwd??process.cwd()}),{clean:l,conflicts:d}=Bo(s.entries);r=l;let m=Go(s.entries);if(m>0&&console.log(M(`\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.`)),d.length>0&&console.log(M(Vo(d.length))),r.length===0&&d.length>0)return console.log(g("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(C(`Could not compute sync status: ${s.message}`)),console.log(g("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(E("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(g(" (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} ${g(`(${s.label})`)}`);return console.log(g("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>hh({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(g("Cancelled.")),{kind:"continue"}}if(o==="--all")return await ct(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:vs(o),display:`/publish ${o}`}}async function _n(){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(`
321
- `),display:"/audit"}}H();import{readProjectConfig as $h}from"document360-engine";function Ts(){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(`
322
- `)}async function Yl(e,t){let n=t?.cwd??process.cwd();return $h(n)?{kind:"forward-to-agent",prompt:Ts(),display:"/discover"}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}H();import{checkbox as vh}from"@inquirer/prompts";import{inventoryRepo as Ch,readProjectConfig as zl,writeProjectConfig as Rh}from"document360-engine";function Ds(e,t){let n=zl(e);n&&(n.authoritativeSourceFiles=t,Rh(n,e))}function zo(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 Kl(e,t){let n=t?.cwd??process.cwd();if(!zl(n))return console.log(C("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Ch(n);if(o.length===0)return console.log(g('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(L("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${g(zo(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>vh({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${zo(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(g("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};Ds(n,r),console.log(E(`\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"}}H();import{confirm as _h}from"@inquirer/prompts";import{applyPull as Es,computeSyncStatus as rc,compareRemoteSources as Lh,planPull as sc,planImport as Oh,applyImport as Mh,establishBaselines as Uh,rebaselineServerMeta as Wh,D360AuthError as Fh}from"document360-engine";H();var Xl=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:C,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:M,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:L,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:C,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:C,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:g,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:g,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 Sh(e){return e.path?e.path:`${e.title??"(untitled)"} ${ae(`[${e.articleId}]`)}`}function Ph(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 Ko(e,t){let n=[],o=e.entries.filter(y=>y.link);if(o.length>0){n.push(""),n.push(xe("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let y of o)n.push(` ${M("~")} ${M(y.path??"")} ${ae(`\u2192 "${y.link.title}"`)}`)}for(let y of Xl){let v=e.entries.filter($=>$.status===y.status&&!(y.status==="untracked-local"&&$.link));if(v.length!==0){n.push(""),n.push(xe(y.header));for(let $ of v)n.push(` ${y.paint(y.mark)} ${y.paint(Sh($))}${$.detail?ae(` (${$.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"},d=o.length,m=s===r?E("\u2713 everything up to date"):[r>0?E(`\u2713 ${r} up to date`):null,d>0?`${d} to link`:null,...Xl.map(y=>{let v=(e.counts[y.status]??0)-(y.status==="untracked-local"?d:0);return v>0?`${v} ${l[y.status]}`:null})].filter(Boolean).join(ae(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${Ph(t)}`:"";return n.push(m+ae(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as Th}from"diff";import Ql from"picocolors";var Jl=80,Dh="\x1B[48;2;74;28;28m",Ah="\x1B[48;2;24;66;24m",Zl="\x1B[49m",As=e=>String(e).padStart(5);function ec(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function tc(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 Qe(e,t,n){let o=$=>{let _=$.replace(/\r\n/g,`
323
- `);return _.endsWith(`
324
- `)||_===""?_:_+`
325
- `},r=o(e),s=o(t);if(r===s)return null;let l=Math.max(20,n-10),d=Th("a","b",r,s,"","",{context:3}),m=0,k=0,y=[];d.hunks.forEach(($,_)=>{_>0&&y.push(Ql.gray(" \u2026"));let R=$.oldStart,N=$.newStart,T=[],F=[],z=()=>{for(let K=0;K<T.length;K++){let X=K<F.length?ec(T[K],F[K]):void 0;k++,y.push(`${Dh}${As(R++)} - ${tc(T[K],l,X)}${Zl}`)}for(let K=0;K<F.length;K++){let X=K<T.length?ec(T[K],F[K]):void 0;m++,y.push(`${Ah}${As(N++)} + ${tc(F[K],l,X)}${Zl}`)}T=[],F=[]};for(let K of $.lines){let X=K[0],he=K.slice(1);X==="-"?T.push(he):X==="+"?F.push(he):(z(),y.push(Ql.gray(As(N))+" "+he.slice(0,l)),R++,N++)}z()});let v=y.slice(0,Jl);return{added:m,removed:k,lines:v,hidden:Math.max(0,y.length-Jl)}}H();import{select as jh}from"@inquirer/prompts";import{applyPull as Eh,computeSyncStatus as Nh,planPull as Ih}from"document360-engine";var nc=e=>e===1?"":"s";async function js(e,t){console.log(""),console.log(`${L("\u25CF")} ${xe(t.title)} ${ae(`(${t.path})`)}`);for(let r of t.notes)console.log(M(` \u26A0 ${r}`));let n=Qe(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${nc(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(g(` \u2026 +${n.hidden} more diff lines`))}else console.log(g(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>jh({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"?(Eh({cwd:e.cwd,profileName:e.profileName},t),console.log(E(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(g(" Skipped \u2014 still a conflict.")),"skipped")}async function oc(e,t){let n=Ie(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Nh({cwd:t.cwd,profileName:t.profileName})).entries.filter(d=>d.status==="conflict"&&d.path).map(d=>d.path);if(o){if(!s.includes(o))return console.log(E(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(E("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let l=[];for(let d of s){let m=await Ih({cwd:t.cwd,profileName:t.profileName,relPath:d});await js(t,m)==="keep-local"&&l.push(d)}if(l.length>0)return console.log(g(`Publishing ${l.length} kept-local article${nc(l.length)} over the portal\u2026`)),await ct(t,l)}catch(r){console.log(C(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function ic(e,t){let n=Ie(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await qh(t),{kind:"continue"};if(o==="--baseline")return await Hh(t,e.filter(l=>l!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Bh(t),{kind:"continue"};if(o)return console.log(C(`Unknown option: ${o}`)),console.log(g("Usage: /pull pull portal edits + import new portal articles")),console.log(g(" /pull <path> pull one article (or resolve a conflict)")),console.log(g(" /pull --status drift report only (no writes)")),console.log(g(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Vh(t,r),{kind:"continue"};console.log(g("Pulling changes from Document360\u2026"));let s=await Ns({cwd:t.cwd,profileName:t.profileName});for(let l of Is(s))console.log(l.tone==="ok"?E(l.text):l.tone==="warn"?M(l.text):g(l.text));console.log("")}catch(r){r instanceof Fh?console.log(C(r.message)):console.log(C(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Ns(e){let t=await rc({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 sc({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Es({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 Oh({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Mh({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 Xo=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Tt=e=>e===1?"":"s";function Is(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Tt(e.pulled.length)} into local: ${Xo(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Tt(e.imported.length)}: ${Xo(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Tt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Tt(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). (${Xo(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Tt(e.failed.length)} failed: ${Xo(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 qh(e){console.log(g("Checking Document360 for drift\u2026"));let t=Date.now(),n=await rc({cwd:e.cwd,profileName:e.profileName});for(let o of Ko(n,Date.now()-t))console.log(o);console.log("")}async function Hh(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(g(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Uh({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Wh({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(E("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(E(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(E(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(M(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(g(` - ${s.path} (${s.reason})`))}}async function Bh(e){console.log(g("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Lh({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${xe(String(t.legacyCount))} \xB7 Manifest: ${xe(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(E("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(C(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(M(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(M(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(g(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Vh(e,t){let n=t.replace(/\\/g,"/"),o=await sc({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await js(e,o)==="keep-local"&&(console.log(g(`Publishing ${o.path} over the portal\u2026`)),await ct(e,[o.path]));return}console.log(""),console.log(`${L("\u25CF")} ${xe(o.title)} ${ae(`(${o.path})`)}`);for(let l of o.notes)console.log(M(` \u26A0 ${l}`));let r=Qe(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(g(" Local file already matches the remote content \u2014 advancing the sync base only.")),Es({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ae(` \u23BF Added ${r.added} line${Tt(r.added)}, removed ${r.removed} line${Tt(r.removed)}`));for(let l of r.lines)console.log(l);if(r.hidden>0&&console.log(g(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>_h({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(g(" Skipped."));return}Es({cwd:e.cwd,profileName:e.profileName},o),console.log(E(` \u2713 Pulled ${o.path} (sync base advanced).`))}H();import{statSync as Gh}from"node:fs";import{resolve as Yh}from"node:path";import{estimateBulkCost as zh,planPartitions as Kh,readProjectConfig as Xh,resolveModelForOperation as Qh,runPartitioned as Jh,trackedArticlePaths as Zh}from"document360-engine";var _s=3;function Ls(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 Os(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Ms(e,t){return t.map(n=>{let o=0;try{o=Gh(Yh(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Us(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:
318
+ `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}var In=3;function Cs(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, normalize cross-article links). For each <!-- SCREENSHOT ... --> block, read its id BEFORE stripping the block: when <outputDir>/<id>.png exists (the annotated capture), upload it (d360_search_drive first to reuse, else d360_upload_drive_file) and replace the visible [Screenshot: ...] line with the image markdown; only when no PNG exists does the visible line stay as text.","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(`
319
+ `)}var ql={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Rs(e){return e.filter(t=>t.path!==null&&t.status in ql&&!t.link).map(t=>({path:t.path,label:ql[t.status]}))}function Bo(e){let t=Rs(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 Vo(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 Go(e){return e.filter(t=>t.link).length}function Ss(e,t){try{let n=xh(e,vh(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Ch(mh(gh(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 Rh(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 Yl(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,d)=>l.path.localeCompare(d.path));n.push({kind:"category",label:`${Rh(r)} (${s.length})`,paths:s.map(l=>l.path),indent:!1});for(let l of s){let d=l.path.replace(/\\/g,"/").split("/").pop()??l.path;n.push({kind:"article",label:d,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 _n(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). Compute each publish form IN MEMORY and pass it straight to the tool \u2014 NEVER write it to disk (no *.publish.md siblings, no temp copies anywhere in the docs tree; the local .md files stay untouched). 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(`
320
+ `)}function Ps(e,t,n){let o=x=>t[x.index]?.paths.length??0,r=e.filter(x=>x.ok),s=e.filter(x=>!x.ok),l=e.reduce((x,I)=>x+o(I),0),d=r.reduce((x,I)=>x+o(I),0),m=n==="api"?`${xe(e.reduce((x,I)=>x+I.costUsd,0))} total`:lt(e.reduce((x,I)=>x+I.outputTokens,0)),y=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,b=x=>`${x} article${x===1?"":"s"}`,v=[];if(s.length===0)v.push(`Published ${b(l)} (${y}) successfully \xB7 ${m}.`),v.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{v.push(`Published ${d}/${b(l)} (${y}) \xB7 ${m}.`),v.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 x of s)v.push(` \u2717 ${x.label}${x.error?` \u2014 ${x.error}`:""}`)}return v}async function ct(e,t){let{model:n}=bh(e.cwd,"standard"),o=async(r,s)=>{let l=yh(r);console.log(g(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${In} agents at once) on ${n}\u2026`)),s||console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let d=!1;for await(let m of $h({cwd:e.cwd,partitions:l,promptFor:y=>_n(y.paths),concurrency:In,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(m.type==="partition_status")m.status==="running"?console.log(g(` \u25B8 ${m.label} \u2014 publishing\u2026`)):m.status==="done"?console.log(N(` \u2713 ${m.label}`)):console.log(C(` \u2717 ${m.label}`));else if(m.type==="run_done"){d=m.aborted,console.log("");let y=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let v of Ps(m.results,l,y))console.log(m.ok?N(v):M(v));let b=Ss(e.cwd,e.profileName);b&&console.log(g(b));try{let v=Bl(await Hl({cwd:e.cwd,profileName:e.profileName}));v&&console.log(g(v))}catch{}try{let v=Gl(await Vl({cwd:e.cwd,profileName:e.profileName}));v&&console.log(g(v))}catch{}}return d};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(C(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Yo(e,t,n){let o=kh(e,n);if(o.length===0)return[];let r=new Set(Rs((await Ho({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 Ho({cwd:e,profileName:t});return Rs(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function zl(e,t){let n=Ie(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let r=t?.cwd??process.cwd(),s=Wo(qe(r));return s.length===0?(console.log(g("No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}):t?await ct(t,s):{kind:"forward-to-agent",prompt:_n(s),display:"/publish --screenshots"}}if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Yo(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(N("\u2713 All related articles are already published.")),{kind:"continue"}):await ct(t,r)}if(o==="--all"){console.log(g("Checking what needs publishing\u2026"));try{let r=await Ho({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:l}=Bo(r.entries),d=Go(r.entries),m=e.includes("--force")&&l.length>0;d>0&&console.log(M(`\u26A0 ${d} 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(M(Vo(l.length)));let y=m?[...s,...l]:s;if(y.length===0){if(l.length>0)return console.log(g("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(N(d>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let b=Bl(await Hl({cwd:t.cwd,profileName:t.profileName}));b&&console.log(g(b));let v=Gl(await Vl({cwd:t.cwd,profileName:t.profileName}));v&&console.log(g(v))}catch{}return{kind:"continue"}}return t?await ct(t,y.map(b=>b.path)):{kind:"forward-to-agent",prompt:_n(y.map(b=>b.path)),display:"/publish --all"}}catch(r){return console.log(C(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(g("Checking what needs publishing\u2026"));let r;try{let s=await Ho({cwd:t?.cwd??process.cwd()}),{clean:l,conflicts:d}=Bo(s.entries);r=l;let m=Go(s.entries);if(m>0&&console.log(M(`\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.`)),d.length>0&&console.log(M(Vo(d.length))),r.length===0&&d.length>0)return console.log(g("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(C(`Could not compute sync status: ${s.message}`)),console.log(g("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(N("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(g(" (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} ${g(`(${s.label})`)}`);return console.log(g("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>wh({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(g("Cancelled.")),{kind:"continue"}}if(o==="--all")return await ct(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Cs(o),display:`/publish ${o}`}}async function Ln(){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(`
321
+ `),display:"/audit"}}H();import{readProjectConfig as Sh}from"document360-engine";function Ds(){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(`
322
+ `)}async function Kl(e,t){let n=t?.cwd??process.cwd();return Sh(n)?{kind:"forward-to-agent",prompt:Ds(),display:"/discover"}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}H();import{checkbox as Ph}from"@inquirer/prompts";import{inventoryRepo as Th,readProjectConfig as Xl,writeProjectConfig as Dh}from"document360-engine";function As(e,t){let n=Xl(e);n&&(n.authoritativeSourceFiles=t,Dh(n,e))}function zo(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 Ql(e,t){let n=t?.cwd??process.cwd();if(!Xl(n))return console.log(C("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Th(n);if(o.length===0)return console.log(g('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(L("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${g(zo(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Ph({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${zo(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(g("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};As(n,r),console.log(N(`\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"}}H();import{confirm as Uh}from"@inquirer/prompts";import{applyPull as Ns,computeSyncStatus as ic,compareRemoteSources as Wh,planPull as ac,planImport as Fh,applyImport as qh,establishBaselines as Hh,rebaselineServerMeta as Bh,D360AuthError as Vh}from"document360-engine";H();var Jl=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:C,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:M,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:L,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:C,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:C,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:g,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:g,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 Ah(e){return e.path?e.path:`${e.title??"(untitled)"} ${ae(`[${e.articleId}]`)}`}function jh(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 Ko(e,t){let n=[],o=e.entries.filter(b=>b.link);if(o.length>0){n.push(""),n.push($e("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let b of o)n.push(` ${M("~")} ${M(b.path??"")} ${ae(`\u2192 "${b.link.title}"`)}`)}for(let b of Jl){let v=e.entries.filter(x=>x.status===b.status&&!(b.status==="untracked-local"&&x.link));if(v.length!==0){n.push(""),n.push($e(b.header));for(let x of v)n.push(` ${b.paint(b.mark)} ${b.paint(Ah(x))}${x.detail?ae(` (${x.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"},d=o.length,m=s===r?N("\u2713 everything up to date"):[r>0?N(`\u2713 ${r} up to date`):null,d>0?`${d} to link`:null,...Jl.map(b=>{let v=(e.counts[b.status]??0)-(b.status==="untracked-local"?d:0);return v>0?`${v} ${l[b.status]}`:null})].filter(Boolean).join(ae(" \xB7 ")),y=t!==void 0?` \xB7 synced in ${jh(t)}`:"";return n.push(m+ae(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${y}`)),n}import{structuredPatch as Eh}from"diff";import Zl from"picocolors";var ec=80,Nh="\x1B[48;2;74;28;28m",Ih="\x1B[48;2;24;66;24m",tc="\x1B[49m",js=e=>String(e).padStart(5);function nc(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function oc(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 Qe(e,t,n){let o=x=>{let I=x.replace(/\r\n/g,`
323
+ `);return I.endsWith(`
324
+ `)||I===""?I:I+`
325
+ `},r=o(e),s=o(t);if(r===s)return null;let l=Math.max(20,n-10),d=Eh("a","b",r,s,"","",{context:3}),m=0,y=0,b=[];d.hunks.forEach((x,I)=>{I>0&&b.push(Zl.gray(" \u2026"));let P=x.oldStart,j=x.newStart,D=[],U=[],G=()=>{for(let K=0;K<D.length;K++){let X=K<U.length?nc(D[K],U[K]):void 0;y++,b.push(`${Nh}${js(P++)} - ${oc(D[K],l,X)}${tc}`)}for(let K=0;K<U.length;K++){let X=K<D.length?nc(D[K],U[K]):void 0;m++,b.push(`${Ih}${js(j++)} + ${oc(U[K],l,X)}${tc}`)}D=[],U=[]};for(let K of x.lines){let X=K[0],he=K.slice(1);X==="-"?D.push(he):X==="+"?U.push(he):(G(),b.push(Zl.gray(js(j))+" "+he.slice(0,l)),P++,j++)}G()});let v=b.slice(0,ec);return{added:m,removed:y,lines:v,hidden:Math.max(0,b.length-ec)}}H();import{select as _h}from"@inquirer/prompts";import{applyPull as Lh,computeSyncStatus as Oh,planPull as Mh}from"document360-engine";var rc=e=>e===1?"":"s";async function Es(e,t){console.log(""),console.log(`${L("\u25CF")} ${$e(t.title)} ${ae(`(${t.path})`)}`);for(let r of t.notes)console.log(M(` \u26A0 ${r}`));let n=Qe(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${rc(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(g(` \u2026 +${n.hidden} more diff lines`))}else console.log(g(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>_h({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"?(Lh({cwd:e.cwd,profileName:e.profileName},t),console.log(N(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(g(" Skipped \u2014 still a conflict.")),"skipped")}async function sc(e,t){let n=Ie(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Oh({cwd:t.cwd,profileName:t.profileName})).entries.filter(d=>d.status==="conflict"&&d.path).map(d=>d.path);if(o){if(!s.includes(o))return console.log(N(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(N("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let l=[];for(let d of s){let m=await Mh({cwd:t.cwd,profileName:t.profileName,relPath:d});await Es(t,m)==="keep-local"&&l.push(d)}if(l.length>0)return console.log(g(`Publishing ${l.length} kept-local article${rc(l.length)} over the portal\u2026`)),await ct(t,l)}catch(r){console.log(C(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function lc(e,t){let n=Ie(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Gh(t),{kind:"continue"};if(o==="--baseline")return await Yh(t,e.filter(l=>l!=="--baseline")),{kind:"continue"};if(o==="--compare")return await zh(t),{kind:"continue"};if(o)return console.log(C(`Unknown option: ${o}`)),console.log(g("Usage: /pull pull portal edits + import new portal articles")),console.log(g(" /pull <path> pull one article (or resolve a conflict)")),console.log(g(" /pull --status drift report only (no writes)")),console.log(g(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Kh(t,r),{kind:"continue"};console.log(g("Pulling changes from Document360\u2026"));let s=await Is({cwd:t.cwd,profileName:t.profileName});for(let l of _s(s))console.log(l.tone==="ok"?N(l.text):l.tone==="warn"?M(l.text):g(l.text));console.log("")}catch(r){r instanceof Vh?console.log(C(r.message)):console.log(C(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Is(e){let t=await ic({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 ac({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Ns({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 Fh({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});qh({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 Xo=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Tt=e=>e===1?"":"s";function _s(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Tt(e.pulled.length)} into local: ${Xo(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Tt(e.imported.length)}: ${Xo(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Tt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Tt(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). (${Xo(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Tt(e.failed.length)} failed: ${Xo(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 Gh(e){console.log(g("Checking Document360 for drift\u2026"));let t=Date.now(),n=await ic({cwd:e.cwd,profileName:e.profileName});for(let o of Ko(n,Date.now()-t))console.log(o);console.log("")}async function Yh(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(g(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Hh({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Bh({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(N("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(N(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(N(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(M(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(g(` - ${s.path} (${s.reason})`))}}async function zh(e){console.log(g("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Wh({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${$e(String(t.legacyCount))} \xB7 Manifest: ${$e(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(N("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(C(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(M(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(M(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(g(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Kh(e,t){let n=t.replace(/\\/g,"/"),o=await ac({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Es(e,o)==="keep-local"&&(console.log(g(`Publishing ${o.path} over the portal\u2026`)),await ct(e,[o.path]));return}console.log(""),console.log(`${L("\u25CF")} ${$e(o.title)} ${ae(`(${o.path})`)}`);for(let l of o.notes)console.log(M(` \u26A0 ${l}`));let r=Qe(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(g(" Local file already matches the remote content \u2014 advancing the sync base only.")),Ns({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ae(` \u23BF Added ${r.added} line${Tt(r.added)}, removed ${r.removed} line${Tt(r.removed)}`));for(let l of r.lines)console.log(l);if(r.hidden>0&&console.log(g(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Uh({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(g(" Skipped."));return}Ns({cwd:e.cwd,profileName:e.profileName},o),console.log(N(` \u2713 Pulled ${o.path} (sync base advanced).`))}H();import{statSync as Xh}from"node:fs";import{resolve as Qh}from"node:path";import{estimateBulkCost as Jh,planPartitions as Zh,readProjectConfig as ef,resolveModelForOperation as tf,runPartitioned as nf,trackedArticlePaths as of}from"document360-engine";var Ls=3;function Os(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 Ms(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Us(e,t){return t.map(n=>{let o=0;try{o=Xh(Qh(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Ws(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:
326
326
  - 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.
327
327
  - 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.
328
328
  - 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.
329
329
  - Work only on these files:
330
330
  `+e.paths.map(t=>`- ${t}`).join(`
331
- `)}function Ws(e,t,n){let o=e.reduce((d,m)=>d+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(d=>` \u2022 ${d.label} \u2014 ${d.paths.length} article${d.paths.length===1?"":"s"}`),"",`Estimated cost: ${$e(r)}\u2013${$e(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Fs(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),l=e.reduce((R,N)=>R+o(N),0),d=r.reduce((R,N)=>R+o(N),0),m=e.reduce((R,N)=>R+N.costUsd,0),k=e.reduce((R,N)=>R+N.outputTokens,0),y=n==="api"?`${$e(m)} total`:lt(k),v=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,$=R=>`${R} article${R===1?"":"s"}`,_=[];if(s.length===0)_.push(`Converted ${$(l)} (${v}) successfully \xB7 ${y}.`);else{_.push(`Converted ${d}/${$(l)} (${v}) \xB7 ${y}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let R of s)_.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return _}async function ac(e,t){if(!Xh(t.cwd))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Ls(e),r=Zh(t.cwd,t.profileName);if(r.length===0)return console.log(C("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Os(r,n);if(s.length===0)return console.log(C(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let l=Kh(s),d=`/convert${n?` --scope ${n}`:""} --run`,{model:m,forced:k}=Qh(t.cwd,"light");if(!o){let y=zh({files:Ms(t.cwd,s),op:"convert",model:m});n&&console.log(g(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let v of Ws(l,y,_s))console.log(v);return console.log(g(`Model: ${m}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(g(`Run ${d} to start.`)),console.log(""),{kind:"continue"}}console.log(g(`Converting ${s.length} articles across ${l.length} partitions (\u2264${_s} agents at once) on ${m}\u2026`)),console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let y of Jh({cwd:t.cwd,partitions:l,promptFor:Us,concurrency:_s,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:m}))if(y.type==="partition_status")y.status==="running"?console.log(g(` \u25B8 ${y.label} \u2014 converting\u2026`)):y.status==="done"?console.log(E(` \u2713 ${y.label}`)):console.log(C(` \u2717 ${y.label}`));else if(y.type==="run_done"){console.log("");let v=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let $ of Fs(y.results,l,v))console.log(y.ok?E($):M($))}}catch(y){console.log(C(`Convert run failed: ${y.message}`))}return console.log(""),{kind:"continue"}}H();import{statSync as uc}from"node:fs";import{resolve as dc}from"node:path";import{estimateBulkCost as cf,lintDocs as uf,planPartitions as df,readDocsPlan as pf,readProjectConfig as pc,DEFAULT_DOCS_DIR as hf,resolveModelForOperation as ff,runPartitioned as mf,stampArticles as gf,CONTENT_CAP_VERSION as wf}from"document360-engine";import{readProjectConfig as ef,loadProfileMap as tf,resolveActiveProfile as nf,desiredCategoryOrder as of,desiredArticleOrder as rf,DEFAULT_DOCS_DIR as sf}from"document360-engine";var qs=e=>e.replace(/\\/g,"/"),af=e=>qs(e).split("/").pop()??e;function lf(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function Ln(e,t){try{let n=ef(e);if(!n)return[];let o=nf(e,t),r=tf(e,o.name);if(!r)return[];let s=qs(n.docsDir??sf).replace(/\/+$/,""),l=new Map;for(let m of rf(r))l.set(m.categoryPath,(l.get(m.categoryPath)??0)+1);let d=[];for(let m of of(r)){let k=qs(m.path),y=k.startsWith(`${s}/`)?k.slice(s.length+1):k===s?"":k;y&&d.push({token:y,label:lf(af(k)),count:l.get(m.path)??0})}return d}catch{return[]}}function lc(e,t){let n=Ln(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 ut(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function on(e,t,n,o){let r=Ln(e,o);if(r.length<=1)return[];let s=n.filter(k=>k.startsWith("--")).join(" "),l=s?` ${s}`:"",d=`/${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,y)=>k+y.count,0)} articles). Pick a target:`,` ${d} (everything)`,...r.map(k=>` ${m(k.token)} (${k.label} \xB7 ${k.count} article${k.count===1?"":"s"})`)]}function Qo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function cc(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 yf=3,kf=8;function Hs(e){return e===void 0||!Number.isFinite(e)?yf:Math.max(1,Math.min(Math.floor(e),kf))}function Bs(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 d=m=>m?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:d(t),path:d(n),preview:o,concurrency:s,rewrite:r}}function bf(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 Vs(e,t,n){return n.filter(o=>{try{return uc(dc(e,t,o)).size===0}catch{return!0}})}function Gs(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+=uc(dc(e,l)).size}catch{}return{path:r,bytes:s}})}function Ys(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.
331
+ `)}function Fs(e,t,n){let o=e.reduce((d,m)=>d+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(d=>` \u2022 ${d.label} \u2014 ${d.paths.length} article${d.paths.length===1?"":"s"}`),"",`Estimated cost: ${xe(r)}\u2013${xe(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function qs(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,j)=>P+o(j),0),d=r.reduce((P,j)=>P+o(j),0),m=e.reduce((P,j)=>P+j.costUsd,0),y=e.reduce((P,j)=>P+j.outputTokens,0),b=n==="api"?`${xe(m)} total`:lt(y),v=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=P=>`${P} article${P===1?"":"s"}`,I=[];if(s.length===0)I.push(`Converted ${x(l)} (${v}) successfully \xB7 ${b}.`);else{I.push(`Converted ${d}/${x(l)} (${v}) \xB7 ${b}.`),I.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let P of s)I.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return I}async function cc(e,t){if(!ef(t.cwd))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Os(e),r=of(t.cwd,t.profileName);if(r.length===0)return console.log(C("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Ms(r,n);if(s.length===0)return console.log(C(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let l=Zh(s),d=`/convert${n?` --scope ${n}`:""} --run`,{model:m,forced:y}=tf(t.cwd,"light");if(!o){let b=Jh({files:Us(t.cwd,s),op:"convert",model:m});n&&console.log(g(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let v of Fs(l,b,Ls))console.log(v);return console.log(g(`Model: ${m}${y?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(g(`Run ${d} to start.`)),console.log(""),{kind:"continue"}}console.log(g(`Converting ${s.length} articles across ${l.length} partitions (\u2264${Ls} agents at once) on ${m}\u2026`)),console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let b of nf({cwd:t.cwd,partitions:l,promptFor:Ws,concurrency:Ls,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:m}))if(b.type==="partition_status")b.status==="running"?console.log(g(` \u25B8 ${b.label} \u2014 converting\u2026`)):b.status==="done"?console.log(N(` \u2713 ${b.label}`)):console.log(C(` \u2717 ${b.label}`));else if(b.type==="run_done"){console.log("");let v=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let x of qs(b.results,l,v))console.log(b.ok?N(x):M(x))}}catch(b){console.log(C(`Convert run failed: ${b.message}`))}return console.log(""),{kind:"continue"}}H();import{statSync as pc}from"node:fs";import{resolve as hc}from"node:path";import{estimateBulkCost as hf,lintDocs as ff,planPartitions as mf,readDocsPlan as gf,readProjectConfig as fc,DEFAULT_DOCS_DIR as wf,resolveModelForOperation as yf,runPartitioned as kf,stampArticles as bf,CONTENT_CAP_VERSION as $f}from"document360-engine";import{readProjectConfig as rf,loadProfileMap as sf,resolveActiveProfile as af,desiredCategoryOrder as lf,desiredArticleOrder as cf,DEFAULT_DOCS_DIR as uf}from"document360-engine";var Hs=e=>e.replace(/\\/g,"/"),df=e=>Hs(e).split("/").pop()??e;function pf(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function On(e,t){try{let n=rf(e);if(!n)return[];let o=af(e,t),r=sf(e,o.name);if(!r)return[];let s=Hs(n.docsDir??uf).replace(/\/+$/,""),l=new Map;for(let m of cf(r))l.set(m.categoryPath,(l.get(m.categoryPath)??0)+1);let d=[];for(let m of lf(r)){let y=Hs(m.path),b=y.startsWith(`${s}/`)?y.slice(s.length+1):y===s?"":y;b&&d.push({token:b,label:pf(df(y)),count:l.get(m.path)??0})}return d}catch{return[]}}function uc(e,t){let n=On(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 ut(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function on(e,t,n,o){let r=On(e,o);if(r.length<=1)return[];let s=n.filter(y=>y.startsWith("--")).join(" "),l=s?` ${s}`:"",d=`/${t}${l} --all`.replace(/\s+/g," "),m=y=>t==="write"?`/write --scope ${y}${l}`:`/${t} ${y}${l}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((y,b)=>y+b.count,0)} articles). Pick a target:`,` ${d} (everything)`,...r.map(y=>` ${m(y.token)} (${y.label} \xB7 ${y.count} article${y.count===1?"":"s"})`)]}function Qo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function dc(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 xf=3,vf=8;function Bs(e){return e===void 0||!Number.isFinite(e)?xf:Math.max(1,Math.min(Math.floor(e),vf))}function Vs(e){let t,n,o=!1,r=!1,s,l=m=>{let y=Number(m);return m!==void 0&&Number.isFinite(y)?y:void 0};for(let m=0;m<e.length;m++){let y=e[m];if(y==="--preview"||y==="--dry-run")o=!0;else if(y==="--rewrite"||y==="--force")r=!0;else{if(y==="--run"||y==="--yes"||y==="--all")continue;y==="--scope"?t=e[++m]:y?.startsWith("--scope=")?t=y.slice(8):y==="--concurrency"?s=l(e[++m]):y?.startsWith("--concurrency=")?s=l(y.slice(14)):y&&!y.startsWith("--")&&(n=y)}}let d=m=>m?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:d(t),path:d(n),preview:o,concurrency:s,rewrite:r}}function Cf(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Rf(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Gs(e,t,n){return n.filter(o=>{try{return pc(hc(e,t,o)).size===0}catch{return!0}})}function Ys(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+=pc(hc(e,l)).size}catch{}return{path:r,bytes:s}})}function zs(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.
332
332
  `:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
333
333
  - 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).
334
334
  - 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).
@@ -338,94 +338,94 @@ ${s}${m}`).join("")}).join(`
338
338
  - 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.
339
339
  Articles:
340
340
  `+e.paths.map(r=>`- ${r}`).join(`
341
- `)}function zs(e,t,n){let o=e.reduce((l,d)=>l+d.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: ${$e(r)}\u2013${$e(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Ks(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),l=e.reduce((R,N)=>R+o(N),0),d=r.reduce((R,N)=>R+o(N),0),m=e.reduce((R,N)=>R+N.costUsd,0),k=e.reduce((R,N)=>R+N.outputTokens,0),y=n==="api"?`${$e(m)} total`:lt(k),v=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,$=R=>`${R} article${R===1?"":"s"}`,_=[];if(s.length===0)_.push(`Wrote ${$(l)} (${v}) successfully \xB7 ${y}.`),_.push("Next \u2014 push them to Document360:"),_.push("/publish --all"),_.push("Or add screenshots first with /screenshot author --all. Drafts are reviewable in the portal after publishing.");else{_.push(`Wrote ${d}/${$(l)} (${v}) \xB7 ${y}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let R of s)_.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return _}function Xs(e,t,n){try{let o=uf({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 Qs(e,t,n){let o=(pc(e)?.docsDir??hf).replace(/\/+$/,""),r=t.map(d=>d.path);if(n.path){let d=bf(n.path,o);return r.includes(d)?{docsDir:o,targets:[d],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${d}" 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=Vs(e,o,s);if(l.length===0){let d=n.scope?` under "${n.scope}"`:"",m=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${d} 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 hc(e,t){if(!pc(t.cwd))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Qo(e)){for(let F of lc(t.cwd,t.profileName))console.log(g(F));return{kind:"continue"}}if(ut("write",e)){let F=on(t.cwd,"write",e,t.profileName);if(F.length>0){for(let z of F)console.log(g(z));return{kind:"continue"}}}let n=pf(t.cwd);if(n.length===0)return console.log(C("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:d}=Bs(e),{docsDir:m,targets:k,reason:y,rewriting:v}=Qs(t.cwd,n,{scope:o,path:r,rewrite:d});if(k.length===0)return console.log(y?M(y):M("Nothing to write.")),{kind:"continue"};v&&console.log(M(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let $=df(k),_=Hs(l),{model:R,forced:N}=ff(t.cwd,"standard"),T=!!r;if(s&&!T){let F=cf({files:Gs(t.cwd,n,k),op:"write",model:R});o&&console.log(g(`Scope: ${o} (${k.length} pending).`));for(let z of zs($,F,_))console.log(z);return console.log(g(`Model: ${R}${N?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(g(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(g(`Writing ${k.length} article${k.length===1?"":"s"} across ${$.length} partition${$.length===1?"":"s"} (\u2264${_} agents at once) on ${R}\u2026`)),console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let F of mf({cwd:t.cwd,partitions:$,promptFor:z=>Ys(z,m,{rewrite:v||T}),concurrency:_,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:R}))if(F.type==="partition_status")F.status==="running"?console.log(g(` \u25B8 ${F.label} \u2014 writing\u2026`)):F.status==="done"?console.log(E(` \u2713 ${F.label}`)):console.log(C(` \u2717 ${F.label}`));else if(F.type==="run_done"){console.log("");let z=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let X of Ks(F.results,$,z))console.log(F.ok?E(X):M(X));if(F.ok)try{gf(t.cwd,k.map(X=>`${m}/${X}`),{writtenCap:wf})}catch{}let K=Xs(t.cwd,m,k);K&&console.log(M(K))}}catch(F){console.log(C(`Write run failed: ${F.message}`))}return console.log(""),{kind:"continue"}}H();import{existsSync as $f,readdirSync as fc,statSync as mc}from"node:fs";import{join as gc}from"node:path";import{inputDir as vf,readProjectConfig as Cf}from"document360-engine";var wc=/\.(md|markdown|pdf|txt)$/i;function Js(e){let t=vf(e);if(!$f(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of fc(t)){let s=gc(t,r),l=!1;try{l=mc(s).isDirectory()}catch{continue}if(l){if(r.startsWith("."))continue;let d=Rf(s);d>0&&n.push({name:r,docCount:d})}else wc.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Rf(e){let t=0;for(let n of fc(e))try{mc(gc(e,n)).isFile()&&wc.test(n)&&t++}catch{}return t}function Zs(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 Jo(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(`
342
- `)}var ei="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function yc(e,t){let n=t?.cwd??process.cwd();if(!Cf(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Js(n);if(o.length===0&&r===0)return console.log(g(ei)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(g("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let m of o)console.log(` ${m.name} ${g(`(${m.docCount} doc${m.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let d=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Jo(d),display:d?`/draft ${d}`:"/draft"}}let l=Zs(o,s);return{kind:"forward-to-agent",prompt:Jo(l??"",l?void 0:s),display:`/draft ${s}`}}H();import{listOpenForDocs as Sf,readProjectConfig as Pf}from"document360-engine";function ti(e){try{return Sf(e).filter(t=>t.kind==="request").length}catch{return 0}}function ni(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function oi(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(`
343
- `)}var ri="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 kc(e,t){let n=t?.cwd??process.cwd();if(!Pf(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=ni(e);if(!r&&ti(n)===0)return console.log(g(ri)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:oi(r,o),display:s}}H();import{search as Tf}from"@inquirer/prompts";import{findByName as Df,getSession as Af,listSessions as jf,relativeTime as xc}from"document360-engine";async function $c(e,t){let n=jf(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(g("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=Df(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(C(`No session matches "${o}".`)),bc(n),{kind:"continue"})}if(!process.stdin.isTTY)return bc(n),console.log(g("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Tf({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let l=(s??"").toLowerCase();return n.filter(d=>!l||d.name.toLowerCase().includes(l)||d.firstPrompt.toLowerCase().includes(l)).map(d=>({name:`${d.name} ${xc(d.updatedAt)}`,value:d.uuid,description:d.firstPrompt.slice(0,100)}))}})),r=Af(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function bc(e){console.log("");for(let t of e.slice(0,15))console.log(` ${L(t.name)} ${g(xc(t.updatedAt))}`),console.log(` ${g(t.firstPrompt.slice(0,80))}`);console.log("")}H();import{renameSession as Ef}from"document360-engine";function si(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 vc(e,t){let n=si(e.join(" "));if(!n)return console.log(C("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Ef(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log(C("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(E(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Cc,readProjectConfig as Nf,writeProjectConfig as If}from"document360-engine";H();function ii(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Nf(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 Cc().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},If(o,e),null):`Unknown environment "${r}". Known: ${Cc().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function Rc(e,t){let n=e[0];if(!n)return Do(t.cwd),{kind:"continue"};if(n==="add"){let o=ii(t.cwd,e[1],e[2]);return o?(console.log(C(o)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${L(`/profile ${e[1]}`)} then ${L("/login")}`),{kind:"continue"})}return Ao(t.cwd,n),jo(t.cwd,n),console.log(g(" Restarting agent for the new profile\u2026")),{kind:"clear"}}H();import{select as _f}from"@inquirer/prompts";import{readProjectConfig as Lf,readUserConfig as Sc,resolveModelSetting as ai,writeUserConfig as Pc}from"document360-engine";var He=[{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 Zo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=He.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Of(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 On(e,t){let n=()=>ai(e).model;if(t==="default"){let s=Sc();return s.defaultModel?(delete s.defaultModel,Pc(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${ai(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}}Pc({...Sc(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Lf(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 Tc(e,t){let n=e[0]?.trim();if(!n){let l=ai(t.cwd);if(!process.stdin.isTTY)return console.log(`${xe("Model:")} ${L(l.model)}${l.source==="auto"?g(" (auto)"):""}`),console.log(g(` source: ${Of(l)}`)),console.log(g(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let d=Zo(l),m;try{m=await t.withPausedInput(()=>_f({message:`Select model (current: ${l.model}${l.source==="auto"?" \xB7 auto":""})`,default:He[d].value,choices:He.map(($,_)=>({name:`${$.label}${_===d?" \u2714":""}`,value:$.value,description:$.desc}))}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}let{lines:k,changed:y,effective:v}=On(t.cwd,m??"default");for(let $ of k)console.log($.startsWith("\u26A0")?M($):$.startsWith("\u2713")?E($):g($));return y&&await t.setModel(v),{kind:"continue"}}let{lines:o,changed:r,effective:s}=On(t.cwd,n);for(let l of o)console.log(l.startsWith("\u26A0")?M(l):l.startsWith("\u2713")?E(l):g(l));return r&&await t.setModel(s),{kind:"continue"}}er();async function Ic(e,t){return await t.withPausedInput(()=>Kt(t.cwd)),{kind:"clear"}}async function _c(e,t){return await t.withPausedInput(()=>Ro(t.cwd,t.profileName)),{kind:"clear"}}H();import{resolveActiveProfile as tm}from"document360-engine";async function Lc(e,t){let n=!1;try{n=tm(t.cwd).production}catch{}return n?(console.log(M("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(g("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}H();var Oc=async(e,t)=>{try{await t.withPausedInput(()=>To({}))}catch(n){console.log(C(`Login failed: ${n.message}`))}return{kind:"continue"}};H();import{resolveActiveProfile as nm,clearTokens as om,clearProfileProject as rm}from"document360-engine";async function Mc(e,t){let n;try{n=nm(t.cwd,t.profileName).name}catch(r){return console.log(C(r.message)),{kind:"continue"}}let o=om(n);return rm(t.cwd,n),console.log(o?E(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):g(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(g("Run /login to sign in and pick a project.")),{kind:"continue"}}import{spawn as Wc}from"node:child_process";import{existsSync as ci,readFileSync as Uc,statSync as sm}from"node:fs";import{homedir as im}from"node:os";import{basename as am,isAbsolute as lm,join as Un,resolve as cm}from"node:path";import{readProjectConfig as um,DEFAULT_OUTPUT_DIR as dm}from"document360-engine";var pm=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function ui(e){let t=e.find(n=>!n.startsWith("--"));return e.includes("--all")?{mode:"all"}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:pm(t)}:{mode:"single",id:t}:{mode:"picker"}}function di(e,t){let n=qe(e,t);return{ready:n.filter(o=>o.state==="spec").map(o=>o.id),captured:n.filter(o=>o.state==="captured").map(o=>o.id)}}function Fc(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"),o=[],r=t.filter(s=>!s.mutates);r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),Uo(o,t,"capture");for(let s of[...n].sort((l,d)=>l.id.localeCompare(d.id)))o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:" \u25CF captured \u2014 re-capture"});return o}function hm(e,t){let n=um(e)?.outputDir??dm;return lm(n)?Un(n,`${t}.png`):cm(e,n,`${t}.png`)}function pi(e,t,n,o){let r=hm(e,t);return ci(r)&&sm(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function qc(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}function Hc(e){let n=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).filter(o=>/\b\w*Error\b|Cannot navigate|Timeout \d+m?s (exceeded|waiting)|net::|browser has been closed/i.test(o)&&!/^Error Context:/i.test(o));return n.length>0?[...new Set(n)].slice(0,3).join(`
344
- `):hi(e)}function hi(e,t=4){let n=/captured\s+·|^▶ Annotating|^✓ \d+ captured|^\s*[⊘✗]\s+\S+\s*$|^▶ Running \d+ spec/;return e.split(/\r?\n/).map(r=>r.trimEnd()).filter(r=>r.trim().length>0&&!n.test(r.trim())).slice(-t).join(`
345
- `)}var fm=/^[A-Za-z0-9._-]+$/;function fi(e){return new Promise((t,n)=>{if(!fm.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=Wc(`d360-capture capture ${e.id}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";e.stdio==="pipe"&&(o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{r+=l.toString()}));let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",l=>{e.signal?.removeEventListener("abort",s),n(l)}),o.on("close",l=>{e.signal?.removeEventListener("abort",s),t({exitCode:l??1,output:r})})})}function Bc(e,t=im()){try{let n=JSON.parse(Uc(Un(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(Uc(Un(e,"package.json"),"utf8")).name}catch{}o||=am(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?ci(Un(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function Vc(e){return new Promise((t,n)=>{let o=Wc("d360-capture auth --auto",{cwd:e.cwd,shell:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{r+=l.toString()});let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",l=>{e.signal?.removeEventListener("abort",s),n(l)}),o.on("close",l=>{e.signal?.removeEventListener("abort",s),t({exitCode:l??1,output:r})})})}function mi(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function tr(e){return ci(Un(e,".d360-writer","capture.json"))}function gi(){return["Screenshot capture is not configured in this repo yet (no `.d360-writer/capture.json`). Set it up","conversationally \u2014 never tell the user to run `d360-capture init`:","","1. Find the live app URL yourself first: `.d360-writer/config.json` `appUrl`, the product brief, the"," architecture brief, the repo (README, deploy config). Present what you found for confirmation \u2014 or"," ask for it if unknown. In the SAME message also ask: (a) is that URL the production environment?"," (b) which prepared demo context should screenshots enter \u2014 the capture scope (read the product"," source to know what this product scopes by: project / workspace / org; a single-context product"," needs none). One short numbered message, then END YOUR TURN and wait for the answers.","2. On the answers, write `.d360-writer/capture.json` in exactly this shape (fill the values):","```json","{",' "projectId": "<projectId from .d360-writer/config.json>",',' "profiles": {',' "<production or staging, matching their answer>": {',' "connection": { "startUrl": "<the app URL>" },',' "production": <true when they said production>,',' "scope": { "<scopeKey>": "<their demo context>" }'," }"," },",' "defaultProfile": "<the same profile name>"',"}","```"," Omit `scope` for a single-context product. Do not add captureDir/outputDir (defaults apply).","3. Also record the app URL as `appUrl` in `.d360-writer/config.json` \u2014 add/update just that key,",' preserving everything else. It is the canonical "where the product lives" fact (you may use it to'," deep-link stable app screens from articles).","4. Close with the ONE remaining external step, then the retry:"," `d360-capture auth` (run in this repo's terminal; first time also `npm i -g document360-capture`)"," then `/screenshot capture`."].join(`
346
- `)}function Gc(e,t){let n=new Map(qe(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function wi(e,t){let n=t?.cwd??process.cwd(),o=ui(e);if(!tr(n))return console.log("Screenshot capture is not set up in this repo yet. Run: d360-capture init"),{kind:"continue"};let{ready:r,captured:s}=di(n,o.mode==="scope"?o.scope:void 0),l=o.mode==="single"?[o.id]:o.mode==="picker"?r:[...r,...s];if(l.length===0)return console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};let d=Date.now(),m=[];for(let y of l){console.log(`\u25B6 ${y}`);try{let{exitCode:v}=await fi({cwd:n,id:y,stdio:"inherit"});m.push({id:y,outcome:pi(n,y,v,d)})}catch(v){if(v.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};m.push({id:y,outcome:"failed",detail:v.message})}}let k=y=>m.filter(v=>v.outcome===y).length;return console.log(`\u2713 ${k("captured")} captured \xB7 \u2298 ${k("skipped")} skipped \xB7 \u2717 ${k("failed")} failed`),{kind:"continue"}}import{existsSync as mm,readFileSync as gm}from"node:fs";import{isAbsolute as wm,join as ym,resolve as km}from"node:path";import{readProjectConfig as bm,DEFAULT_CAPTURE_DIR as xm}from"document360-engine";async function rn(){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-writer/capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-CHECKLIST.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
347
- `),display:"/screenshot checklist"}}var Yc="-".repeat(64);function yi(e){let t=xm;try{let y=bm(e);y?.captureDir&&(t=y.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=wm(t)?ym(t,"CAPTURE-TESTID-REQUESTS.json"):km(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!mm(n))return null;let o;try{let y=JSON.parse(gm(n,"utf8").replace(/^/,""));o=Array.isArray(y?.requests)?y.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(y=>y.file).filter(Boolean)).size,s=o.length,l=`${s} data-testid attribute${s===1?"":"s"}`,d=`${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 ${d}.`,"\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.","",Yc,`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.",Yc]}it();H();import{listOpenForDocs as $m,readProjectConfig as vm}from"document360-engine";function ki(e){try{return $m(e).length}catch{return 0}}function bi(){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(`
348
- `)}async function zc(e,t){let n=t?.cwd??process.cwd();return vm(n)?ki(n)===0?(console.log(g("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:bi(),display:"/inbox"}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}H();import{listOpenHints as Cm,listOpenForDocs as Rm,listOpenDirectives as Sm,readProjectConfig as Pm,computeSyncStatus as Tm,planPull as Dm,applyPull as Am,planImport as jm,applyImport as Em}from"document360-engine";function Wn(e){let t=0,n=0,o=0,r=0;try{t=Cm(e).length}catch{}try{let s=Rm(e);n=s.filter(l=>l.kind==="request").length,o=s.filter(l=>l.kind==="answer").length}catch{}try{r=Sm(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function Fn(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 $i(e){return{publish:e.includes("--publish")}}function vi({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) \u2014 including a step whose work you can verify an EARLIER session already completed but left unstamped \u2014 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(`
349
- `)}var Nm={status:Tm,plan:Dm,apply:Am,planImport:jm,applyImport:Em};async function Ci(e,t=Nm){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 xi=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,nr=e=>e===1?"":"s";function Ri(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${nr(e.pulled.length)} into local: ${xi(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${nr(e.imported.length)} into local drafts: ${xi(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${nr(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${xi(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${nr(e.failed.length)} failed \u2014 left for /pull.`),t}async function Kc(e,t){let n=t?.cwd??process.cwd();if(!Pm(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ie(n,t?.profileName);if(!o.ok)return console.log(C(o.reason)),{kind:"continue"};let{publish:r}=$i(e);console.log(g("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await Ci({cwd:n,profileName:t?.profileName});for(let d of Ri(s))console.log(d.startsWith("\u2713")?E(d):d.startsWith("\u2139")?g(d):M(d));let l=Fn(Wn(n));return console.log(g(l?`Catching up on ${l}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:vi({publish:r}),display:`/catch-up${r?" --publish":""}`}}H();import{spawn as Xc}from"node:child_process";var sn="document360-writer",or=`npm i -g ${sn}@latest`,Im="document360-capture";function _m(){return new Promise(e=>{try{let t=Xc("d360-capture --version",{stdio:"ignore",shell:!0,windowsHide:!0});t.on("error",()=>e(!1)),t.on("close",n=>e(n===0))}catch{e(!1)}})}async function rr(){let e=process.platform==="win32",n=await _m()?[sn,Im]:[sn];return new Promise(o=>{try{let r=Xc(`npm i -g ${n.map(s=>`${s}@latest`).join(" ")}`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});r.on("error",s=>o({ok:!1,output:String(s),packages:n})),r.on("close",s=>o({ok:s===0,output:"",packages:n})),e||r.unref()}catch(r){o({ok:!1,output:String(r),packages:n})}})}async function Qc(){console.log(g("Updating the d360-writer toolchain\u2026"));let e=await rr();return e.ok?console.log(E(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)):console.log(C(`Update failed \u2014 run manually: ${or}`)),{kind:"continue"}}H();it();import{existsSync as Si,rmSync as Lm}from"node:fs";import{basename as Jc,resolve as Pi}from"node:path";import{execFileSync as Om}from"node:child_process";import{input as Mm}from"@inquirer/prompts";import{readProjectConfig as Um,devHintsGuidePath as Wm}from"document360-engine";var Fm=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],qm=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),sr=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Zc=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function eu(e){let t=sr(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Zc(t)?!0:qm.has(t)}function Ti(e){let t=null;try{t=Um(e)}catch{t=null}let n=new Set(Fm);for(let o of[sr(t?.docsDir),sr(t?.captureDir),sr(t?.outputDir)])o&&Zc(o)&&n.add(o);return[...n].filter(o=>eu(o)&&Si(Pi(e,o)))}function Di(e,t){let n=[],o=[];for(let r of t){if(!eu(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Lm(Pi(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function tu(e,t){try{return Om("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
350
- `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Hm(e){return tu(e,".d360-writer/hints")}function Bm(e){return tu(e,".d360-writer/messages")}function Ai(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Hm(e),o=Bm(e),r=Si(Pi(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: ${Jc(e)}`]}async function nu(e,t){let n=Ti(t.cwd);for(let m of Ai(t.cwd,n))console.log(n.length===0?g(m):m);if(n.length===0)return{kind:"continue"};let o=Jc(t.cwd);if((await t.withPausedInput(()=>Mm({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(M("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Si(Wm(t.cwd)),{removed:l,failed:d}=Di(t.cwd,n);console.log(E(`\u2713 Reset complete \u2014 removed ${l.length} item${l.length===1?"":"s"}. The repo is back to its original state.`));for(let m of d)console.log(C(` \u2717 ${m.path}: ${m.error}`));if(s){for(let m of _o())console.log(m);console.log(g("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(g("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}H();import{lintDocs as Vm}from"document360-engine";function ir(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 ji(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.","- stray-file: a junk *.publish.md file (a publish transform wrongly written to disk). DELETE the file \u2014",' do not edit it, do not publish it; the real article is its sibling without ".publish". Nothing else changes.',"","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(`
341
+ `)}function Ks(e,t,n){let o=e.reduce((l,d)=>l+d.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: ${xe(r)}\u2013${xe(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,j)=>P+o(j),0),d=r.reduce((P,j)=>P+o(j),0),m=e.reduce((P,j)=>P+j.costUsd,0),y=e.reduce((P,j)=>P+j.outputTokens,0),b=n==="api"?`${xe(m)} total`:lt(y),v=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=P=>`${P} article${P===1?"":"s"}`,I=[];if(s.length===0)I.push(`Wrote ${x(l)} (${v}) successfully \xB7 ${b}.`),I.push("Next \u2014 push them to Document360:"),I.push("/publish --all"),I.push("Or add screenshots first with /screenshot author --all. Drafts are reviewable in the portal after publishing.");else{I.push(`Wrote ${d}/${x(l)} (${v}) \xB7 ${b}.`),I.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let P of s)I.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return I}function Qs(e,t,n){try{let o=ff({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 Js(e,t,n){let o=(fc(e)?.docsDir??wf).replace(/\/+$/,""),r=t.map(d=>d.path);if(n.path){let d=Cf(n.path,o);return r.includes(d)?{docsDir:o,targets:[d],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${d}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=Rf(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=Gs(e,o,s);if(l.length===0){let d=n.scope?` under "${n.scope}"`:"",m=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${d} 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 mc(e,t){if(!fc(t.cwd))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Qo(e)){for(let U of uc(t.cwd,t.profileName))console.log(g(U));return{kind:"continue"}}if(ut("write",e)){let U=on(t.cwd,"write",e,t.profileName);if(U.length>0){for(let G of U)console.log(g(G));return{kind:"continue"}}}let n=gf(t.cwd);if(n.length===0)return console.log(C("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:d}=Vs(e),{docsDir:m,targets:y,reason:b,rewriting:v}=Js(t.cwd,n,{scope:o,path:r,rewrite:d});if(y.length===0)return console.log(b?M(b):M("Nothing to write.")),{kind:"continue"};v&&console.log(M(`--rewrite: regenerating ${y.length} already-written article${y.length===1?"":"s"} (overwrites them; git has your baseline).`));let x=mf(y),I=Bs(l),{model:P,forced:j}=yf(t.cwd,"standard"),D=!!r;if(s&&!D){let U=hf({files:Ys(t.cwd,n,y),op:"write",model:P});o&&console.log(g(`Scope: ${o} (${y.length} pending).`));for(let G of Ks(x,U,I))console.log(G);return console.log(g(`Model: ${P}${j?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(g(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(g(`Writing ${y.length} article${y.length===1?"":"s"} across ${x.length} partition${x.length===1?"":"s"} (\u2264${I} agents at once) on ${P}\u2026`)),console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let U of kf({cwd:t.cwd,partitions:x,promptFor:G=>zs(G,m,{rewrite:v||D}),concurrency:I,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:P}))if(U.type==="partition_status")U.status==="running"?console.log(g(` \u25B8 ${U.label} \u2014 writing\u2026`)):U.status==="done"?console.log(N(` \u2713 ${U.label}`)):console.log(C(` \u2717 ${U.label}`));else if(U.type==="run_done"){console.log("");let G=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let X of Xs(U.results,x,G))console.log(U.ok?N(X):M(X));if(U.ok)try{bf(t.cwd,y.map(X=>`${m}/${X}`),{writtenCap:$f})}catch{}let K=Qs(t.cwd,m,y);K&&console.log(M(K))}}catch(U){console.log(C(`Write run failed: ${U.message}`))}return console.log(""),{kind:"continue"}}H();import{existsSync as Sf,readdirSync as gc,statSync as wc}from"node:fs";import{join as yc}from"node:path";import{inputDir as Pf,readProjectConfig as Tf}from"document360-engine";var kc=/\.(md|markdown|pdf|txt)$/i;function Zs(e){let t=Pf(e);if(!Sf(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of gc(t)){let s=yc(t,r),l=!1;try{l=wc(s).isDirectory()}catch{continue}if(l){if(r.startsWith("."))continue;let d=Df(s);d>0&&n.push({name:r,docCount:d})}else kc.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Df(e){let t=0;for(let n of gc(e))try{wc(yc(e,n)).isFile()&&kc.test(n)&&t++}catch{}return t}function ei(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 Jo(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(`
342
+ `)}var ti="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function bc(e,t){let n=t?.cwd??process.cwd();if(!Tf(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Zs(n);if(o.length===0&&r===0)return console.log(g(ti)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(g("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let m of o)console.log(` ${m.name} ${g(`(${m.docCount} doc${m.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let d=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Jo(d),display:d?`/draft ${d}`:"/draft"}}let l=ei(o,s);return{kind:"forward-to-agent",prompt:Jo(l??"",l?void 0:s),display:`/draft ${s}`}}H();import{listOpenForDocs as Af,readProjectConfig as jf}from"document360-engine";function ni(e){try{return Af(e).filter(t=>t.kind==="request").length}catch{return 0}}function oi(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function ri(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(`
343
+ `)}var si="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 $c(e,t){let n=t?.cwd??process.cwd();if(!jf(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=oi(e);if(!r&&ni(n)===0)return console.log(g(si)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:ri(r,o),display:s}}H();import{search as Ef}from"@inquirer/prompts";import{findByName as Nf,getSession as If,listSessions as _f,relativeTime as vc}from"document360-engine";async function Cc(e,t){let n=_f(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(g("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=Nf(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(C(`No session matches "${o}".`)),xc(n),{kind:"continue"})}if(!process.stdin.isTTY)return xc(n),console.log(g("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Ef({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let l=(s??"").toLowerCase();return n.filter(d=>!l||d.name.toLowerCase().includes(l)||d.firstPrompt.toLowerCase().includes(l)).map(d=>({name:`${d.name} ${vc(d.updatedAt)}`,value:d.uuid,description:d.firstPrompt.slice(0,100)}))}})),r=If(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function xc(e){console.log("");for(let t of e.slice(0,15))console.log(` ${L(t.name)} ${g(vc(t.updatedAt))}`),console.log(` ${g(t.firstPrompt.slice(0,80))}`);console.log("")}H();import{renameSession as Lf}from"document360-engine";function ii(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 Rc(e,t){let n=ii(e.join(" "));if(!n)return console.log(C("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Lf(o,n)?console.log(N(`\u2713 Session renamed to "${n}"`)):console.log(C("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(N(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Sc,readProjectConfig as Of,writeProjectConfig as Mf}from"document360-engine";H();function ai(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Of(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 Sc().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Mf(o,e),null):`Unknown environment "${r}". Known: ${Sc().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function Pc(e,t){let n=e[0];if(!n)return Do(t.cwd),{kind:"continue"};if(n==="add"){let o=ai(t.cwd,e[1],e[2]);return o?(console.log(C(o)),{kind:"continue"}):(console.log(N(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${L(`/profile ${e[1]}`)} then ${L("/login")}`),{kind:"continue"})}return Ao(t.cwd,n),jo(t.cwd,n),console.log(g(" Restarting agent for the new profile\u2026")),{kind:"clear"}}H();import{select as Uf}from"@inquirer/prompts";import{readProjectConfig as Wf,readUserConfig as Tc,resolveModelSetting as li,writeUserConfig as Dc}from"document360-engine";var He=[{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 Zo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=He.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Ff(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 Mn(e,t){let n=()=>li(e).model;if(t==="default"){let s=Tc();return s.defaultModel?(delete s.defaultModel,Dc(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${li(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}}Dc({...Tc(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Wf(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 Ac(e,t){let n=e[0]?.trim();if(!n){let l=li(t.cwd);if(!process.stdin.isTTY)return console.log(`${$e("Model:")} ${L(l.model)}${l.source==="auto"?g(" (auto)"):""}`),console.log(g(` source: ${Ff(l)}`)),console.log(g(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let d=Zo(l),m;try{m=await t.withPausedInput(()=>Uf({message:`Select model (current: ${l.model}${l.source==="auto"?" \xB7 auto":""})`,default:He[d].value,choices:He.map((x,I)=>({name:`${x.label}${I===d?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}let{lines:y,changed:b,effective:v}=Mn(t.cwd,m??"default");for(let x of y)console.log(x.startsWith("\u26A0")?M(x):x.startsWith("\u2713")?N(x):g(x));return b&&await t.setModel(v),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Mn(t.cwd,n);for(let l of o)console.log(l.startsWith("\u26A0")?M(l):l.startsWith("\u2713")?N(l):g(l));return r&&await t.setModel(s),{kind:"continue"}}tr();async function Mc(e,t){return await t.withPausedInput(()=>Kt(t.cwd)),{kind:"clear"}}async function Uc(e,t){return await t.withPausedInput(()=>Ro(t.cwd,t.profileName)),{kind:"clear"}}H();import{resolveActiveProfile as cm}from"document360-engine";async function Wc(e,t){let n=!1;try{n=cm(t.cwd).production}catch{}return n?(console.log(M("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(g("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}H();var Fc=async(e,t)=>{try{await t.withPausedInput(()=>To({}))}catch(n){console.log(C(`Login failed: ${n.message}`))}return{kind:"continue"}};H();import{resolveActiveProfile as um,clearTokens as dm,clearProfileProject as pm}from"document360-engine";async function qc(e,t){let n;try{n=um(t.cwd,t.profileName).name}catch(r){return console.log(C(r.message)),{kind:"continue"}}let o=dm(n);return pm(t.cwd,n),console.log(o?N(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):g(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(g("Run /login to sign in and pick a project.")),{kind:"continue"}}import{spawn as Bc}from"node:child_process";import{existsSync as di,readFileSync as Hc,statSync as hm}from"node:fs";import{homedir as fm}from"node:os";import{basename as mm,isAbsolute as gm,join as Wn,resolve as wm}from"node:path";import{readProjectConfig as ym,DEFAULT_OUTPUT_DIR as km}from"document360-engine";var bm=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function pi(e){let t=e.find(n=>!n.startsWith("--"));return e.includes("--all")?{mode:"all"}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:bm(t)}:{mode:"single",id:t}:{mode:"picker"}}function hi(e,t){let n=qe(e,t);return{ready:n.filter(o=>o.state==="spec").map(o=>o.id),captured:n.filter(o=>o.state==="captured").map(o=>o.id)}}function Vc(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"),o=[],r=t.filter(s=>!s.mutates);r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),Uo(o,t,"capture");for(let s of[...n].sort((l,d)=>l.id.localeCompare(d.id)))o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:" \u25CF captured \u2014 re-capture"});return o}function $m(e,t){let n=ym(e)?.outputDir??km;return gm(n)?Wn(n,`${t}.png`):wm(e,n,`${t}.png`)}function fi(e,t,n,o){let r=$m(e,t);return di(r)&&hm(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function Gc(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}function Yc(e){let n=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).filter(o=>/\b\w*Error\b|Cannot navigate|Timeout \d+m?s (exceeded|waiting)|net::|browser has been closed/i.test(o)&&!/^Error Context:/i.test(o));return n.length>0?[...new Set(n)].slice(0,3).join(`
344
+ `):mi(e)}function mi(e,t=4){let n=/captured\s+·|^▶ Annotating|^✓ \d+ captured|^\s*[⊘✗]\s+\S+\s*$|^▶ Running \d+ spec/;return e.split(/\r?\n/).map(r=>r.trimEnd()).filter(r=>r.trim().length>0&&!n.test(r.trim())).slice(-t).join(`
345
+ `)}var xm=/^[A-Za-z0-9._-]+$/;function gi(e){return new Promise((t,n)=>{if(!xm.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=Bc(`d360-capture capture ${e.id}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";e.stdio==="pipe"&&(o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{r+=l.toString()}));let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",l=>{e.signal?.removeEventListener("abort",s),n(l)}),o.on("close",l=>{e.signal?.removeEventListener("abort",s),t({exitCode:l??1,output:r})})})}function zc(e,t=fm()){try{let n=JSON.parse(Hc(Wn(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(Hc(Wn(e,"package.json"),"utf8")).name}catch{}o||=mm(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?di(Wn(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function Kc(e){return new Promise((t,n)=>{let o=Bc("d360-capture auth --auto",{cwd:e.cwd,shell:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{r+=l.toString()});let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",l=>{e.signal?.removeEventListener("abort",s),n(l)}),o.on("close",l=>{e.signal?.removeEventListener("abort",s),t({exitCode:l??1,output:r})})})}function wi(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function nr(e){return di(Wn(e,".d360-writer","capture.json"))}function yi(){return["Screenshot capture is not configured in this repo yet (no `.d360-writer/capture.json`). Set it up","conversationally \u2014 never tell the user to run `d360-capture init`:","","1. Find the live app URL yourself first: `.d360-writer/config.json` `appUrl`, the product brief, the"," architecture brief, the repo (README, deploy config). Present what you found for confirmation \u2014 or"," ask for it if unknown. In the SAME message also ask: (a) is that URL the production environment?"," (b) which prepared demo context should screenshots enter \u2014 the capture scope (read the product"," source to know what this product scopes by: project / workspace / org; a single-context product"," needs none). One short numbered message, then END YOUR TURN and wait for the answers.","2. On the answers, write `.d360-writer/capture.json` in exactly this shape (fill the values):","```json","{",' "projectId": "<projectId from .d360-writer/config.json>",',' "profiles": {',' "<production or staging, matching their answer>": {',' "connection": { "startUrl": "<the app URL>" },',' "production": <true when they said production>,',' "scope": { "<scopeKey>": "<their demo context>" }'," }"," },",' "defaultProfile": "<the same profile name>"',"}","```"," Omit `scope` for a single-context product. Do not add captureDir/outputDir (defaults apply).","3. Also record the app URL as `appUrl` in `.d360-writer/config.json` \u2014 add/update just that key,",' preserving everything else. It is the canonical "where the product lives" fact (you may use it to'," deep-link stable app screens from articles).","4. Close with the ONE remaining external step, then the retry:"," `d360-capture auth` (run in this repo's terminal; first time also `npm i -g document360-capture`)"," then `/screenshot capture`."].join(`
346
+ `)}function Xc(e,t){let n=new Map(qe(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function ki(e,t){let n=t?.cwd??process.cwd(),o=pi(e);if(!nr(n))return console.log("Screenshot capture is not set up in this repo yet. Run: d360-capture init"),{kind:"continue"};let{ready:r,captured:s}=hi(n,o.mode==="scope"?o.scope:void 0),l=o.mode==="single"?[o.id]:o.mode==="picker"?r:[...r,...s];if(l.length===0)return console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};let d=Date.now(),m=[];for(let b of l){console.log(`\u25B6 ${b}`);try{let{exitCode:v}=await gi({cwd:n,id:b,stdio:"inherit"});m.push({id:b,outcome:fi(n,b,v,d)})}catch(v){if(v.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};m.push({id:b,outcome:"failed",detail:v.message})}}let y=b=>m.filter(v=>v.outcome===b).length;return console.log(`\u2713 ${y("captured")} captured \xB7 \u2298 ${y("skipped")} skipped \xB7 \u2717 ${y("failed")} failed`),{kind:"continue"}}import{existsSync as vm,readFileSync as Cm}from"node:fs";import{isAbsolute as Rm,join as Sm,resolve as Pm}from"node:path";import{readProjectConfig as Tm,DEFAULT_CAPTURE_DIR as Dm}from"document360-engine";async function rn(){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-writer/capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-CHECKLIST.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
347
+ `),display:"/screenshot checklist"}}var Qc="-".repeat(64);function bi(e){let t=Dm;try{let b=Tm(e);b?.captureDir&&(t=b.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Rm(t)?Sm(t,"CAPTURE-TESTID-REQUESTS.json"):Pm(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!vm(n))return null;let o;try{let b=JSON.parse(Cm(n,"utf8").replace(/^/,""));o=Array.isArray(b?.requests)?b.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(b=>b.file).filter(Boolean)).size,s=o.length,l=`${s} data-testid attribute${s===1?"":"s"}`,d=`${r} source file${r===1?"":"s"}`,m=`${t}/CAPTURE-TESTID-REQUESTS.md`,y=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${l} requested across ${d}.`,"\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.","",Qc,`Read ${m} and ${y}. 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.",Qc]}it();H();import{listOpenForDocs as Am,readProjectConfig as jm}from"document360-engine";function $i(e){try{return Am(e).length}catch{return 0}}function xi(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape.",' \u2022 answer 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(`
348
+ `)}async function Jc(e,t){let n=t?.cwd??process.cwd();return jm(n)?$i(n)===0?(console.log(g("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:xi(),display:"/inbox"}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}H();import{listOpenHints as Em,listOpenForDocs as Nm,listOpenDirectives as Im,readProjectConfig as _m,computeSyncStatus as Lm,planPull as Om,applyPull as Mm,planImport as Um,applyImport as Wm}from"document360-engine";function Fn(e){let t=0,n=0,o=0,r=0;try{t=Em(e).length}catch{}try{let s=Nm(e);n=s.filter(l=>l.kind==="request").length,o=s.filter(l=>l.kind==="answer").length}catch{}try{r=Im(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function qn(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),t.length?t.join(", "):null}function Ci(e){return{publish:e.includes("--publish")}}function Ri({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page" \u2014 .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (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) \u2014 including a step whose work you can verify an EARLIER session already completed but left unstamped \u2014 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(`
349
+ `)}var Fm={status:Lm,plan:Om,apply:Mm,planImport:Um,applyImport:Wm};async function Si(e,t=Fm){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 vi=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,or=e=>e===1?"":"s";function Pi(e){if(e.error)return[`\u26A0 Couldn't check Document360 for portal changes (${e.error.slice(0,100)}) \u2014 proceeding; the agent will re-check.`];let t=[];return e.pulled.length&&t.push(`\u2713 Pulled ${e.pulled.length} portal edit${or(e.pulled.length)} into local: ${vi(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${or(e.imported.length)} into local drafts: ${vi(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${or(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${vi(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${or(e.failed.length)} failed \u2014 left for /pull.`),t}async function Zc(e,t){let n=t?.cwd??process.cwd();if(!_m(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ie(n,t?.profileName);if(!o.ok)return console.log(C(o.reason)),{kind:"continue"};let{publish:r}=Ci(e);console.log(g("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await Si({cwd:n,profileName:t?.profileName});for(let d of Pi(s))console.log(d.startsWith("\u2713")?N(d):d.startsWith("\u2139")?g(d):M(d));let l=qn(Fn(n));return console.log(g(l?`Catching up on ${l}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Ri({publish:r}),display:`/catch-up${r?" --publish":""}`}}H();import{spawn as eu}from"node:child_process";var sn="document360-writer",rr=`npm i -g ${sn}@latest`,qm="document360-capture";function Hm(){return new Promise(e=>{try{let t=eu("d360-capture --version",{stdio:"ignore",shell:!0,windowsHide:!0});t.on("error",()=>e(!1)),t.on("close",n=>e(n===0))}catch{e(!1)}})}async function sr(){let e=process.platform==="win32",n=await Hm()?[sn,qm]:[sn];return new Promise(o=>{try{let r=eu(`npm i -g ${n.map(s=>`${s}@latest`).join(" ")}`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});r.on("error",s=>o({ok:!1,output:String(s),packages:n})),r.on("close",s=>o({ok:s===0,output:"",packages:n})),e||r.unref()}catch(r){o({ok:!1,output:String(r),packages:n})}})}async function tu(){console.log(g("Updating the d360-writer toolchain\u2026"));let e=await sr();return e.ok?console.log(N(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)):console.log(C(`Update failed \u2014 run manually: ${rr}`)),{kind:"continue"}}H();it();import{existsSync as Ti,rmSync as Bm}from"node:fs";import{basename as nu,resolve as Di}from"node:path";import{execFileSync as Vm}from"node:child_process";import{input as Gm}from"@inquirer/prompts";import{readProjectConfig as Ym,devHintsGuidePath as zm}from"document360-engine";var Km=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Xm=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),ir=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),ou=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function ru(e){let t=ir(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:ou(t)?!0:Xm.has(t)}function Ai(e){let t=null;try{t=Ym(e)}catch{t=null}let n=new Set(Km);for(let o of[ir(t?.docsDir),ir(t?.captureDir),ir(t?.outputDir)])o&&ou(o)&&n.add(o);return[...n].filter(o=>ru(o)&&Ti(Di(e,o)))}function ji(e,t){let n=[],o=[];for(let r of t){if(!ru(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Bm(Di(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function su(e,t){try{return Vm("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
350
+ `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Qm(e){return su(e,".d360-writer/hints")}function Jm(e){return su(e,".d360-writer/messages")}function Ei(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Qm(e),o=Jm(e),r=Ti(Di(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: ${nu(e)}`]}async function iu(e,t){let n=Ai(t.cwd);for(let m of Ei(t.cwd,n))console.log(n.length===0?g(m):m);if(n.length===0)return{kind:"continue"};let o=nu(t.cwd);if((await t.withPausedInput(()=>Gm({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(M("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Ti(zm(t.cwd)),{removed:l,failed:d}=ji(t.cwd,n);console.log(N(`\u2713 Reset complete \u2014 removed ${l.length} item${l.length===1?"":"s"}. The repo is back to its original state.`));for(let m of d)console.log(C(` \u2717 ${m.path}: ${m.error}`));if(s){for(let m of _o())console.log(m);console.log(g("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(g("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}H();import{lintDocs as Zm}from"document360-engine";function ar(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 Ni(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.","- stray-file: a junk *.publish.md file (a publish transform wrongly written to disk). DELETE the file \u2014",' do not edit it, do not publish it; the real article is its sibling without ".publish". Nothing else changes.',"","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(`
351
351
  `)).join(`
352
352
  `)].join(`
353
- `)}async function ou(e,t){let n=e.includes("--fix"),o=e.find(l=>!l.startsWith("--")),r=o?` ${o}`:"",s=Vm({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(E("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(g(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:ji(s),display:`/check${r} --fix`});console.log(g("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let l of ir(s))console.log(s.length===0?E(l):M(l));return s.length>0&&console.log(g("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}H();import{lintDocs as Qm,loadStyleGuide as Jm,buildReviewPrompt as Zm,readProjectConfig as eg,DEFAULT_DOCS_DIR as tg}from"document360-engine";H();import{readProjectConfig as Gm,loadProfileMap as Ym,resolveActiveProfile as zm,desiredCategoryOrder as Km,desiredArticleOrder as Xm}from"document360-engine";function ru(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var su=e=>e.replace(/\\/g,"/").split("/").pop()??e;function qn(e,t){try{if(!Gm(e))return[];let n=zm(e,t),o=Ym(e,n.name);if(!o)return[];let r=new Map;for(let l of Xm(o)){let d=r.get(l.categoryPath);d?d.push(l):r.set(l.categoryPath,[l])}let s=[];for(let l of Km(o)){s.push(ru(su(l.path)));for(let d of(r.get(l.path)??[]).sort((m,k)=>m.order-k.order))s.push(` ${ru(su(d.path))}`)}return s}catch{return[]}}async function iu(e,t){let n=qn(t.cwd,t.profileName);if(n.length===0)return console.log(g("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(L("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Ei(e,t){let n=eg(e);if(!n)return null;let o=(n.docsDir??tg).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(y=>!y.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),l=Qm({cwd:e}),d=s?l.filter(y=>y.path===`${o}/${s}`||y.path.startsWith(`${o}/${s}/`)):l,m=s?"":qn(e).join(`
354
- `);return{prompt:Zm({docsRoot:o,scope:s,styleGuide:Jm(e),deterministicFindings:d,fix:r,structure:m||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function au(e,t){if(ut("review",e)){let o=on(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(g(r));return{kind:"continue"}}}let n=Ei(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}H();import{readProjectConfig as ng}from"document360-engine";function Ni(e,t){if(!ng(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(`
355
- `),display:`/reorder${n?` ${n}`:""}`}}async function lu(e,t){if(ut("reorder",e)){let o=on(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(g(r));return{kind:"continue"}}}let n=Ni(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}H();import{readProjectConfig as og,writeProjectConfig as cu,isAppType as rg,playbookSkillName as sg,detectAppType as uu}from"document360-engine";var du=["web","cli","service","library"],ig=new Set(["web","cli"]);function Ii(e){return ig.has(e)?`${sg(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function ar(e,t){let n=t.cwd,o=og(n);if(!o)return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??uu(n);if(s){let l=o.appType?"set in config":"auto-detected";console.log(`${L("Genre:")} ${s} (${l}) \u2014 ${Ii(s)}`)}else console.log(M("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(g(`Set it: /genre <${du.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(g("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...l}=o;cu(l,n);let d=uu(n);return console.log(E(`\u2713 Genre reset to auto-detect \u2014 now: ${d?`${d} (${Ii(d)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return rg(r)?(cu({...o,appType:r},n),console.log(E(`\u2713 Genre set to ${r} \u2014 ${Ii(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(C(`Unknown genre "${r}". Choose one of: ${du.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}H();import{listRoadmap as lr,roadmapProgress as pu,stampRoadmapDone as ag}from"document360-engine";function _i(e){let t=lr(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=pu(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 marks the next step you finished yourself \u2014 add words from a title to pick another.)"),o}function cr(e,t){let n=lr(e).filter(k=>k.status==="open"),o=t.trim();if(n.length===0)return{ok:!1,line:"The roadmap has no open steps \u2014 nothing to mark done."};let r=k=>k.trim().toLowerCase(),s=n.find(k=>r(k.title)===r(o)),l=o?s?[s]:n.filter(k=>r(k.title).includes(r(o))):[n[0]];if(l.length>1)return{ok:!1,line:`"${o}" matches ${l.length} open steps \u2014 add a distinguishing word:
356
- ${l.map(k=>` \u25CB ${k.title}`).join(`
353
+ `)}async function au(e,t){let n=e.includes("--fix"),o=e.find(l=>!l.startsWith("--")),r=o?` ${o}`:"",s=Zm({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(N("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(g(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:Ni(s),display:`/check${r} --fix`});console.log(g("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let l of ar(s))console.log(s.length===0?N(l):M(l));return s.length>0&&console.log(g("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}H();import{lintDocs as sg,loadStyleGuide as ig,buildReviewPrompt as ag,readProjectConfig as lg,DEFAULT_DOCS_DIR as cg}from"document360-engine";H();import{readProjectConfig as eg,loadProfileMap as tg,resolveActiveProfile as ng,desiredCategoryOrder as og,desiredArticleOrder as rg}from"document360-engine";function lu(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var cu=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Hn(e,t){try{if(!eg(e))return[];let n=ng(e,t),o=tg(e,n.name);if(!o)return[];let r=new Map;for(let l of rg(o)){let d=r.get(l.categoryPath);d?d.push(l):r.set(l.categoryPath,[l])}let s=[];for(let l of og(o)){s.push(lu(cu(l.path)));for(let d of(r.get(l.path)??[]).sort((m,y)=>m.order-y.order))s.push(` ${lu(cu(d.path))}`)}return s}catch{return[]}}async function uu(e,t){let n=Hn(t.cwd,t.profileName);if(n.length===0)return console.log(g("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(L("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Ii(e,t){let n=lg(e);if(!n)return null;let o=(n.docsDir??cg).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(b=>!b.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),l=sg({cwd:e}),d=s?l.filter(b=>b.path===`${o}/${s}`||b.path.startsWith(`${o}/${s}/`)):l,m=s?"":Hn(e).join(`
354
+ `);return{prompt:ag({docsRoot:o,scope:s,styleGuide:ig(e),deterministicFindings:d,fix:r,structure:m||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function du(e,t){if(ut("review",e)){let o=on(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(g(r));return{kind:"continue"}}}let n=Ii(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}H();import{readProjectConfig as ug}from"document360-engine";function _i(e,t){if(!ug(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(`
355
+ `),display:`/reorder${n?` ${n}`:""}`}}async function pu(e,t){if(ut("reorder",e)){let o=on(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(g(r));return{kind:"continue"}}}let n=_i(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}H();import{readProjectConfig as dg,writeProjectConfig as hu,isAppType as pg,playbookSkillName as hg,detectAppType as fu}from"document360-engine";var mu=["web","cli","service","library"],fg=new Set(["web","cli"]);function Li(e){return fg.has(e)?`${hg(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function lr(e,t){let n=t.cwd,o=dg(n);if(!o)return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??fu(n);if(s){let l=o.appType?"set in config":"auto-detected";console.log(`${L("Genre:")} ${s} (${l}) \u2014 ${Li(s)}`)}else console.log(M("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(g(`Set it: /genre <${mu.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(g("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...l}=o;hu(l,n);let d=fu(n);return console.log(N(`\u2713 Genre reset to auto-detect \u2014 now: ${d?`${d} (${Li(d)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return pg(r)?(hu({...o,appType:r},n),console.log(N(`\u2713 Genre set to ${r} \u2014 ${Li(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(C(`Unknown genre "${r}". Choose one of: ${mu.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}H();import{listRoadmap as cr,roadmapProgress as gu,stampRoadmapDone as mg}from"document360-engine";function Oi(e){let t=cr(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=gu(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 marks the next step you finished yourself \u2014 add words from a title to pick another.)"),o}function ur(e,t){let n=cr(e).filter(y=>y.status==="open"),o=t.trim();if(n.length===0)return{ok:!1,line:"The roadmap has no open steps \u2014 nothing to mark done."};let r=y=>y.trim().toLowerCase(),s=n.find(y=>r(y.title)===r(o)),l=o?s?[s]:n.filter(y=>r(y.title).includes(r(o))):[n[0]];if(l.length>1)return{ok:!1,line:`"${o}" matches ${l.length} open steps \u2014 add a distinguishing word:
356
+ ${l.map(y=>` \u25CB ${y.title}`).join(`
357
357
  `)}`};if(l.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
358
- ${n.map(k=>` \u25CB ${k.title}`).join(`
359
- `)}`};let d=l[0].title;ag(e,d,{doneAt:new Date().toISOString()});let m=pu(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${d}${m?` \u2014 next up: ${m.title}${m.run?` (${m.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function Li(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?lr(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function hu(e,t){let n=Li(e,t);return n?[`Note: this command executes the open docs-roadmap step "${n.title}".`,`Close the loop IN THE SAME TURN the step's goal state is reached: call d360_roadmap_done with exactly the title "${n.title}", then tell the user it is marked done \u2014 including when you find the goal already holds ("no action needed" completes the STEP, not just the turn). Leave it open ONLY if the work is genuinely incomplete, and say exactly what remains.`].join(`
360
- `):null}function fu(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=lr(e).find(r=>r.status==="open"&&r.title.trim().toLowerCase()===n);return o?[`Execute this open docs-roadmap step: "${o.title}".`,o.run?`Its run command: ${o.run}`:"",o.body?`Step detail:
358
+ ${n.map(y=>` \u25CB ${y.title}`).join(`
359
+ `)}`};let d=l[0].title;mg(e,d,{doneAt:new Date().toISOString()});let m=gu(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${d}${m?` \u2014 next up: ${m.title}${m.run?` (${m.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function Mi(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?cr(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function wu(e,t){let n=Mi(e,t);return n?[`Note: this command executes the open docs-roadmap step "${n.title}".`,`Close the loop IN THE SAME TURN the step's goal state is reached: call d360_roadmap_done with exactly the title "${n.title}", then tell the user it is marked done \u2014 including when you find the goal already holds ("no action needed" completes the STEP, not just the turn). Leave it open ONLY if the work is genuinely incomplete, and say exactly what remains.`].join(`
360
+ `):null}function yu(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=cr(e).find(r=>r.status==="open"&&r.title.trim().toLowerCase()===n);return o?[`Execute this open docs-roadmap step: "${o.title}".`,o.run?`Its run command: ${o.run}`:"",o.body?`Step detail:
361
361
  ${o.body}`:"","",`Close the loop IN THE SAME TURN the step's goal state is reached: call d360_roadmap_done with exactly the title "${o.title}", then tell the user it is marked done. This INCLUDES discovering the goal already holds \u2014 "no action needed" completes the STEP, not just the turn, so stamp it done then too. Leave it open ONLY if the work is genuinely incomplete (blocked, or background results not yet applied) \u2014 then say exactly what remains before it can be closed.`].filter(Boolean).join(`
362
- `):null}async function mu(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=cr(n,e.slice(1).join(" ").trim());return console.log(r.ok?E(r.line):M(r.line)),{kind:"continue"}}let o=_i(n);console.log(L(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?g(r):r);return{kind:"continue"}}var gu={help:es,"?":es,clear:Qa,exit:ts,quit:ts,init:is,mcp:Mo,publish:Gl,audit:_n,discover:Yl,scope:Kl,pull:ic,resolve:oc,convert:ac,write:hc,draft:yc,document:kc,resume:$c,rename:vc,profile:Rc,model:Tc,doctor:Mn,workspace:Ic,project:_c,"allow-prod":Lc,login:Oc,logout:Mc,screenshot:async(e,t)=>{let n=En(e);return n.mode==="capture"?wi(n.rest,t):n.mode==="checklist"?rn():qo(e,t)},capture:wi,"capture-setup":rn,devhints:ll,inbox:zc,"catch-up":Kc,update:Qc,reset:nu,check:ou,review:au,reorder:lu,structure:iu,genre:ar,roadmap:mu};function wu(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}it();var lg="Or just tell me what to write or update.",cg='\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 de(e){return e===1?"":"s"}function ur(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Hn(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var ug={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 dg(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:ug,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${de(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.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${de(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
363
- \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${de(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${de(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${de(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${de(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${de(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${de(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${de(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${de(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${de(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${de(n)}.`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${de(n)} under .d360-writer/ \u2014 a commit request is standing in your builder's mailbox (the sync bookkeeping in there protects against duplicate publishes)`,lead:null,picker:null,follow:null})}return t}function yu(e){return e.find(t=>t.lead||t.picker)??null}function Oi(e,t){let n=t.filter(l=>l.bullet).map(l=>` \u2022 ${l.bullet}`),o=yu(t),r=[];o?.lead?r.push(Hn(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(d=>d!==o).slice(0,2))l.follow&&r.push(l.follow);let s=[[e,...n].join(`
364
- `)];return r.length&&s.push(r.join(" ")),s.push(lg),s.join(`
365
-
366
- `)}function Bn(e){if(!e.ready)return{kind:"idle"};let t=dg(e);if(!e.hasDocs){let s=yu(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:Oi("\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:cg,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${de(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${de(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${de(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:Oi("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:Oi("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as Mi,readdirSync as Wi}from"node:fs";import{spawnSync as pg}from"node:child_process";import{join as dr}from"node:path";import{readProjectConfig as bu,resolveActiveProfile as xu,loadTokens as hg,isExpired as fg,loadProfileMap as $u,localAheadPaths as mg,loadKnownConflicts as gg,readDocsPlan as wg,devHintsGuidePath as yg,DEFAULT_DOCS_DIR as Ui,roadmapProgress as kg,listRoadmap as bg,readProductBriefState as xg,reconcileCommitRequest as $g}from"document360-engine";it();function ku(e){try{return Wi(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Fi(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>ku(dr(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&ku(dr(e,o)))}function qi(e,t){try{let n=bu(e);if(!n)return!1;let o=xu(e,t),r=$u(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=dr(e,(n.docsDir??Ui).replace(/\/+$/,""));return!!(Mi(s)&&Wi(s).length>0||Mi(yg(e)))}catch{return!1}}function Vn(e,t,n){try{let o=bu(e);if(!o)return null;let r=xu(e,t),s=hg(r.name),l=!!s&&(!fg(s)||!!s.refreshToken),d=qi(e,t)||!Fi(e,o.authoritativeSourceFiles),m=$u(e,r.name),k=m?Object.keys(m.articles).length:0,y=dr(e,(o.docsDir??Ui).replace(/\/+$/,"")),v=!1;try{v=Mi(y)&&Wi(y).length>0}catch{}let $=0;if(m?.lastAnalyzedCommit)try{let ve=pg("git",["rev-list","--count",`${m.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});ve.status===0&&($=parseInt((ve.stdout||"").trim(),10)||0)}catch{}let _=0;try{let ve=wg(e);if(ve.length>0){let ht=(o.docsDir??Ui).replace(/\/+$/,"");_=Vs(e,ht,ve.map(Be=>Be.path)).length}}catch{}let R=Wn(e),N=Fn({...R,directives:0}),T=mg(e,t),F=new Set(gg(e,r.name)),z=T.filter(ve=>F.has(ve)).length,K=T.length-z,X=Ne(e),he=kg(e),Je=$g(e,new Date().toISOString()),ge=xg(e),jt=ge?{status:ge.status,openQuestions:ge.openQuestions}:null;return!jt&&v&&bg(e).some(ht=>ht.status==="open"&&(ht.run??"").trim()==="/discover")&&(jt={status:"pending",openQuestions:0}),{ready:l&&d&&!n.claudeMissing,hasDocs:v,tracked:k,pendingText:N,directives:R.directives,behind:$,pendingWrites:_,localAhead:K,conflicts:z,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:X.status,devhintsCompletedVersion:X.completedVersion,devhintsToVersion:le,builderStarted:Xe(e),genreUnknown:n.genreUnknown,roadmap:he,discovery:jt,uncommittedDocs:Je.dirty.length}}catch{return null}}function vu(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 pr(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 d of vu(`${l+1}. ${s.feature}`,76))o.push(n(d));o.push(n());for(let d of vu(s.why,73))o.push(n(` ${d}`));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}H();var vg={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"},Ru=160,Bi=200,Su=40;function Te(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Cu(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}: ${Te(typeof r=="string"?r:JSON.stringify(r),Su)}`);return t.length>4&&n.push("\u2026"),Te(n.join(", "),Ru)}var dt=e=>typeof e=="string"&&e?e:null,Hi=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Cg(e){let t=dt(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 Rg(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=dt(t.title);if(!o)return null;let r=Cg(t.local_path);return n("Create article",`"${Te(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=dt(t.title),r=Hi(t.article_id);return n("Update article",o?`"${Te(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Hi(t.article_id)?`id ${Hi(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",dt(t.name)?`"${Te(dt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=dt(t.file_path);return n("Upload image",o?Te(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function hr(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),l=s.join("__");if(r==="document360"){let k=Rg(l,t);if(k)return k}let d=l.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${d}`,sep:" ",arg:Cu(t)}}let n=vg[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:Te(o,Ru)}:{title:e,sep:"",arg:Cu(t)}}function Sg(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 Pg(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Sg).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Te(r,Bi))]}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}: ${Te(String(r),Su)}`);return n.length>0?[Te(n.join(" \xB7 "),Bi)]:null}return null}function Tg(e){let t=dt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Dg(e,t,n){switch(e){case"d360_create_article":{let o=Tg(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=dt(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 ${Te(o[0],120)}`:""}`]}default:return null}}function fr(e,t=4,n,o){let r=e.replace(/\r\n/g,`
367
- `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let l=Dg(n.slice(18),o,r);if(l)return{lines:l,hidden:0}}let s=Pg(r)??r.split(`
368
- `);return{lines:s.slice(0,t).map(l=>Te(l,Bi)),hidden:Math.max(0,s.length-t)}}function mr(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function gr(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 Pu(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 wr(e){return Pu(e,"url")}function yr(e){return Pu(e,"preview_url")}var Kg=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Xg(e,t,n,o){if(Kg.test(e))try{let r=Au(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,l=gr(t,n),d=wr(n);e.endsWith("publish_article")&&d&&console.log(L(` \u2B95 Live: ${d}`));let m=yr(n);m?console.log(L(` \u2B95 Preview: ${m}`)):l&&s&&console.log(L(` \u2B95 Preview: ${mr(r.connection.portalUrl,s,l,r.project.languageCode??"en")}`))}catch{}}async function ju(e=process.cwd(),t="auto",n,o){let r=jg(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${L("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${L('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Qg(e,n),r.kind==="subscription"&&(r.stored?console.log(g(" Using your Claude subscription (no API key set).")):console.log(g(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,l=Vi({cwd:e,profileName:n,allowProdWrites:s}),d={uuid:null,firstPrompt:null,titleFired:!1},m=Ag({input:process.stdin,output:process.stdout}),k=[],y=null,v=!1;m.on("line",R=>{if(y){let N=y;y=null,N(R)}else k.push(R)}),m.on("close",()=>{if(v=!0,y){let R=y;y=null,R(null)}});function $(){return k.length>0?Promise.resolve(k.shift()):v?Promise.resolve(null):(process.stdout.write(L("> ")),new Promise(R=>{y=R}))}let _={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{l.close(),l=Vi({cwd:e,profileName:n,allowProdWrites:s}),d={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>d.uuid,setPendingName:R=>{d.pendingName=R},setModel:async R=>l.setModel(R),withPausedInput:async R=>{m.pause();try{return await R()}finally{m.resume()}}};try{for(;;){let R=await $();if(R===null)break;let N=R.trim();if(N){if(N.startsWith("/")){let T=wu(N);if(!T)continue;let F=gu[T.name];if(!F){console.log(C(`Unknown command: /${T.name}`)),console.log(g("Type /help for the list."));continue}let z=await F(T.args,_);if(z.kind==="exit")break;if(z.kind==="clear"){_.restartAgent();continue}if(z.kind==="allow-prod"){s=!0,_.restartAgent(),console.log(E("\u2713 Production writes authorized for this session.")),console.log("");continue}if(z.kind==="resume"){l.close(),l=Vi({cwd:e,resume:z.uuid,profileName:n,allowProdWrites:s});let K=Eg(z.uuid);d={uuid:z.uuid,firstPrompt:K?.firstPrompt??null,titleFired:!0},Du(z.uuid),console.log(E(`\u2713 Resumed "${z.name}"`)),console.log("");continue}if(z.kind==="forward-to-agent"){d.firstPrompt||(d.firstPrompt=z.display??z.prompt);let K=(z.display??"").trim().split(/\s+/),X=(K[0]==="/check"||K[0]==="/review")&&K.includes("--fix"),he=K.slice(1).find(ge=>!ge.startsWith("--")),Je=X?Yg(e,he):[];if(await Gi(l,z.prompt,r,d,e),X)try{Gg(e,Je,{reviewedCap:zg})}catch{}}else Jg(e,n);continue}if(qg(N)){let T=Hg(N);if(T){try{Bg(e,{title:T,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}d.firstPrompt||(d.firstPrompt=N),await Gi(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,d,e);continue}}d.firstPrompt||(d.firstPrompt=N),await Gi(l,N,r,d,e)}}}finally{l.close(),m.close()}}function Qg(e,t){console.log(""),console.log(Cn("document360-writer")),console.log(g(` cwd: ${e}`));let n=Og(e);if(console.log(g(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Zg(e,t)),!Mg(e))console.log(M(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{let o=!1;try{if(No(e),!Xe(e))for(let r of Io(e))console.log(M(` ${r}`))}catch{}try{let r=Ug(e);r.persisted&&r.appType?console.log(g(` \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=Vg(e);for(let s of pr(r.applied))console.log(M(` ${s}`))}catch{}try{let r=Vn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Bn(r):null;if(s?.kind==="recommend"&&s.rec.note){let l=s.rec.tone==="warn"?M:g;for(let d of fs(s.rec.note).split(`
369
- `))console.log(l(` ${d}`));s.rec.picker&&console.log(L(` Pick one: ${s.rec.picker.options.map(d=>d.cmd).join(" \xB7 ")}`))}}catch{}}console.log(g(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Jg(e,t){try{let n=Vn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Bn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(g(` Next: ${Hn(o.rec.lead)}`))}catch{}}function Zg(e,t){try{let n=Au(e,t),o=n.production?M(" \u26A0 PRODUCTION"):"",r=Fg(n.name);if(!r)return g(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Tu(r.idToken)??{},...Tu(r.accessToken)??{}},l=s.email??s.preferred_username??"signed in";return Wg(r)&&!r.refreshToken?M(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):g(` Document360: ${l} \xB7 profile "${n.name}"${o}`)}catch(n){return g(` Document360: ${n.message.split(".")[0]}`)}}function ew(){console.error(""),console.error(`Sign in with your Claude subscription: run ${L("claude")} once, then retry.`),console.error(` (No Claude Code? ${L("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${L("https://console.anthropic.com/settings/keys")}`)}function tw(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;_g({uuid:t,name:r??Ig(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function nw(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Lg(o,t).then(r=>{r&&Ng(n,r)}).catch(()=>{})}async function Gi(e,t,n,o,r){let s=new Map;for await(let l of e.send(t))ow(l,o,r,n,s)}function ow(e,t,n,o,r){switch(e.type){case"session":t.uuid||tw(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=hr(e.name,e.input);s&&(process.stdout.write(`
370
-
371
- `),console.log(`${E("\u25CF")} ${xe(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=Qe(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let l=d=>d===1?"":"s";console.log(ae(` \u23BF Added ${s.added} line${l(s.added)}, removed ${s.removed} line${l(s.removed)}`));for(let d of s.lines)console.log(d);s.hidden>0&&console.log(g(` \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=fr(e.output,4,e.isError?void 0:s.name,s.input),d=e.isError?C:ae;l.lines.forEach((m,k)=>console.log(d((k===0?" \u23BF ":" ")+m))),l.hidden>0&&console.log(g(` \u2026 +${l.hidden} lines`)),e.isError||Xg(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
372
- `);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(g(` (${An(s)}\u2192${An(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Du(t.uuid),t.titleFired||nw(t,n));break}case"error":console.error(""),console.error(C(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&ew();break}}import{render as yy}from"ink";import{resolveAuth as ky}from"document360-engine";import{useCallback as G,useEffect as Ae,useMemo as Ji,useRef as ee,useState as B}from"react";import{Box as se,Text as A,useApp as yw,useInput as kw,useStdout as bw}from"ink";import{existsSync as ln,readFileSync as Sr,readdirSync as xw}from"node:fs";import{basename as Yn,isAbsolute as $w,join as Zi}from"node:path";import{createSession as nd,classifyClaudeAuth as sa,CLAUDE_CODE_SETUP_HINT as vw,loginPkce as Cw,toStoredTokens as Rw,saveTokens as Sw,getAccessToken as Pw,resolveActiveProfile as De,resolveProjectId as Tw,getArticle as Dw,decodeJwtClaims as un,isExpired as pt,loadTokens as At,clearTokens as Aw,clearProfileProject as jw,setTitle as Ew,slugify as Nw,touchSession as ea,upsertSession as Iw,generateTitle as od,findByName as _w,listSessions as Lw,renameSession as Ow,suggestNextAction as Mw,readProjectConfig as re,writeProjectConfig as rd,resolveAndPersistAppType as Uw,detectAppType as Ww,resolveModelSetting as ia,loadProfileMap as sd,applyPull as id,computeSyncStatus as ta,lintDocs as ad,compareRemoteSources as Fw,planPull as ld,establishBaselines as qw,rebaselineServerMeta as Hw,inventoryRepo as Bw,knownEnvironments as Vw,resolveEnvironment as Gw,planPartitions as na,partitionEvenly as Yw,screenshotPlaceholderIds as zw,trackedArticlePaths as Kw,runPartitioned as Pr,estimateBulkCost as cd,resolveModelForOperation as Tr,readDocsPlan as Xw,checkForUpdate as Qw,detectInstallKind as Jw,isSelfUpdatable as Zw,devHintsGuidePath as ud,toolFeedbackPath as dd,reconcileToolFeedback as ey,reconcileUpgradeActions as ty,stampArticles as oa,listArticleFiles as pd,CONTENT_CAP_VERSION as ra,ENGINE_VERSION as bd,DEFAULT_DOCS_DIR as xd,setProfileProject as ny,writeCrashLog as oy,applyStructureOrder as hd,orderSyncLine as fd,applyRelatedArticles as md,relatedSyncLine as gd}from"document360-engine";it();import{spawn as Eu}from"node:child_process";function rw(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function sw(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?Eu([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Eu(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 Yi(e){for(let[t,n]of rw())if(await sw(t,n,e))return!0;return!1}var iw=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function zi(e,t){if(t.closed)return e;let n=e.split(`
373
- `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){iw.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(`
374
- `)}import{existsSync as aw,mkdirSync as lw,readFileSync as cw,writeFileSync as uw}from"node:fs";import{join as Nu}from"node:path";import{writerDir as dw}from"document360-engine";function Iu(e){return Nu(dw(e),".sessions")}function _u(e,t){return Nu(Iu(e),`${t}.json`)}function Lu(e,t,n){try{lw(Iu(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");uw(_u(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Ki(e,t){try{let n=_u(e,t);if(!aw(n))return[];let o=JSON.parse(cw(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var pw=e=>`\x1B]0;${e}\x07`,hw=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Ou(e){process.stdout.isTTY&&process.stdout.write(e)}function an(e){Ou(pw(e))}function kr(e){Ou(hw(e))}var br=["\xB7 "," \xB7"],xr="\u{1F7E3}";er();Oo();H();import{Box as Mu,Text as ue}from"ink";import{jsx as pe,jsxs as $r}from"react/jsx-runtime";function fw({row:e}){switch(e.t){case"head":return pe(ue,{color:V,bold:!0,children:e.s});case"text":return pe(ue,{children:e.s});case"dim":return pe(ue,{dimColor:!0,children:e.s});case"sub":return pe(ue,{bold:!0,dimColor:!0,children:e.s});case"good":return pe(ue,{color:"green",children:e.s});case"step":return $r(ue,{children:[pe(ue,{color:V,children:`${e.n}. `}),e.s]});case"cmd":return $r(ue,{children:[" ",pe(ue,{color:V,children:e.name.padEnd(20)}),pe(ue,{dimColor:!0,children:e.s})]});case"gap":return pe(ue,{children:" "})}}function Uu({tab:e,width:t,version:n,engineVersion:o}){let r=Ee[e]??Ee[0],s=6+Ee.reduce((d,m)=>d+m.label.length+4,0),l="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return $r(Mu,{flexDirection:"column",paddingX:1,children:[$r(ue,{children:[pe(ue,{color:V,bold:!0,children:"Help "}),Ee.map((d,m)=>m===e?pe(ue,{color:"white",backgroundColor:V,bold:!0,children:` ${d.label} `},d.key):pe(ue,{dimColor:!0,children:` ${d.label} `},d.key))]}),pe(ue,{color:V,children:l}),pe(Mu,{flexDirection:"column",marginTop:1,children:r.rows.map((d,m)=>pe(fw,{row:d},m))}),pe(ue,{dimColor:!0,children:`
375
- \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var mw=/^(?:\d+[.)]|[-*•])\s+/;function Wu(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
376
- `)){let l=s.trim().replace(mw,""),d=l.match(/^`([^`]+)`$/);d&&(l=d[1].trim());let m=l.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!m||!o.has(m[1].toLowerCase()))continue;let k=`/${m[1].toLowerCase()}${m[2]?` ${m[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}H();function Gn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function _e(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Fu(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var gw=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function qu(e,t,n){if(!gw.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(s=>{let l=s.replace(/\\/g,"/");return r===l||r.endsWith(`/${l}`)})??null}function Xi(e){return e.replace(/^[\w.-]+\//,"")}var vr=16,Hu={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Dt(e){return typeof e=="string"?e:e.cmd}function Bu(e){return typeof e=="string"?void 0:e.desc}function Qi(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Vu(e,t){let n=Qi(t);return e.some(r=>Dt(r).trim()===t.trim()||!!n&&Qi(Dt(r))===n)?e.filter(r=>Dt(r).trim()!==t.trim()&&!(n&&Qi(Dt(r))===n)):[]}import{isDirectiveMention as ry,stripDirectiveMention as sy,appendDirective as iy}from"document360-engine";var ww=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Gu(e){return e.replace(/\r\n?/g,`
377
- `)}function Yu(e){return e.includes(`
378
- `)||e.length>200}function zu(e,t){let n=t.split(`
379
- `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Ku(e,t){return e.replace(ww,n=>t.get(n)??n)}function Xu(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Cr(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
380
- `)){if(s.length===0)o.push({start:r,end:r});else for(let l=0;l<s.length;l+=n)o.push({start:r+l,end:r+Math.min(l+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function Rr(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Qu(e,t,n){let o=Rr(e,t),r=o+n;if(r<0||r>=e.length)return t;let s=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+s,e[r].end)}function Ju(e,t,n){let o=e[Rr(e,t)];return n==="start"?o.start:o.end}function Zu(e,t,n){let o=Math.max(1,n),r=e.split(`
362
+ `):null}async function ku(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=ur(n,e.slice(1).join(" ").trim());return console.log(r.ok?N(r.line):M(r.line)),{kind:"continue"}}let o=Oi(n);console.log(L(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?g(r):r);return{kind:"continue"}}var bu={help:ts,"?":ts,clear:Za,exit:ns,quit:ns,init:as,mcp:Mo,publish:zl,audit:Ln,discover:Kl,scope:Ql,pull:lc,resolve:sc,convert:cc,write:mc,draft:bc,document:$c,resume:Cc,rename:Rc,profile:Pc,model:Ac,doctor:Un,workspace:Mc,project:Uc,"allow-prod":Wc,login:Fc,logout:qc,screenshot:async(e,t)=>{let n=Nn(e);return n.mode==="capture"?ki(n.rest,t):n.mode==="checklist"?rn():qo(e,t)},capture:ki,"capture-setup":rn,devhints:ul,inbox:Jc,"catch-up":Zc,update:tu,reset:iu,check:au,review:du,reorder:pu,structure:uu,genre:lr,roadmap:ku};function $u(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}it();var gg="Or just tell me what to write or update.",wg='\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 de(e){return e===1?"":"s"}function dr(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Bn(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var yg={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 kg(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:yg,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${de(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.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${de(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
363
+ \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${de(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${de(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${de(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${de(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${de(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${de(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${de(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${de(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${de(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${de(n)}.`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${de(n)} under .d360-writer/ \u2014 a commit request is standing in your builder's mailbox (the sync bookkeeping in there protects against duplicate publishes)`,lead:null,picker:null,follow:null})}return t}function xu(e){return e.find(t=>t.lead||t.picker)??null}function Ui(e,t){let n=t.filter(l=>l.bullet).map(l=>` \u2022 ${l.bullet}`),o=xu(t),r=[];o?.lead?r.push(Bn(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(d=>d!==o).slice(0,2))l.follow&&r.push(l.follow);let s=[[e,...n].join(`
364
+ `)];return r.length&&s.push(r.join(" ")),s.push(gg),s.join(`
365
+
366
+ `)}function Vn(e){if(!e.ready)return{kind:"idle"};let t=kg(e);if(!e.hasDocs){let s=xu(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:Ui("\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:wg,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${de(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${de(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${de(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:Ui("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:Ui("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as Wi,readdirSync as qi}from"node:fs";import{spawnSync as bg}from"node:child_process";import{join as pr}from"node:path";import{readProjectConfig as Cu,resolveActiveProfile as Ru,loadTokens as $g,isExpired as xg,loadProfileMap as Su,localAheadPaths as vg,loadKnownConflicts as Cg,readDocsPlan as Rg,devHintsGuidePath as Sg,DEFAULT_DOCS_DIR as Fi,roadmapProgress as Pg,listRoadmap as Tg,readProductBriefState as Dg,reconcileCommitRequest as Ag}from"document360-engine";it();function vu(e){try{return qi(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Hi(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>vu(pr(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&vu(pr(e,o)))}function Bi(e,t){try{let n=Cu(e);if(!n)return!1;let o=Ru(e,t),r=Su(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=pr(e,(n.docsDir??Fi).replace(/\/+$/,""));return!!(Wi(s)&&qi(s).length>0||Wi(Sg(e)))}catch{return!1}}function Gn(e,t,n){try{let o=Cu(e);if(!o)return null;let r=Ru(e,t),s=$g(r.name),l=!!s&&(!xg(s)||!!s.refreshToken),d=Bi(e,t)||!Hi(e,o.authoritativeSourceFiles),m=Su(e,r.name),y=m?Object.keys(m.articles).length:0,b=pr(e,(o.docsDir??Fi).replace(/\/+$/,"")),v=!1;try{v=Wi(b)&&qi(b).length>0}catch{}let x=0;if(m?.lastAnalyzedCommit)try{let ve=bg("git",["rev-list","--count",`${m.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});ve.status===0&&(x=parseInt((ve.stdout||"").trim(),10)||0)}catch{}let I=0;try{let ve=Rg(e);if(ve.length>0){let ht=(o.docsDir??Fi).replace(/\/+$/,"");I=Gs(e,ht,ve.map(Be=>Be.path)).length}}catch{}let P=Fn(e),j=qn({...P,directives:0}),D=vg(e,t),U=new Set(Cg(e,r.name)),G=D.filter(ve=>U.has(ve)).length,K=D.length-G,X=Ne(e),he=Pg(e),Je=Ag(e,new Date().toISOString()),ge=Dg(e),jt=ge?{status:ge.status,openQuestions:ge.openQuestions}:null;return!jt&&v&&Tg(e).some(ht=>ht.status==="open"&&(ht.run??"").trim()==="/discover")&&(jt={status:"pending",openQuestions:0}),{ready:l&&d&&!n.claudeMissing,hasDocs:v,tracked:y,pendingText:j,directives:P.directives,behind:x,pendingWrites:I,localAhead:K,conflicts:G,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:X.status,devhintsCompletedVersion:X.completedVersion,devhintsToVersion:le,builderStarted:Xe(e),genreUnknown:n.genreUnknown,roadmap:he,discovery:jt,uncommittedDocs:Je.dirty.length}}catch{return null}}function Pu(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 hr(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 d of Pu(`${l+1}. ${s.feature}`,76))o.push(n(d));o.push(n());for(let d of Pu(s.why,73))o.push(n(` ${d}`));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}H();var jg={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"},Du=160,Gi=200,Au=40;function Te(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Tu(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}: ${Te(typeof r=="string"?r:JSON.stringify(r),Au)}`);return t.length>4&&n.push("\u2026"),Te(n.join(", "),Du)}var dt=e=>typeof e=="string"&&e?e:null,Vi=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Eg(e){let t=dt(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 Ng(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=dt(t.title);if(!o)return null;let r=Eg(t.local_path);return n("Create article",`"${Te(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=dt(t.title),r=Vi(t.article_id);return n("Update article",o?`"${Te(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Vi(t.article_id)?`id ${Vi(t.article_id)}\u2026`:null);case"d360_publish_article":{let o=t.version_number;return n("Publish article LIVE",typeof o=="number"?`v${o}`:null)}case"d360_unpublish_article":return n("Unpublish article",null);case"d360_create_category":return n("Create category",dt(t.name)?`"${Te(dt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=dt(t.file_path);return n("Upload image",o?Te(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function fr(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),l=s.join("__");if(r==="document360"){let y=Ng(l,t);if(y)return y}let d=l.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${d}`,sep:" ",arg:Tu(t)}}let n=jg[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:Te(o,Du)}:{title:e,sep:"",arg:Tu(t)}}function Ig(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 _g(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Ig).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Te(r,Gi))]}if(t!==null&&typeof t=="object"){let n=Object.entries(t).filter(([,o])=>o!==null&&(typeof o=="string"||typeof o=="number"||typeof o=="boolean")).slice(0,6).map(([o,r])=>`${o}: ${Te(String(r),Au)}`);return n.length>0?[Te(n.join(" \xB7 "),Gi)]:null}return null}function Lg(e){let t=dt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Og(e,t,n){switch(e){case"d360_create_article":{let o=Lg(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=dt(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 ${Te(o[0],120)}`:""}`]}default:return null}}function mr(e,t=4,n,o){let r=e.replace(/\r\n/g,`
367
+ `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let l=Og(n.slice(18),o,r);if(l)return{lines:l,hidden:0}}let s=_g(r)??r.split(`
368
+ `);return{lines:s.slice(0,t).map(l=>Te(l,Gi)),hidden:Math.max(0,s.length-t)}}function gr(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function wr(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 ju(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 yr(e){return ju(e,"url")}function kr(e){return ju(e,"preview_url")}var ow=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function rw(e,t,n,o){if(ow.test(e))try{let r=Iu(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,l=wr(t,n),d=yr(n);e.endsWith("publish_article")&&d&&console.log(L(` \u2B95 Live: ${d}`));let m=kr(n);m?console.log(L(` \u2B95 Preview: ${m}`)):l&&s&&console.log(L(` \u2B95 Preview: ${gr(r.connection.portalUrl,s,l,r.project.languageCode??"en")}`))}catch{}}async function _u(e=process.cwd(),t="auto",n,o){let r=Ug(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${L("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${L('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),sw(e,n),r.kind==="subscription"&&(r.stored?console.log(g(" Using your Claude subscription (no API key set).")):console.log(g(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,l=Yi({cwd:e,profileName:n,allowProdWrites:s}),d={uuid:null,firstPrompt:null,titleFired:!1},m=Mg({input:process.stdin,output:process.stdout}),y=[],b=null,v=!1;m.on("line",P=>{if(b){let j=b;b=null,j(P)}else y.push(P)}),m.on("close",()=>{if(v=!0,b){let P=b;b=null,P(null)}});function x(){return y.length>0?Promise.resolve(y.shift()):v?Promise.resolve(null):(process.stdout.write(L("> ")),new Promise(P=>{b=P}))}let I={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{l.close(),l=Yi({cwd:e,profileName:n,allowProdWrites:s}),d={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>d.uuid,setPendingName:P=>{d.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 x();if(P===null)break;let j=P.trim();if(j){if(j.startsWith("/")){let D=$u(j);if(!D)continue;let U=bu[D.name];if(!U){console.log(C(`Unknown command: /${D.name}`)),console.log(g("Type /help for the list."));continue}let G=await U(D.args,I);if(G.kind==="exit")break;if(G.kind==="clear"){I.restartAgent();continue}if(G.kind==="allow-prod"){s=!0,I.restartAgent(),console.log(N("\u2713 Production writes authorized for this session.")),console.log("");continue}if(G.kind==="resume"){l.close(),l=Yi({cwd:e,resume:G.uuid,profileName:n,allowProdWrites:s});let K=Wg(G.uuid);d={uuid:G.uuid,firstPrompt:K?.firstPrompt??null,titleFired:!0},Nu(G.uuid),console.log(N(`\u2713 Resumed "${G.name}"`)),console.log("");continue}if(G.kind==="forward-to-agent"){d.firstPrompt||(d.firstPrompt=G.display??G.prompt);let K=(G.display??"").trim().split(/\s+/),X=(K[0]==="/check"||K[0]==="/review")&&K.includes("--fix"),he=K.slice(1).find(ge=>!ge.startsWith("--")),Je=X?tw(e,he):[];if(await zi(l,G.prompt,r,d,e),X)try{ew(e,Je,{reviewedCap:nw})}catch{}}else iw(e,n);continue}if(Xg(j)){let D=Qg(j);if(D){try{Jg(e,{title:D,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}d.firstPrompt||(d.firstPrompt=j),await zi(l,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${D}". 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 "${D}" and the article path(s) you wrote.`,r,d,e);continue}}d.firstPrompt||(d.firstPrompt=j),await zi(l,j,r,d,e)}}}finally{l.close(),m.close()}}function sw(e,t){console.log(""),console.log(Rn("document360-writer")),console.log(g(` cwd: ${e}`));let n=Vg(e);if(console.log(g(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(aw(e,t)),!Gg(e))console.log(M(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{let o=!1;try{if(No(e),!Xe(e))for(let r of Io(e))console.log(M(` ${r}`))}catch{}try{let r=Yg(e);r.persisted&&r.appType?console.log(g(` \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=Zg(e);for(let s of hr(r.applied))console.log(M(` ${s}`))}catch{}try{let r=Gn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Vn(r):null;if(s?.kind==="recommend"&&s.rec.note){let l=s.rec.tone==="warn"?M:g;for(let d of ms(s.rec.note).split(`
369
+ `))console.log(l(` ${d}`));s.rec.picker&&console.log(L(` Pick one: ${s.rec.picker.options.map(d=>d.cmd).join(" \xB7 ")}`))}}catch{}}console.log(g(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function iw(e,t){try{let n=Gn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Vn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(g(` Next: ${Bn(o.rec.lead)}`))}catch{}}function aw(e,t){try{let n=Iu(e,t),o=n.production?M(" \u26A0 PRODUCTION"):"",r=Kg(n.name);if(!r)return g(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Eu(r.idToken)??{},...Eu(r.accessToken)??{}},l=s.email??s.preferred_username??"signed in";return zg(r)&&!r.refreshToken?M(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):g(` Document360: ${l} \xB7 profile "${n.name}"${o}`)}catch(n){return g(` Document360: ${n.message.split(".")[0]}`)}}function lw(){console.error(""),console.error(`Sign in with your Claude subscription: run ${L("claude")} once, then retry.`),console.error(` (No Claude Code? ${L("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${L("https://console.anthropic.com/settings/keys")}`)}function cw(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Hg({uuid:t,name:r??qg(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function uw(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Bg(o,t).then(r=>{r&&Fg(n,r)}).catch(()=>{})}async function zi(e,t,n,o,r){let s=new Map;for await(let l of e.send(t))dw(l,o,r,n,s)}function dw(e,t,n,o,r){switch(e.type){case"session":t.uuid||cw(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=fr(e.name,e.input);s&&(process.stdout.write(`
370
+
371
+ `),console.log(`${N("\u25CF")} ${$e(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=Qe(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let l=d=>d===1?"":"s";console.log(ae(` \u23BF Added ${s.added} line${l(s.added)}, removed ${s.removed} line${l(s.removed)}`));for(let d of s.lines)console.log(d);s.hidden>0&&console.log(g(` \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=mr(e.output,4,e.isError?void 0:s.name,s.input),d=e.isError?C:ae;l.lines.forEach((m,y)=>console.log(d((y===0?" \u23BF ":" ")+m))),l.hidden>0&&console.log(g(` \u2026 +${l.hidden} lines`)),e.isError||rw(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
372
+ `);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(g(` (${jn(s)}\u2192${jn(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Nu(t.uuid),t.titleFired||uw(t,n));break}case"error":console.error(""),console.error(C(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&lw();break}}import{render as Sy}from"ink";import{resolveAuth as Py}from"document360-engine";import{useCallback as Y,useEffect as Ae,useMemo as ea,useRef as ee,useState as B}from"react";import{Box as se,Text as A,useApp as Sw,useInput as Pw,useStdout as Tw}from"ink";import{existsSync as ln,readFileSync as Pr,readdirSync as Dw}from"node:fs";import{basename as zn,isAbsolute as Aw,join as ta}from"node:path";import{createSession as id,classifyClaudeAuth as aa,CLAUDE_CODE_SETUP_HINT as jw,loginPkce as Ew,toStoredTokens as Nw,saveTokens as Iw,getAccessToken as _w,resolveActiveProfile as De,resolveProjectId as Lw,getArticle as Ow,decodeJwtClaims as un,isExpired as pt,loadTokens as At,clearTokens as Mw,clearProfileProject as Uw,setTitle as Ww,slugify as Fw,touchSession as na,upsertSession as qw,generateTitle as ad,findByName as Hw,listSessions as Bw,renameSession as Vw,suggestNextAction as Gw,readProjectConfig as re,writeProjectConfig as ld,resolveAndPersistAppType as Yw,detectAppType as zw,resolveModelSetting as la,loadProfileMap as cd,applyPull as ud,computeSyncStatus as oa,lintDocs as dd,compareRemoteSources as Kw,planPull as pd,establishBaselines as Xw,rebaselineServerMeta as Qw,inventoryRepo as Jw,knownEnvironments as Zw,resolveEnvironment as ey,planPartitions as ra,partitionEvenly as ty,screenshotPlaceholderIds as ny,trackedArticlePaths as oy,runPartitioned as Tr,estimateBulkCost as hd,resolveModelForOperation as Dr,readDocsPlan as ry,checkForUpdate as sy,detectInstallKind as iy,isSelfUpdatable as ay,devHintsGuidePath as fd,toolFeedbackPath as md,reconcileToolFeedback as ly,reconcileUpgradeActions as cy,stampArticles as sa,listArticleFiles as gd,CONTENT_CAP_VERSION as ia,ENGINE_VERSION as Cd,DEFAULT_DOCS_DIR as Rd,setProfileProject as uy,writeCrashLog as dy,applyStructureOrder as wd,orderSyncLine as yd,applyRelatedArticles as kd,relatedSyncLine as bd}from"document360-engine";ci();it();import{spawn as Lu}from"node:child_process";function pw(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function hw(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?Lu([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Lu(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 Ki(e){for(let[t,n]of pw())if(await hw(t,n,e))return!0;return!1}var fw=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Xi(e,t){if(t.closed)return e;let n=e.split(`
373
+ `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){fw.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(`
374
+ `)}import{existsSync as mw,mkdirSync as gw,readFileSync as ww,writeFileSync as yw}from"node:fs";import{join as Ou}from"node:path";import{writerDir as kw}from"document360-engine";function Mu(e){return Ou(kw(e),".sessions")}function Uu(e,t){return Ou(Mu(e),`${t}.json`)}function Wu(e,t,n){try{gw(Mu(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");yw(Uu(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Qi(e,t){try{let n=Uu(e,t);if(!mw(n))return[];let o=JSON.parse(ww(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var bw=e=>`\x1B]0;${e}\x07`,$w=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Fu(e){process.stdout.isTTY&&process.stdout.write(e)}function an(e){Fu(bw(e))}function br(e){Fu($w(e))}var $r=["\xB7 "," \xB7"],xr="\u{1F7E3}";tr();Oo();H();import{Box as qu,Text as ue}from"ink";import{jsx as pe,jsxs as vr}from"react/jsx-runtime";function xw({row:e}){switch(e.t){case"head":return pe(ue,{color:V,bold:!0,children:e.s});case"text":return pe(ue,{children:e.s});case"dim":return pe(ue,{dimColor:!0,children:e.s});case"sub":return pe(ue,{bold:!0,dimColor:!0,children:e.s});case"good":return pe(ue,{color:"green",children:e.s});case"step":return vr(ue,{children:[pe(ue,{color:V,children:`${e.n}. `}),e.s]});case"cmd":return vr(ue,{children:[" ",pe(ue,{color:V,children:e.name.padEnd(20)}),pe(ue,{dimColor:!0,children:e.s})]});case"gap":return pe(ue,{children:" "})}}function Hu({tab:e,width:t,version:n,engineVersion:o}){let r=Ee[e]??Ee[0],s=6+Ee.reduce((d,m)=>d+m.label.length+4,0),l="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return vr(qu,{flexDirection:"column",paddingX:1,children:[vr(ue,{children:[pe(ue,{color:V,bold:!0,children:"Help "}),Ee.map((d,m)=>m===e?pe(ue,{color:"white",backgroundColor:V,bold:!0,children:` ${d.label} `},d.key):pe(ue,{dimColor:!0,children:` ${d.label} `},d.key))]}),pe(ue,{color:V,children:l}),pe(qu,{flexDirection:"column",marginTop:1,children:r.rows.map((d,m)=>pe(xw,{row:d},m))}),pe(ue,{dimColor:!0,children:`
375
+ \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var vw=/^(?:\d+[.)]|[-*•])\s+/;function Bu(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
376
+ `)){let l=s.trim().replace(vw,""),d=l.match(/^`([^`]+)`$/);d&&(l=d[1].trim());let m=l.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!m||!o.has(m[1].toLowerCase()))continue;let y=`/${m[1].toLowerCase()}${m[2]?` ${m[2]}`:""}`;if(r.includes(y)||r.push(y),r.length>=n)break}return r}H();function Yn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function _e(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Vu(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Cw=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Gu(e,t,n){if(!Cw.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(s=>{let l=s.replace(/\\/g,"/");return r===l||r.endsWith(`/${l}`)})??null}function Ji(e){return e.replace(/^[\w.-]+\//,"")}var Cr=16,Yu={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Dt(e){return typeof e=="string"?e:e.cmd}function zu(e){return typeof e=="string"?void 0:e.desc}function Zi(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Ku(e,t){let n=Zi(t);return e.some(r=>Dt(r).trim()===t.trim()||!!n&&Zi(Dt(r))===n)?e.filter(r=>Dt(r).trim()!==t.trim()&&!(n&&Zi(Dt(r))===n)):[]}import{isDirectiveMention as py,stripDirectiveMention as hy,appendDirective as fy}from"document360-engine";var Rw=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Xu(e){return e.replace(/\r\n?/g,`
377
+ `)}function Qu(e){return e.includes(`
378
+ `)||e.length>200}function Ju(e,t){let n=t.split(`
379
+ `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Zu(e,t){return e.replace(Rw,n=>t.get(n)??n)}function ed(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Rr(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
380
+ `)){if(s.length===0)o.push({start:r,end:r});else for(let l=0;l<s.length;l+=n)o.push({start:r+l,end:r+Math.min(l+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function Sr(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function td(e,t,n){let o=Sr(e,t),r=o+n;if(r<0||r>=e.length)return t;let s=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+s,e[r].end)}function nd(e,t,n){let o=e[Sr(e,t)];return n==="start"?o.start:o.end}function od(e,t,n){let o=Math.max(1,n),r=e.split(`
381
381
  `),s=0;for(let l=r.length-1;l>=0;l--){let d=r[l];if(s+=Math.max(1,Math.ceil(d.length/o)),s>=t){let m=s-t;return{text:[m>0?d.slice(m*o):d,...r.slice(l+1)].join(`
382
- `),truncated:l>0||m>0}}}return{text:e,truncated:!1}}function ed(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 td(e){let t=!1,n=0,o=0;for(let r of e.split(`
383
- `)){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 zn,jsx as j,jsxs as Y}from"react/jsx-runtime";var ay={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},wd=` 1. /init \u2014 pick your Document360 environment & scaffold config
382
+ `),truncated:l>0||m>0}}}return{text:e,truncated:!1}}function rd(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 sd(e){let t=!1,n=0,o=0;for(let r of e.split(`
383
+ `)){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 Kn,jsx as E,jsxs as z}from"react/jsx-runtime";var my={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},$d=` 1. /init \u2014 pick your Document360 environment & scaffold config
384
384
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
385
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function ly(e,t,n,o){let r=sa(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=ia(e),d=re(e),m=(d?.docsDir??xd).replace(/\/+$/,""),k=d?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${m}/ + config`,y={version:t,engineVersion:bd,claude:s,model:l.model,modelSource:ay[l.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:d!==null,mode:k};if(d===null)return y;try{let v=De(e,o);y.profile=v.name,y.apiUrl=v.connection.apiUrl,y.prod=v.production,y.project=v.project.projectName??v.project.projectId??"(chosen at login)";let $=At(v.name);if($){let _={...un($.idToken)??{},...un($.accessToken)??{}},R=_.email??_.preferred_username??"signed in";pt($)?$.refreshToken&&(y.who=R,y.loggedOut=!1,y.sessionHint="session expired \u2014 refreshing\u2026"):(y.who=R,y.loggedOut=!1,y.sessionHint=`session valid until ${new Date($.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return y}function cy(e,t){try{let n=De(e,t),o=At(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...un(o.idToken)??{},...un(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return pt(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 yd=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],dn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],uy="Ask me to write or update an article\u2026";function cn({ch:e,dim:t}){let[n,o]=B(!0);return Ae(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),j(A,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var dy=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function kd(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var py=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function hy({startTime:e,chars:t}){let[n,o]=B(0);Ae(()=>{let m=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(m)},[]);let r=dn[n%dn.length],s=yd[Math.floor(n/16)%yd.length],l=Math.floor((Date.now()-e)/1e3),d=Math.round(t/4);return Y(se,{children:[j(A,{color:V,children:` ${r} ${s}\u2026 `}),j(A,{color:"gray",children:`(${jn(l)} \xB7 ~${d} tokens \xB7 esc to interrupt)`})]})}function fy({text:e}){let[t,n]=B(0);return Ae(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),j(se,{paddingX:1,children:j(A,{color:V,children:`${dn[t%dn.length]} ${e}`})})}var my=12e4;function gy({p:e}){let[t,n]=B(0);Ae(()=>{let T=setInterval(()=>n(F=>F+1),150);return()=>clearInterval(T)},[]);let o=dn[t%dn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),l=Math.round(e.chars/4),d=Date.now()-e.lastAt>=my,m=e.verb??"Converting",k=e.unit??"article",y=e.rows.reduce((T,F)=>T+F.items,0),v=m.toLowerCase(),$=e.rows,_=0;if($.length>vr){let T=$.findIndex(z=>z.status==="active"||z.status==="pending"),F=Math.max(0,Math.min(T-2,$.length-vr));_=$.slice(0,F).filter(z=>z.status==="done").length,$=$.slice(F,F+vr)}let R=Math.min(40,Math.max(...$.map(T=>Xi(T.label).length),0)),N=T=>T==="failed"?"red":T==="active"?V:void 0;return Y(se,{flexDirection:"column",children:[Y(se,{children:[j(A,{color:V,children:` ${o} ${m} ${y} ${k}${y===1?"":"s"} `}),j(A,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${l} tokens \xB7 ${jn(r)} \xB7 esc to stop`})]}),_>0&&j(A,{dimColor:!0,children:` \u2714 +${_} done`}),$.map(T=>Y(A,{color:N(T.status),dimColor:T.status==="done"||T.status==="pending",children:[` ${Hu[T.status]} ${Xi(T.label).padEnd(R)}`,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 ${v}\u2026`:""]},T.label)),d&&j(A,{color:"yellow",children:` \u26A0 no activity for ${jn(s)} \u2014 press esc to stop if it's wedged`})]})}var wy=10800*1e3;function $d({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=yw(),[s,l]=B(n),[d,m]=B(null),[k,y]=B({text:"",pos:0}),v=k.text,$=G(c=>{y(a=>{let i=typeof c=="function"?c(a.text):c;return{text:i,pos:i.length}})},[]),_=G(c=>{y(a=>({text:a.text.slice(0,a.pos)+c+a.text.slice(a.pos),pos:a.pos+c.length}))},[]),R=G(()=>{y(c=>{if(c.pos===0)return c;let a=c.text.slice(0,c.pos),i=Xu(a)??a.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[N,T]=B(!1),[F,z]=B(!1),[K,X]=B(0),[he,Je]=B(!1),[ge,jt]=B(null),[ve,ht]=B(null),[Be,ft]=B([]),Kn=ee(!1),Ar=ee(!1),[jr,ua]=B(!1),Xn=ee(0),[Dd,Qn]=B(!1),[Ad,Jn]=B(!1),[Er,da]=B(null),[jd,Et]=B(0),mt=ee(0),[pn,Nt]=B(0),[It,Zn]=B(null),pa=ee(new Map),Ed=ee(0),_t=ee([]),je=ee(null);je.current===null&&(je.current=nd({cwd:e,profileName:s,allowProdWrites:!1}));let Ve=ee({uuid:null,firstPrompt:null,titleFired:!1}),eo=ee(new Map),Lt=ee(!1),Nr=ee([]),ce=ee([]),Ot=ee([]),to=ee(null),[ha,gt]=B(null),Ir=ee(null),[wt,yt]=B(null),[Ge,Mt]=B(null),[Ye,Ut]=B(null),[we,Wt]=B(null),[Ce,kt]=B(null),[Ze,Ft]=B(null),[et,bt]=B(null),[ze,xt]=B(null),[fa,hn]=B(null),[Re,$t]=B(null),[ke,qt]=B(null),[ma,_r]=B([]),vt=ee([]),fn=ee(!1),fe=ee(null),[no,oe]=B(null),[ga,oo]=B(null),ro=ee(!1),mn=ee(null),gn=ee(null),[Se,Ct]=B(null),[so,wn]=B(null),Lr=!!(Ye||we||Ce||Ze||et||ze||Re||ke||Se||so),[wa,Ht]=B(0),[ya,Bt]=B(0),[Nd,ka]=B(0),Or=Ji(()=>{try{let c=ia(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,Nd]),{stdout:Oe}=bw(),[,Id]=B(0),ba=ee(`${Oe.columns??80}x${Oe.rows??24}`),tt=G(()=>Math.max(20,(Oe.columns??80)-1),[Oe]),u=G(c=>{_t.current.push(c),console.log(ms(c,tt()))},[tt]),ye=G((c,a)=>{Xn.current++,jt(c),ht(a??null)},[]),Me=G(()=>{Xn.current++,jt(null),ht(null)},[]),Q=G(c=>ye(c,ur({kind:"cmd",cmd:c,reason:""})),[ye]),io=G((c,a)=>{!a?.silent&&c.note&&u({kind:"note",tone:c.tone,text:c.note}),c.picker&&(ft(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),hn(c.picker.title)),c.lead&&ye(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,ur(c.lead))},[u,ye]),be=G((c,a,i="info")=>{c&&u({kind:"note",tone:i,text:c}),a&&ye(a.kind==="cmd"?a.cmd:a.text,ur(a))},[u,ye]),[yn,Mr]=B(null),[_d,xa]=B(!1),Vt=G(c=>{Mr(c),xa(!1),u({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),Ur=ee(!1),Wr=G(async()=>{try{if(Ur.current||!Zw(Jw())||re(e)?.mode==="engineer")return;let c=await Qw({pkg:sn,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;Ur.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${sn} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),Jn(!0),(await rr().finally(()=>Jn(!1))).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),Q("/exit"),da(c.latest)):u({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${or}`})}catch{}},[e,o,u,Q]),ao=G(c=>{let a=Ie(e,s);return a.ok?!0:(u({kind:"note",tone:"warn",text:a.reason}),gn.current=c,Q("/login"),!1)},[e,s,u,Q]),[lo,Fr]=B(null),Rt=G(c=>{let a=Vn(e,s,{claudeMissing:sa(t).state==="missing",allowAutoAudit:c,genreUnknown:Ar.current});return a?Bn(a):{kind:"idle"}},[e,s,t]),kn=ee(!0),Gt=ee(!1),co=ee(0),bn=ee(0);Ae(()=>{let c=setInterval(()=>{if(kn.current){co.current=0,bn.current=0;return}if(!N)try{if(!ln(ud(e)))return;if(Ne(e).status==="current"){kn.current=!0,co.current=0,bn.current=0;let i=Rt(!1),f=i.kind==="recommend"?i.rec:null,S=Gt.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.";u({kind:"note",tone:"ok",text:`${S}${f?.lead?` ${Hn(f.lead)}`:""}`}),Mr(null),f&&(f.lead||f.picker)?io(f,{silent:!0}):Gt.current||ye("write the docs for this repo"),X(W=>W+1);return}if(Gt.current)return;co.current+=1;let a=co.current;if((a===4||a%15===0)&&bn.current<3){bn.current+=1;let i=bn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";u({kind:"note",tone:"info",text:Xe(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,u,Rt,io,ye]),Ae(()=>{let c=ha??Yn(e);if(!N){kr(0),an(`${xr} ${c}`);return}kr(3);let a=0;an(`${br[0]} ${c}`);let i=setInterval(()=>{a=(a+1)%br.length,an(`${br[a]} ${c}`)},400);return()=>clearInterval(i)},[N,e,ha]),Ae(()=>()=>kr(0),[]),Ae(()=>{let c=performance.now(),a=[],i=(h,b)=>{let w=performance.now();try{return b()}finally{let D=Math.round(performance.now()-w);D>=80&&a.push(`${h}: ${D}ms`)}};u({kind:"banner",info:i("banner",()=>ly(e,o,t,s))});let f=sa(t).state==="missing";if(f&&u({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
386
- ${vw}
385
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function gy(e,t,n,o){let r=aa(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=la(e),d=re(e),m=(d?.docsDir??Rd).replace(/\/+$/,""),y=d?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${m}/ + config`,b={version:t,engineVersion:Cd,captureVersion:er(),claude:s,model:l.model,modelSource:my[l.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:d!==null,mode:y};if(d===null)return b;try{let v=De(e,o);b.profile=v.name,b.apiUrl=v.connection.apiUrl,b.prod=v.production,b.project=v.project.projectName??v.project.projectId??"(chosen at login)";let x=At(v.name);if(x){let I={...un(x.idToken)??{},...un(x.accessToken)??{}},P=I.email??I.preferred_username??"signed in";pt(x)?x.refreshToken&&(b.who=P,b.loggedOut=!1,b.sessionHint="session expired \u2014 refreshing\u2026"):(b.who=P,b.loggedOut=!1,b.sessionHint=`session valid until ${new Date(x.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return b}function wy(e,t){try{let n=De(e,t),o=At(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...un(o.idToken)??{},...un(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return pt(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 xd=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],dn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],yy="Ask me to write or update an article\u2026";function cn({ch:e,dim:t}){let[n,o]=B(!0);return Ae(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),E(A,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var ky=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function vd(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var by=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function $y({startTime:e,chars:t}){let[n,o]=B(0);Ae(()=>{let m=setInterval(()=>o(y=>y+1),120);return()=>clearInterval(m)},[]);let r=dn[n%dn.length],s=xd[Math.floor(n/16)%xd.length],l=Math.floor((Date.now()-e)/1e3),d=Math.round(t/4);return z(se,{children:[E(A,{color:V,children:` ${r} ${s}\u2026 `}),E(A,{color:"gray",children:`(${En(l)} \xB7 ~${d} tokens \xB7 esc to interrupt)`})]})}function xy({text:e}){let[t,n]=B(0);return Ae(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),E(se,{paddingX:1,children:E(A,{color:V,children:`${dn[t%dn.length]} ${e}`})})}var vy=12e4;function Cy({p:e}){let[t,n]=B(0);Ae(()=>{let D=setInterval(()=>n(U=>U+1),150);return()=>clearInterval(D)},[]);let o=dn[t%dn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),l=Math.round(e.chars/4),d=Date.now()-e.lastAt>=vy,m=e.verb??"Converting",y=e.unit??"article",b=e.rows.reduce((D,U)=>D+U.items,0),v=m.toLowerCase(),x=e.rows,I=0;if(x.length>Cr){let D=x.findIndex(G=>G.status==="active"||G.status==="pending"),U=Math.max(0,Math.min(D-2,x.length-Cr));I=x.slice(0,U).filter(G=>G.status==="done").length,x=x.slice(U,U+Cr)}let P=Math.min(40,Math.max(...x.map(D=>Ji(D.label).length),0)),j=D=>D==="failed"?"red":D==="active"?V:void 0;return z(se,{flexDirection:"column",children:[z(se,{children:[E(A,{color:V,children:` ${o} ${m} ${b} ${y}${b===1?"":"s"} `}),E(A,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${l} tokens \xB7 ${En(r)} \xB7 esc to stop`})]}),I>0&&E(A,{dimColor:!0,children:` \u2714 +${I} done`}),x.map(D=>z(A,{color:j(D.status),dimColor:D.status==="done"||D.status==="pending",children:[` ${Yu[D.status]} ${Ji(D.label).padEnd(P)}`,D.status==="active"&&D.itemsDone!==void 0?` (${D.itemsDone}/${D.items} ${y}${D.items===1?"":"s"})`:D.status!=="pending"?` (${D.items} ${y}${D.items===1?"":"s"})`:"",D.status==="active"?` \u2190 ${v}\u2026`:""]},D.label)),d&&E(A,{color:"yellow",children:` \u26A0 no activity for ${En(s)} \u2014 press esc to stop if it's wedged`})]})}var Ry=10800*1e3;function Sd({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Sw(),[s,l]=B(n),[d,m]=B(null),[y,b]=B({text:"",pos:0}),v=y.text,x=Y(c=>{b(a=>{let i=typeof c=="function"?c(a.text):c;return{text:i,pos:i.length}})},[]),I=Y(c=>{b(a=>({text:a.text.slice(0,a.pos)+c+a.text.slice(a.pos),pos:a.pos+c.length}))},[]),P=Y(()=>{b(c=>{if(c.pos===0)return c;let a=c.text.slice(0,c.pos),i=ed(a)??a.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[j,D]=B(!1),[U,G]=B(!1),[K,X]=B(0),[he,Je]=B(!1),[ge,jt]=B(null),[ve,ht]=B(null),[Be,ft]=B([]),Xn=ee(!1),jr=ee(!1),[Er,pa]=B(!1),Qn=ee(0),[Nd,Jn]=B(!1),[Id,Zn]=B(!1),[Nr,ha]=B(null),[_d,Et]=B(0),mt=ee(0),[pn,Nt]=B(0),[It,eo]=B(null),fa=ee(new Map),Ld=ee(0),_t=ee([]),je=ee(null);je.current===null&&(je.current=id({cwd:e,profileName:s,allowProdWrites:!1}));let Ve=ee({uuid:null,firstPrompt:null,titleFired:!1}),to=ee(new Map),Lt=ee(!1),Ir=ee([]),ce=ee([]),Ot=ee([]),no=ee(null),[ma,gt]=B(null),_r=ee(null),[wt,yt]=B(null),[Ge,Mt]=B(null),[Ye,Ut]=B(null),[we,Wt]=B(null),[Ce,kt]=B(null),[Ze,Ft]=B(null),[et,bt]=B(null),[ze,$t]=B(null),[ga,hn]=B(null),[Re,xt]=B(null),[ke,qt]=B(null),[wa,Lr]=B([]),vt=ee([]),fn=ee(!1),fe=ee(null),[oo,oe]=B(null),[ya,ro]=B(null),so=ee(!1),mn=ee(null),gn=ee(null),[Se,Ct]=B(null),[io,wn]=B(null),Or=!!(Ye||we||Ce||Ze||et||ze||Re||ke||Se||io),[ka,Ht]=B(0),[ba,Bt]=B(0),[Od,$a]=B(0),Mr=ea(()=>{try{let c=la(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,Od]),{stdout:Oe}=Tw(),[,Md]=B(0),xa=ee(`${Oe.columns??80}x${Oe.rows??24}`),tt=Y(()=>Math.max(20,(Oe.columns??80)-1),[Oe]),u=Y(c=>{_t.current.push(c),console.log(gs(c,tt()))},[tt]),ye=Y((c,a)=>{Qn.current++,jt(c),ht(a??null)},[]),Me=Y(()=>{Qn.current++,jt(null),ht(null)},[]),Q=Y(c=>ye(c,dr({kind:"cmd",cmd:c,reason:""})),[ye]),ao=Y((c,a)=>{!a?.silent&&c.note&&u({kind:"note",tone:c.tone,text:c.note}),c.picker&&(ft(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),hn(c.picker.title)),c.lead&&ye(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,dr(c.lead))},[u,ye]),be=Y((c,a,i="info")=>{c&&u({kind:"note",tone:i,text:c}),a&&ye(a.kind==="cmd"?a.cmd:a.text,dr(a))},[u,ye]),[yn,Ur]=B(null),[Ud,va]=B(!1),Vt=Y(c=>{Ur(c),va(!1),u({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),Wr=ee(!1),Fr=Y(async()=>{try{if(Wr.current||!ay(iy())||re(e)?.mode==="engineer")return;let c=await sy({pkg:sn,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;Wr.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${sn} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),Zn(!0),(await sr().finally(()=>Zn(!1))).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),Q("/exit"),ha(c.latest)):u({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${rr}`})}catch{}},[e,o,u,Q]),lo=Y(c=>{let a=Ie(e,s);return a.ok?!0:(u({kind:"note",tone:"warn",text:a.reason}),gn.current=c,Q("/login"),!1)},[e,s,u,Q]),[co,qr]=B(null),Rt=Y(c=>{let a=Gn(e,s,{claudeMissing:aa(t).state==="missing",allowAutoAudit:c,genreUnknown:jr.current});return a?Vn(a):{kind:"idle"}},[e,s,t]),kn=ee(!0),Gt=ee(!1),uo=ee(0),bn=ee(0);Ae(()=>{let c=setInterval(()=>{if(kn.current){uo.current=0,bn.current=0;return}if(!j)try{if(!ln(fd(e)))return;if(Ne(e).status==="current"){kn.current=!0,uo.current=0,bn.current=0;let i=Rt(!1),f=i.kind==="recommend"?i.rec:null,R=Gt.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.";u({kind:"note",tone:"ok",text:`${R}${f?.lead?` ${Bn(f.lead)}`:""}`}),Ur(null),f&&(f.lead||f.picker)?ao(f,{silent:!0}):Gt.current||ye("write the docs for this repo"),X(F=>F+1);return}if(Gt.current)return;uo.current+=1;let a=uo.current;if((a===4||a%15===0)&&bn.current<3){bn.current+=1;let i=bn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";u({kind:"note",tone:"info",text:Xe(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,j,u,Rt,ao,ye]),Ae(()=>{let c=ma??zn(e);if(!j){br(0),an(`${xr} ${c}`);return}br(3);let a=0;an(`${$r[0]} ${c}`);let i=setInterval(()=>{a=(a+1)%$r.length,an(`${$r[a]} ${c}`)},400);return()=>clearInterval(i)},[j,e,ma]),Ae(()=>()=>br(0),[]),Ae(()=>{let c=performance.now(),a=[],i=(h,k)=>{let w=performance.now();try{return k()}finally{let T=Math.round(performance.now()-w);T>=80&&a.push(`${h}: ${T}ms`)}};u({kind:"banner",info:i("banner",()=>gy(e,o,t,s))});let f=aa(t).state==="missing";if(f&&u({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
386
+ ${jw}
387
387
  Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!re(e)){u({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
388
- ${wd}`}),Q(f?"/doctor":"/init");return}f&&Q("/doctor");try{let h=De(e,s),b=At(h.name);b&&pt(b)&&b.refreshToken?Pw({profile:h.name,connection:h.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),X(w=>w+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Q("/login")}):(!b||pt(b))&&(u({kind:"note",tone:"warn",text:`Profile "${h.name}" is not signed in \u2014 sign in with /login.`}),Q("/login"))}catch{}try{let h=re(e),b=De(e,s),w=At(b.name);h&&w&&!pt(w)&&Fi(e,h.authoritativeSourceFiles)&&!qi(e,s)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),Q("/scope"))}catch{}try{let h=i("resolve-genre",()=>Uw(e));h.persisted&&h.appType?u({kind:"note",tone:"ok",text:`\u2713 Detected a ${h.appType} app \u2014 enabled the ${h.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):h.source==="unknown"&&re(e)&&(Ar.current=!0)}catch{}let S=Ne(e);try{if(i("reconcile-devhints",()=>No(e)),S.status!=="current"&&!Xe(e)){let h=Io(e);h.length&&(u({kind:"note",tone:"warn",text:h.join(`
389
- `)}),Vt(Pt()),kn.current=!1,Gt.current=!1)}}catch{}try{let h=i("reconcile-feedback",()=>ey(e));h.archived>0&&u({kind:"note",tone:"ok",text:`\u2713 Tidied ${h.archived} resolved item${h.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${h.open>0?`; ${h.open} still open`:""}.`})}catch{}try{let h=i("upgrade-actions",()=>ty(e));h.applied.length>0&&u({kind:"note",tone:"warn",text:pr(h.applied).join(`
390
- `)})}catch{}let W=i("ready-decision",()=>Rt(!0));W.kind==="autoAudit"?(u({kind:"note",tone:"info",text:W.note}),_n().then(h=>{h.kind==="forward-to-agent"&&h.prompt&&te(h.prompt,{display:h.display,quietUser:!0})})):W.kind==="recommend"&&io(W.rec);let p=Math.round(performance.now()-c);p>=800&&oy({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${p}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${a.length?a.join(`
388
+ ${$d}`}),Q(f?"/doctor":"/init");return}f&&Q("/doctor");try{let h=De(e,s),k=At(h.name);k&&pt(k)&&k.refreshToken?_w({profile:h.name,connection:h.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),X(w=>w+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Q("/login")}):(!k||pt(k))&&(u({kind:"note",tone:"warn",text:`Profile "${h.name}" is not signed in \u2014 sign in with /login.`}),Q("/login"))}catch{}try{let h=re(e),k=De(e,s),w=At(k.name);h&&w&&!pt(w)&&Hi(e,h.authoritativeSourceFiles)&&!Bi(e,s)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),Q("/scope"))}catch{}try{let h=i("resolve-genre",()=>Yw(e));h.persisted&&h.appType?u({kind:"note",tone:"ok",text:`\u2713 Detected a ${h.appType} app \u2014 enabled the ${h.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):h.source==="unknown"&&re(e)&&(jr.current=!0)}catch{}let R=Ne(e);try{if(i("reconcile-devhints",()=>No(e)),R.status!=="current"&&!Xe(e)){let h=Io(e);h.length&&(u({kind:"note",tone:"warn",text:h.join(`
389
+ `)}),Vt(Pt()),kn.current=!1,Gt.current=!1)}}catch{}try{let h=i("reconcile-feedback",()=>ly(e));h.archived>0&&u({kind:"note",tone:"ok",text:`\u2713 Tidied ${h.archived} resolved item${h.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${h.open>0?`; ${h.open} still open`:""}.`})}catch{}try{let h=i("upgrade-actions",()=>cy(e));h.applied.length>0&&u({kind:"note",tone:"warn",text:hr(h.applied).join(`
390
+ `)})}catch{}let F=i("ready-decision",()=>Rt(!0));F.kind==="autoAudit"?(u({kind:"note",tone:"info",text:F.note}),Ln().then(h=>{h.kind==="forward-to-agent"&&h.prompt&&te(h.prompt,{display:h.display,quietUser:!0})})):F.kind==="recommend"&&ao(F.rec);let p=Math.round(performance.now()-c);p>=800&&dy({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${p}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${a.length?a.join(`
391
391
  `):"no single phase \u226580ms"}
392
- cwd: ${e}`}),Wr()},[]),Ae(()=>{let c=setInterval(()=>{Wr()},wy);return()=>clearInterval(c)},[Wr]),Ae(()=>{if(N||he||jr||Kn.current||ge!==null||Be.length>0||v!==""||yn!==null||ce.current.length>0||to.current||Lr)return;let c=Rt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&io(c.rec,{silent:!0})},[N,he,ge,Be,v,yn,Lr,K,Rt,jr]),Ae(()=>{let c=null,a=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let f=`${Oe.columns??80}x${Oe.rows??24}`;f!==ba.current&&(ba.current=f,Id(S=>S+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+El(_t.current,tt())+"\x1B[?2026l")},80))},400)};return Oe.on("resize",i),()=>{c&&clearTimeout(c),a&&clearTimeout(a),Oe.off("resize",i)}},[Oe,tt]);let Ue=Math.max(20,(Oe.columns??80)-1),$a=Ji(()=>cy(e,s),[e,s,K]),qr=(()=>{if(Ad)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Er!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Er?` v${Er}`:""}\u2026`,isSetup:!0};if(lo)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(yn)return _d?{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=re(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let a=Zi(e,(c.docsDir??xd).replace(/\/+$/,"")),i=(()=>{try{return ln(a)&&xw(a).length>0}catch{return!1}})();try{let f=De(e,s),S=At(f.name);if(!(!!S&&!(pt(S)&&!S.refreshToken)))return{text:`Sign in with /login (profile "${f.name}")\u2026`,isSetup:!0};if(!f.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!f.project.workspaceId&&!i)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return i?{text:uy,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),xn=vl(v),va=xn.length>0&&!N,Hr=d!==null?Zu(d,8,Ue):null,uo=Re?Re.paths.filter(c=>!Re.query||c.toLowerCase().includes(Re.query.toLowerCase())).slice(0,8):[],po=Se?Se.sessions.filter(c=>{let a=Se.query.toLowerCase();return!a||c.name.toLowerCase().includes(a)||c.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],Pe=G((c,a)=>{je.current?.close(),je.current=nd({cwd:e,resume:c,profileName:a??s,allowProdWrites:Lt.current}),c||(Ve.current={uuid:null,firstPrompt:null,titleFired:!1},gt(null)),Ht(0),Bt(0)},[e,s]),Ca=G((c,a,i)=>{if(dy.test(c))try{let f=De(e,s),S=typeof a.project_id=="string"&&a.project_id||f.project.projectId,W=gr(a,i),p=[],h=wr(i);c.endsWith("publish_article")&&h&&p.push(`Live: ${h}`);let b=yr(i);b?p.push(`Preview: ${b}`):W&&S&&p.push(`Preview: ${mr(f.connection.portalUrl,S,W,f.project.languageCode??"en")}`),p.length>0&&u({kind:"link",lines:p})}catch{}},[e,s,u]),te=G(async(c,a)=>{Qn(!0),Kn.current=!1,Me(),ft([]),hn(null),Mr(null);let i=Xn.current;if(a?.display?.startsWith("/"))try{let P=hu(e,a.display);P&&(c=`${c}
393
-
394
- ${P}`)}catch{}a?.quietUser||u({kind:"user",text:a?.echoDisplay&&a.display?a.display:c});let f=Ve.current;f.firstPrompt||(f.firstPrompt=a?.display??c),mt.current=Date.now(),Et(0),T(!0),eo.current.clear();let S="",W=!1,p=!1,h="",b={num:0,closed:!1,cueSeen:!1},w=null,D=()=>{w||(w=setTimeout(()=>{w=null,m(h.length>0?h:null)},60))},x=()=>{w&&clearTimeout(w),w=null,m(null)},I=(P=!1)=>{let{head:q,keep:O}=ed(h,P);q.trim()&&u({kind:"assistant",text:zi(q.trimEnd(),b)}),h=O,x()};try{for await(let P of je.current.send(c))if(P.type==="session"){if(!f.uuid){f.uuid=P.sessionId;let q=new Date().toISOString(),O=Ir.current,U=O??Nw(f.firstPrompt??"session");Iw({uuid:P.sessionId,name:U,renamed:!!O,titled:!1,cwd:e,firstPrompt:f.firstPrompt??"",createdAt:q,updatedAt:q}),gt(U),Ir.current=null}}else if(P.type==="text"){h+=P.delta,S+=P.delta;let q=td(h);if(q>0){let O=h.slice(0,q).trimEnd();O&&u({kind:"assistant",text:zi(O,b)}),h=h.slice(q)}D(),Et(O=>O+P.delta.length)}else if(P.type==="tool"){W=!0;let q=hr(P.name,P.input);q&&(I(),u({kind:"tool",title:q.title,sep:q.sep,arg:q.arg}),eo.current.set(P.id,{name:P.name,input:P.input}))}else if(P.type==="article_diff"){let q=Qe(P.oldContent,P.newContent,tt());q&&(I(),u({kind:"diff",added:q.added,removed:q.removed,lines:q.lines,hidden:q.hidden}))}else if(P.type==="tool_result"){P.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(P.output)&&(ro.current=!0);let q=eo.current.get(P.id);if(q){eo.current.delete(P.id),I();let O=fr(P.output,4,P.isError?void 0:q.name,q.input);u({kind:"tool-result",lines:O.lines,hidden:O.hidden,isError:P.isError}),P.isError||Ca(q.name,q.input,P.output)}}else if(P.type==="result"){I(!0),Ht(O=>O+P.outputTokens),Bt(O=>O+P.costUsd);let q=P.inputTokens+P.cacheReadTokens+P.cacheCreationTokens;if(u({kind:"done",seconds:Math.round((Date.now()-mt.current)/1e3),tokens:P.outputTokens,costUsd:P.costUsd,ok:P.ok,...q>0?{inTokens:q,cachedPct:Math.round(P.cacheReadTokens/q*100)}:{}}),!p&&!W&&!S.trim()&&!fn.current&&u({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),P.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(S))try{let O=dd(e);if(ln(O)){let U=Sr(O,"utf8").trim();U&&(Fr(U),u({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(P.ok&&b.cueSeen)ua(!0),ft([]);else{let O=P.ok?Wu(S,tn.map(U=>U.name)):[];if(O.length>0)Q(O[0]);else if(P.ok&&S.trim()){let U=Rt(!1);U.kind==="recommend"&&(U.rec.lead||U.rec.picker)||Mw(c,S,e).then(ne=>{ne&&Xn.current===i&&ye(ne)}).catch(()=>{})}}if(f.uuid&&(ea(f.uuid),!f.titleFired)){f.titleFired=!0;let O=f.uuid,U=f.firstPrompt;U&&od(U,e).then(ne=>{ne&&(Ew(O,ne),gt(ne))}).catch(()=>{})}}else P.type==="error"&&(I(!0),p=!0,P.kind==="auth"&&(ro.current=!0),u({kind:"note",text:`agent error: ${P.message}`,tone:"error"}))}finally{T(!1),x(),X(P=>P+1),Ve.current.uuid&&Lu(e,Ve.current.uuid,_t.current),ro.current?(ro.current=!1,mn.current=a?.display??c,ye("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):mn.current=null,fn.current&&(fn.current=!1,vt.current.length>0&&(u({kind:"note",tone:"info",text:`(${vt.current.length} queued message(s) discarded)`}),vt.current=[],_r([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,Ca,tt,ye,Q,Me,Rt]),St=G(async c=>{let a=Tr(e,"standard");mt.current=Date.now(),Et(0),T(!0);let i=new AbortController;fe.current=i;let f=async(S,W)=>{let p=na(S);oe({verb:"Publishing",total:p.length,done:0,active:[],rows:Gn(p),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:W?`Resolving cross-links in ${S.length} article${S.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${S.length} article${S.length===1?"":"s"} across ${p.length} partition${p.length===1?"":"s"} (\u2264${Nn} agents at once) on ${a.model}\u2026 (esc to stop)`});let h=!1;for await(let b of Pr({cwd:e,partitions:p,promptFor:w=>In(w.paths),concurrency:Nn,profileName:s,allowProdWrites:Lt.current,model:a.model,signal:i.signal}))if(b.type==="partition_status")b.status==="running"?oe(w=>w&&{...w,active:[...w.active,b.label],rows:_e(w.rows,b.label,"active"),lastAt:Date.now()}):oe(w=>w&&{...w,active:w.active.filter(D=>D!==b.label),done:w.done+1,rows:_e(w.rows,b.label,b.status==="done"?"done":"failed"),lastAt:Date.now()});else if(b.type==="partition_event")oe(w=>{if(!w)return w;let D={...w,lastAt:Date.now()};return b.event.type==="tool"?D.tools=w.tools+1:b.event.type==="text"&&(D.chars=w.chars+b.event.delta.length),D});else if(b.type==="run_done"){h=b.aborted,Bt(I=>I+b.totalCostUsd),Ht(I=>I+b.results.reduce((P,q)=>P+q.outputTokens,0));let w=b.aborted?"Stopped. ":"",D=t.kind==="api"?"api":"subscription";u({kind:"note",tone:b.aborted?"warn":b.ok?"ok":"warn",text:w+Ss(b.results,p,D).join(`
395
- `)});let x=Rs(e,s);if(x&&u({kind:"note",tone:"info",text:x}),!b.aborted){try{let I=await hd({cwd:e,profileName:s}),P=fd(I);P?u({kind:"note",tone:"info",text:P}):I.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${I.skipped}`})}catch(I){u({kind:"note",tone:"warn",text:`Order sync failed: ${I.message}`})}try{let I=gd(await md({cwd:e,profileName:s}));I&&u({kind:"note",tone:"info",text:I})}catch(I){u({kind:"note",tone:"warn",text:`Related-articles sync failed: ${I.message}`})}}}return h};try{if(!await f(c,!1)){let W=await Ps(e,s,c);W.length>0&&await f(W,!0)}}catch(S){u({kind:"note",tone:"error",text:`Publish run failed: ${S.message}`})}finally{fe.current=null,oe(null),T(!1),X(S=>S+1)}},[e,s,u,t]),Br=G(async c=>{await te(vs(c),{display:`/publish ${c}`,quietUser:!0});try{let a=await Yo(e,s,c.replace(/\\/g,"/"));a.length>0&&(hn(`Related articles not yet published (${a.length}):`),ft([`/publish --related ${c}`,...a.map(i=>`/publish ${i}`)]))}catch{}},[e,s,te]),ho=G(c=>{if(c)try{for(let a of Array.isArray(c)?c:[c]){let i=Li(e,a);if(!i)continue;cr(e,i.title).ok&&u({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${i.title}`});return}}catch{}},[e,u]),Ra=G(async(c,a)=>{let f=Yw(c,3),S=Tr(e,"standard");mt.current=Date.now(),Et(0),T(!0);let W=new AbortController;fe.current=W,oe({verb:"Authoring",unit:"spec",total:f.length,done:0,active:[],rows:Gn(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${c.length} screenshot spec${c.length===1?"":"s"} across ${f.length} partition${f.length===1?"":"s"} (\u22646 agents at once) on ${S.model}${S.forced?" (forced)":""}\u2026 (esc to stop)`});let p=!1;try{for await(let h of Pr({cwd:e,partitions:f,promptFor:Ul,concurrency:6,profileName:s,allowProdWrites:Lt.current,model:S.model,signal:W.signal}))if(h.type==="partition_status")h.status==="running"?oe(b=>b&&{...b,active:[...b.active,h.label],rows:_e(b.rows,h.label,"active"),lastAt:Date.now()}):oe(b=>b&&{...b,active:b.active.filter(w=>w!==h.label),done:b.done+1,rows:_e(b.rows,h.label,h.status==="done"?"done":"failed"),lastAt:Date.now()});else if(h.type==="partition_event")oe(b=>{if(!b)return b;let w={...b,lastAt:Date.now()};return h.event.type==="tool"?w.tools=b.tools+1:h.event.type==="text"&&(w.chars=b.chars+h.event.delta.length),w});else if(h.type==="run_done"){Bt(x=>x+h.totalCostUsd),Ht(x=>x+h.results.reduce((I,P)=>I+P.outputTokens,0));let b=h.results.filter(x=>x.ok).length,w=h.aborted?"Stopped. ":"";p=!h.aborted&&a.setup;let D=h.aborted?"":p?" Refreshing the capture-setup checklist\u2026":" Next: /screenshot capture --all (or /screenshot checklist first for the staging checklist).";u({kind:"note",tone:h.aborted?"warn":h.ok?"ok":"warn",text:`${w}Authored specs \u2014 ${b}/${h.results.length} batches ok.${D}`}),!h.aborted&&h.ok&&ho(a.runLine)}}catch(h){u({kind:"note",tone:"error",text:`Spec authoring failed: ${h.message}`})}finally{fe.current=null,oe(null),T(!1),X(h=>h+1)}if(p){let h=await rn();h.kind==="forward-to-agent"&&h.prompt&&await te(h.prompt,{display:h.display,quietUser:!0});let b=yi(e);b&&u({kind:"note",tone:"info",text:b.join(`
396
- `)})}},[e,s,u,te,ho]),Sa=G(async c=>{let a=await qo([c]);a.kind==="forward-to-agent"&&a.prompt&&await te(a.prompt,{display:a.display,quietUser:!0}),_l(e,c)&&be(`Spec ready \u2014 /screenshot capture ${c} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${c}`,reason:""})},[e,te,be]),Vr=G(async(c,a)=>{if(!tr(e)){await te(gi(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!Bc(e)){u({kind:"note",tone:"info",text:"No saved login for screenshot capture yet \u2014 opening a browser window. Sign in to your app (MFA included); I'll continue automatically once the session saves. (esc cancels)"}),T(!0),oo("Waiting for you to finish logging in (browser window)\u2026");let x=new AbortController;fe.current=x;let I;try{I=await Vc({cwd:e,signal:x.signal})}catch(P){u({kind:"note",tone:"error",text:`Could not launch the login: ${P.message}`});return}finally{fe.current=null,oo(null),T(!1)}if(I.exitCode!==0){mi(I.exitCode,I.output)?u({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."}):/unknown option/i.test(I.output)?u({kind:"note",tone:"warn",text:"Your d360-capture is older than this writer. Update it: npm i -g document360-capture \u2014 then /screenshot capture again."}):u({kind:"note",tone:x.signal.aborted?"warn":"error",text:x.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
397
- ${hi(I.output)}`});return}u({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let i=new Map(c.map(x=>[x,Ol(e,x)]));if(c.length>1){let x=c.filter(I=>i.get(I).mutates);if(x.length>0&&(c=c.filter(I=>!i.get(I).mutates),u({kind:"note",tone:"warn",text:`\u26A0 ${x.length} spec${x.length===1?"":"s"} perform${x.length===1?"s":""} a REAL write in your app and ${x.length===1?"is":"are"} excluded from bulk capture. Run each deliberately, on its own:
398
- `+x.map(I=>`/screenshot capture ${I}${i.get(I).what?` (${i.get(I).what})`:""}`).join(`
399
- `)}),c.length===0))return}else if(c.length===1&&i.get(c[0]).mutates){let x=i.get(c[0]);u({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${x.what?`: ${x.what}`:x.declared?"":" (detected from the spec: form fill + commit click / file upload)"}. Running because you named it explicitly \u2014 check the result and clean up what it created.`})}T(!0);let f=new AbortController;fe.current=f;let S=c.map(x=>({label:x,items:1,status:"pending"}));oe({verb:"Capturing",unit:"screenshot",total:c.length,done:0,active:[],rows:S,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Capturing ${c.length} screenshot${c.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`});let W=Date.now(),p=[];try{for(let x of c){if(f.signal.aborted)break;oe(U=>U&&{...U,active:[x],rows:_e(U.rows,x,"active"),lastAt:Date.now()});let{exitCode:I,output:P}=await fi({cwd:e,id:x,signal:f.signal,stdio:"pipe"});if(mi(I,P)){u({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."});return}let q=f.signal.aborted&&I!==0?"failed":pi(e,x,I,W),O=q==="captured"?void 0:q==="skipped"?qc(P)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Hc(P);p.push({id:x,outcome:q,detail:O}),oe(U=>U&&{...U,active:[],done:U.done+1,rows:_e(U.rows,x,q==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(x){u({kind:"note",tone:"error",text:`Capture run failed: ${x.message}`})}finally{fe.current=null,oe(null),T(!1),X(x=>x+1)}if(p.length===0)return;let h=p.filter(x=>x.outcome==="captured"),b=p.filter(x=>x.outcome==="skipped"),w=p.filter(x=>x.outcome==="failed"),D=c.length-p.length;u({kind:"note",tone:w.length?"warn":h.length?"ok":"info",text:`\u2713 ${h.length} captured`+(b.length?` \xB7 \u2298 ${b.length} skipped`:"")+(w.length?` \xB7 \u2717 ${w.length} failed`:"")+(D?` \xB7 ${D} not run (stopped)`:"")});for(let x of b)u({kind:"note",tone:"info",text:`\u2298 ${x.id} \u2014 ${x.detail}`});for(let x of w)x.detail&&u({kind:"note",tone:"error",text:`\u2717 ${x.id}
400
- ${x.detail}`});if(h.length>0){let x=Gc(e,h.map(P=>P.id)),I=x.length===1?`/publish ${x[0]}`:"/publish --screenshots";be(`PNG${h.length===1?"":"s"} saved \u2014 ${I} re-saves the article${x.length===1?"":"s"} so the image${h.length===1?"":"s"} embed${h.length===1?"s":""}.`,{kind:"cmd",cmd:I,reason:""})}else if(b.length>0){let x=c.length===1?`/screenshot capture ${c[0]}`:"/screenshot capture";be(null,{kind:"cmd",cmd:x,reason:""})}p.length===c.length&&w.length===0&&b.length===0&&ho(a?.runLine)},[e,u,be,te,ho]),Gr=G(c=>{let a=At(c);if(!a||pt(a)&&!a.refreshToken)return null;let i={...un(a.idToken)??{},...un(a.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),Yr=G((c,a)=>{if(a){let i=re(e);i&&(i.defaultProfile=c,rd(i,e))}l(c),Pe(void 0,c),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Gr(c)||(u({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),Q("/login")),X(i=>i+1)},[e,u,Pe,Gr,Q]),fo=G((c,a,i)=>{vo(e,c,a,i.id,i.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Pe(),sd(e,c)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),u({kind:"note",tone:"info",text:Zt(Jt(e)).join(`
401
- `)}),Vt(Pt()),kn.current=Ne(e).status==="current",Gt.current=Xe(e),u({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,u,Pe,Vt]),mo=G(async c=>{let a;try{a=await Rn(e,c)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Q("/workspace");return}if(a.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=a.workspaces.filter(S=>(S.workspace_type??"").toLowerCase()!=="apidocumentation"),f=i.length>0?i:a.workspaces;if(f.length===1){let S=f[0],W=a.workspaces.length-f.length;u({kind:"note",tone:"ok",text:`Selected the "${S.name??S.id}" workspace${W>0?" (skipped the API-documentation workspace)":""}.`}),fo(a.profile,a.projectId,S);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${f.length} available).`}),Q("/workspace")},[e,u,fo,Q]),go=G((c,a)=>{Co(e,c,a.id,a.name),u({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),Pe(),mo(c)},[e,u,Pe,mo]),Pa=G(async c=>{let a;try{a=De(e,c)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:i}=await rt(e,a.name),f=i.find(S=>S.id===a.project.projectId);f?.name&&ny(e,a.name,{projectName:f.name})}catch{}await mo(a.name);return}try{let{projects:i}=await rt(e,a.name);if(i.length===1){let f=i[0];u({kind:"note",tone:"ok",text:`Using your Document360 project "${f.name??f.id}".`}),go(a.name,{id:f.id,name:f.name});return}if(i.length>1){let f=i.map(S=>({id:S.id,name:S.name??S.id,sub:S.sub_domain}));u({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),kt({cursor:0,current:-1,rows:f,profile:a.name,environment:a.connection.name});return}}catch{}u({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Q("/project")}},[e,u,mo,go,Q]),Yt=G(()=>{let c=ce.current[0];if(!c)return;Me();let{plan:a,mode:i}=c;u({kind:"note",tone:"info",text:`\u25CF ${a.title} (${a.path})`});for(let S of a.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${S}`});a.overwritesLocalChanges&&i==="pull"&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let f=Qe(a.oldContent,a.newContent,tt());u(f?{kind:"diff",added:f.added,removed:f.removed,lines:f.lines,hidden:f.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),i==="conflict"?(u({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),u({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):u({kind:"note",tone:"info",text:`Write ${a.path}? (y/n \u2014 anything else cancels)`})},[u,tt,Me]),zr=G(()=>{if(ce.current.length>0){Yt();return}let c=Ot.current;Ot.current=[],c.length>0?(u({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),St(c)):Q("/pull")},[Yt,u,St,Q]),Ta=G(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(),Ot.current.push(i.plan.path),u({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{id({cwd:e,profileName:s},i.plan),u({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(f){u({kind:"note",tone:"error",text:`Take-portal failed: ${f.message}`})}}else if(a==="s"||a==="skip"||a==="n")ce.current.shift(),u({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let f=ce.current.length;return ce.current=[],Ot.current=[],u({kind:"note",tone:"info",text:`Resolve cancelled (${f} conflict${f===1?"":"s"} left untouched).`}),!0}return zr(),!0}if(a==="y"||a==="yes"){let f=ce.current.shift().plan;try{id({cwd:e,profileName:s},f),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${f.path} (sync base advanced).`})}catch(S){u({kind:"note",tone:"error",text:`Pull failed: ${S.message}`})}}else if(a==="n"||a==="no"){let f=ce.current.shift().plan;u({kind:"note",tone:"info",text:`Skipped ${f.path}.`})}else{let f=ce.current.length;return ce.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${f} article(s) left untouched).`}),!0}return zr(),!0},[e,s,zr,u]),Kr=G(async c=>{u({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let a=await ta({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),f=a.entries.filter(W=>W.status==="conflict"&&W.path).map(W=>W.path);if(i){if(!f.includes(i)){u({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}f=[i]}if(f.length===0){u({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let S=[];for(let W of f)try{S.push({plan:await ld({cwd:e,profileName:s,relPath:W}),mode:"conflict"})}catch(p){u({kind:"note",tone:"error",text:`Could not load ${W} from Document360: ${p.message}`})}if(S.length===0)return;u({kind:"note",tone:"info",text:`Resolving ${S.length} conflict${S.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),ce.current=S,Ot.current=[],Yt()}catch(a){u({kind:"note",tone:"error",text:`Could not compute sync status: ${a.message}`})}},[e,s,u,Yt]),Da=G(c=>{let a=to.current;if(!a)return!1;if(to.current=null,Me(),c.trim()!==a.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:f}=Di(e,a.targets);u({kind:"note",tone:f.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 S of f)u({kind:"note",tone:"error",text:` \u2717 ${S.path}: ${S.error}`});return a.hadDevhints&&(u({kind:"note",tone:"warn",text:_o().join(`
402
- `)}),Vt(rs())),u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
403
- ${wd}`}),Q("/init"),Qn(!1),!0},[e,u,Vt,Me,Q]),$n=G(async c=>{let a=c.slice(1).trim().split(/\s+/),i=(a[0]??"").toLowerCase(),f=a.slice(1);if(Qn(!0),Qo(f)&&["write","check","review","reorder"].includes(i)){let p=Ln(e,s);if(p.length===0){u({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let h=b=>i==="write"?`/write ${cc(f,b).join(" ")}`.trim():`/${i} ${[b,...f.filter(w=>w!=="--scope")].join(" ")}`.trim();if(p.length===1){$n(h(p[0].token));return}xt({cursor:0,rows:p,run:b=>{$n(h(b))}});return}if(ut(i,f)){let p=Ln(e,s);if(p.length>1){let h=f.filter(x=>x.startsWith("--")).join(" "),b=x=>`/${i}${x?` ${i==="write"?`--scope ${x}`:x}`:""}${h?` ${h}`:""} ${x?"":"--all"}`.replace(/\s+/g," ").trim(),w=p.reduce((x,I)=>x+I.count,0),D={token:"",label:i==="review"?`Everything \u2014 all ${w} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${p.length} categories`:`Everything \u2014 rewrite all ${w} planned articles`,count:w};xt({cursor:0,rows:[D,...p],run:x=>{$n(b(x))}});return}}let S=async p=>{let h=ui(p);if(!tr(e)){await te(gi(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(h.mode==="single"){await Vr([h.id],{runLine:[`/screenshot capture ${h.id}`,`/capture ${h.id}`]});return}if(h.mode==="all"||h.mode==="scope"){let{ready:w,captured:D}=di(e,h.mode==="scope"?h.scope:void 0),x=[...w,...D];if(x.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Q("/screenshot");return}let I=h.mode==="scope"?[`/screenshot capture ${h.scope}`,`/capture ${h.scope}`]:["/screenshot capture --all","/capture --all"];await Vr(x,{runLine:I});return}let b=Fc(qe(e));if(b.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Q("/screenshot");return}bt({cursor:0,rows:b,title:"Capture screenshots \u2014 pick what to shoot:"})},W=async()=>{let p=await rn();p.kind==="forward-to-agent"&&p.prompt&&await te(p.prompt,{display:p.display,quietUser:!0});let h=yi(e);h&&u({kind:"note",tone:"info",text:h.join(`
404
- `)})};switch(i){case"help":wn({tab:0});return;case"exit":case"quit":je.current?.close(),r();return;case"clear":Pe(),_t.current=[],Qn(!1),Me(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let p;try{p=De(e,s)}catch(h){u({kind:"note",tone:"error",text:h.message});return}u({kind:"note",tone:"info",text:`Profile "${p.name}" \u2192 ${p.connection.name} (${p.connection.apiUrl})${p.production?" \u26A0 PRODUCTION":""}`}),z(!0);try{let h=await Cw(p.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},w=>u({kind:"note",tone:"info",text:w})),b=Rw(p.name,h);if(Sw(b),await Zr(b,p.name,w=>u({kind:"note",tone:"info",text:w})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${p.name}" as ${Po(b)}`}),await Pa(s),gn.current){let w=gn.current;gn.current=null;let D=Ie(e,s);D.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${w}.`}),Q(w)):(u({kind:"note",tone:"warn",text:`${D.reason} (then ${w}.)`}),Q("/login"),gn.current=w)}else mn.current&&(ye(mn.current,"\u21E5 tab to re-send your last prompt\u2026"),mn.current=null)}catch(h){u({kind:"note",tone:"error",text:`Login failed: ${h.message}`})}finally{z(!1),X(h=>h+1)}return}case"allow-prod":{let p=!1;try{p=De(e,s).production}catch{}if(!p){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Lt.current=!0,Pe(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let p=si(f.join(" ")),h=Ve.current.uuid;if(!h){if(!p){u({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Ir.current=p,gt(p),an(`${xr} ${p}`),u({kind:"note",tone:"ok",text:`Session will be named "${p}" once it starts.`});return}if(!p){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let b=Ve.current.firstPrompt??"";od(b,e).then(w=>{w?(ye(`/rename ${w}`),u({kind:"note",tone:"info",text:`Suggestion: "${w}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Ow(h,p),gt(p),an(`${xr} ${p}`),u({kind:"note",tone:"ok",text:`Session renamed to "${p}".`});return}case"profile":{let p=f[0],h=re(e);if(!p){let b=Object.entries(h?.profiles??{});if(b.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let w=b.map(([I,P])=>({name:I,env:P.connection?.environment??"custom",prod:P.production===!0,who:Gr(I)})),D=s??h?.defaultProfile,x=Math.max(0,w.findIndex(I=>I.name===D));Mt({cursor:x,current:x,rows:w});return}if(p==="add"){let b=ii(e,f[1],f[2]);if(b){u({kind:"note",tone:"error",text:b});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${f[1]}" created (environment: ${f[2]??f[1]}).`}),Yr(f[1],!1);return}if(!h?.profiles?.[p]){u({kind:"note",tone:"error",text:`Unknown profile "${p}". Create it: /profile add ${p} <environment>`});return}Yr(p,!0);return}case"doctor":await Mn(f,{cwd:e,version:o});return;case"genre":{await ar(f,{cwd:e});try{Ar.current=!(re(e)?.appType??Ww(e))}catch{}X(p=>p+1);return}case"roadmap":{if(f[0]?.toLowerCase()==="done"){let p=cr(e,f.slice(1).join(" ").trim());u({kind:"note",tone:p.ok?"ok":"warn",text:p.line}),X(h=>h+1);return}u({kind:"note",tone:"info",text:_i(e).join(`
405
- `)});return}case"mcp":await Mo(f);return;case"init":{if(re(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let p=Vw().map(h=>({name:h,apiUrl:Gw(h).apiUrl}));Ut({cursor:0,rows:p});return}case"resume":{let p=f.join(" ").trim(),h=Lw(e).filter(D=>D.uuid!==Ve.current.uuid);if(!p){if(!h.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Ct({query:"",cursor:0,sessions:h});return}let b=_w(e,p);if(!b){u({kind:"note",tone:"error",text:`No session matches "${p}".`});return}Pe(b.uuid),Ve.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},gt(b.name),ea(b.uuid),_t.current=[];let w=Ki(e,b.uuid);for(let D of w)u(D);u({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 p=f.join(" ").trim(),h;try{h=await Rn(e,s)}catch(w){u({kind:"note",tone:"error",text:`Could not list workspaces: ${w.message}`});return}if(!p){let w=h.workspaces.map(x=>({id:x.id,name:x.name??x.id,type:x.workspace_type}));if(w.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let D=Math.max(0,w.findIndex(x=>x.id===h.current));Wt({cursor:D,current:D,rows:w,profile:h.profile,projectId:h.projectId,projectName:h.projectName,environment:h.environment});return}let b=Qr(h.workspaces,p);if(!b){u({kind:"note",tone:"error",text:`No workspace matches "${p}".`});return}fo(h.profile,h.projectId,b);return}case"project":{let p=f.join(" ").trim(),h;try{h=await rt(e,s)}catch(w){u({kind:"note",tone:"error",text:`Could not list projects: ${w.message} (signed in? try /login)`});return}if(!p){let w=h.projects.map(x=>({id:x.id,name:x.name??x.id,sub:x.sub_domain}));if(w.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let D=w.findIndex(x=>x.id===h.current);kt({cursor:Math.max(0,D),current:D,rows:w,profile:h.profile,environment:h.environment});return}let b=Jr(h.projects,p);if(!b){u({kind:"note",tone:"error",text:`No project matches "${p}". Available: ${h.projects.map(w=>w.name??w.id).join(", ")}`});return}go(h.profile,b);return}case"logout":{let p;try{p=De(e,s).name}catch(b){u({kind:"note",tone:"error",text:b.message});return}let h=Aw(p);jw(e,p),Pe(),X(b=>b+1),u({kind:"note",tone:h?"ok":"info",text:h?`\u2713 Signed out of "${p}" and cleared its project/workspace selection.`:`Profile "${p}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Q("/login");return}case"publish":{if(!ao(c.trim()))return;if(f.includes("--screenshots")||f.includes("--shots")){let w=Wo(qe(e));if(w.length===0){u({kind:"note",tone:"info",text:"No captured screenshots yet \u2014 /screenshot capture first."});return}u({kind:"note",tone:"info",text:`Re-saving ${w.length} article${w.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await St(w);return}if(f[0]==="--related"&&f[1]){let w=await Yo(e,s,f[1].replace(/\\/g,"/"));if(w.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await St(w);return}let p=f.filter(w=>!w.startsWith("--"));if(p[0]){await Br(p[0]);return}let h=f.includes("--all"),b=f.includes("--force");u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let w=await ta({cwd:e,profileName:s}),{clean:D,conflicts:x}=Bo(w.entries),I=h&&b&&x.length>0,P=Go(w.entries);if(P>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${P} article${P===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&&!I&&u({kind:"note",tone:"warn",text:Vo(x.length)}),D.length===0&&!I){if(x.length>0){Q("/resolve");return}u({kind:"note",tone:"ok",text:P>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let q=w.counts["unknown-base"]??0;q>0&&u({kind:"note",tone:"info",text:`(${q} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),oo("Reconciling structure on Document360 (order + related articles)\u2026");try{let O=await hd({cwd:e,profileName:s}),U=gd(await md({cwd:e,profileName:s})),ne=fd(O);ne?u({kind:"note",tone:"info",text:ne}):O.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${O.skipped}`}),U&&u({kind:"note",tone:"info",text:U}),u({kind:"note",tone:"ok",text:ne||U?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(ne||U)&&Q("/structure")}catch(O){u({kind:"note",tone:"warn",text:`Structure sync failed: ${O.message}`})}finally{oo(null)}return}if(h){let q=(I?[...D,...x]:D).map(O=>O.path);await St(q),x.length>0&&!I&&Q("/resolve");return}Ft({cursor:0,rows:Vl(D,x)})}catch(w){u({kind:"note",tone:"error",text:`Could not compute sync status: ${w.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!ao(c.trim()))return;await Kr(f.find(p=>!p.startsWith("--")));return}case"preview":{let p=f.join(" ").trim();if(!p){let b=[];try{b=Object.keys(sd(e,De(e,s).name)?.articles??{})}catch{}if(b.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}$t({query:"",cursor:0,paths:b});return}let h=$w(p)?p:Zi(e,p);if(ln(h)){try{u({kind:"preview",name:Yn(h),text:kd(Sr(h,"utf8"))})}catch(b){u({kind:"note",tone:"error",text:`Could not read ${h}: ${b.message}`})}return}if(py.test(p)){try{let b=De(e,s),w={profile:b.name,connection:b.connection},D=b.project.projectId??Tw(w),x=await Dw(w,D,p);u({kind:"preview",name:x.title??p,text:x.content??"*(article has no content)*"})}catch(b){u({kind:"note",tone:"error",text:`Could not fetch article: ${b.message}`})}return}u({kind:"note",tone:"error",text:`"${p}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let p=f[0]?.trim();if(!p){let D=Zo(ia(e));yt({cursor:D,current:D});return}let{lines:h,changed:b,effective:w}=On(e,p);for(let D of h)u({kind:"note",tone:D.startsWith("\u26A0")?"warn":D.startsWith("\u2713")?"ok":"info",text:D});b&&(ka(D=>D+1),je.current?.setModel(w));return}case"convert":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:p,run:h}=Ls(f),b=Kw(e,s);if(b.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let w=Os(b,p);if(w.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${p}". (${b.length} are tracked overall.)`});return}let D=na(w),x=3,I=`/convert${p?` --scope ${p}`:""} --run`,P=Tr(e,"light");if(!h){let O=cd({files:Ms(e,w),op:"convert",model:P.model}),U=p?`Scope: ${p} (${w.length} of ${b.length} tracked)
392
+ cwd: ${e}`}),Fr()},[]),Ae(()=>{let c=setInterval(()=>{Fr()},Ry);return()=>clearInterval(c)},[Fr]),Ae(()=>{if(j||he||Er||Xn.current||ge!==null||Be.length>0||v!==""||yn!==null||ce.current.length>0||no.current||Or)return;let c=Rt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&ao(c.rec,{silent:!0})},[j,he,ge,Be,v,yn,Or,K,Rt,Er]),Ae(()=>{let c=null,a=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let f=`${Oe.columns??80}x${Oe.rows??24}`;f!==xa.current&&(xa.current=f,Md(R=>R+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Il(_t.current,tt())+"\x1B[?2026l")},80))},400)};return Oe.on("resize",i),()=>{c&&clearTimeout(c),a&&clearTimeout(a),Oe.off("resize",i)}},[Oe,tt]);let Ue=Math.max(20,(Oe.columns??80)-1),Ca=ea(()=>wy(e,s),[e,s,K]),Hr=(()=>{if(Id)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Nr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Nr?` v${Nr}`:""}\u2026`,isSetup:!0};if(co)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(yn)return Ud?{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=re(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let a=ta(e,(c.docsDir??Rd).replace(/\/+$/,"")),i=(()=>{try{return ln(a)&&Dw(a).length>0}catch{return!1}})();try{let f=De(e,s),R=At(f.name);if(!(!!R&&!(pt(R)&&!R.refreshToken)))return{text:`Sign in with /login (profile "${f.name}")\u2026`,isSetup:!0};if(!f.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!f.project.workspaceId&&!i)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return i?{text:yy,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),$n=Rl(v),Ra=$n.length>0&&!j,Br=d!==null?od(d,8,Ue):null,po=Re?Re.paths.filter(c=>!Re.query||c.toLowerCase().includes(Re.query.toLowerCase())).slice(0,8):[],ho=Se?Se.sessions.filter(c=>{let a=Se.query.toLowerCase();return!a||c.name.toLowerCase().includes(a)||c.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],Pe=Y((c,a)=>{je.current?.close(),je.current=id({cwd:e,resume:c,profileName:a??s,allowProdWrites:Lt.current}),c||(Ve.current={uuid:null,firstPrompt:null,titleFired:!1},gt(null)),Ht(0),Bt(0)},[e,s]),Sa=Y((c,a,i)=>{if(ky.test(c))try{let f=De(e,s),R=typeof a.project_id=="string"&&a.project_id||f.project.projectId,F=wr(a,i),p=[],h=yr(i);c.endsWith("publish_article")&&h&&p.push(`Live: ${h}`);let k=kr(i);k?p.push(`Preview: ${k}`):F&&R&&p.push(`Preview: ${gr(f.connection.portalUrl,R,F,f.project.languageCode??"en")}`),p.length>0&&u({kind:"link",lines:p})}catch{}},[e,s,u]),te=Y(async(c,a)=>{Jn(!0),Xn.current=!1,Me(),ft([]),hn(null),Ur(null);let i=Qn.current;if(a?.display?.startsWith("/"))try{let S=wu(e,a.display);S&&(c=`${c}
393
+
394
+ ${S}`)}catch{}a?.quietUser||u({kind:"user",text:a?.echoDisplay&&a.display?a.display:c});let f=Ve.current;f.firstPrompt||(f.firstPrompt=a?.display??c),mt.current=Date.now(),Et(0),D(!0),to.current.clear();let R="",F=!1,p=!1,h="",k={num:0,closed:!1,cueSeen:!1},w=null,T=()=>{w||(w=setTimeout(()=>{w=null,m(h.length>0?h:null)},60))},$=()=>{w&&clearTimeout(w),w=null,m(null)},_=(S=!1)=>{let{head:q,keep:O}=rd(h,S);q.trim()&&u({kind:"assistant",text:Xi(q.trimEnd(),k)}),h=O,$()};try{for await(let S of je.current.send(c))if(S.type==="session"){if(!f.uuid){f.uuid=S.sessionId;let q=new Date().toISOString(),O=_r.current,W=O??Fw(f.firstPrompt??"session");qw({uuid:S.sessionId,name:W,renamed:!!O,titled:!1,cwd:e,firstPrompt:f.firstPrompt??"",createdAt:q,updatedAt:q}),gt(W),_r.current=null}}else if(S.type==="text"){h+=S.delta,R+=S.delta;let q=sd(h);if(q>0){let O=h.slice(0,q).trimEnd();O&&u({kind:"assistant",text:Xi(O,k)}),h=h.slice(q)}T(),Et(O=>O+S.delta.length)}else if(S.type==="tool"){F=!0;let q=fr(S.name,S.input);q&&(_(),u({kind:"tool",title:q.title,sep:q.sep,arg:q.arg}),to.current.set(S.id,{name:S.name,input:S.input}))}else if(S.type==="article_diff"){let q=Qe(S.oldContent,S.newContent,tt());q&&(_(),u({kind:"diff",added:q.added,removed:q.removed,lines:q.lines,hidden:q.hidden}))}else if(S.type==="tool_result"){S.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(S.output)&&(so.current=!0);let q=to.current.get(S.id);if(q){to.current.delete(S.id),_();let O=mr(S.output,4,S.isError?void 0:q.name,q.input);u({kind:"tool-result",lines:O.lines,hidden:O.hidden,isError:S.isError}),S.isError||Sa(q.name,q.input,S.output)}}else if(S.type==="result"){_(!0),Ht(O=>O+S.outputTokens),Bt(O=>O+S.costUsd);let q=S.inputTokens+S.cacheReadTokens+S.cacheCreationTokens;if(u({kind:"done",seconds:Math.round((Date.now()-mt.current)/1e3),tokens:S.outputTokens,costUsd:S.costUsd,ok:S.ok,...q>0?{inTokens:q,cachedPct:Math.round(S.cacheReadTokens/q*100)}:{}}),!p&&!F&&!R.trim()&&!fn.current&&u({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),S.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(R))try{let O=md(e);if(ln(O)){let W=Pr(O,"utf8").trim();W&&(qr(W),u({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(S.ok&&k.cueSeen)pa(!0),ft([]);else{let O=S.ok?Bu(R,tn.map(W=>W.name)):[];if(O.length>0)Q(O[0]);else if(S.ok&&R.trim()){let W=Rt(!1);W.kind==="recommend"&&(W.rec.lead||W.rec.picker)||Gw(c,R,e).then(ne=>{ne&&Qn.current===i&&ye(ne)}).catch(()=>{})}}if(f.uuid&&(na(f.uuid),!f.titleFired)){f.titleFired=!0;let O=f.uuid,W=f.firstPrompt;W&&ad(W,e).then(ne=>{ne&&(Ww(O,ne),gt(ne))}).catch(()=>{})}}else S.type==="error"&&(_(!0),p=!0,S.kind==="auth"&&(so.current=!0),u({kind:"note",text:`agent error: ${S.message}`,tone:"error"}))}finally{D(!1),$(),X(S=>S+1),Ve.current.uuid&&Wu(e,Ve.current.uuid,_t.current),so.current?(so.current=!1,mn.current=a?.display??c,ye("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):mn.current=null,fn.current&&(fn.current=!1,vt.current.length>0&&(u({kind:"note",tone:"info",text:`(${vt.current.length} queued message(s) discarded)`}),vt.current=[],Lr([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,Sa,tt,ye,Q,Me,Rt]),St=Y(async c=>{let a=Dr(e,"standard");mt.current=Date.now(),Et(0),D(!0);let i=new AbortController;fe.current=i;let f=async(R,F)=>{let p=ra(R);oe({verb:"Publishing",total:p.length,done:0,active:[],rows:Yn(p),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:F?`Resolving cross-links in ${R.length} article${R.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${R.length} article${R.length===1?"":"s"} across ${p.length} partition${p.length===1?"":"s"} (\u2264${In} agents at once) on ${a.model}\u2026 (esc to stop)`});let h=!1;for await(let k of Tr({cwd:e,partitions:p,promptFor:w=>_n(w.paths),concurrency:In,profileName:s,allowProdWrites:Lt.current,model:a.model,signal:i.signal}))if(k.type==="partition_status")k.status==="running"?oe(w=>w&&{...w,active:[...w.active,k.label],rows:_e(w.rows,k.label,"active"),lastAt:Date.now()}):oe(w=>w&&{...w,active:w.active.filter(T=>T!==k.label),done:w.done+1,rows:_e(w.rows,k.label,k.status==="done"?"done":"failed"),lastAt:Date.now()});else if(k.type==="partition_event")oe(w=>{if(!w)return w;let T={...w,lastAt:Date.now()};return k.event.type==="tool"?T.tools=w.tools+1:k.event.type==="text"&&(T.chars=w.chars+k.event.delta.length),T});else if(k.type==="run_done"){h=k.aborted,Bt(_=>_+k.totalCostUsd),Ht(_=>_+k.results.reduce((S,q)=>S+q.outputTokens,0));let w=k.aborted?"Stopped. ":"",T=t.kind==="api"?"api":"subscription";u({kind:"note",tone:k.aborted?"warn":k.ok?"ok":"warn",text:w+Ps(k.results,p,T).join(`
395
+ `)});let $=Ss(e,s);if($&&u({kind:"note",tone:"info",text:$}),!k.aborted){try{let _=await wd({cwd:e,profileName:s}),S=yd(_);S?u({kind:"note",tone:"info",text:S}):_.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${_.skipped}`})}catch(_){u({kind:"note",tone:"warn",text:`Order sync failed: ${_.message}`})}try{let _=bd(await kd({cwd:e,profileName:s}));_&&u({kind:"note",tone:"info",text:_})}catch(_){u({kind:"note",tone:"warn",text:`Related-articles sync failed: ${_.message}`})}}}return h};try{if(!await f(c,!1)){let F=await Ts(e,s,c);F.length>0&&await f(F,!0)}}catch(R){u({kind:"note",tone:"error",text:`Publish run failed: ${R.message}`})}finally{fe.current=null,oe(null),D(!1),X(R=>R+1)}},[e,s,u,t]),Vr=Y(async c=>{await te(Cs(c),{display:`/publish ${c}`,quietUser:!0});try{let a=await Yo(e,s,c.replace(/\\/g,"/"));a.length>0&&(hn(`Related articles not yet published (${a.length}):`),ft([`/publish --related ${c}`,...a.map(i=>`/publish ${i}`)]))}catch{}},[e,s,te]),fo=Y(c=>{if(c)try{for(let a of Array.isArray(c)?c:[c]){let i=Mi(e,a);if(!i)continue;ur(e,i.title).ok&&u({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${i.title}`});return}}catch{}},[e,u]),Pa=Y(async(c,a)=>{let f=ty(c,3),R=Dr(e,"standard");mt.current=Date.now(),Et(0),D(!0);let F=new AbortController;fe.current=F,oe({verb:"Authoring",unit:"spec",total:f.length,done:0,active:[],rows:Yn(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${c.length} screenshot spec${c.length===1?"":"s"} across ${f.length} partition${f.length===1?"":"s"} (\u22646 agents at once) on ${R.model}${R.forced?" (forced)":""}\u2026 (esc to stop)`});let p=!1;try{for await(let h of Tr({cwd:e,partitions:f,promptFor:Fl,concurrency:6,profileName:s,allowProdWrites:Lt.current,model:R.model,signal:F.signal}))if(h.type==="partition_status")h.status==="running"?oe(k=>k&&{...k,active:[...k.active,h.label],rows:_e(k.rows,h.label,"active"),lastAt:Date.now()}):oe(k=>k&&{...k,active:k.active.filter(w=>w!==h.label),done:k.done+1,rows:_e(k.rows,h.label,h.status==="done"?"done":"failed"),lastAt:Date.now()});else if(h.type==="partition_event")oe(k=>{if(!k)return k;let w={...k,lastAt:Date.now()};return h.event.type==="tool"?w.tools=k.tools+1:h.event.type==="text"&&(w.chars=k.chars+h.event.delta.length),w});else if(h.type==="run_done"){Bt($=>$+h.totalCostUsd),Ht($=>$+h.results.reduce((_,S)=>_+S.outputTokens,0));let k=h.results.filter($=>$.ok).length,w=h.aborted?"Stopped. ":"";p=!h.aborted&&a.setup;let T=h.aborted?"":p?" Refreshing the capture-setup checklist\u2026":" Next: /screenshot capture --all (or /screenshot checklist first for the staging checklist).";u({kind:"note",tone:h.aborted?"warn":h.ok?"ok":"warn",text:`${w}Authored specs \u2014 ${k}/${h.results.length} batches ok.${T}`}),!h.aborted&&h.ok&&fo(a.runLine)}}catch(h){u({kind:"note",tone:"error",text:`Spec authoring failed: ${h.message}`})}finally{fe.current=null,oe(null),D(!1),X(h=>h+1)}if(p){let h=await rn();h.kind==="forward-to-agent"&&h.prompt&&await te(h.prompt,{display:h.display,quietUser:!0});let k=bi(e);k&&u({kind:"note",tone:"info",text:k.join(`
396
+ `)})}},[e,s,u,te,fo]),Ta=Y(async c=>{let a=await qo([c]);a.kind==="forward-to-agent"&&a.prompt&&await te(a.prompt,{display:a.display,quietUser:!0}),Ol(e,c)&&be(`Spec ready \u2014 /screenshot capture ${c} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${c}`,reason:""})},[e,te,be]),Gr=Y(async(c,a)=>{if(!nr(e)){await te(yi(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!zc(e)){u({kind:"note",tone:"info",text:"No saved login for screenshot capture yet \u2014 opening a browser window. Sign in to your app (MFA included); I'll continue automatically once the session saves. (esc cancels)"}),D(!0),ro("Waiting for you to finish logging in (browser window)\u2026");let $=new AbortController;fe.current=$;let _;try{_=await Kc({cwd:e,signal:$.signal})}catch(S){u({kind:"note",tone:"error",text:`Could not launch the login: ${S.message}`});return}finally{fe.current=null,ro(null),D(!1)}if(_.exitCode!==0){wi(_.exitCode,_.output)?u({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."}):/unknown option/i.test(_.output)?u({kind:"note",tone:"warn",text:"Your d360-capture is older than this writer. Update it: npm i -g document360-capture \u2014 then /screenshot capture again."}):u({kind:"note",tone:$.signal.aborted?"warn":"error",text:$.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
397
+ ${mi(_.output)}`});return}u({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let i=new Map(c.map($=>[$,Ul(e,$)]));if(c.length>1){let $=c.filter(_=>i.get(_).mutates);if($.length>0&&(c=c.filter(_=>!i.get(_).mutates),u({kind:"note",tone:"warn",text:`\u26A0 ${$.length} spec${$.length===1?"":"s"} perform${$.length===1?"s":""} a REAL write in your app and ${$.length===1?"is":"are"} excluded from bulk capture. Run each deliberately, on its own:
398
+ `+$.map(_=>`/screenshot capture ${_}${i.get(_).what?` (${i.get(_).what})`:""}`).join(`
399
+ `)}),c.length===0))return}else if(c.length===1&&i.get(c[0]).mutates){let $=i.get(c[0]);u({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${$.what?`: ${$.what}`:$.declared?"":" (detected from the spec: form fill + commit click / file upload)"}. Running because you named it explicitly \u2014 check the result and clean up what it created.`})}D(!0);let f=new AbortController;fe.current=f;let R=c.map($=>({label:$,items:1,status:"pending"}));oe({verb:"Capturing",unit:"screenshot",total:c.length,done:0,active:[],rows:R,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Capturing ${c.length} screenshot${c.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`});let F=Date.now(),p=[];try{for(let $ of c){if(f.signal.aborted)break;oe(W=>W&&{...W,active:[$],rows:_e(W.rows,$,"active"),lastAt:Date.now()});let{exitCode:_,output:S}=await gi({cwd:e,id:$,signal:f.signal,stdio:"pipe"});if(wi(_,S)){u({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."});return}let q=f.signal.aborted&&_!==0?"failed":fi(e,$,_,F),O=q==="captured"?void 0:q==="skipped"?Gc(S)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Yc(S);p.push({id:$,outcome:q,detail:O}),oe(W=>W&&{...W,active:[],done:W.done+1,rows:_e(W.rows,$,q==="captured"?"done":"failed"),lastAt:Date.now()})}}catch($){u({kind:"note",tone:"error",text:`Capture run failed: ${$.message}`})}finally{fe.current=null,oe(null),D(!1),X($=>$+1)}if(p.length===0)return;let h=p.filter($=>$.outcome==="captured"),k=p.filter($=>$.outcome==="skipped"),w=p.filter($=>$.outcome==="failed"),T=c.length-p.length;u({kind:"note",tone:w.length?"warn":h.length?"ok":"info",text:`\u2713 ${h.length} captured`+(k.length?` \xB7 \u2298 ${k.length} skipped`:"")+(w.length?` \xB7 \u2717 ${w.length} failed`:"")+(T?` \xB7 ${T} not run (stopped)`:"")});for(let $ of k)u({kind:"note",tone:"info",text:`\u2298 ${$.id} \u2014 ${$.detail}`});for(let $ of w)$.detail&&u({kind:"note",tone:"error",text:`\u2717 ${$.id}
400
+ ${$.detail}`});if(h.length>0){let $=Xc(e,h.map(S=>S.id)),_=$.length===1?`/publish ${$[0]}`:"/publish --screenshots";be(`PNG${h.length===1?"":"s"} saved \u2014 ${_} re-saves the article${$.length===1?"":"s"} so the image${h.length===1?"":"s"} embed${h.length===1?"s":""}.`,{kind:"cmd",cmd:_,reason:""})}else if(k.length>0){let $=c.length===1?`/screenshot capture ${c[0]}`:"/screenshot capture";be(null,{kind:"cmd",cmd:$,reason:""})}p.length===c.length&&w.length===0&&k.length===0&&fo(a?.runLine)},[e,u,be,te,fo]),Yr=Y(c=>{let a=At(c);if(!a||pt(a)&&!a.refreshToken)return null;let i={...un(a.idToken)??{},...un(a.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),zr=Y((c,a)=>{if(a){let i=re(e);i&&(i.defaultProfile=c,ld(i,e))}l(c),Pe(void 0,c),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Yr(c)||(u({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),Q("/login")),X(i=>i+1)},[e,u,Pe,Yr,Q]),mo=Y((c,a,i)=>{vo(e,c,a,i.id,i.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Pe(),cd(e,c)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),u({kind:"note",tone:"info",text:Zt(Jt(e)).join(`
401
+ `)}),Vt(Pt()),kn.current=Ne(e).status==="current",Gt.current=Xe(e),u({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,u,Pe,Vt]),go=Y(async c=>{let a;try{a=await Sn(e,c)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Q("/workspace");return}if(a.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=a.workspaces.filter(R=>(R.workspace_type??"").toLowerCase()!=="apidocumentation"),f=i.length>0?i:a.workspaces;if(f.length===1){let R=f[0],F=a.workspaces.length-f.length;u({kind:"note",tone:"ok",text:`Selected the "${R.name??R.id}" workspace${F>0?" (skipped the API-documentation workspace)":""}.`}),mo(a.profile,a.projectId,R);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${f.length} available).`}),Q("/workspace")},[e,u,mo,Q]),wo=Y((c,a)=>{Co(e,c,a.id,a.name),u({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),Pe(),go(c)},[e,u,Pe,go]),Da=Y(async c=>{let a;try{a=De(e,c)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:i}=await rt(e,a.name),f=i.find(R=>R.id===a.project.projectId);f?.name&&uy(e,a.name,{projectName:f.name})}catch{}await go(a.name);return}try{let{projects:i}=await rt(e,a.name);if(i.length===1){let f=i[0];u({kind:"note",tone:"ok",text:`Using your Document360 project "${f.name??f.id}".`}),wo(a.name,{id:f.id,name:f.name});return}if(i.length>1){let f=i.map(R=>({id:R.id,name:R.name??R.id,sub:R.sub_domain}));u({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),kt({cursor:0,current:-1,rows:f,profile:a.name,environment:a.connection.name});return}}catch{}u({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Q("/project")}},[e,u,go,wo,Q]),Yt=Y(()=>{let c=ce.current[0];if(!c)return;Me();let{plan:a,mode:i}=c;u({kind:"note",tone:"info",text:`\u25CF ${a.title} (${a.path})`});for(let R of a.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${R}`});a.overwritesLocalChanges&&i==="pull"&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let f=Qe(a.oldContent,a.newContent,tt());u(f?{kind:"diff",added:f.added,removed:f.removed,lines:f.lines,hidden:f.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),i==="conflict"?(u({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),u({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):u({kind:"note",tone:"info",text:`Write ${a.path}? (y/n \u2014 anything else cancels)`})},[u,tt,Me]),Kr=Y(()=>{if(ce.current.length>0){Yt();return}let c=Ot.current;Ot.current=[],c.length>0?(u({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),St(c)):Q("/pull")},[Yt,u,St,Q]),Aa=Y(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(),Ot.current.push(i.plan.path),u({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{ud({cwd:e,profileName:s},i.plan),u({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(f){u({kind:"note",tone:"error",text:`Take-portal failed: ${f.message}`})}}else if(a==="s"||a==="skip"||a==="n")ce.current.shift(),u({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let f=ce.current.length;return ce.current=[],Ot.current=[],u({kind:"note",tone:"info",text:`Resolve cancelled (${f} conflict${f===1?"":"s"} left untouched).`}),!0}return Kr(),!0}if(a==="y"||a==="yes"){let f=ce.current.shift().plan;try{ud({cwd:e,profileName:s},f),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${f.path} (sync base advanced).`})}catch(R){u({kind:"note",tone:"error",text:`Pull failed: ${R.message}`})}}else if(a==="n"||a==="no"){let f=ce.current.shift().plan;u({kind:"note",tone:"info",text:`Skipped ${f.path}.`})}else{let f=ce.current.length;return ce.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${f} article(s) left untouched).`}),!0}return Kr(),!0},[e,s,Kr,u]),Xr=Y(async c=>{u({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let a=await oa({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),f=a.entries.filter(F=>F.status==="conflict"&&F.path).map(F=>F.path);if(i){if(!f.includes(i)){u({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}f=[i]}if(f.length===0){u({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let R=[];for(let F of f)try{R.push({plan:await pd({cwd:e,profileName:s,relPath:F}),mode:"conflict"})}catch(p){u({kind:"note",tone:"error",text:`Could not load ${F} from Document360: ${p.message}`})}if(R.length===0)return;u({kind:"note",tone:"info",text:`Resolving ${R.length} conflict${R.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),ce.current=R,Ot.current=[],Yt()}catch(a){u({kind:"note",tone:"error",text:`Could not compute sync status: ${a.message}`})}},[e,s,u,Yt]),ja=Y(c=>{let a=no.current;if(!a)return!1;if(no.current=null,Me(),c.trim()!==a.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:f}=ji(e,a.targets);u({kind:"note",tone:f.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 R of f)u({kind:"note",tone:"error",text:` \u2717 ${R.path}: ${R.error}`});return a.hadDevhints&&(u({kind:"note",tone:"warn",text:_o().join(`
402
+ `)}),Vt(ss())),u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
403
+ ${$d}`}),Q("/init"),Jn(!1),!0},[e,u,Vt,Me,Q]),xn=Y(async c=>{let a=c.slice(1).trim().split(/\s+/),i=(a[0]??"").toLowerCase(),f=a.slice(1);if(Jn(!0),Qo(f)&&["write","check","review","reorder"].includes(i)){let p=On(e,s);if(p.length===0){u({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let h=k=>i==="write"?`/write ${dc(f,k).join(" ")}`.trim():`/${i} ${[k,...f.filter(w=>w!=="--scope")].join(" ")}`.trim();if(p.length===1){xn(h(p[0].token));return}$t({cursor:0,rows:p,run:k=>{xn(h(k))}});return}if(ut(i,f)){let p=On(e,s);if(p.length>1){let h=f.filter($=>$.startsWith("--")).join(" "),k=$=>`/${i}${$?` ${i==="write"?`--scope ${$}`:$}`:""}${h?` ${h}`:""} ${$?"":"--all"}`.replace(/\s+/g," ").trim(),w=p.reduce(($,_)=>$+_.count,0),T={token:"",label:i==="review"?`Everything \u2014 all ${w} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${p.length} categories`:`Everything \u2014 rewrite all ${w} planned articles`,count:w};$t({cursor:0,rows:[T,...p],run:$=>{xn(k($))}});return}}let R=async p=>{let h=pi(p);if(!nr(e)){await te(yi(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(h.mode==="single"){await Gr([h.id],{runLine:[`/screenshot capture ${h.id}`,`/capture ${h.id}`]});return}if(h.mode==="all"||h.mode==="scope"){let{ready:w,captured:T}=hi(e,h.mode==="scope"?h.scope:void 0),$=[...w,...T];if($.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Q("/screenshot");return}let _=h.mode==="scope"?[`/screenshot capture ${h.scope}`,`/capture ${h.scope}`]:["/screenshot capture --all","/capture --all"];await Gr($,{runLine:_});return}let k=Vc(qe(e));if(k.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Q("/screenshot");return}bt({cursor:0,rows:k,title:"Capture screenshots \u2014 pick what to shoot:"})},F=async()=>{let p=await rn();p.kind==="forward-to-agent"&&p.prompt&&await te(p.prompt,{display:p.display,quietUser:!0});let h=bi(e);h&&u({kind:"note",tone:"info",text:h.join(`
404
+ `)})};switch(i){case"help":wn({tab:0});return;case"exit":case"quit":je.current?.close(),r();return;case"clear":Pe(),_t.current=[],Jn(!1),Me(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let p;try{p=De(e,s)}catch(h){u({kind:"note",tone:"error",text:h.message});return}u({kind:"note",tone:"info",text:`Profile "${p.name}" \u2192 ${p.connection.name} (${p.connection.apiUrl})${p.production?" \u26A0 PRODUCTION":""}`}),G(!0);try{let h=await Ew(p.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},w=>u({kind:"note",tone:"info",text:w})),k=Nw(p.name,h);if(Iw(k),await es(k,p.name,w=>u({kind:"note",tone:"info",text:w})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${p.name}" as ${Po(k)}`}),await Da(s),gn.current){let w=gn.current;gn.current=null;let T=Ie(e,s);T.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${w}.`}),Q(w)):(u({kind:"note",tone:"warn",text:`${T.reason} (then ${w}.)`}),Q("/login"),gn.current=w)}else mn.current&&(ye(mn.current,"\u21E5 tab to re-send your last prompt\u2026"),mn.current=null)}catch(h){u({kind:"note",tone:"error",text:`Login failed: ${h.message}`})}finally{G(!1),X(h=>h+1)}return}case"allow-prod":{let p=!1;try{p=De(e,s).production}catch{}if(!p){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Lt.current=!0,Pe(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let p=ii(f.join(" ")),h=Ve.current.uuid;if(!h){if(!p){u({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}_r.current=p,gt(p),an(`${xr} ${p}`),u({kind:"note",tone:"ok",text:`Session will be named "${p}" once it starts.`});return}if(!p){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let k=Ve.current.firstPrompt??"";ad(k,e).then(w=>{w?(ye(`/rename ${w}`),u({kind:"note",tone:"info",text:`Suggestion: "${w}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Vw(h,p),gt(p),an(`${xr} ${p}`),u({kind:"note",tone:"ok",text:`Session renamed to "${p}".`});return}case"profile":{let p=f[0],h=re(e);if(!p){let k=Object.entries(h?.profiles??{});if(k.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let w=k.map(([_,S])=>({name:_,env:S.connection?.environment??"custom",prod:S.production===!0,who:Yr(_)})),T=s??h?.defaultProfile,$=Math.max(0,w.findIndex(_=>_.name===T));Mt({cursor:$,current:$,rows:w});return}if(p==="add"){let k=ai(e,f[1],f[2]);if(k){u({kind:"note",tone:"error",text:k});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${f[1]}" created (environment: ${f[2]??f[1]}).`}),zr(f[1],!1);return}if(!h?.profiles?.[p]){u({kind:"note",tone:"error",text:`Unknown profile "${p}". Create it: /profile add ${p} <environment>`});return}zr(p,!0);return}case"doctor":await Un(f,{cwd:e,version:o});return;case"genre":{await lr(f,{cwd:e});try{jr.current=!(re(e)?.appType??zw(e))}catch{}X(p=>p+1);return}case"roadmap":{if(f[0]?.toLowerCase()==="done"){let p=ur(e,f.slice(1).join(" ").trim());u({kind:"note",tone:p.ok?"ok":"warn",text:p.line}),X(h=>h+1);return}u({kind:"note",tone:"info",text:Oi(e).join(`
405
+ `)});return}case"mcp":await Mo(f);return;case"init":{if(re(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let p=Zw().map(h=>({name:h,apiUrl:ey(h).apiUrl}));Ut({cursor:0,rows:p});return}case"resume":{let p=f.join(" ").trim(),h=Bw(e).filter(T=>T.uuid!==Ve.current.uuid);if(!p){if(!h.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Ct({query:"",cursor:0,sessions:h});return}let k=Hw(e,p);if(!k){u({kind:"note",tone:"error",text:`No session matches "${p}".`});return}Pe(k.uuid),Ve.current={uuid:k.uuid,firstPrompt:k.firstPrompt,titleFired:!0},gt(k.name),na(k.uuid),_t.current=[];let w=Qi(e,k.uuid);for(let T of w)u(T);u({kind:"note",tone:"ok",text:w.length?`Resumed "${k.name}" \u2014 restored ${w.length} message(s); continue where you left off.`:`Resumed "${k.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let p=f.join(" ").trim(),h;try{h=await Sn(e,s)}catch(w){u({kind:"note",tone:"error",text:`Could not list workspaces: ${w.message}`});return}if(!p){let w=h.workspaces.map($=>({id:$.id,name:$.name??$.id,type:$.workspace_type}));if(w.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let T=Math.max(0,w.findIndex($=>$.id===h.current));Wt({cursor:T,current:T,rows:w,profile:h.profile,projectId:h.projectId,projectName:h.projectName,environment:h.environment});return}let k=Jr(h.workspaces,p);if(!k){u({kind:"note",tone:"error",text:`No workspace matches "${p}".`});return}mo(h.profile,h.projectId,k);return}case"project":{let p=f.join(" ").trim(),h;try{h=await rt(e,s)}catch(w){u({kind:"note",tone:"error",text:`Could not list projects: ${w.message} (signed in? try /login)`});return}if(!p){let w=h.projects.map($=>({id:$.id,name:$.name??$.id,sub:$.sub_domain}));if(w.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let T=w.findIndex($=>$.id===h.current);kt({cursor:Math.max(0,T),current:T,rows:w,profile:h.profile,environment:h.environment});return}let k=Zr(h.projects,p);if(!k){u({kind:"note",tone:"error",text:`No project matches "${p}". Available: ${h.projects.map(w=>w.name??w.id).join(", ")}`});return}wo(h.profile,k);return}case"logout":{let p;try{p=De(e,s).name}catch(k){u({kind:"note",tone:"error",text:k.message});return}let h=Mw(p);Uw(e,p),Pe(),X(k=>k+1),u({kind:"note",tone:h?"ok":"info",text:h?`\u2713 Signed out of "${p}" and cleared its project/workspace selection.`:`Profile "${p}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Q("/login");return}case"publish":{if(!lo(c.trim()))return;if(f.includes("--screenshots")||f.includes("--shots")){let w=Wo(qe(e));if(w.length===0){u({kind:"note",tone:"info",text:"No captured screenshots yet \u2014 /screenshot capture first."});return}u({kind:"note",tone:"info",text:`Re-saving ${w.length} article${w.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await St(w);return}if(f[0]==="--related"&&f[1]){let w=await Yo(e,s,f[1].replace(/\\/g,"/"));if(w.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await St(w);return}let p=f.filter(w=>!w.startsWith("--"));if(p[0]){await Vr(p[0]);return}let h=f.includes("--all"),k=f.includes("--force");u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let w=await oa({cwd:e,profileName:s}),{clean:T,conflicts:$}=Bo(w.entries),_=h&&k&&$.length>0,S=Go(w.entries);if(S>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${S} article${S===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.`}),$.length>0&&!_&&u({kind:"note",tone:"warn",text:Vo($.length)}),T.length===0&&!_){if($.length>0){Q("/resolve");return}u({kind:"note",tone:"ok",text:S>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let q=w.counts["unknown-base"]??0;q>0&&u({kind:"note",tone:"info",text:`(${q} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),ro("Reconciling structure on Document360 (order + related articles)\u2026");try{let O=await wd({cwd:e,profileName:s}),W=bd(await kd({cwd:e,profileName:s})),ne=yd(O);ne?u({kind:"note",tone:"info",text:ne}):O.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${O.skipped}`}),W&&u({kind:"note",tone:"info",text:W}),u({kind:"note",tone:"ok",text:ne||W?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(ne||W)&&Q("/structure")}catch(O){u({kind:"note",tone:"warn",text:`Structure sync failed: ${O.message}`})}finally{ro(null)}return}if(h){let q=(_?[...T,...$]:T).map(O=>O.path);await St(q),$.length>0&&!_&&Q("/resolve");return}Ft({cursor:0,rows:Yl(T,$)})}catch(w){u({kind:"note",tone:"error",text:`Could not compute sync status: ${w.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!lo(c.trim()))return;await Xr(f.find(p=>!p.startsWith("--")));return}case"preview":{let p=f.join(" ").trim();if(!p){let k=[];try{k=Object.keys(cd(e,De(e,s).name)?.articles??{})}catch{}if(k.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}xt({query:"",cursor:0,paths:k});return}let h=Aw(p)?p:ta(e,p);if(ln(h)){try{u({kind:"preview",name:zn(h),text:vd(Pr(h,"utf8"))})}catch(k){u({kind:"note",tone:"error",text:`Could not read ${h}: ${k.message}`})}return}if(by.test(p)){try{let k=De(e,s),w={profile:k.name,connection:k.connection},T=k.project.projectId??Lw(w),$=await Ow(w,T,p);u({kind:"preview",name:$.title??p,text:$.content??"*(article has no content)*"})}catch(k){u({kind:"note",tone:"error",text:`Could not fetch article: ${k.message}`})}return}u({kind:"note",tone:"error",text:`"${p}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let p=f[0]?.trim();if(!p){let T=Zo(la(e));yt({cursor:T,current:T});return}let{lines:h,changed:k,effective:w}=Mn(e,p);for(let T of h)u({kind:"note",tone:T.startsWith("\u26A0")?"warn":T.startsWith("\u2713")?"ok":"info",text:T});k&&($a(T=>T+1),je.current?.setModel(w));return}case"convert":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:p,run:h}=Os(f),k=oy(e,s);if(k.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let w=Ms(k,p);if(w.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${p}". (${k.length} are tracked overall.)`});return}let T=ra(w),$=3,_=`/convert${p?` --scope ${p}`:""} --run`,S=Dr(e,"light");if(!h){let O=hd({files:Us(e,w),op:"convert",model:S.model}),W=p?`Scope: ${p} (${w.length} of ${k.length} tracked)
406
406
  `:"",ne=`
407
- Model: ${P.model}${P.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:U+Ws(D,O,x).join(`
408
- `)+ne}),Q(I);return}mt.current=Date.now(),Et(0),T(!0);let q=new AbortController;fe.current=q,oe({verb:"Converting",total:D.length,done:0,active:[],rows:Gn(D),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${w.length} articles across ${D.length} partitions (\u2264${x} agents at once) on ${P.model}\u2026 (esc to stop)`});try{for await(let O of Pr({cwd:e,partitions:D,promptFor:Us,concurrency:x,profileName:s,allowProdWrites:Lt.current,model:P.model,signal:q.signal}))if(O.type==="partition_status")O.status==="running"?oe(U=>U&&{...U,active:[...U.active,O.label],rows:_e(U.rows,O.label,"active"),lastAt:Date.now()}):oe(U=>U&&{...U,active:U.active.filter(ne=>ne!==O.label),done:U.done+1,rows:_e(U.rows,O.label,O.status==="done"?"done":"failed"),lastAt:Date.now()});else if(O.type==="partition_event")oe(U=>{if(!U)return U;let ne={...U,lastAt:Date.now()};return O.event.type==="tool"?ne.tools=U.tools+1:O.event.type==="text"&&(ne.chars=U.chars+O.event.delta.length),ne});else if(O.type==="run_done"){Bt(We=>We+O.totalCostUsd),Ht(We=>We+O.results.reduce((ko,bo)=>ko+bo.outputTokens,0));let U=O.aborted?"Stopped. ":"",ne=t.kind==="api"?"api":"subscription";u({kind:"note",tone:O.aborted?"warn":O.ok?"ok":"warn",text:U+Fs(O.results,D,ne).join(`
409
- `)})}}catch(O){u({kind:"note",tone:"error",text:`Convert run failed: ${O.message}`})}finally{fe.current=null,oe(null),T(!1),X(O=>O+1)}return}case"write":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=Xw(e);if(p.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:h,path:b,preview:w,concurrency:D,rewrite:x}=Bs(f),{docsDir:I,targets:P,reason:q,rewriting:O}=Qs(e,p,{scope:h,path:b,rewrite:x});if(P.length===0){u({kind:"note",tone:"warn",text:q??"Nothing to write."});return}O&&u({kind:"note",tone:"warn",text:`--rewrite: regenerating ${P.length} already-written article${P.length===1?"":"s"} (overwrites them; git has your baseline).`});let U=na(P),ne=Hs(D),We=Tr(e,"standard"),ko=!!b;if(w&&!ko){let J=cd({files:Gs(e,p,P),op:"write",model:We.model}),ie=h?`Scope: ${h} (${P.length} pending)
407
+ Model: ${S.model}${S.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:W+Fs(T,O,$).join(`
408
+ `)+ne}),Q(_);return}mt.current=Date.now(),Et(0),D(!0);let q=new AbortController;fe.current=q,oe({verb:"Converting",total:T.length,done:0,active:[],rows:Yn(T),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${w.length} articles across ${T.length} partitions (\u2264${$} agents at once) on ${S.model}\u2026 (esc to stop)`});try{for await(let O of Tr({cwd:e,partitions:T,promptFor:Ws,concurrency:$,profileName:s,allowProdWrites:Lt.current,model:S.model,signal:q.signal}))if(O.type==="partition_status")O.status==="running"?oe(W=>W&&{...W,active:[...W.active,O.label],rows:_e(W.rows,O.label,"active"),lastAt:Date.now()}):oe(W=>W&&{...W,active:W.active.filter(ne=>ne!==O.label),done:W.done+1,rows:_e(W.rows,O.label,O.status==="done"?"done":"failed"),lastAt:Date.now()});else if(O.type==="partition_event")oe(W=>{if(!W)return W;let ne={...W,lastAt:Date.now()};return O.event.type==="tool"?ne.tools=W.tools+1:O.event.type==="text"&&(ne.chars=W.chars+O.event.delta.length),ne});else if(O.type==="run_done"){Bt(We=>We+O.totalCostUsd),Ht(We=>We+O.results.reduce((bo,$o)=>bo+$o.outputTokens,0));let W=O.aborted?"Stopped. ":"",ne=t.kind==="api"?"api":"subscription";u({kind:"note",tone:O.aborted?"warn":O.ok?"ok":"warn",text:W+qs(O.results,T,ne).join(`
409
+ `)})}}catch(O){u({kind:"note",tone:"error",text:`Convert run failed: ${O.message}`})}finally{fe.current=null,oe(null),D(!1),X(O=>O+1)}return}case"write":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=ry(e);if(p.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:h,path:k,preview:w,concurrency:T,rewrite:$}=Vs(f),{docsDir:_,targets:S,reason:q,rewriting:O}=Js(e,p,{scope:h,path:k,rewrite:$});if(S.length===0){u({kind:"note",tone:"warn",text:q??"Nothing to write."});return}O&&u({kind:"note",tone:"warn",text:`--rewrite: regenerating ${S.length} already-written article${S.length===1?"":"s"} (overwrites them; git has your baseline).`});let W=ra(S),ne=Bs(T),We=Dr(e,"standard"),bo=!!k;if(w&&!bo){let J=hd({files:Ys(e,p,S),op:"write",model:We.model}),ie=h?`Scope: ${h} (${S.length} pending)
410
410
  `:"",me=`
411
- Model: ${We.model}${We.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:ie+zs(U,J,ne).join(`
412
- `)+me}),Q(`/write${h?` --scope ${h}`:""}`);return}mt.current=Date.now(),Et(0),T(!0);let bo=new AbortController;fe.current=bo,oe({verb:"Writing",total:U.length,done:0,active:[],rows:Gn(U),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${P.length} article${P.length===1?"":"s"} across ${U.length} partition${U.length===1?"":"s"} (\u2264${ne} agents at once) on ${We.model}${We.forced?" (forced)":""}\u2026 (esc to stop)`});let xo=new Set;try{for await(let J of Pr({cwd:e,partitions:U,promptFor:ie=>Ys(ie,I,{rewrite:O||ko}),concurrency:ne,profileName:s,allowProdWrites:Lt.current,model:We.model,signal:bo.signal}))if(J.type==="partition_status")J.status==="running"?oe(ie=>ie&&{...ie,active:[...ie.active,J.label],rows:_e(ie.rows,J.label,"active"),lastAt:Date.now()}):oe(ie=>ie&&{...ie,active:ie.active.filter(me=>me!==J.label),done:ie.done+1,rows:_e(ie.rows,J.label,J.status==="done"?"done":"failed"),lastAt:Date.now()});else if(J.type==="partition_event"){let ie=null;if(J.event.type==="tool"){let me=qu(J.event.name,J.event.input,U[J.index]?.paths??[]);me&&!xo.has(me)&&(xo.add(me),ie=J.label)}oe(me=>{if(!me)return me;let Fe={...me,lastAt:Date.now()};return J.event.type==="tool"?Fe.tools=me.tools+1:J.event.type==="text"&&(Fe.chars=me.chars+J.event.delta.length),ie&&(Fe.rows=Fu(Fe.rows,ie)),Fe})}else if(J.type==="run_done"){Bt(nt=>nt+J.totalCostUsd),Ht(nt=>nt+J.results.reduce((Ke,Md)=>Ke+Md.outputTokens,0));let ie=J.aborted?"Stopped. ":"",me=t.kind==="api"?"api":"subscription";if(u({kind:"note",tone:J.aborted?"warn":J.ok?"ok":"warn",text:ie+Ks(J.results,U,me).join(`
413
- `)}),!J.aborted&&J.ok)try{let nt=(xo.size>0?[...xo]:P).map(Ke=>`${I}/${Ke}`);oa(e,nt,{writtenCap:ra})}catch{}let Fe=J.aborted?null:Xs(e,I,P);if(Fe&&u({kind:"note",tone:"warn",text:Fe}),!J.aborted&&J.ok){let nt=h??b??"",Ke=nt?` ${nt}`:"";be(Fe?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${Ke} --fix, then /review${Ke} --fix for editorial quality, then /publish --all (add /screenshot author --all first if you want images).`:`Written. I\u2019d run /review${Ke} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot author --all first if you want images).`,{kind:"cmd",cmd:Fe?`/check${Ke} --fix`:`/review${Ke} --fix`,reason:""})}}}catch(J){u({kind:"note",tone:"error",text:`Write run failed: ${J.message}`})}finally{fe.current=null,oe(null),T(!1),X(J=>J+1)}return}case"draft":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:p,looseDocs:h}=Js(e);if(p.length===0&&h===0){u({kind:"note",tone:"info",text:ei});return}let b=f.join(" ").trim();if(!b&&p.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
414
- ${p.map(x=>` \u2022 ${x.name} (${x.docCount} doc${x.docCount===1?"":"s"})`).join(`
415
- `)}`}),ft(p.map(x=>`/draft ${x.name}`));return}let w="",D;if(b){let x=Zs(p,b);x?w=x:D=b}else w=p[0]?.name??"";await te(Jo(w,D),{display:b?`/draft ${b}`:"/draft",quietUser:!0});return}case"pull":{if(!ao(c.trim()))return;let p=f.find(h=>h.startsWith("--"));try{if(p==="--status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let w=Date.now(),D=await ta({cwd:e,profileName:s});u({kind:"note",tone:"info",text:Ko(D,Date.now()-w).join(`
416
- `)});return}if(p==="--baseline"){let w=f.find(P=>!P.startsWith("--")),D=w?w.replace(/\\/g,"/"):void 0;u({kind:"note",tone:"info",text:D?`Setting the sync baseline for ${D}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let x=await qw({cwd:e,profileName:s,relPaths:D?[D]:void 0}),I=D?{rebaselined:[],skipped:[]}:await Hw({cwd:e,profileName:s});if(x.baselined.length===0&&x.skipped.length===0&&I.rebaselined.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}x.baselined.length>0&&u({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.`}),I.rebaselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${I.rebaselined.length} article${I.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),x.skipped.length>0&&u({kind:"note",tone:"warn",text:`${x.skipped.length} skipped:
417
- ${x.skipped.map(P=>` - ${P.path} (${P.reason})`).join(`
418
- `)}`}),X(P=>P+1);return}if(p==="--compare"){u({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let w=await Fw({cwd:e,profileName:s}),D=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}`];D?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.")),u({kind:"note",tone:D?"ok":"warn",text:x.join(`
419
- `)});return}if(p){u({kind:"note",tone:"error",text:`Unknown option: ${p} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let h=f[0];if(h){let w=await ld({cwd:e,profileName:s,relPath:h.replace(/\\/g,"/")});ce.current=[{plan:w,mode:w.overwritesLocalChanges?"conflict":"pull"}],Ot.current=[],Yt();return}u({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let b=await Ns({cwd:e,profileName:s});for(let w of Is(b))u({kind:"note",tone:w.tone,text:w.text});X(w=>w+1)}catch(h){u({kind:"note",tone:"error",text:`Pull failed: ${h.message}`})}return}case"scope":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=Bw(e);if(p.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}qt({cursor:0,rows:p.map(h=>({...h,checked:h.recommended}))});return}case"audit":{if(f[0]==="--auto"){let h=re(e);if(!h){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=f[1]!=="off";rd({...h,autoAudit:b},e),u({kind:"note",tone:"ok",text:b?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let p=await _n();p.kind==="forward-to-agent"&&p.prompt&&await te(p.prompt,{display:p.display,quietUser:!0});return}case"check":{let p=f.find(w=>!w.startsWith("--")),h=p?` ${p}`:"",b=ad({cwd:e,scope:p});if(f.includes("--fix")){if(b.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}u({kind:"note",tone:"info",text:`Fixing ${b.length} doc issue${b.length===1?"":"s"}\u2026`});let w=pd(e,p);await te(ji(b),{display:`/check${h} --fix`,quietUser:!0});try{oa(e,w,{reviewedCap:ra})}catch{}let D=ad({cwd:e,scope:p});u({kind:"note",tone:D.length===0?"ok":"warn",text:D.length===0?"\u2713 Doc-checker: all issues resolved.":ir(D).join(`
420
- `)}),be(D.length===0?`Deterministic issues fixed. Next: /review${h} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${h} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${h} --fix`,reason:""});return}u({kind:"note",tone:b.length===0?"ok":"warn",text:ir(b).join(`
421
- `)}),b.length>0&&be(`Found ${b.length} doc issue${b.length===1?"":"s"} above. /check${h} --fix has the agent fix them in place (or /review${h} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${h} --fix`,reason:""});return}case"structure":{let p=qn(e,s);if(p.length===0){u({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}u({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...p].join(`
422
- `)});return}case"reorder":{let p=Ni(e,f);if(!p){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await te(p.prompt,{display:p.display,quietUser:!0}),be("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let p=Ei(e,f);if(!p){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=f.includes("--fix"),b=f.find(D=>!D.startsWith("--")),w=h?pd(e,b):[];if(await te(p.prompt,{display:p.display,quietUser:!0}),h)try{oa(e,w,{reviewedCap:ra})}catch{}if(h)be("\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 D=f.filter(x=>x!=="--fix").join(" ");be(`The review listed issues above. /review${D?` ${D}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${D?` ${D}`:""} --fix`,reason:""})}return}case"capture-setup":{await W();return}case"devhints":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:Zt(Jt(e)).join(`
423
- `)}),Vt(Pt()),kn.current=Ne(e).status==="current",Gt.current=Xe(e);return}case"discover":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await te(Ts(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(ki(e)===0){u({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await te(bi(),{display:"/inbox",quietUser:!0});return}case"feedback":{let p=dd(e),h="";try{h=ln(p)?Sr(p,"utf8"):""}catch{h=""}if(!/^## /m.test(h)){u({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 Yi(h.trim());u({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 ${p} and copy it manually.`}),b&&Fr(null);return}case"document":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:p,what:h}=ni(f);if(!h&&ti(e)===0){u({kind:"note",tone:"info",text:ri});return}let b=`/document${h?` ${h}`:""}${p?" --publish":""}`;await te(oi(h,p),{display:b,quietUser:!0});return}case"catch-up":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!ao(c.trim()))return;let{publish:p}=$i(f);u({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let h=await Ci({cwd:e,profileName:s});for(let w of Ri(h))u({kind:"note",tone:w.startsWith("\u2713")?"ok":w.startsWith("\u2139")?"info":"warn",text:w});let b=Fn(Wn(e));u({kind:"note",tone:"info",text:b?`Catching up on ${b}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await te(vi({publish:p}),{display:`/catch-up${p?" --publish":""}`,quietUser:!0});return}case"update":{Ur.current=!0,u({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),Jn(!0);let p=await rr().finally(()=>Jn(!1));p.ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated ${p.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),Q("/exit"),da("")):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${or}`});return}case"screenshot":{let p=En(f);if(p.mode==="capture"){await S(p.rest);return}if(p.mode==="checklist"){await W();return}if(p.mode==="list"){if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=qe(e,p.scope);if(p.picker){if(w.length===0){u({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let x=Ml(w);if(x.length===0){u({kind:"note",tone:"info",text:Fo(w,p.scope).join(`
424
- `)}),be(`\u2713 All ${w.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}bt({cursor:0,rows:x,title:"Screenshots \u2014 pick what to author or capture:"});return}u({kind:"note",tone:"info",text:Fo(w,p.scope).join(`
425
- `)});let D=w.filter(x=>x.state==="placeholder").length;if(D>0){let x=p.scope?`/screenshot author ${p.scope}`:"/screenshot author --all";be(`${D} of ${w.length} still need${D===1?"s":""} a spec \u2014 /screenshot author <id> authors one, ${x} authors them all in parallel.`,{kind:"cmd",cmd:x,reason:""})}return}if(p.mode==="single"){await Sa(p.id);return}if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=p.mode==="scope"?p.scope:void 0,b=zw(e,{scope:h}).map(w=>w.id);if(b.length===0){u({kind:"note",tone:"info",text:h?`No screenshot placeholders under ${h}.`:"No screenshot placeholders found in the docs."});return}await Ra(b,{setup:p.setup,runLine:p.mode==="scope"?[`/screenshot author ${p.scope}`,`/screenshot ${p.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await S(f);return}case"reset":{let p=Ti(e);if(p.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}to.current={repoName:Yn(e),targets:p,hadDevhints:ln(ud(e))},u({kind:"note",tone:"warn",text:Ai(e,p).join(`
426
- `)}),ye(Yn(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Yt,Kr,u,Pe,te,St,Br,Pa]),wo=G(c=>{let a=(c??v).trim();if($(""),Zn(null),Nt(0),a.startsWith("/")&&(Kn.current=!1,Me(),hn(null),ft(f=>Vu(f,a))),!a||(ua(!1),Da(a))||Ta(a))return;Nr.current.push(a);let i=Ku(a,pa.current);if(a.startsWith("/"))u({kind:"user",text:a}),Je(!0),$n(i).finally(()=>Je(!1));else if(ry(i)){u({kind:"user",text:a});let f=sy(i);if(!f)te(i,{display:a,quietUser:!0});else{try{iy(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}te(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${f}". 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 "${f}" and the article path(s) you wrote.`,{display:a,quietUser:!0})}}else{let f=fu(e,i);te(f??i,{display:a})}},[v,Da,Ta,$n,te]),Aa=G(c=>{if(c.length>1){if(c.includes("\x1B"))return;let a=Gu(c);if(Yu(a)){let i=zu(++Ed.current,a);pa.current.set(i,a),_(i)}else _(a);return}_(c)},[_]),zt=Math.max(10,Ue-6),ja=Ji(()=>Cr(k.text,zt),[k.text,zt]),Xr=G(c=>y(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+c))})),[]),yo=G(c=>y(a=>({...a,pos:Qu(Cr(a.text,zt),a.pos,c)})),[zt]),vn=G(c=>y(a=>({...a,pos:Ju(Cr(a.text,zt),a.pos,c)})),[zt]),Ld=["\x1B[H","\x1B[1~","\x1BOH"],Od=["\x1B[F","\x1B[4~","\x1BOF"],Ea=G((c,a)=>a.leftArrow?(Xr(-1),!0):a.rightArrow?(Xr(1),!0):c&&Ld.includes(c)?(vn("start"),!0):c&&Od.includes(c)?(vn("end"),!0):a.ctrl&&c==="a"?(vn("start"),!0):a.ctrl&&c==="e"?(vn("end"),!0):!1,[Xr,vn]);return kw((c,a)=>{if(a.ctrl&&c==="c"){je.current?.close(),r();return}if(!F){if(N){if(a.escape){if(fe.current){if(!fe.current.signal.aborted){let i=(no?.verb??"work").toLowerCase(),f=no?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${f}s)\u2026`}),fe.current.abort()}return}fn.current||(fn.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),je.current?.interrupt());return}if(a.return){let i=v.trim();if(!i)return;vt.current.push(i),_r([...vt.current]),$("");return}if(Ea(c,a))return;if(a.upArrow){yo(-1);return}if(a.downArrow){yo(1);return}if(a.backspace||a.delete){R();return}c&&!a.ctrl&&!a.meta&&Aa(c);return}if(wt){if(a.upArrow){yt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){yt(i=>i&&{...i,cursor:Math.min(He.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=He.length){yt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=He[wt.cursor];yt(null);let{lines:f,changed:S,effective:W}=On(e,i.value??"default");for(let p of f)u({kind:"note",tone:p.startsWith("\u26A0")?"warn":p.startsWith("\u2713")?"ok":"info",text:p});S&&(ka(p=>p+1),je.current?.setModel(W));return}if(c==="s"){let i=He[wt.cursor];yt(null),je.current?.setModel(i.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){yt(null);return}return}if(Ge){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(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ge.rows.length){Mt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return||c==="s"){let i=Ge.rows[Ge.cursor];Mt(null),Yr(i.name,a.return===!0);return}if(a.escape){Mt(null);return}return}if(so){if(a.escape){wn(null);return}if(a.leftArrow||a.tab&&a.shift){wn(i=>i&&{tab:(i.tab-1+Ee.length)%Ee.length});return}if(a.rightArrow||a.tab){wn(i=>i&&{tab:(i.tab+1)%Ee.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ee.length){wn({tab:Number(c)-1});return}return}if(Ye){if(a.upArrow){Ut(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ut(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ye.rows.length){Ut(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Ye.rows[Ye.cursor].name;if(Ut(null),!ss(e,i).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let S=!1;try{let W=At(i);S=!!W&&!(pt(W)&&!W.refreshToken)}catch{S=!1}u({kind:"note",tone:"info",text:S?`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"),X(W=>W+1);return}if(a.escape){Ut(null);return}return}if(we){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(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=we.rows.length){Wt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=we.rows[we.cursor],{profile:f,projectId:S}=we;Wt(null),fo(f,S,i);return}if(a.escape){Wt(null);return}return}if(Ce){if(a.upArrow){kt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){kt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ce.rows.length){kt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Ce.rows[Ce.cursor],{profile:f}=Ce;kt(null),go(f,i);return}if(a.escape){kt(null);return}return}if(ke){if(a.upArrow){qt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){qt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){qt(i=>i&&{...i,rows:i.rows.map((f,S)=>S===i.cursor?{...f,checked:!f.checked}:f)});return}if(a.return){let i=ke.rows.filter(f=>f.checked).map(f=>f.path);if(qt(null),i.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Ds(e,i),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of i)u({kind:"note",tone:"info",text:` ${f}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){qt(null);return}return}if(ze){if(a.upArrow){xt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){xt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ze.rows.length){xt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=ze.rows[ze.cursor],f=ze.run;xt(null),f(i.token);return}if(a.escape){xt(null);return}return}if(Ze){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)<=Ze.rows.length){Ft(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Ze.rows[Ze.cursor];Ft(null),i.conflict?Kr(i.paths[0]):i.kind==="article"?Br(i.paths[0]):St(i.paths);return}if(a.escape){Ft(null);return}return}if(et){if(a.upArrow){bt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){bt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=et.rows.length){bt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=et.rows[et.cursor];bt(null),i.action==="capture"?Vr(i.ids,{runLine:i.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):i.kind==="shot"?Sa(i.ids[0]):Ra(i.ids,{setup:!0,runLine:i.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(a.escape){bt(null);return}return}if(Re){if(a.escape){$t(null);return}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(Math.max(0,uo.length-1),i.cursor+1)});return}if(a.return){let i=uo[Re.cursor];if(i){$t(null);try{u({kind:"preview",name:Yn(i),text:kd(Sr(Zi(e,i),"utf8"))})}catch(f){u({kind:"note",tone:"error",text:`Could not read ${i}: ${f.message}`})}}return}if(a.backspace||a.delete){$t(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){$t(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(Se){if(a.escape){Ct(null);return}if(a.upArrow){Ct(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ct(i=>i&&{...i,cursor:Math.min(Math.max(0,po.length-1),i.cursor+1)});return}if(a.return){let i=po[Se.cursor];if(i){Ct(null),Pe(i.uuid),Ve.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},gt(i.name),ea(i.uuid),_t.current=[];let f=Ki(e,i.uuid);for(let S of f)u(S);u({kind:"note",tone:"ok",text:f.length?`Resumed "${i.name}" \u2014 restored ${f.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){Ct(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){Ct(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(a.tab&&!v&&ge){$(ge),Me();return}if(!v&&Be.length>0&&!jr&&c&&/^[1-9]$/.test(c)){let i=Be[Number(c)-1];if(i){$(Dt(i));return}}if(!v&&(lo||yn)&&c==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let i=lo!=null;Yi(lo??yn).then(S=>{u({kind:"note",tone:S?"ok":"warn",text:S?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."}),S&&i&&Fr(null),S&&!i&&xa(!0)});return}if(!Ea(c,a)){if(va){if(a.upArrow){Nt(i=>Math.max(0,i-1));return}if(a.downArrow){Nt(i=>Math.min(xn.length-1,i+1));return}if(a.tab){$("/"+(xn[pn]?.name??"")+" "),Nt(0);return}if(a.return){let i=xn[pn];if(i){let f=v.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Cl(i.usage)&&!f){$("/"+i.name+" "),Nt(0);return}wo("/"+i.name+(f?" "+f:""));return}}}else{if(a.upArrow){if(v!==""&&It===null){yo(-1);return}let i=Nr.current;if(!i.length)return;let f=It===null?i.length-1:Math.max(0,It-1);Zn(f),$(i[f]??"");return}if(a.downArrow){if(v!==""&&It===null){yo(1);return}let i=Nr.current;if(It===null)return;let f=It+1;f>=i.length?(Zn(null),$("")):(Zn(f),$(i[f]??""));return}}if(a.return){wo();return}if(a.backspace||a.delete){R();return}if(a.escape){$(""),Nt(0),Me(),ft([]),hn(null),Kn.current=!0;return}c&&!a.ctrl&&!a.meta&&Aa(c)}}}),Ae(()=>{if(N||F)return;let c=vt.current.shift();c!==void 0&&(_r([...vt.current]),wo(c))},[N,F,wo]),Y(se,{flexDirection:"column",width:Ue,children:[Hr!==null&&Y(se,{marginTop:1,flexDirection:"column",children:[Hr.truncated&&j(A,{dimColor:!0,children:"\u2026"}),j(A,{children:Hr.text})]}),N&&(no?j(gy,{p:no}):j(hy,{startTime:mt.current,chars:jd})),!N&&ga?j(fy,{text:ga}):null,j(se,{borderStyle:"round",borderColor:$a.prod?"yellow":V,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:v?ja.map((c,a)=>{let i=k.text.slice(c.start,c.end),f=a===Rr(ja,k.pos),S=Math.min(k.pos,c.end)-c.start;return Y(A,{children:[j(A,{color:V,children:a===0?"> ":" "}),f?Y(zn,{children:[i.slice(0,S),j(cn,{ch:i[S]??" "}),i.slice(S+1)]}):i||" "]},`${a}-${c.start}`)}):Y(A,{children:[j(A,{color:V,children:"> "}),Lr?j(cn,{ch:" "}):ge&&!N&&ve?Y(zn,{children:[j(cn,{ch:ve[0],dim:!0}),j(A,{color:"gray",children:ve.slice(1)})]}):ge&&!N?Y(zn,{children:[j(cn,{ch:ge[0],dim:!0}),j(A,{color:"gray",children:ge.slice(1)}),j(A,{dimColor:!0,children:" (tab)"})]}):(qr.isSetup||!Dd)&&!N?Y(zn,{children:[j(cn,{ch:qr.text[0],dim:!0}),j(A,{color:"gray",children:qr.text.slice(1)})]}):j(cn,{ch:" "})]})}),ma.length>0&&j(se,{flexDirection:"column",paddingX:1,children:ma.map((c,a)=>j(A,{color:"gray",children:`\u29D7 queued: ${c}`},`${a}-${c.slice(0,24)}`))}),so?j(Uu,{tab:so.tab,width:Ue,version:o,engineVersion:bd}):wt?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Select model"}),j(A,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),He.map((c,a)=>Y(A,{color:a===wt.cursor?V:void 0,children:[a===wt.cursor?"\u276F ":" ",`${a+1}. ${c.label}${a===wt.current?" \u2714":""}`.padEnd(16),j(A,{color:"gray",children:c.desc})]},c.label)),j(A,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Ge?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Switch connection profile"}),Ge.rows.map((c,a)=>Y(A,{color:a===Ge.cursor?V:void 0,children:[a===Ge.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===Ge.current?" \u2714":""}`.padEnd(20),j(A,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?j(A,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),j(A,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ye?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Pick your Document360 environment"}),Ye.rows.map((c,a)=>Y(A,{color:a===Ye.cursor?V:void 0,children:[a===Ye.cursor?"\u276F ":" ",`${a+1}. ${c.name}`.padEnd(16),j(A,{color:"gray",children:c.apiUrl})]},c.name)),j(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):we?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Switch workspace"}),j(A,{dimColor:!0,children:`environment ${we.environment} \xB7 project ${we.projectName??`${we.projectId.slice(0,8)}\u2026`}`}),we.rows.map((c,a)=>Y(A,{color:a===we.cursor?V:void 0,children:[a===we.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===we.current?" \u2714":""}`.padEnd(30),j(A,{color:"gray",children:c.type??""})]},c.id)),j(A,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):Ce?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Choose project"}),j(A,{dimColor:!0,children:`environment ${Ce.environment}`}),Ce.rows.map((c,a)=>Y(A,{color:a===Ce.cursor?V:void 0,children:[a===Ce.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===Ce.current?" \u2714":""}`.padEnd(30),j(A,{color:"gray",children:c.sub??""})]},c.id)),j(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ke?(()=>{let a=Math.min(Math.max(0,ke.cursor-Math.floor(7)),Math.max(0,ke.rows.length-14)),i=ke.rows.slice(a,a+14),f=ke.rows.filter(S=>S.checked).length;return Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:`Which folders back the user docs? (${f} selected of ${ke.rows.length})`}),a>0?j(A,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((S,W)=>{let p=a+W;return Y(A,{color:p===ke.cursor?V:void 0,children:[p===ke.cursor?"\u276F ":" ",S.checked?"\u25C9 ":"\u25CB ",S.path.padEnd(Math.min(48,Ue-34)),j(A,{color:"gray",children:zo(S)})]},S.path)}),a+14<ke.rows.length?j(A,{dimColor:!0,children:` \u2193 ${ke.rows.length-a-14} more`}):null,j(A,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():ze?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Which category? (pick one to scope to)"}),ze.rows.map((c,a)=>{let i=a===ze.cursor,f=`${a+1}.`.padEnd(3);return Y(A,{color:i?V:void 0,children:[i?"\u276F ":" ",`${f} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Ue-24))),j(A,{color:"gray",children:` ${c.token}`})]},c.token)}),j(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Ze?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Ze.rows.map((c,a)=>{let i=a===Ze.cursor,f=c.indent?" ":" ",S=`${a+1}.`.padEnd(3);return Y(A,{color:i?V:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${f}${S} ${c.label}`.padEnd(Math.min(56,Ue-24)),c.note?j(A,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),j(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):et?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:et.title}),(()=>{let{rows:a,cursor:i}=et,f=Math.max(0,Math.min(i-Math.floor(12/2),a.length-12)),S=a.slice(f,f+12),W=`${a.length}.`.length+1;return Y(zn,{children:[f>0?j(A,{color:"gray",children:` \u2026 ${f} more above`}):null,S.map((p,h)=>{let b=f+h,w=b===i;return Y(A,{color:w?V:void 0,bold:(p.kind==="all"||p.kind==="category")&&!w,children:[w?"\u276F ":" ",`${b+1}.`.padEnd(W)," ".repeat(p.depth),p.label,p.note?j(A,{color:"gray",children:p.note}):null]},`${p.action}:${p.kind}:${p.ids.join(",")}`)}),f+12<a.length?j(A,{color:"gray",children:` \u2026 ${a.length-f-12} more below`}):null]})})(),j(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):Re?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:`Preview article${Re.query?` \u2014 filter: ${Re.query}`:" (type to filter)"}`}),uo.length===0?j(A,{color:"gray",children:"no articles match"}):uo.map((c,a)=>Y(A,{color:a===Re.cursor?V:void 0,children:[a===Re.cursor?"\u276F ":" ",c]},c)),j(A,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Se?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:`Resume session${Se.query?` \u2014 filter: ${Se.query}`:" (type to filter)"}`}),po.length===0?j(A,{color:"gray",children:"no sessions match"}):po.map((c,a)=>Y(A,{color:a===Se.cursor?V:void 0,children:[a===Se.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),j(A,{color:a===Se.cursor?V:"gray",children:c.firstPrompt.slice(0,Math.max(10,Ue-40))})]},c.uuid)),j(A,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):va?Y(se,{flexDirection:"column",children:[xn.map((c,a)=>Y(A,{color:a===pn?V:void 0,children:[a===pn?"\u276F ":" ",c.usage.padEnd(22)," ",j(A,{color:a===pn?V:"gray",children:c.name==="model"&&Or?`${c.desc} (currently ${Or})`:c.desc})]},c.name)),j(A,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!v&&Be.length>0?Y(se,{flexDirection:"column",paddingX:1,children:[fa?j(A,{color:V,children:fa}):null,Be.map((c,a)=>{let i=Dt(c),f=i.slice(0,Math.max(20,Ue-5)),S=Ue-f.length-7,W=S>=12?(Bu(c)??$l(i)).slice(0,S):"";return Y(A,{children:[j(A,{color:V,children:a+1})," ",f,W?j(A,{dimColor:!0,children:` \u2014 ${W}`}):null]},i)}),j(A,{dimColor:!0,children:`press 1-${Be.length} to fill \xB7 esc cancel`})]}):j(se,{paddingX:1,children:Y(A,{color:"gray",children:[$a.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Or??"model n/a"}${t.kind==="api"?ya>0?` \xB7 ${$e(ya)}`:"":wa>0?` \xB7 ${lt(wa)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}H();import{jsx as by}from"react/jsx-runtime";async function vd(e=process.cwd(),t="auto",n,o="0.0.0"){let r=ky(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=yy(by($d,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
427
- `),process.exit(0)}H();import{writeCrashLog as Cd,isBenignTransportError as xy}from"document360-engine";var Rd=!1;function aa(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Sd(e){if(Rd)return;Rd=!0;let t=(n,o)=>{if(xy(o)){Cd({kind:n,level:"transport",message:aa(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=Cd({kind:n,level:"fatal",message:aa(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
428
- `+C(`\u2717 d360-writer crashed: ${aa(o)}`)+`
411
+ Model: ${We.model}${We.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:ie+Ks(W,J,ne).join(`
412
+ `)+me}),Q(`/write${h?` --scope ${h}`:""}`);return}mt.current=Date.now(),Et(0),D(!0);let $o=new AbortController;fe.current=$o,oe({verb:"Writing",total:W.length,done:0,active:[],rows:Yn(W),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${S.length} article${S.length===1?"":"s"} across ${W.length} partition${W.length===1?"":"s"} (\u2264${ne} agents at once) on ${We.model}${We.forced?" (forced)":""}\u2026 (esc to stop)`});let xo=new Set;try{for await(let J of Tr({cwd:e,partitions:W,promptFor:ie=>zs(ie,_,{rewrite:O||bo}),concurrency:ne,profileName:s,allowProdWrites:Lt.current,model:We.model,signal:$o.signal}))if(J.type==="partition_status")J.status==="running"?oe(ie=>ie&&{...ie,active:[...ie.active,J.label],rows:_e(ie.rows,J.label,"active"),lastAt:Date.now()}):oe(ie=>ie&&{...ie,active:ie.active.filter(me=>me!==J.label),done:ie.done+1,rows:_e(ie.rows,J.label,J.status==="done"?"done":"failed"),lastAt:Date.now()});else if(J.type==="partition_event"){let ie=null;if(J.event.type==="tool"){let me=Gu(J.event.name,J.event.input,W[J.index]?.paths??[]);me&&!xo.has(me)&&(xo.add(me),ie=J.label)}oe(me=>{if(!me)return me;let Fe={...me,lastAt:Date.now()};return J.event.type==="tool"?Fe.tools=me.tools+1:J.event.type==="text"&&(Fe.chars=me.chars+J.event.delta.length),ie&&(Fe.rows=Vu(Fe.rows,ie)),Fe})}else if(J.type==="run_done"){Bt(nt=>nt+J.totalCostUsd),Ht(nt=>nt+J.results.reduce((Ke,qd)=>Ke+qd.outputTokens,0));let ie=J.aborted?"Stopped. ":"",me=t.kind==="api"?"api":"subscription";if(u({kind:"note",tone:J.aborted?"warn":J.ok?"ok":"warn",text:ie+Xs(J.results,W,me).join(`
413
+ `)}),!J.aborted&&J.ok)try{let nt=(xo.size>0?[...xo]:S).map(Ke=>`${_}/${Ke}`);sa(e,nt,{writtenCap:ia})}catch{}let Fe=J.aborted?null:Qs(e,_,S);if(Fe&&u({kind:"note",tone:"warn",text:Fe}),!J.aborted&&J.ok){let nt=h??k??"",Ke=nt?` ${nt}`:"";be(Fe?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${Ke} --fix, then /review${Ke} --fix for editorial quality, then /publish --all (add /screenshot author --all first if you want images).`:`Written. I\u2019d run /review${Ke} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot author --all first if you want images).`,{kind:"cmd",cmd:Fe?`/check${Ke} --fix`:`/review${Ke} --fix`,reason:""})}}}catch(J){u({kind:"note",tone:"error",text:`Write run failed: ${J.message}`})}finally{fe.current=null,oe(null),D(!1),X(J=>J+1)}return}case"draft":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:p,looseDocs:h}=Zs(e);if(p.length===0&&h===0){u({kind:"note",tone:"info",text:ti});return}let k=f.join(" ").trim();if(!k&&p.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
414
+ ${p.map($=>` \u2022 ${$.name} (${$.docCount} doc${$.docCount===1?"":"s"})`).join(`
415
+ `)}`}),ft(p.map($=>`/draft ${$.name}`));return}let w="",T;if(k){let $=ei(p,k);$?w=$:T=k}else w=p[0]?.name??"";await te(Jo(w,T),{display:k?`/draft ${k}`:"/draft",quietUser:!0});return}case"pull":{if(!lo(c.trim()))return;let p=f.find(h=>h.startsWith("--"));try{if(p==="--status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let w=Date.now(),T=await oa({cwd:e,profileName:s});u({kind:"note",tone:"info",text:Ko(T,Date.now()-w).join(`
416
+ `)});return}if(p==="--baseline"){let w=f.find(S=>!S.startsWith("--")),T=w?w.replace(/\\/g,"/"):void 0;u({kind:"note",tone:"info",text:T?`Setting the sync baseline for ${T}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let $=await Xw({cwd:e,profileName:s,relPaths:T?[T]:void 0}),_=T?{rebaselined:[],skipped:[]}:await Qw({cwd:e,profileName:s});if($.baselined.length===0&&$.skipped.length===0&&_.rebaselined.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}$.baselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Baselined ${$.baselined.length} article${$.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),_.rebaselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${_.rebaselined.length} article${_.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),$.skipped.length>0&&u({kind:"note",tone:"warn",text:`${$.skipped.length} skipped:
417
+ ${$.skipped.map(S=>` - ${S.path} (${S.reason})`).join(`
418
+ `)}`}),X(S=>S+1);return}if(p==="--compare"){u({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let w=await Kw({cwd:e,profileName:s}),T=w.onlyInLegacy.length===0&&w.onlyInManifest.length===0&&w.mappedMissingFromManifest.length===0,$=[`Legacy listing: ${w.legacyCount} \xB7 Manifest: ${w.manifestCount} \xB7 in both: ${w.inBoth}`];T?$.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(w.mappedMissingFromManifest.length&&$.push(`\u2717 ${w.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${w.mappedMissingFromManifest.slice(0,5).join(", ")}`),w.onlyInLegacy.length&&$.push(`\u26A0 ${w.onlyInLegacy.length} only in the legacy listing: ${w.onlyInLegacy.slice(0,5).join(", ")}`),w.onlyInManifest.length&&$.push(`\u26A0 ${w.onlyInManifest.length} only in the manifest: ${w.onlyInManifest.slice(0,5).join(", ")}`),$.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),u({kind:"note",tone:T?"ok":"warn",text:$.join(`
419
+ `)});return}if(p){u({kind:"note",tone:"error",text:`Unknown option: ${p} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let h=f[0];if(h){let w=await pd({cwd:e,profileName:s,relPath:h.replace(/\\/g,"/")});ce.current=[{plan:w,mode:w.overwritesLocalChanges?"conflict":"pull"}],Ot.current=[],Yt();return}u({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let k=await Is({cwd:e,profileName:s});for(let w of _s(k))u({kind:"note",tone:w.tone,text:w.text});X(w=>w+1)}catch(h){u({kind:"note",tone:"error",text:`Pull failed: ${h.message}`})}return}case"scope":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=Jw(e);if(p.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}qt({cursor:0,rows:p.map(h=>({...h,checked:h.recommended}))});return}case"audit":{if(f[0]==="--auto"){let h=re(e);if(!h){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=f[1]!=="off";ld({...h,autoAudit:k},e),u({kind:"note",tone:"ok",text:k?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let p=await Ln();p.kind==="forward-to-agent"&&p.prompt&&await te(p.prompt,{display:p.display,quietUser:!0});return}case"check":{let p=f.find(w=>!w.startsWith("--")),h=p?` ${p}`:"",k=dd({cwd:e,scope:p});if(f.includes("--fix")){if(k.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}u({kind:"note",tone:"info",text:`Fixing ${k.length} doc issue${k.length===1?"":"s"}\u2026`});let w=gd(e,p);await te(Ni(k),{display:`/check${h} --fix`,quietUser:!0});try{sa(e,w,{reviewedCap:ia})}catch{}let T=dd({cwd:e,scope:p});u({kind:"note",tone:T.length===0?"ok":"warn",text:T.length===0?"\u2713 Doc-checker: all issues resolved.":ar(T).join(`
420
+ `)}),be(T.length===0?`Deterministic issues fixed. Next: /review${h} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${h} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${h} --fix`,reason:""});return}u({kind:"note",tone:k.length===0?"ok":"warn",text:ar(k).join(`
421
+ `)}),k.length>0&&be(`Found ${k.length} doc issue${k.length===1?"":"s"} above. /check${h} --fix has the agent fix them in place (or /review${h} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${h} --fix`,reason:""});return}case"structure":{let p=Hn(e,s);if(p.length===0){u({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}u({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...p].join(`
422
+ `)});return}case"reorder":{let p=_i(e,f);if(!p){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await te(p.prompt,{display:p.display,quietUser:!0}),be("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let p=Ii(e,f);if(!p){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=f.includes("--fix"),k=f.find(T=>!T.startsWith("--")),w=h?gd(e,k):[];if(await te(p.prompt,{display:p.display,quietUser:!0}),h)try{sa(e,w,{reviewedCap:ia})}catch{}if(h)be("\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 T=f.filter($=>$!=="--fix").join(" ");be(`The review listed issues above. /review${T?` ${T}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${T?` ${T}`:""} --fix`,reason:""})}return}case"capture-setup":{await F();return}case"devhints":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:Zt(Jt(e)).join(`
423
+ `)}),Vt(Pt()),kn.current=Ne(e).status==="current",Gt.current=Xe(e);return}case"discover":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await te(Ds(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if($i(e)===0){u({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await te(xi(),{display:"/inbox",quietUser:!0});return}case"feedback":{let p=md(e),h="";try{h=ln(p)?Pr(p,"utf8"):""}catch{h=""}if(!/^## /m.test(h)){u({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let k=await Ki(h.trim());u({kind:"note",tone:k?"ok":"warn",text:k?"\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 ${p} and copy it manually.`}),k&&qr(null);return}case"document":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:p,what:h}=oi(f);if(!h&&ni(e)===0){u({kind:"note",tone:"info",text:si});return}let k=`/document${h?` ${h}`:""}${p?" --publish":""}`;await te(ri(h,p),{display:k,quietUser:!0});return}case"catch-up":{if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!lo(c.trim()))return;let{publish:p}=Ci(f);u({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let h=await Si({cwd:e,profileName:s});for(let w of Pi(h))u({kind:"note",tone:w.startsWith("\u2713")?"ok":w.startsWith("\u2139")?"info":"warn",text:w});let k=qn(Fn(e));u({kind:"note",tone:"info",text:k?`Catching up on ${k}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await te(Ri({publish:p}),{display:`/catch-up${p?" --publish":""}`,quietUser:!0});return}case"update":{Wr.current=!0,u({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),Zn(!0);let p=await sr().finally(()=>Zn(!1));p.ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated ${p.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),Q("/exit"),ha("")):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${rr}`});return}case"screenshot":{let p=Nn(f);if(p.mode==="capture"){await R(p.rest);return}if(p.mode==="checklist"){await F();return}if(p.mode==="list"){if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=qe(e,p.scope);if(p.picker){if(w.length===0){u({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let $=Wl(w);if($.length===0){u({kind:"note",tone:"info",text:Fo(w,p.scope).join(`
424
+ `)}),be(`\u2713 All ${w.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}bt({cursor:0,rows:$,title:"Screenshots \u2014 pick what to author or capture:"});return}u({kind:"note",tone:"info",text:Fo(w,p.scope).join(`
425
+ `)});let T=w.filter($=>$.state==="placeholder").length;if(T>0){let $=p.scope?`/screenshot author ${p.scope}`:"/screenshot author --all";be(`${T} of ${w.length} still need${T===1?"s":""} a spec \u2014 /screenshot author <id> authors one, ${$} authors them all in parallel.`,{kind:"cmd",cmd:$,reason:""})}return}if(p.mode==="single"){await Ta(p.id);return}if(!re(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=p.mode==="scope"?p.scope:void 0,k=ny(e,{scope:h}).map(w=>w.id);if(k.length===0){u({kind:"note",tone:"info",text:h?`No screenshot placeholders under ${h}.`:"No screenshot placeholders found in the docs."});return}await Pa(k,{setup:p.setup,runLine:p.mode==="scope"?[`/screenshot author ${p.scope}`,`/screenshot ${p.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await R(f);return}case"reset":{let p=Ai(e);if(p.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}no.current={repoName:zn(e),targets:p,hadDevhints:ln(fd(e))},u({kind:"note",tone:"warn",text:Ei(e,p).join(`
426
+ `)}),ye(zn(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Yt,Xr,u,Pe,te,St,Vr,Da]),yo=Y(c=>{let a=(c??v).trim();if(x(""),eo(null),Nt(0),a.startsWith("/")&&(Xn.current=!1,Me(),hn(null),ft(f=>Ku(f,a))),!a||(pa(!1),ja(a))||Aa(a))return;Ir.current.push(a);let i=Zu(a,fa.current);if(a.startsWith("/"))u({kind:"user",text:a}),Je(!0),xn(i).finally(()=>Je(!1));else if(py(i)){u({kind:"user",text:a});let f=hy(i);if(!f)te(i,{display:a,quietUser:!0});else{try{fy(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}te(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${f}". 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 "${f}" and the article path(s) you wrote.`,{display:a,quietUser:!0})}}else{let f=yu(e,i);te(f??i,{display:a})}},[v,ja,Aa,xn,te]),Ea=Y(c=>{if(c.length>1){if(c.includes("\x1B"))return;let a=Xu(c);if(Qu(a)){let i=Ju(++Ld.current,a);fa.current.set(i,a),I(i)}else I(a);return}I(c)},[I]),zt=Math.max(10,Ue-6),Na=ea(()=>Rr(y.text,zt),[y.text,zt]),Qr=Y(c=>b(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+c))})),[]),ko=Y(c=>b(a=>({...a,pos:td(Rr(a.text,zt),a.pos,c)})),[zt]),vn=Y(c=>b(a=>({...a,pos:nd(Rr(a.text,zt),a.pos,c)})),[zt]),Wd=["\x1B[H","\x1B[1~","\x1BOH"],Fd=["\x1B[F","\x1B[4~","\x1BOF"],Ia=Y((c,a)=>a.leftArrow?(Qr(-1),!0):a.rightArrow?(Qr(1),!0):c&&Wd.includes(c)?(vn("start"),!0):c&&Fd.includes(c)?(vn("end"),!0):a.ctrl&&c==="a"?(vn("start"),!0):a.ctrl&&c==="e"?(vn("end"),!0):!1,[Qr,vn]);return Pw((c,a)=>{if(a.ctrl&&c==="c"){je.current?.close(),r();return}if(!U){if(j){if(a.escape){if(fe.current){if(!fe.current.signal.aborted){let i=(oo?.verb??"work").toLowerCase(),f=oo?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${f}s)\u2026`}),fe.current.abort()}return}fn.current||(fn.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),je.current?.interrupt());return}if(a.return){let i=v.trim();if(!i)return;vt.current.push(i),Lr([...vt.current]),x("");return}if(Ia(c,a))return;if(a.upArrow){ko(-1);return}if(a.downArrow){ko(1);return}if(a.backspace||a.delete){P();return}c&&!a.ctrl&&!a.meta&&Ea(c);return}if(wt){if(a.upArrow){yt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){yt(i=>i&&{...i,cursor:Math.min(He.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=He.length){yt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=He[wt.cursor];yt(null);let{lines:f,changed:R,effective:F}=Mn(e,i.value??"default");for(let p of f)u({kind:"note",tone:p.startsWith("\u26A0")?"warn":p.startsWith("\u2713")?"ok":"info",text:p});R&&($a(p=>p+1),je.current?.setModel(F));return}if(c==="s"){let i=He[wt.cursor];yt(null),je.current?.setModel(i.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){yt(null);return}return}if(Ge){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(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ge.rows.length){Mt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return||c==="s"){let i=Ge.rows[Ge.cursor];Mt(null),zr(i.name,a.return===!0);return}if(a.escape){Mt(null);return}return}if(io){if(a.escape){wn(null);return}if(a.leftArrow||a.tab&&a.shift){wn(i=>i&&{tab:(i.tab-1+Ee.length)%Ee.length});return}if(a.rightArrow||a.tab){wn(i=>i&&{tab:(i.tab+1)%Ee.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ee.length){wn({tab:Number(c)-1});return}return}if(Ye){if(a.upArrow){Ut(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ut(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ye.rows.length){Ut(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Ye.rows[Ye.cursor].name;if(Ut(null),!is(e,i).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let R=!1;try{let F=At(i);R=!!F&&!(pt(F)&&!F.refreshToken)}catch{R=!1}u({kind:"note",tone:"info",text:R?`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"),X(F=>F+1);return}if(a.escape){Ut(null);return}return}if(we){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(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=we.rows.length){Wt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=we.rows[we.cursor],{profile:f,projectId:R}=we;Wt(null),mo(f,R,i);return}if(a.escape){Wt(null);return}return}if(Ce){if(a.upArrow){kt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){kt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ce.rows.length){kt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Ce.rows[Ce.cursor],{profile:f}=Ce;kt(null),wo(f,i);return}if(a.escape){kt(null);return}return}if(ke){if(a.upArrow){qt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){qt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){qt(i=>i&&{...i,rows:i.rows.map((f,R)=>R===i.cursor?{...f,checked:!f.checked}:f)});return}if(a.return){let i=ke.rows.filter(f=>f.checked).map(f=>f.path);if(qt(null),i.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}As(e,i),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of i)u({kind:"note",tone:"info",text:` ${f}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){qt(null);return}return}if(ze){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&&/^[1-9]$/.test(c)&&Number(c)<=ze.rows.length){$t(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=ze.rows[ze.cursor],f=ze.run;$t(null),f(i.token);return}if(a.escape){$t(null);return}return}if(Ze){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)<=Ze.rows.length){Ft(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Ze.rows[Ze.cursor];Ft(null),i.conflict?Xr(i.paths[0]):i.kind==="article"?Vr(i.paths[0]):St(i.paths);return}if(a.escape){Ft(null);return}return}if(et){if(a.upArrow){bt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){bt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=et.rows.length){bt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=et.rows[et.cursor];bt(null),i.action==="capture"?Gr(i.ids,{runLine:i.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):i.kind==="shot"?Ta(i.ids[0]):Pa(i.ids,{setup:!0,runLine:i.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(a.escape){bt(null);return}return}if(Re){if(a.escape){xt(null);return}if(a.upArrow){xt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){xt(i=>i&&{...i,cursor:Math.min(Math.max(0,po.length-1),i.cursor+1)});return}if(a.return){let i=po[Re.cursor];if(i){xt(null);try{u({kind:"preview",name:zn(i),text:vd(Pr(ta(e,i),"utf8"))})}catch(f){u({kind:"note",tone:"error",text:`Could not read ${i}: ${f.message}`})}}return}if(a.backspace||a.delete){xt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){xt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(Se){if(a.escape){Ct(null);return}if(a.upArrow){Ct(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ct(i=>i&&{...i,cursor:Math.min(Math.max(0,ho.length-1),i.cursor+1)});return}if(a.return){let i=ho[Se.cursor];if(i){Ct(null),Pe(i.uuid),Ve.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},gt(i.name),na(i.uuid),_t.current=[];let f=Qi(e,i.uuid);for(let R of f)u(R);u({kind:"note",tone:"ok",text:f.length?`Resumed "${i.name}" \u2014 restored ${f.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){Ct(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){Ct(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(a.tab&&!v&&ge){x(ge),Me();return}if(!v&&Be.length>0&&!Er&&c&&/^[1-9]$/.test(c)){let i=Be[Number(c)-1];if(i){x(Dt(i));return}}if(!v&&(co||yn)&&c==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let i=co!=null;Ki(co??yn).then(R=>{u({kind:"note",tone:R?"ok":"warn",text:R?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."}),R&&i&&qr(null),R&&!i&&va(!0)});return}if(!Ia(c,a)){if(Ra){if(a.upArrow){Nt(i=>Math.max(0,i-1));return}if(a.downArrow){Nt(i=>Math.min($n.length-1,i+1));return}if(a.tab){x("/"+($n[pn]?.name??"")+" "),Nt(0);return}if(a.return){let i=$n[pn];if(i){let f=v.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Sl(i.usage)&&!f){x("/"+i.name+" "),Nt(0);return}yo("/"+i.name+(f?" "+f:""));return}}}else{if(a.upArrow){if(v!==""&&It===null){ko(-1);return}let i=Ir.current;if(!i.length)return;let f=It===null?i.length-1:Math.max(0,It-1);eo(f),x(i[f]??"");return}if(a.downArrow){if(v!==""&&It===null){ko(1);return}let i=Ir.current;if(It===null)return;let f=It+1;f>=i.length?(eo(null),x("")):(eo(f),x(i[f]??""));return}}if(a.return){yo();return}if(a.backspace||a.delete){P();return}if(a.escape){x(""),Nt(0),Me(),ft([]),hn(null),Xn.current=!0;return}c&&!a.ctrl&&!a.meta&&Ea(c)}}}),Ae(()=>{if(j||U)return;let c=vt.current.shift();c!==void 0&&(Lr([...vt.current]),yo(c))},[j,U,yo]),z(se,{flexDirection:"column",width:Ue,children:[Br!==null&&z(se,{marginTop:1,flexDirection:"column",children:[Br.truncated&&E(A,{dimColor:!0,children:"\u2026"}),E(A,{children:Br.text})]}),j&&(oo?E(Cy,{p:oo}):E($y,{startTime:mt.current,chars:_d})),!j&&ya?E(xy,{text:ya}):null,E(se,{borderStyle:"round",borderColor:Ca.prod?"yellow":V,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:v?Na.map((c,a)=>{let i=y.text.slice(c.start,c.end),f=a===Sr(Na,y.pos),R=Math.min(y.pos,c.end)-c.start;return z(A,{children:[E(A,{color:V,children:a===0?"> ":" "}),f?z(Kn,{children:[i.slice(0,R),E(cn,{ch:i[R]??" "}),i.slice(R+1)]}):i||" "]},`${a}-${c.start}`)}):z(A,{children:[E(A,{color:V,children:"> "}),Or?E(cn,{ch:" "}):ge&&!j&&ve?z(Kn,{children:[E(cn,{ch:ve[0],dim:!0}),E(A,{color:"gray",children:ve.slice(1)})]}):ge&&!j?z(Kn,{children:[E(cn,{ch:ge[0],dim:!0}),E(A,{color:"gray",children:ge.slice(1)}),E(A,{dimColor:!0,children:" (tab)"})]}):(Hr.isSetup||!Nd)&&!j?z(Kn,{children:[E(cn,{ch:Hr.text[0],dim:!0}),E(A,{color:"gray",children:Hr.text.slice(1)})]}):E(cn,{ch:" "})]})}),wa.length>0&&E(se,{flexDirection:"column",paddingX:1,children:wa.map((c,a)=>E(A,{color:"gray",children:`\u29D7 queued: ${c}`},`${a}-${c.slice(0,24)}`))}),io?E(Hu,{tab:io.tab,width:Ue,version:o,engineVersion:Cd}):wt?z(se,{flexDirection:"column",paddingX:1,children:[E(A,{color:V,bold:!0,children:"Select model"}),E(A,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),He.map((c,a)=>z(A,{color:a===wt.cursor?V:void 0,children:[a===wt.cursor?"\u276F ":" ",`${a+1}. ${c.label}${a===wt.current?" \u2714":""}`.padEnd(16),E(A,{color:"gray",children:c.desc})]},c.label)),E(A,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Ge?z(se,{flexDirection:"column",paddingX:1,children:[E(A,{color:V,bold:!0,children:"Switch connection profile"}),Ge.rows.map((c,a)=>z(A,{color:a===Ge.cursor?V:void 0,children:[a===Ge.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===Ge.current?" \u2714":""}`.padEnd(20),E(A,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?E(A,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),E(A,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ye?z(se,{flexDirection:"column",paddingX:1,children:[E(A,{color:V,bold:!0,children:"Pick your Document360 environment"}),Ye.rows.map((c,a)=>z(A,{color:a===Ye.cursor?V:void 0,children:[a===Ye.cursor?"\u276F ":" ",`${a+1}. ${c.name}`.padEnd(16),E(A,{color:"gray",children:c.apiUrl})]},c.name)),E(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):we?z(se,{flexDirection:"column",paddingX:1,children:[E(A,{color:V,bold:!0,children:"Switch workspace"}),E(A,{dimColor:!0,children:`environment ${we.environment} \xB7 project ${we.projectName??`${we.projectId.slice(0,8)}\u2026`}`}),we.rows.map((c,a)=>z(A,{color:a===we.cursor?V:void 0,children:[a===we.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===we.current?" \u2714":""}`.padEnd(30),E(A,{color:"gray",children:c.type??""})]},c.id)),E(A,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):Ce?z(se,{flexDirection:"column",paddingX:1,children:[E(A,{color:V,bold:!0,children:"Choose project"}),E(A,{dimColor:!0,children:`environment ${Ce.environment}`}),Ce.rows.map((c,a)=>z(A,{color:a===Ce.cursor?V:void 0,children:[a===Ce.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===Ce.current?" \u2714":""}`.padEnd(30),E(A,{color:"gray",children:c.sub??""})]},c.id)),E(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ke?(()=>{let a=Math.min(Math.max(0,ke.cursor-Math.floor(7)),Math.max(0,ke.rows.length-14)),i=ke.rows.slice(a,a+14),f=ke.rows.filter(R=>R.checked).length;return z(se,{flexDirection:"column",paddingX:1,children:[E(A,{color:V,bold:!0,children:`Which folders back the user docs? (${f} selected of ${ke.rows.length})`}),a>0?E(A,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((R,F)=>{let p=a+F;return z(A,{color:p===ke.cursor?V:void 0,children:[p===ke.cursor?"\u276F ":" ",R.checked?"\u25C9 ":"\u25CB ",R.path.padEnd(Math.min(48,Ue-34)),E(A,{color:"gray",children:zo(R)})]},R.path)}),a+14<ke.rows.length?E(A,{dimColor:!0,children:` \u2193 ${ke.rows.length-a-14} more`}):null,E(A,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():ze?z(se,{flexDirection:"column",paddingX:1,children:[E(A,{color:V,bold:!0,children:"Which category? (pick one to scope to)"}),ze.rows.map((c,a)=>{let i=a===ze.cursor,f=`${a+1}.`.padEnd(3);return z(A,{color:i?V:void 0,children:[i?"\u276F ":" ",`${f} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Ue-24))),E(A,{color:"gray",children:` ${c.token}`})]},c.token)}),E(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Ze?z(se,{flexDirection:"column",paddingX:1,children:[E(A,{color:V,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Ze.rows.map((c,a)=>{let i=a===Ze.cursor,f=c.indent?" ":" ",R=`${a+1}.`.padEnd(3);return z(A,{color:i?V:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${f}${R} ${c.label}`.padEnd(Math.min(56,Ue-24)),c.note?E(A,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),E(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):et?z(se,{flexDirection:"column",paddingX:1,children:[E(A,{color:V,bold:!0,children:et.title}),(()=>{let{rows:a,cursor:i}=et,f=Math.max(0,Math.min(i-Math.floor(12/2),a.length-12)),R=a.slice(f,f+12),F=`${a.length}.`.length+1;return z(Kn,{children:[f>0?E(A,{color:"gray",children:` \u2026 ${f} more above`}):null,R.map((p,h)=>{let k=f+h,w=k===i;return z(A,{color:w?V:void 0,bold:(p.kind==="all"||p.kind==="category")&&!w,children:[w?"\u276F ":" ",`${k+1}.`.padEnd(F)," ".repeat(p.depth),p.label,p.note?E(A,{color:"gray",children:p.note}):null]},`${p.action}:${p.kind}:${p.ids.join(",")}`)}),f+12<a.length?E(A,{color:"gray",children:` \u2026 ${a.length-f-12} more below`}):null]})})(),E(A,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):Re?z(se,{flexDirection:"column",paddingX:1,children:[E(A,{color:V,bold:!0,children:`Preview article${Re.query?` \u2014 filter: ${Re.query}`:" (type to filter)"}`}),po.length===0?E(A,{color:"gray",children:"no articles match"}):po.map((c,a)=>z(A,{color:a===Re.cursor?V:void 0,children:[a===Re.cursor?"\u276F ":" ",c]},c)),E(A,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Se?z(se,{flexDirection:"column",paddingX:1,children:[E(A,{color:V,bold:!0,children:`Resume session${Se.query?` \u2014 filter: ${Se.query}`:" (type to filter)"}`}),ho.length===0?E(A,{color:"gray",children:"no sessions match"}):ho.map((c,a)=>z(A,{color:a===Se.cursor?V:void 0,children:[a===Se.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),E(A,{color:a===Se.cursor?V:"gray",children:c.firstPrompt.slice(0,Math.max(10,Ue-40))})]},c.uuid)),E(A,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Ra?z(se,{flexDirection:"column",children:[$n.map((c,a)=>z(A,{color:a===pn?V:void 0,children:[a===pn?"\u276F ":" ",c.usage.padEnd(22)," ",E(A,{color:a===pn?V:"gray",children:c.name==="model"&&Mr?`${c.desc} (currently ${Mr})`:c.desc})]},c.name)),E(A,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!j&&!v&&Be.length>0?z(se,{flexDirection:"column",paddingX:1,children:[ga?E(A,{color:V,children:ga}):null,Be.map((c,a)=>{let i=Dt(c),f=i.slice(0,Math.max(20,Ue-5)),R=Ue-f.length-7,F=R>=12?(zu(c)??Cl(i)).slice(0,R):"";return z(A,{children:[E(A,{color:V,children:a+1})," ",f,F?E(A,{dimColor:!0,children:` \u2014 ${F}`}):null]},i)}),E(A,{dimColor:!0,children:`press 1-${Be.length} to fill \xB7 esc cancel`})]}):E(se,{paddingX:1,children:z(A,{color:"gray",children:[Ca.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Mr??"model n/a"}${t.kind==="api"?ba>0?` \xB7 ${xe(ba)}`:"":ka>0?` \xB7 ${lt(ka)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}H();import{jsx as Ty}from"react/jsx-runtime";async function Pd(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Py(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Sy(Ty(Sd,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
427
+ `),process.exit(0)}H();import{writeCrashLog as Td,isBenignTransportError as Dy}from"document360-engine";var Dd=!1;function ca(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Ad(e){if(Dd)return;Dd=!0;let t=(n,o)=>{if(Dy(o)){Td({kind:n,level:"transport",message:ca(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=Td({kind:n,level:"fatal",message:ca(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
428
+ `+C(`\u2717 d360-writer crashed: ${ca(o)}`)+`
429
429
  `),r&&process.stderr.write(g(` Crash details: ${r}`)+`
430
430
  `+g(" Run: d360-writer logs")+`
431
- `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Ry=vy(import.meta.url),Dr=Ry("../package.json");Sd("d360-writer");var Le=new $y;function la(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Le.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{la(e),await To({profile:e.profile,manual:e.manual})});Le.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{la(e),await Ba({profile:e.profile})});Le.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{la(e),await Ha({profile:e.profile})});var ca=Le.command("profile").description("Manage connection profiles for the current repo");ca.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Do(process.cwd()));ca.command("use <name>").description("Set the default profile for this repo").action(e=>Ao(process.cwd(),e));ca.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>jo(process.cwd(),e));var Pd=Le.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Pd.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Kt(process.cwd(),e.profile));Pd.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await La(process.cwd(),e,t.profile)});var Td=Le.command("project").description("Choose the Document360 project for this repo (active profile's identity)");Td.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Ro(process.cwd(),e.profile));Td.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Ma(process.cwd(),e,t.profile)});Le.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Oo(),kl));await e()});Le.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>za());Le.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(er(),Nc)),n=await t(process.cwd(),Dr.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Le.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Dr.version,"-v, --version").option("-p, --prompt <text>","One-shot prompt mode (non-interactive)").option("-r, --resume <name>","Resume a saved session (with --prompt; use /resume inside the REPL)").option("-C, --cwd <dir>","Working directory",process.cwd()).option("--auth <mode>","Auth mode: auto | api | subscription","auto").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--yes","Skip the production write confirmation (for one-shot/CI)").option("--classic","Use the plain readline REPL instead of the Ink TUI").action(async e=>{if(Cy.includes(e.auth)||(console.error(`\u2717 Invalid --auth mode: ${e.auth}`),console.error("Run: d360-writer --auth auto | api | subscription"),process.exit(2)),e.prompt){await Ka(e.cwd,e.prompt,e.auth,e.resume,e.profile,e.yes);return}e.resume&&(console.error("\u2717 --resume requires --prompt. In the interactive REPL, use /resume instead."),process.exit(2)),e.classic||!process.stdin.isTTY?await ju(e.cwd,e.auth,e.profile,Dr.version):await vd(e.cwd,e.auth,e.profile,Dr.version)});Le.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
431
+ `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Ny=jy(import.meta.url),Ar=Ny("../package.json");Ad("d360-writer");var Le=new Ay;function ua(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Le.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{ua(e),await To({profile:e.profile,manual:e.manual})});Le.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{ua(e),await Ga({profile:e.profile})});Le.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{ua(e),await Va({profile:e.profile})});var da=Le.command("profile").description("Manage connection profiles for the current repo");da.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Do(process.cwd()));da.command("use <name>").description("Set the default profile for this repo").action(e=>Ao(process.cwd(),e));da.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>jo(process.cwd(),e));var jd=Le.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");jd.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Kt(process.cwd(),e.profile));jd.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Ma(process.cwd(),e,t.profile)});var Ed=Le.command("project").description("Choose the Document360 project for this repo (active profile's identity)");Ed.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Ro(process.cwd(),e.profile));Ed.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Wa(process.cwd(),e,t.profile)});Le.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Oo(),$l));await e()});Le.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>Xa());Le.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(tr(),Oc)),n=await t(process.cwd(),Ar.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Le.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Ar.version,"-v, --version").option("-p, --prompt <text>","One-shot prompt mode (non-interactive)").option("-r, --resume <name>","Resume a saved session (with --prompt; use /resume inside the REPL)").option("-C, --cwd <dir>","Working directory",process.cwd()).option("--auth <mode>","Auth mode: auto | api | subscription","auto").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--yes","Skip the production write confirmation (for one-shot/CI)").option("--classic","Use the plain readline REPL instead of the Ink TUI").action(async e=>{if(Ey.includes(e.auth)||(console.error(`\u2717 Invalid --auth mode: ${e.auth}`),console.error("Run: d360-writer --auth auto | api | subscription"),process.exit(2)),e.prompt){await Qa(e.cwd,e.prompt,e.auth,e.resume,e.profile,e.yes);return}e.resume&&(console.error("\u2717 --resume requires --prompt. In the interactive REPL, use /resume instead."),process.exit(2)),e.classic||!process.stdin.isTTY?await _u(e.cwd,e.auth,e.profile,Ar.version):await Pd(e.cwd,e.auth,e.profile,Ar.version)});Le.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});