document360-writer 0.5.132 → 0.5.134

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 +105 -104
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var Su=Object.defineProperty;var yo=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var ba=(e,t)=>{for(var n in t)Su(e,n,{get:t[n],enumerable:!0})};import nt from"picocolors";var V,Pu,Tu,Du,$a,Cn,m,v,M,E,L,ae,$e,H=yo(()=>{"use strict";V="#7f56d9",[Pu,Tu,Du]=[127,86,217],$a=e=>nt.isColorSupported?`\x1B[38;2;${Pu};${Tu};${Du}m${e}\x1B[39m`:e,Cn=e=>nt.bold($a(e)),m=e=>nt.dim(e),v=e=>nt.red(e),M=e=>nt.yellow(e),E=e=>nt.green(e),L=$a,ae=e=>nt.gray(e),$e=e=>nt.bold(e)});import{existsSync as Qt,writeFileSync as rt,readFileSync as fp,readdirSync as mp}from"node:fs";import{join as Ua}from"node:path";import{devHintsGuidePath as To,hintsDir as Wa,hooksDir as Fa,architectureDir as Ga,messagesDir as Qr,creatorNotesPath as Ha,devhintsStatePath as Ya,directivesPath as qa,DIRECTIVES_HEADER as gp,roadmapPath as Ba,ROADMAP_HEADER as wp,ensureDir as Pn,writeMessage as yp,listOpenForDev as kp}from"document360-engine";function za(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var Pu=Object.defineProperty;var ko=(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)Pu(e,n,{get:t[n],enumerable:!0})};import nt from"picocolors";var V,Tu,Du,Au,xa,Cn,m,v,M,E,L,ae,$e,q=ko(()=>{"use strict";V="#7f56d9",[Tu,Du,Au]=[127,86,217],xa=e=>nt.isColorSupported?`\x1B[38;2;${Tu};${Du};${Au}m${e}\x1B[39m`:e,Cn=e=>nt.bold(xa(e)),m=e=>nt.dim(e),v=e=>nt.red(e),M=e=>nt.yellow(e),E=e=>nt.green(e),L=xa,ae=e=>nt.gray(e),$e=e=>nt.bold(e)});import{existsSync as Qt,writeFileSync as rt,readFileSync as mp,readdirSync as gp}from"node:fs";import{join as Wa}from"node:path";import{devHintsGuidePath as Do,hintsDir as Fa,hooksDir as qa,architectureDir as Ya,messagesDir as Jr,creatorNotesPath as Ha,devhintsStatePath as za,directivesPath as Ba,DIRECTIVES_HEADER as wp,roadmapPath as Va,ROADMAP_HEADER as yp,ensureDir as Pn,writeMessage as kp,listOpenForDev as bp}from"document360-engine";function Ka(){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 $p(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
221
+ `}function xp(){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 Zt(e){Pn(Wa(e)),Pn(Ga(e)),Pn(Qr(e));for(let n of[Wa(e),Qr(e)]){let o=Ua(n,".gitkeep");Qt(o)||rt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
236
- `)}Qt(Ha(e))||rt(Ha(e),$p()),Qt(qa(e))||rt(qa(e),gp),Qt(Ba(e))||rt(Ba(e),wp),rt(To(e),za()),Pn(Fa(e)),rt(Ua(Fa(e),"open-questions.mjs"),bp);let t=Ie(e);return Xa(e,new Date().toISOString()),t}async function Ka(e,t){for(let n of en(Zt(t.cwd)))console.log(n);return{kind:"continue"}}function Ct(){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 Jr(e){try{let t=fp(Ya(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Xa(e,t){let o={...Jr(e)??{},emittedVersion:le,emittedAt:t};rt(Ya(e),`${JSON.stringify(o,null,2)}
238
- `)}function Ke(e){try{return mp(Ga(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ie(e){let n=Jr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<le?"stale":"current",completedVersion:n}}function Do(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:le};try{if(!Qt(To(e)))return n;let o=Jr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;le>r&&(Pn(Qr(e)),rt(To(e),za()),Xa(e,t),n.guideRefreshed=!0),le>s&&(kp(e).some(u=>u.kind==="request"&&u.subject.startsWith(Va))||(yp(e,{id:`onb${le}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Va}${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:","",Ct()].join(`
239
- `)}),n.notifiedBuilder=!0))}catch{}return n}function Ao(e){if(!Qt(To(e)))return[];let t=Ie(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${le}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Jt,Ct(),Jt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Zr(){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 jo(){return['\u{1F9F9} One leftover: your builder still has the "Documentation hand-off" rule in its CLAUDE.md / AGENTS.md'," (reset only clears d360-writer's own .d360-writer/ folder \u2014 never your repo's files)."," To restore it, paste this prompt into your repo's coding agent (Claude Code / Codex / Cursor):",Jt,Zr(),Jt]}function en(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):",Jt,Ct(),Jt,"","That one run writes the architecture brief, adds the ongoing rule to your agent memory (CLAUDE.md / AGENTS.md)","and commits it so teammates inherit it, answers any open questions the writer left, and asks you for tribal","knowledge \u2014 no manual file edits. It also sets up the two-way channel: the writer can ask you questions","(`/inbox` on its side), and you can ask it to document a session on demand (Part 4 of the guide).","","When it finishes, come back to THIS terminal and run:"," write the docs for this repo"]}var Jt,le,bp,Va,st=yo(()=>{"use strict";Jt="-".repeat(64),le=10,bp=`#!/usr/bin/env node
235
+ `}function Zt(e){Pn(Fa(e)),Pn(Ya(e)),Pn(Jr(e));for(let n of[Fa(e),Jr(e)]){let o=Wa(n,".gitkeep");Qt(o)||rt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
236
+ `)}Qt(Ha(e))||rt(Ha(e),xp()),Qt(Ba(e))||rt(Ba(e),wp),Qt(Va(e))||rt(Va(e),yp),rt(Do(e),Ka()),Pn(qa(e)),rt(Wa(qa(e),"open-questions.mjs"),$p);let t=Ie(e);return Qa(e,new Date().toISOString()),t}async function Xa(e,t){for(let n of en(Zt(t.cwd)))console.log(n);return{kind:"continue"}}function Ct(){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 Zr(e){try{let t=mp(za(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Qa(e,t){let o={...Zr(e)??{},emittedVersion:le,emittedAt:t};rt(za(e),`${JSON.stringify(o,null,2)}
238
+ `)}function Ke(e){try{return gp(Ya(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ie(e){let n=Zr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<le?"stale":"current",completedVersion:n}}function Ao(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:le};try{if(!Qt(Do(e)))return n;let o=Zr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;le>r&&(Pn(Jr(e)),rt(Do(e),Ka()),Qa(e,t),n.guideRefreshed=!0),le>s&&(bp(e).some(u=>u.kind==="request"&&u.subject.startsWith(Ga))||(kp(e,{id:`onb${le}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Ga}${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:","",Ct()].join(`
239
+ `)}),n.notifiedBuilder=!0))}catch{}return n}function jo(e){if(!Qt(Do(e)))return[];let t=Ie(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${le}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Jt,Ct(),Jt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function es(){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 Eo(){return['\u{1F9F9} One leftover: your builder still has the "Documentation hand-off" rule in its CLAUDE.md / AGENTS.md'," (reset only clears d360-writer's own .d360-writer/ folder \u2014 never your repo's files)."," To restore it, paste this prompt into your repo's coding agent (Claude Code / Codex / Cursor):",Jt,es(),Jt]}function en(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):",Jt,Ct(),Jt,"","That one run writes the architecture brief, adds the ongoing rule to your agent memory (CLAUDE.md / AGENTS.md)","and commits it so teammates inherit it, answers any open questions the writer left, and asks you for tribal","knowledge \u2014 no manual file edits. It also sets up the two-way channel: the writer can ask you questions","(`/inbox` on its side), and you can ask it to document a session on demand (Part 4 of the guide).","","When it finishes, come back to THIS terminal and run:"," write the docs for this repo"]}var Jt,le,$p,Ga,st=ko(()=>{"use strict";Jt="-".repeat(64),le=10,$p=`#!/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,56 +275,56 @@ try {
275
275
  } catch {
276
276
  /* a session-start nudge must never break the session */
277
277
  }
278
- `;Va="Re-run dev\u2194docs onboarding (protocol v"});var il={};ba(il,{initCommand:()=>ts,scaffoldInit:()=>es});import{input as Tn,confirm as xp}from"@inquirer/prompts";import{basename as Qa,join as Eo}from"node:path";import{existsSync as tn,readFileSync as vp,readdirSync as Cp,writeFileSync as Rp}from"node:fs";import{writeProjectConfig as Ja,readProjectConfig as Sp,projectConfigPath as Za,writerDir as Pp,DEFAULT_DOCS_DIR as el,DEFAULT_CAPTURE_DIR as tl,DEFAULT_OUTPUT_DIR as nl}from"document360-engine";function es(e,t="berlin"){let n=Za(e);if(tn(n))return{created:!1,path:n,profileName:""};let o={projectId:rl(e)??Qa(e),docsDir:el,captureDir:tl,outputDir:nl,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:sl(e)};return Ja(o,e),ol(e),{created:!0,path:n,profileName:t}}function ol(e){let t=Eo(Pp(e),".gitignore");tn(t)||Rp(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
279
- `),"utf8")}async function ts(){let e=process.cwd(),t=Za(e);if(tn(t)&&!await xp({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(m("init cancelled.")),{kind:"continue"};let n=rl(e)??Qa(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:tl}),s=await Tn({message:"Screenshot output directory:",default:nl}),a=await Tn({message:"Default connection profile name:",default:"berlin"}),u=await Tn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:el,captureDir:r,outputDir:s,profiles:{[a]:{connection:{environment:u},production:!1}},defaultProfile:a,authoritativeSourceFiles:sl(e)},b=Sp(e);b?.terminologyGlossary&&(g.terminologyGlossary=b.terminologyGlossary),Ja(g,e),ol(e);let y=Zt(e);console.log(""),console.log(E(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${L(`d360-writer login --profile ${a}`)} ${m("(sign in; project & workspace auto-selected)")}`),console.log("");for(let P of en(y))console.log(P);return console.log(""),console.log(`${m("Then ask:")} ${L('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function rl(e){let t=Eo(e,"package.json");if(!tn(t))return null;try{return JSON.parse(vp(t,"utf8")).name??null}catch{return null}}function sl(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])tn(Eo(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Eo(e,n);tn(o)&&!Tp(o)&&t.push(n)}return t}function Tp(e){try{return Cp(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var No=yo(()=>{"use strict";H();st()});var fc={};ba(fc,{doctorCommand:()=>Ln,renderDoctorChecks:()=>hc,runDoctorChecks:()=>pc});import{existsSync as bf}from"node:fs";import{d360GetAll as $f,getAccessToken as xf,isExpired as Xs,loadProfileMap as vf,loadTokens as Cf,packageSkillsDir as dc,ENGINE_VERSION as Rf,projectConfigPath as Sf,readProjectConfig as Pf,DEFAULT_DOCS_DIR as Tf,fetchManifestSummary as Df,resolveActiveProfile as Af,classifyClaudeAuth as jf,CLAUDE_CODE_SETUP_HINT as uc,resolveModelSetting as Ef,probeModel as Nf,detectAppType as If,playbookSkillName as _f,D360AuthError as Lf}from"document360-engine";async function pc(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Rf}`});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=jf();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. ${uc}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:uc});let s=Ef(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 C=await Nf(e,s.model??void 0);C.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(C.latencyMs/1e3).toFixed(1)}s`}):C.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 ${C.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 a=Pf(e);if(!a)return n.push({level:"fail",label:`No ${Sf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let u=(a.docsDir??Tf).replace(/\/+$/,"");n.push(a.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${u}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let g=a.authoritativeSourceFiles??[];n.push(g.length>0?{level:"ok",label:`Sources: docs grounded in ${g.length} path(s) (${g.slice(0,3).join(", ")}${g.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=a.appType??If(e);if(b){let C=a.appType?"from config":"auto-detected",N=b==="web"||b==="cli";n.push({level:"ok",label:`Genre: ${b} (${C})${N?` \u2192 ${_f(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 y;try{y=Af(e),n.push({level:"ok",label:`Profile: ${y.name} (${y.connection.name})${y.production?" \u26A0 PRODUCTION":""}`})}catch(C){return n.push({level:"fail",label:`Profile config: ${C.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let P=Cf(y.name);P?Xs(P)&&!P.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Xs(P)?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(P.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 x=vf(e,y.name);x?x.projectId&&y.project.projectId&&x.projectId!==y.project.projectId?n.push({level:"fail",label:`Category map projectId (${x.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(x.articles).length} articles, ${Object.keys(x.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${y.name}" (created on first /publish)`}),n.push(bf(dc())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${dc()}`,fix:"Reinstall document360-writer (broken install)"});let _=Ie(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)"}),P&&(!Xs(P)||P.refreshToken)){let C={profile:y.name,connection:y.connection};try{await xf(C);let D=await $f(C,"/v3/projects");n.push({level:"ok",label:`API reachable (${y.connection.apiUrl}) \u2014 ${D.length} project(s) visible`})}catch(D){n.push({level:"fail",label:`API call failed: ${D.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=x?.projectId??y.project.projectId;if(N&&y.project.workspaceId)try{let D=await Df(C,N,y.project.workspaceId);if(D){let W=(D.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${y.connection.name} (${D.languages?.length??0} language${(D.languages?.length??0)===1?"":"s"}) \xB7 hash ${W||"(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(D){D instanceof Lf||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(D.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 (${D.message.slice(0,80)})`})}}return n}function hc(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?M("\u26A0"):v("\u2717");t.push(` ${s} ${r.label}${r.detail?m(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${m("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"})`}`):v(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Ln(e,t){console.log(m("Running checks\u2026"));for(let n of hc(await pc(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Yo=yo(()=>{"use strict";st();H()});import{Command as iy}from"commander";import{createRequire as ay}from"node:module";import{AUTH_MODES as ly}from"document360-engine";import{input as qu}from"@inquirer/prompts";import{loginPkce as Bu,refreshTokens as Vu,toStoredTokens as Pa,clearTokens as Gu,decodeJwtClaims as Sa,isExpired as Yu,loadTokens as zu,saveTokens as Ta,resolveActiveProfile as xo,setProfileProject as Ku,readProjectConfig as Xu}from"document360-engine";H();import{select as Au}from"@inquirer/prompts";import{resolveActiveProfile as ju,setProfileProject as Eu,resolveProjectId as Nu,listWorkspaces as Iu}from"document360-engine";async function Rn(e,t){let n=ju(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Nu(o);return{workspaces:await Iu(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var xa=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Gr(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 ko(e,t,n,o,r){Eu(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function va(e,t,n){let o;try{o=await Rn(e,n)}catch(s){return console.log(v(`Could not list workspaces: ${s.message}`)),1}let r=Gr(o.workspaces,t);return r?(ko(e,o.profile,o.projectId,r.id,r.name),console.log(E(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(v(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Xt(e,t){let n;try{n=await Rn(e,t)}catch(b){console.log(v(`Could not list workspaces: ${b.message}`));return}let{workspaces:o,projectId:r,profile:s,current:a}=n;if(o.length===0){console.log(m("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let b of o)console.log(` ${b.id===a?L("\u25CF"):" "} ${xa(b)} ${m(b.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let u=await Au({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${xa(b)}${b.id===a?" (current)":""}`,value:b.id}))}),g=o.find(b=>b.id===u);ko(e,s,r,u,g?.name),console.log(E(`\u2713 Workspace set to "${g?.name??u}" for profile "${s}".`))}H();import{select as _u}from"@inquirer/prompts";import{resolveActiveProfile as Lu,setProfileProject as Ou,listProjects as Mu}from"document360-engine";async function ot(e,t){let n=Lu(e,t),o={profile:n.name,connection:n.connection};return{projects:await Mu(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Ca=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Yr(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 bo(e,t,n,o){Ou(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Ra(e,t,n){let o;try{o=await ot(e,n)}catch(s){return console.log(v(`Could not list projects: ${s.message}`)),1}let r=Yr(o.projects,t);return r?(bo(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(v(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function $o(e,t){let n;try{n=await ot(e,t)}catch(g){console.log(v(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(m("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===s?L("\u25CF"):" "} ${Ca(g)} ${m(g.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let a=await _u({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${Ca(g)}${g.id===s?" (current)":""}`,value:g.id}))}),u=o.find(g=>g.id===a);bo(e,r,a,u?.name),console.log(E(`\u2713 Project set to "${u?.name??a}" for profile "${r}". Next: pick a workspace.`))}H();import Uu from"picocolors";function Wu(e=process.env){return e.FORCE_HYPERLINK==="0"||!Uu.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 Fu(e,t=e,n){return Wu(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Hu=/https?:\/\/[^\s\x1b]+/g;function Sn(e,t){return e.replace(Hu,n=>Fu(n,n,t))}function Da(e){return{...Sa(e.idToken)??{},...Sa(e.accessToken)??{}}}function vo(e){let t=Da(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 Co(e){let t=xo(process.cwd(),e.profile),n=t.connection;console.log(m(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Bu(n,{manual:e.manual,promptForRedirect:s=>qu({message:s})},s=>console.log(Sn(s))),r=Pa(t.name,o);if(Ta(r),await zr(r,t.name,s=>console.log(m(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${vo(r)}`)),console.log(m(` access token expires: ${r.expiresAt}`)),console.log(m(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Xu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Xt(process.cwd(),t.name))}catch{}}async function zr(e,t,n){let r=Da(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(xo(process.cwd(),t).project.projectId)return;let a;try{let{projects:u}=await ot(process.cwd(),t);a=u.find(g=>g.id===r)?.name}catch{}Ku(process.cwd(),t,{projectId:r,projectName:a}),n(` Project "${a??r}" written to profile "${t}".`)}catch{}}async function Aa(e){let t=xo(process.cwd(),e.profile),n=t.connection,o=zu(t.name);if(!o){console.log(v(`Not logged in to Document360 (profile "${t.name}").`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${L(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${vo(o)}`),Yu(o))if(o.refreshToken)try{let r=Pa(t.name,await Vu(n,o.refreshToken));Ta(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(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(M("Session expired (no refresh token).")),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(m(` expires: ${o.expiresAt}`))}async function ja(e){let t=xo(process.cwd(),e.profile);Gu(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(m(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}H();import{readProjectConfig as Ea,writeProjectConfig as Qu,resolveActiveProfile as Ju,loadTokens as Zu,isExpired as ep}from"document360-engine";function Ro(e){let t=Ea(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(v("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"):"",a=o.connection.environment??"(inline)",u=Zu(n),g=u?ep(u)&&!u.refreshToken?M("expired"):m("logged in"):m("not logged in");console.log(`${r}${L(n)} \u2192 ${a}${s} [${g}]`)}console.log(""),console.log(m("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function So(e,t){let n=Ea(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(v(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Qu(n,e);let o=n.profiles[t].production?M(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function Po(e,t){try{let n=Ju(e,t);console.log(""),console.log(`Profile ${L(n.name)}${n.production?M(" \u26A0 PRODUCTION"):""}`),console.log(m(` api: ${n.connection.apiUrl}`)),console.log(m(` identity: ${n.connection.authorizationUrl}`)),console.log(m(` clientId: ${n.connection.clientId}`)),console.log(m(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(m(` project: ${n.project.projectId??"(set at login)"}`)),console.log(m(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(v(n.message)),process.exitCode=1}}H();import{existsSync as tp,readdirSync as np,statSync as Na}from"node:fs";import{join as Ia}from"node:path";import{apiLogDir as op}from"document360-engine";function _a(){let e=op();if(console.log(""),console.log(`Document360 API logs: ${L(e)}`),!tp(e)){console.log(m(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=np(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(m(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Na(Ia(e,r)).size/1024).toFixed(1);console.log(` ${r} ${m(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${m("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Na(Ia(e,r)).size/1024).toFixed(1);console.log(` ${v(r)} ${m(`${s} KB`)}`)}}console.log(""),console.log(m("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(m("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}H();import{createSession as rp,resolveAuth as sp,findByName as ip,slugify as ap,touchSession as lp,upsertSession as cp,resolveActiveProfile as dp}from"document360-engine";async function La(e,t,n,o,r,s){let a=sp(n);a.kind==="none"&&(console.error(""),console.error(v("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)),a.kind==="subscription"&&console.error(m("Using your Claude subscription (no API key set)."));let u=null;try{u=dp(e,r)}catch(x){console.error(v(`Document360 profile error: ${x.message}`)),process.exit(2)}u.production&&(console.error(M(`\u26A0 Profile "${u.name}" is PRODUCTION.`)),s||(console.error(v("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(m(" --yes given \u2014 proceeding against production.")));let g;if(o){let x=ip(e,o);x||(console.error(v(`No saved session matches "${o}" in this repo.`)),console.error(m("List sessions inside the REPL with /resume.")),process.exit(2)),g=x.uuid,console.error(m(`Resuming "${x.name}"`))}let b=rp({cwd:e,resume:g,profileName:r,allowProdWrites:s===!0}),y=g??null,P=1;for await(let x of b.send(t))switch(x.type){case"session":if(!y){y=x.sessionId;let _=new Date().toISOString();cp({uuid:y,name:ap(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:_,updatedAt:_})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(ae(` \u2699 ${x.name}`));break;case"result":P=x.ok?0:1,console.error(m(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error(v("agent finished with an error result"));break;case"error":console.error(""),console.error(v(`agent error: ${x.message}`)),process.exit(1)}y&&lp(y),process.stdout.write(`
280
- `),process.exit(P)}import{createInterface as fg}from"node:readline/promises";import{createSession as Ai,resolveAuth as mg,getSession as gg,setTitle as wg,slugify as yg,touchSession as gd,upsertSession as kg,generateTitle as bg,resolveActiveProfile as wd,resolveModelSetting as $g,readProjectConfig as xg,resolveAndPersistAppType as vg,decodeJwtClaims as md,isExpired as Cg,loadTokens as Rg,isDirectiveMention as Sg,stripDirectiveMention as Pg,appendDirective as Tg,reconcileUpgradeActions as Dg,stampArticles as Ag,listArticleFiles as jg,CONTENT_CAP_VERSION as Eg}from"document360-engine";import{ENGINE_VERSION as pp}from"document360-engine";var Ne=[{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:"Re-run /publish so the images go live 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 setup",s:"The data-staging + test-id checklist (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 / setup / 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 up(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 Oa(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 Ne){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(up(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function Kr(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:pp}:void 0;for(let o of Oa(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 hp}from"document360-engine";async function Ma(e,t){let n=t.currentUuid(),o=n?hp(n):void 0;return console.log(o?m(`
278
+ `;Ga="Re-run dev\u2194docs onboarding (protocol v"});var al={};$a(al,{initCommand:()=>ns,scaffoldInit:()=>ts});import{input as Tn,confirm as vp}from"@inquirer/prompts";import{basename as Ja,join as No}from"node:path";import{existsSync as tn,readFileSync as Cp,readdirSync as Rp,writeFileSync as Sp}from"node:fs";import{writeProjectConfig as Za,readProjectConfig as Pp,projectConfigPath as el,writerDir as Tp,DEFAULT_DOCS_DIR as tl,DEFAULT_CAPTURE_DIR as nl,DEFAULT_OUTPUT_DIR as ol}from"document360-engine";function ts(e,t="berlin"){let n=el(e);if(tn(n))return{created:!1,path:n,profileName:""};let o={projectId:sl(e)??Ja(e),docsDir:tl,captureDir:nl,outputDir:ol,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:il(e)};return Za(o,e),rl(e),{created:!0,path:n,profileName:t}}function rl(e){let t=No(Tp(e),".gitignore");tn(t)||Sp(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
279
+ `),"utf8")}async function ns(){let e=process.cwd(),t=el(e);if(tn(t)&&!await vp({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(m("init cancelled.")),{kind:"continue"};let n=sl(e)??Ja(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:nl}),s=await Tn({message:"Screenshot output directory:",default:ol}),a=await Tn({message:"Default connection profile name:",default:"berlin"}),u=await Tn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:tl,captureDir:r,outputDir:s,profiles:{[a]:{connection:{environment:u},production:!1}},defaultProfile:a,authoritativeSourceFiles:il(e)},b=Pp(e);b?.terminologyGlossary&&(g.terminologyGlossary=b.terminologyGlossary),Za(g,e),rl(e);let y=Zt(e);console.log(""),console.log(E(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${L(`d360-writer login --profile ${a}`)} ${m("(sign in; project & workspace auto-selected)")}`),console.log("");for(let P of en(y))console.log(P);return console.log(""),console.log(`${m("Then ask:")} ${L('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function sl(e){let t=No(e,"package.json");if(!tn(t))return null;try{return JSON.parse(Cp(t,"utf8")).name??null}catch{return null}}function il(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])tn(No(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=No(e,n);tn(o)&&!Dp(o)&&t.push(n)}return t}function Dp(e){try{return Rp(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Io=ko(()=>{"use strict";q();st()});var mc={};$a(mc,{doctorCommand:()=>Ln,renderDoctorChecks:()=>fc,runDoctorChecks:()=>hc});import{existsSync as $f}from"node:fs";import{d360GetAll as xf,getAccessToken as vf,isExpired as Qs,loadProfileMap as Cf,loadTokens as Rf,packageSkillsDir as uc,ENGINE_VERSION as Sf,projectConfigPath as Pf,readProjectConfig as Tf,DEFAULT_DOCS_DIR as Df,fetchManifestSummary as Af,resolveActiveProfile as jf,classifyClaudeAuth as Ef,CLAUDE_CODE_SETUP_HINT as pc,resolveModelSetting as Nf,probeModel as If,detectAppType as _f,playbookSkillName as Lf,D360AuthError as Of}from"document360-engine";async function hc(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Sf}`});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=Ef();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. ${pc}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:pc});let s=Nf(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 C=await If(e,s.model??void 0);C.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(C.latencyMs/1e3).toFixed(1)}s`}):C.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 ${C.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 a=Tf(e);if(!a)return n.push({level:"fail",label:`No ${Pf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let u=(a.docsDir??Df).replace(/\/+$/,"");n.push(a.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${u}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let g=a.authoritativeSourceFiles??[];n.push(g.length>0?{level:"ok",label:`Sources: docs grounded in ${g.length} path(s) (${g.slice(0,3).join(", ")}${g.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=a.appType??_f(e);if(b){let C=a.appType?"from config":"auto-detected",N=b==="web"||b==="cli";n.push({level:"ok",label:`Genre: ${b} (${C})${N?` \u2192 ${Lf(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 y;try{y=jf(e),n.push({level:"ok",label:`Profile: ${y.name} (${y.connection.name})${y.production?" \u26A0 PRODUCTION":""}`})}catch(C){return n.push({level:"fail",label:`Profile config: ${C.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let P=Rf(y.name);P?Qs(P)&&!P.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Qs(P)?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(P.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 x=Cf(e,y.name);x?x.projectId&&y.project.projectId&&x.projectId!==y.project.projectId?n.push({level:"fail",label:`Category map projectId (${x.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(x.articles).length} articles, ${Object.keys(x.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${y.name}" (created on first /publish)`}),n.push($f(uc())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${uc()}`,fix:"Reinstall document360-writer (broken install)"});let _=Ie(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)"}),P&&(!Qs(P)||P.refreshToken)){let C={profile:y.name,connection:y.connection};try{await vf(C);let D=await xf(C,"/v3/projects");n.push({level:"ok",label:`API reachable (${y.connection.apiUrl}) \u2014 ${D.length} project(s) visible`})}catch(D){n.push({level:"fail",label:`API call failed: ${D.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=x?.projectId??y.project.projectId;if(N&&y.project.workspaceId)try{let D=await Af(C,N,y.project.workspaceId);if(D){let W=(D.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${y.connection.name} (${D.languages?.length??0} language${(D.languages?.length??0)===1?"":"s"}) \xB7 hash ${W||"(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(D){D instanceof Of||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(D.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 (${D.message.slice(0,80)})`})}}return n}function fc(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?M("\u26A0"):v("\u2717");t.push(` ${s} ${r.label}${r.detail?m(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${m("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"})`}`):v(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Ln(e,t){console.log(m("Running checks\u2026"));for(let n of fc(await hc(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var zo=ko(()=>{"use strict";st();q()});import{Command as ay}from"commander";import{createRequire as ly}from"node:module";import{AUTH_MODES as cy}from"document360-engine";import{input as Bu}from"@inquirer/prompts";import{loginPkce as Vu,refreshTokens as Gu,toStoredTokens as Ta,clearTokens as Yu,decodeJwtClaims as Pa,isExpired as zu,loadTokens as Ku,saveTokens as Da,resolveActiveProfile as vo,setProfileProject as Xu,readProjectConfig as Qu}from"document360-engine";q();import{select as ju}from"@inquirer/prompts";import{resolveActiveProfile as Eu,setProfileProject as Nu,resolveProjectId as Iu,listWorkspaces as _u}from"document360-engine";async function Rn(e,t){let n=Eu(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Iu(o);return{workspaces:await _u(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var va=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Yr(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 bo(e,t,n,o,r){Nu(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Ca(e,t,n){let o;try{o=await Rn(e,n)}catch(s){return console.log(v(`Could not list workspaces: ${s.message}`)),1}let r=Yr(o.workspaces,t);return r?(bo(e,o.profile,o.projectId,r.id,r.name),console.log(E(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(v(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Xt(e,t){let n;try{n=await Rn(e,t)}catch(b){console.log(v(`Could not list workspaces: ${b.message}`));return}let{workspaces:o,projectId:r,profile:s,current:a}=n;if(o.length===0){console.log(m("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let b of o)console.log(` ${b.id===a?L("\u25CF"):" "} ${va(b)} ${m(b.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let u=await ju({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${va(b)}${b.id===a?" (current)":""}`,value:b.id}))}),g=o.find(b=>b.id===u);bo(e,s,r,u,g?.name),console.log(E(`\u2713 Workspace set to "${g?.name??u}" for profile "${s}".`))}q();import{select as Lu}from"@inquirer/prompts";import{resolveActiveProfile as Ou,setProfileProject as Mu,listProjects as Uu}from"document360-engine";async function ot(e,t){let n=Ou(e,t),o={profile:n.name,connection:n.connection};return{projects:await Uu(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Ra=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function 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 $o(e,t,n,o){Mu(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Sa(e,t,n){let o;try{o=await ot(e,n)}catch(s){return console.log(v(`Could not list projects: ${s.message}`)),1}let r=zr(o.projects,t);return r?($o(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(v(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function xo(e,t){let n;try{n=await ot(e,t)}catch(g){console.log(v(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(m("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===s?L("\u25CF"):" "} ${Ra(g)} ${m(g.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let a=await Lu({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${Ra(g)}${g.id===s?" (current)":""}`,value:g.id}))}),u=o.find(g=>g.id===a);$o(e,r,a,u?.name),console.log(E(`\u2713 Project set to "${u?.name??a}" for profile "${r}". Next: pick a workspace.`))}q();import Wu from"picocolors";function Fu(e=process.env){return e.FORCE_HYPERLINK==="0"||!Wu.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 qu(e,t=e,n){return Fu(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Hu=/https?:\/\/[^\s\x1b]+/g;function Sn(e,t){return e.replace(Hu,n=>qu(n,n,t))}function Aa(e){return{...Pa(e.idToken)??{},...Pa(e.accessToken)??{}}}function Co(e){let t=Aa(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 Ro(e){let t=vo(process.cwd(),e.profile),n=t.connection;console.log(m(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Vu(n,{manual:e.manual,promptForRedirect:s=>Bu({message:s})},s=>console.log(Sn(s))),r=Ta(t.name,o);if(Da(r),await Kr(r,t.name,s=>console.log(m(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${Co(r)}`)),console.log(m(` access token expires: ${r.expiresAt}`)),console.log(m(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Qu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Xt(process.cwd(),t.name))}catch{}}async function Kr(e,t,n){let r=Aa(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(vo(process.cwd(),t).project.projectId)return;let a;try{let{projects:u}=await ot(process.cwd(),t);a=u.find(g=>g.id===r)?.name}catch{}Xu(process.cwd(),t,{projectId:r,projectName:a}),n(` Project "${a??r}" written to profile "${t}".`)}catch{}}async function ja(e){let t=vo(process.cwd(),e.profile),n=t.connection,o=Ku(t.name);if(!o){console.log(v(`Not logged in to Document360 (profile "${t.name}").`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${L(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Co(o)}`),zu(o))if(o.refreshToken)try{let r=Ta(t.name,await Gu(n,o.refreshToken));Da(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(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(M("Session expired (no refresh token).")),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(m(` expires: ${o.expiresAt}`))}async function Ea(e){let t=vo(process.cwd(),e.profile);Yu(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(m(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}q();import{readProjectConfig as Na,writeProjectConfig as Ju,resolveActiveProfile as Zu,loadTokens as ep,isExpired as tp}from"document360-engine";function So(e){let t=Na(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(v("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"):"",a=o.connection.environment??"(inline)",u=ep(n),g=u?tp(u)&&!u.refreshToken?M("expired"):m("logged in"):m("not logged in");console.log(`${r}${L(n)} \u2192 ${a}${s} [${g}]`)}console.log(""),console.log(m("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Po(e,t){let n=Na(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(v(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Ju(n,e);let o=n.profiles[t].production?M(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function To(e,t){try{let n=Zu(e,t);console.log(""),console.log(`Profile ${L(n.name)}${n.production?M(" \u26A0 PRODUCTION"):""}`),console.log(m(` api: ${n.connection.apiUrl}`)),console.log(m(` identity: ${n.connection.authorizationUrl}`)),console.log(m(` clientId: ${n.connection.clientId}`)),console.log(m(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(m(` project: ${n.project.projectId??"(set at login)"}`)),console.log(m(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(v(n.message)),process.exitCode=1}}q();import{existsSync as np,readdirSync as op,statSync as Ia}from"node:fs";import{join as _a}from"node:path";import{apiLogDir as rp}from"document360-engine";function La(){let e=rp();if(console.log(""),console.log(`Document360 API logs: ${L(e)}`),!np(e)){console.log(m(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=op(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(m(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Ia(_a(e,r)).size/1024).toFixed(1);console.log(` ${r} ${m(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${m("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Ia(_a(e,r)).size/1024).toFixed(1);console.log(` ${v(r)} ${m(`${s} KB`)}`)}}console.log(""),console.log(m("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(m("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}q();import{createSession as sp,resolveAuth as ip,findByName as ap,slugify as lp,touchSession as cp,upsertSession as dp,resolveActiveProfile as up}from"document360-engine";async function Oa(e,t,n,o,r,s){let a=ip(n);a.kind==="none"&&(console.error(""),console.error(v("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)),a.kind==="subscription"&&console.error(m("Using your Claude subscription (no API key set)."));let u=null;try{u=up(e,r)}catch(x){console.error(v(`Document360 profile error: ${x.message}`)),process.exit(2)}u.production&&(console.error(M(`\u26A0 Profile "${u.name}" is PRODUCTION.`)),s||(console.error(v("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(m(" --yes given \u2014 proceeding against production.")));let g;if(o){let x=ap(e,o);x||(console.error(v(`No saved session matches "${o}" in this repo.`)),console.error(m("List sessions inside the REPL with /resume.")),process.exit(2)),g=x.uuid,console.error(m(`Resuming "${x.name}"`))}let b=sp({cwd:e,resume:g,profileName:r,allowProdWrites:s===!0}),y=g??null,P=1;for await(let x of b.send(t))switch(x.type){case"session":if(!y){y=x.sessionId;let _=new Date().toISOString();dp({uuid:y,name:lp(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:_,updatedAt:_})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(ae(` \u2699 ${x.name}`));break;case"result":P=x.ok?0:1,console.error(m(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error(v("agent finished with an error result"));break;case"error":console.error(""),console.error(v(`agent error: ${x.message}`)),process.exit(1)}y&&cp(y),process.stdout.write(`
280
+ `),process.exit(P)}import{createInterface as mg}from"node:readline/promises";import{createSession as Ei,resolveAuth as gg,getSession as wg,setTitle as yg,slugify as kg,touchSession as wd,upsertSession as bg,generateTitle as $g,resolveActiveProfile as yd,resolveModelSetting as xg,readProjectConfig as vg,resolveAndPersistAppType as Cg,decodeJwtClaims as gd,isExpired as Rg,loadTokens as Sg,isDirectiveMention as Pg,stripDirectiveMention as Tg,appendDirective as Dg,reconcileUpgradeActions as Ag,stampArticles as jg,listArticleFiles as Eg,CONTENT_CAP_VERSION as Ng}from"document360-engine";import{ENGINE_VERSION as hp}from"document360-engine";var Ne=[{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:"Re-run /publish so the images go live 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 pp(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 Ma(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 Ne){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(pp(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function Xr(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:hp}:void 0;for(let o of Ma(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"}}q();import{getSession as fp}from"document360-engine";async function Ua(e,t){let n=t.currentUuid(),o=n?fp(n):void 0;return console.log(o?m(`
281
281
  (conversation reset \u2014 "${o.name}" is still available via /resume)
282
282
  `):m(`
283
283
  (conversation reset \u2014 agent will start fresh on the next prompt)
284
- `)),{kind:"clear"}}async function Xr(){return{kind:"exit"}}No();H();import{readMcpConfig as ns,writeMcpConfig as al}from"document360-engine";async function Io(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Dp(),{kind:"continue"}):t==="add"?(Ap(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(jp(e.slice(1)),{kind:"continue"}):(console.log(v(`Unknown /mcp subcommand: ${t}`)),console.log(m("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Dp(){let e=ns(),t=Object.keys(e.servers);if(t.length===0){console.log(m(`
284
+ `)),{kind:"clear"}}async function Qr(){return{kind:"exit"}}Io();q();import{readMcpConfig as os,writeMcpConfig as ll}from"document360-engine";async function _o(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Ap(),{kind:"continue"}):t==="add"?(jp(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Ep(e.slice(1)),{kind:"continue"}):(console.log(v(`Unknown /mcp subcommand: ${t}`)),console.log(m("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Ap(){let e=os(),t=Object.keys(e.servers);if(t.length===0){console.log(m(`
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)} ${m("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?m(` [headers: ${r.join(", ")}]`):"";console.log(` ${L(n)} ${m(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Ap(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(v("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(v(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=ns(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let a={};for(let u=1;u<o.length;u++)if(o[u]==="-H"||o[u]==="--header"){let g=o[++u],b=g?.match(/^([^:=]+)[:=](.+)$/);if(!b){console.log(v(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}a[b[1].trim()]=b[2].trim()}else{console.log(v(`Unexpected argument: ${o[u]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(a).length>0?a:void 0}}r.servers[t]=s,al(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(m(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function jp(e){let t=e[0];if(!t){console.log(v("Usage: /mcp remove <name>"));return}let n=ns();if(!n.servers[t]){console.log(v(`No server named "${t}".`));return}delete n.servers[t],al(n),console.log(E(`\u2713 Removed "${t}".`)),console.log(m(" Run /clear to drop it from the current session immediately."))}H();import{readFileSync as Yp}from"node:fs";import{join as zp}from"node:path";import{select as Kp}from"@inquirer/prompts";import{computeSyncStatus as _o,planPartitions as Xp,relatedArticlePaths as Qp,resolveModelForOperation as Jp,runPartitioned as Zp,loadProfileMap as eh,resolveActiveProfile as th,resolveCrossLinks as nh,applyStructureOrder as xl,orderSyncLine as vl,applyRelatedArticles as Cl,relatedSyncLine as Rl}from"document360-engine";import Z from"picocolors";import yl from"wrap-ansi";import ls from"string-width";H();import it from"picocolors";import os from"wrap-ansi";import rs from"string-width";var nn=[{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|setup|list] [id|path|--all]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots; setup: data-staging checklist; 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]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"roadmap",usage:"/roadmap [done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done` 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 to the latest version (then relaunch)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],ll={"/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(ll[n])return ll[n];let o=nn.find(r=>r.name===t);return o?o.desc:""}function dl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return nn.filter(n=>n.name.startsWith(t))}function ul(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Ep=new RegExp(`^\\s*/(?:${nn.map(e=>e.name).join("|")})(?:\\s|$)`),pl=e=>Ep.test(e),hl=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),fl=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),ml=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Np(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 u=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)u.push(t[o++]);o++,n.push({kind:"code",lines:u});continue}if(hl(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&fl(t[o+1])){let u=ml(r);o+=2;let g=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)g.push(ml(t[o++]));n.push({kind:"table",header:u,rows:g});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 u=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let g=t[o++];u.push({ordered:/^\s*\d+\.\s+/.test(g),text:g.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:u});continue}if(r.trim()===""){o++;continue}if(pl(r)){n.push({kind:"para",text:r.trim()}),o++;continue}let a=[];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])&&!hl(t[o])&&!(t[o].includes("|")&&o+1<t.length&&fl(t[o+1]));)a.push(t[o++]);n.push({kind:"para",text:a.join(" ")})}return n}function ss(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?it.bold(t.slice(2,-2)):t.startsWith("`")?L(t.slice(1,-1)):it.italic(t.slice(1,-1)))}var Ip=(e,t)=>e+" ".repeat(Math.max(0,t-rs(e)));function _p(e,t,n){let o=e.length,r=e.map((C,N)=>Math.max(rs(C),...t.map(D=>rs(D[N]??"")))),s=Math.max(24,n),a=3*o+1,u=[...r],g=()=>u.reduce((C,N)=>C+N,0)+a,b=0;for(;g()>s&&b++<1e4;){let C=-1,N=6;for(let D=0;D<o;D++)u[D]>N&&(N=u[D],C=D);if(C===-1)break;u[C]-=1}let y=(C,N,D)=>it.gray(C+u.map(W=>"\u2500".repeat(W+2)).join(N)+D),P=it.gray("\u2502"),x=(C,N)=>{let D=u.map((K,X)=>{let he=C[X]??"",Qe=N?it.bold(he):ss(he);return os(Qe,K,{hard:!0}).split(`
288
- `)}),W=Math.max(...D.map(K=>K.length)),z=[];for(let K=0;K<W;K++)z.push(u.map((X,he)=>`${P} ${Ip(D[he][K]??"",X)} `).join("")+P);return z.join(`
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)} ${m("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?m(` [headers: ${r.join(", ")}]`):"";console.log(` ${L(n)} ${m(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function jp(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(v("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(v(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=os(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let a={};for(let u=1;u<o.length;u++)if(o[u]==="-H"||o[u]==="--header"){let g=o[++u],b=g?.match(/^([^:=]+)[:=](.+)$/);if(!b){console.log(v(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}a[b[1].trim()]=b[2].trim()}else{console.log(v(`Unexpected argument: ${o[u]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(a).length>0?a:void 0}}r.servers[t]=s,ll(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(m(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Ep(e){let t=e[0];if(!t){console.log(v("Usage: /mcp remove <name>"));return}let n=os();if(!n.servers[t]){console.log(v(`No server named "${t}".`));return}delete n.servers[t],ll(n),console.log(E(`\u2713 Removed "${t}".`)),console.log(m(" Run /clear to drop it from the current session immediately."))}q();import{readFileSync as zp}from"node:fs";import{join as Kp}from"node:path";import{select as Xp}from"@inquirer/prompts";import{computeSyncStatus as Lo,planPartitions as Qp,relatedArticlePaths as Jp,resolveModelForOperation as Zp,runPartitioned as eh,loadProfileMap as th,resolveActiveProfile as nh,resolveCrossLinks as oh,applyStructureOrder as vl,orderSyncLine as Cl,applyRelatedArticles as Rl,relatedSyncLine as Sl}from"document360-engine";import Z from"picocolors";import kl from"wrap-ansi";import cs from"string-width";q();import it from"picocolors";import rs from"wrap-ansi";import ss from"string-width";var nn=[{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]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"roadmap",usage:"/roadmap [done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done` 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 to the latest version (then relaunch)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],cl={"/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 dl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(cl[n])return cl[n];let o=nn.find(r=>r.name===t);return o?o.desc:""}function ul(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return nn.filter(n=>n.name.startsWith(t))}function pl(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Np=new RegExp(`^\\s*/(?:${nn.map(e=>e.name).join("|")})(?:\\s|$)`),hl=e=>Np.test(e),fl=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),ml=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),gl=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Ip(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 u=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)u.push(t[o++]);o++,n.push({kind:"code",lines:u});continue}if(fl(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&ml(t[o+1])){let u=gl(r);o+=2;let g=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)g.push(gl(t[o++]));n.push({kind:"table",header:u,rows:g});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 u=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let g=t[o++];u.push({ordered:/^\s*\d+\.\s+/.test(g),text:g.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:u});continue}if(r.trim()===""){o++;continue}if(hl(r)){n.push({kind:"para",text:r.trim()}),o++;continue}let a=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!hl(t[o])&&!fl(t[o])&&!(t[o].includes("|")&&o+1<t.length&&ml(t[o+1]));)a.push(t[o++]);n.push({kind:"para",text:a.join(" ")})}return n}function is(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?it.bold(t.slice(2,-2)):t.startsWith("`")?L(t.slice(1,-1)):it.italic(t.slice(1,-1)))}var _p=(e,t)=>e+" ".repeat(Math.max(0,t-ss(e)));function Lp(e,t,n){let o=e.length,r=e.map((C,N)=>Math.max(ss(C),...t.map(D=>ss(D[N]??"")))),s=Math.max(24,n),a=3*o+1,u=[...r],g=()=>u.reduce((C,N)=>C+N,0)+a,b=0;for(;g()>s&&b++<1e4;){let C=-1,N=6;for(let D=0;D<o;D++)u[D]>N&&(N=u[D],C=D);if(C===-1)break;u[C]-=1}let y=(C,N,D)=>it.gray(C+u.map(W=>"\u2500".repeat(W+2)).join(N)+D),P=it.gray("\u2502"),x=(C,N)=>{let D=u.map((K,X)=>{let he=C[X]??"",Qe=N?it.bold(he):is(he);return rs(Qe,K,{hard:!0}).split(`
288
+ `)}),W=Math.max(...D.map(K=>K.length)),z=[];for(let K=0;K<W;K++)z.push(u.map((X,he)=>`${P} ${_p(D[he][K]??"",X)} `).join("")+P);return z.join(`
289
289
  `)},_=[y("\u250C","\u252C","\u2510"),x(e,!0)];return _.push(t.length===0?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524")),t.forEach((C,N)=>{_.push(x(C,!1)),_.push(N===t.length-1?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524"))}),_.join(`
290
- `)}function Lp(e,t){switch(e.kind){case"heading":return it.bold(e.text);case"hr":return it.gray("\u2500".repeat(t));case"para":return os(ss(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),[a="",...u]=os(ss(o.text),Math.max(10,t-s.length)).split(`
290
+ `)}function Op(e,t){switch(e.kind){case"heading":return it.bold(e.text);case"hr":return it.gray("\u2500".repeat(t));case"para":return rs(is(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),[a="",...u]=rs(is(o.text),Math.max(10,t-s.length)).split(`
291
291
  `);return` ${r} ${a}`+u.map(g=>`
292
292
  ${s}${g}`).join("")}).join(`
293
293
  `)}case"code":return e.lines.map(n=>it.gray(" "+n)).join(`
294
- `);case"table":return _p(e.header,e.rows,t)}}function is(e,t){let n=Math.max(20,t);return Np(e).map(o=>Lp(o,n)).join(`
294
+ `);case"table":return Lp(e.header,e.rows,t)}}function as(e,t){let n=Math.max(20,t);return Ip(e).map(o=>Op(o,n)).join(`
295
295
 
296
- `)}H();import Op from"picocolors";var Mp=[127,86,217],Up=[22,38,43],gl={T:Mp,E:Up},Dn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],as=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Wp=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function wl(){if(!Op.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=gl[Dn[n][r]],a=n+1<Dn.length?gl[Dn[n+1][r]]:void 0;s&&a?o+=`${as(s)}${Wp(a)}\u2580\x1B[49m\x1B[39m`:s?o+=`${as(s)}\u2580\x1B[39m`:a?o+=`${as(a)}\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 xe(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function at(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var on=(e,t)=>` ${e.padEnd(13)}${t}`;function Fp(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."),"",on("Claude:",`${e.claude}${Z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),on("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")),on("Profile:",e.configured?`${e.profile}${Z.gray(` (${e.apiUrl})`)}${e.prod?Z.bold(Z.yellow(" \u26A0 PRODUCTION")):""}`:Z.gray("\u2014 (run /init)")),on("Project:",e.project),on("Mode:",Z.gray(e.mode)),on("cwd:",Z.gray(e.cwd))],o=wl();if(o.length===0)return n.join(`
297
- `);let r=2,s=3,a=ls(o[0]);if(!(t>=r+a+s+Math.max(...n.map(y=>ls(y)))))return[...o.map(y=>" "+y),...n].join(`
296
+ `)}q();import Mp from"picocolors";var Up=[127,86,217],Wp=[22,38,43],wl={T:Up,E:Wp},Dn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],ls=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Fp=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function yl(){if(!Mp.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=wl[Dn[n][r]],a=n+1<Dn.length?wl[Dn[n+1][r]]:void 0;s&&a?o+=`${ls(s)}${Fp(a)}\u2580\x1B[49m\x1B[39m`:s?o+=`${ls(s)}\u2580\x1B[39m`:a?o+=`${ls(a)}\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 xe(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function at(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var on=(e,t)=>` ${e.padEnd(13)}${t}`;function qp(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."),"",on("Claude:",`${e.claude}${Z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),on("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")),on("Profile:",e.configured?`${e.profile}${Z.gray(` (${e.apiUrl})`)}${e.prod?Z.bold(Z.yellow(" \u26A0 PRODUCTION")):""}`:Z.gray("\u2014 (run /init)")),on("Project:",e.project),on("Mode:",Z.gray(e.mode)),on("cwd:",Z.gray(e.cwd))],o=yl();if(o.length===0)return n.join(`
297
+ `);let r=2,s=3,a=cs(o[0]);if(!(t>=r+a+s+Math.max(...n.map(y=>cs(y)))))return[...o.map(y=>" "+y),...n].join(`
298
298
  `);let g=Math.max(0,Math.floor((n.length-o.length)/2)),b=[];for(let y=0;y<Math.max(o.length+g,n.length);y++){let P=o[y-g]??" ".repeat(a);b.push((" ".repeat(r)+P+" ".repeat(s)+(n[y]??"")).trimEnd())}return b.join(`
299
- `)}var Hp={error:Z.red,warn:Z.yellow,ok:Z.green,info:Z.gray};function cs(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1$2 ")}function ds(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Fp(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),a=50,u=e.text.split(`
300
- `).flatMap(b=>yl(b,s,{hard:!0}).split(`
299
+ `)}var Hp={error:Z.red,warn:Z.yellow,ok:Z.green,info:Z.gray};function ds(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1$2 ")}function us(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return qp(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),a=50,u=e.text.split(`
300
+ `).flatMap(b=>kl(b,s,{hard:!0}).split(`
301
301
  `)),g=Math.max(0,u.length-a);return g>0&&(u=[...u.slice(0,a),Z.dim(`\u2026 +${g} more lines`)]),`
302
- `+u.map((b,y)=>o+(y===0?L(" \u276F "):" ")+b+" ".repeat(Math.max(0,s-ls(b))+1)+r).join(`
302
+ `+u.map((b,y)=>o+(y===0?L(" \u276F "):" ")+b+" ".repeat(Math.max(0,s-cs(b))+1)+r).join(`
303
303
  `)}case"assistant":return`
304
- `+is(e.text,n);case"tool":{let o=e.arg!==null?Z.gray(`${e.sep}(${e.arg})`):"";return`
305
- `+yl(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,a)=>o((a===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(Z.dim(` \u2026 +${e.hidden} lines`)),r.join(`
304
+ `+as(e.text,n);case"tool":{let o=e.arg!==null?Z.gray(`${e.sep}(${e.arg})`):"";return`
305
+ `+kl(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,a)=>o((a===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(Z.dim(` \u2026 +${e.hidden} lines`)),r.join(`
306
306
  `)}case"diff":{let o=a=>a===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
307
  `)}case"link":return e.lines.map(o=>L(Sn(` \u2B95 ${o}`))).join(`
308
308
  `);case"preview":return`
309
309
  `+Cn(`\u25A3 Preview \u2014 ${e.name}`)+`
310
310
 
311
- `+is(e.text,n);case"note":return`
312
- `+Hp[e.tone](Sn(cs(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 ${xe(e.costUsd)}`:""))}}}function kl(e,t){return e.map(n=>ds(n,t)).join(`
314
- `)}import{resolveActiveProfile as qp,loadTokens as Bp,isExpired as Vp,decodeJwtClaims as bl}from"document360-engine";function Gp(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function _e(e,t){try{let n=qp(e,t),o=Bp(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Vp(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let a={...bl(o.idToken)??{},...bl(o.accessToken)??{}}.doc360_project_id;if(typeof a=="string"&&a&&a!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${Gp(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var En=3;function us(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, strip every <!-- SCREENSHOT ... --> block while keeping the visible [Screenshot: ...] line, normalize cross-article links).","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself \u2014 do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
315
- `)}var $l={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function ps(e){return e.filter(t=>t.path!==null&&t.status in $l&&!t.link).map(t=>({path:t.path,label:$l[t.status]}))}function Lo(e){let t=ps(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 Oo(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 Mo(e){return e.filter(t=>t.link).length}function hs(e,t){try{let n=eh(e,th(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=nh(Yp(zp(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 oh(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 Sl(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("/"),a=o.get(s);a?a.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((a,u)=>a.path.localeCompare(u.path));n.push({kind:"category",label:`${oh(r)} (${s.length})`,paths:s.map(a=>a.path),indent:!1});for(let a of s){let u=a.path.replace(/\\/g,"/").split("/").pop()??a.path;n.push({kind:"article",label:u,paths:[a.path],indent:!0,note:a.label})}}for(let r of[...t].sort((s,a)=>s.path.localeCompare(a.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 Uo(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(`
316
- `)}function fs(e,t,n){let o=x=>t[x.index]?.paths.length??0,r=e.filter(x=>x.ok),s=e.filter(x=>!x.ok),a=e.reduce((x,_)=>x+o(_),0),u=r.reduce((x,_)=>x+o(_),0),g=n==="api"?`${xe(e.reduce((x,_)=>x+_.costUsd,0))} total`:at(e.reduce((x,_)=>x+_.outputTokens,0)),b=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,y=x=>`${x} article${x===1?"":"s"}`,P=[];if(s.length===0)P.push(`Published ${y(a)} (${b}) successfully \xB7 ${g}.`),P.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{P.push(`Published ${u}/${y(a)} (${b}) \xB7 ${g}.`),P.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)P.push(` \u2717 ${x.label}${x.error?` \u2014 ${x.error}`:""}`)}return P}async function Rt(e,t){let{model:n}=Jp(e.cwd,"standard"),o=async(r,s)=>{let a=Xp(r);console.log(m(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 ${a.length} partition${a.length===1?"":"s"} (\u2264${En} agents at once) on ${n}\u2026`)),s||console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let u=!1;for await(let g of Zp({cwd:e.cwd,partitions:a,promptFor:b=>Uo(b.paths),concurrency:En,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(g.type==="partition_status")g.status==="running"?console.log(m(` \u25B8 ${g.label} \u2014 publishing\u2026`)):g.status==="done"?console.log(E(` \u2713 ${g.label}`)):console.log(v(` \u2717 ${g.label}`));else if(g.type==="run_done"){u=g.aborted,console.log("");let b=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let P of fs(g.results,a,b))console.log(g.ok?E(P):M(P));let y=hs(e.cwd,e.profileName);y&&console.log(m(y));try{let P=vl(await xl({cwd:e.cwd,profileName:e.profileName}));P&&console.log(m(P))}catch{}try{let P=Rl(await Cl({cwd:e.cwd,profileName:e.profileName}));P&&console.log(m(P))}catch{}}return u};try{if(!await o(t,!1)){let s=await ms(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(v(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Wo(e,t,n){let o=Qp(e,n);if(o.length===0)return[];let r=new Set(ps((await _o({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function ms(e,t,n){try{let o=new Set(n),r=await _o({cwd:e,profileName:t});return ps(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function Pl(e,t){let n=_e(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Wo(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 Rt(t,r)}if(o==="--all"){console.log(m("Checking what needs publishing\u2026"));try{let r=await _o({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:a}=Lo(r.entries),u=Mo(r.entries),g=e.includes("--force")&&a.length>0;u>0&&console.log(M(`\u26A0 ${u} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),a.length>0&&!g&&console.log(M(Oo(a.length)));let b=g?[...s,...a]:s;if(b.length===0){if(a.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(E(u>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let y=vl(await xl({cwd:t.cwd,profileName:t.profileName}));y&&console.log(m(y));let P=Rl(await Cl({cwd:t.cwd,profileName:t.profileName}));P&&console.log(m(P))}catch{}return{kind:"continue"}}return t?await Rt(t,b.map(y=>y.path)):{kind:"forward-to-agent",prompt:Uo(b.map(y=>y.path)),display:"/publish --all"}}catch(r){return console.log(v(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(m("Checking what needs publishing\u2026"));let r;try{let s=await _o({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:u}=Lo(s.entries);r=a;let g=Mo(s.entries);if(g>0&&console.log(M(`\u26A0 ${g} 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.`)),u.length>0&&console.log(M(Oo(u.length))),r.length===0&&u.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(v(`Could not compute sync status: ${s.message}`)),console.log(m("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(m(" (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} ${m(`(${s.label})`)}`);return console.log(m("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>Kp({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(m("Cancelled.")),{kind:"continue"}}if(o==="--all")return await Rt(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:us(o),display:`/publish ${o}`}}async function Nn(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
317
- `),display:"/audit"}}H();import{readProjectConfig as rh}from"document360-engine";function gs(){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(`
318
- `)}async function Tl(e,t){let n=t?.cwd??process.cwd();return rh(n)?{kind:"forward-to-agent",prompt:gs(),display:"/discover"}:(console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}H();import{checkbox as sh}from"@inquirer/prompts";import{inventoryRepo as ih,readProjectConfig as Dl,writeProjectConfig as ah}from"document360-engine";function ws(e,t){let n=Dl(e);n&&(n.authoritativeSourceFiles=t,ah(n,e))}function Fo(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 Al(e,t){let n=t?.cwd??process.cwd();if(!Dl(n))return console.log(v("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=ih(n);if(o.length===0)return console.log(m('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} ${m(Fo(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>sh({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Fo(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(m("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};ws(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 wh}from"@inquirer/prompts";import{applyPull as bs,computeSyncStatus as Ul,compareRemoteSources as yh,planPull as Wl,planImport as kh,applyImport as bh,establishBaselines as $h,rebaselineServerMeta as xh,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:v,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:v,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:v,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ae,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:m,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:m,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 lh(e){return e.path?e.path:`${e.title??"(untitled)"} ${ae(`[${e.articleId}]`)}`}function ch(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60);return`${n}m ${Math.round(t-n*60)}s`}function Ho(e,t){let n=[],o=e.entries.filter(y=>y.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 y of o)n.push(` ${M("~")} ${M(y.path??"")} ${ae(`\u2192 "${y.link.title}"`)}`)}for(let y of jl){let P=e.entries.filter(x=>x.status===y.status&&!(y.status==="untracked-local"&&x.link));if(P.length!==0){n.push(""),n.push($e(y.header));for(let x of P)n.push(` ${y.paint(y.mark)} ${y.paint(lh(x))}${x.detail?ae(` (${x.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let a={"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"},u=o.length,g=s===r?E("\u2713 everything up to date"):[r>0?E(`\u2713 ${r} up to date`):null,u>0?`${u} to link`:null,...jl.map(y=>{let P=(e.counts[y.status]??0)-(y.status==="untracked-local"?u:0);return P>0?`${P} ${a[y.status]}`:null})].filter(Boolean).join(ae(" \xB7 ")),b=t!==void 0?` \xB7 synced in ${ch(t)}`:"";return n.push(g+ae(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${b}`)),n}import{structuredPatch as dh}from"diff";import El from"picocolors";var Nl=80,uh="\x1B[48;2;74;28;28m",ph="\x1B[48;2;24;66;24m",Il="\x1B[49m",ys=e=>String(e).padStart(5);function _l(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function Ll(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 Xe(e,t,n){let o=x=>{let _=x.replace(/\r\n/g,`
311
+ `+as(e.text,n);case"note":return`
312
+ `+Hp[e.tone](Sn(ds(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 ${xe(e.costUsd)}`:""))}}}function bl(e,t){return e.map(n=>us(n,t)).join(`
314
+ `)}import{resolveActiveProfile as Bp,loadTokens as Vp,isExpired as Gp,decodeJwtClaims as $l}from"document360-engine";function Yp(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function _e(e,t){try{let n=Bp(e,t),o=Vp(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Gp(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let a={...$l(o.idToken)??{},...$l(o.accessToken)??{}}.doc360_project_id;if(typeof a=="string"&&a&&a!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${Yp(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var En=3;function ps(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, strip every <!-- SCREENSHOT ... --> block while keeping the visible [Screenshot: ...] line, normalize cross-article links).","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself \u2014 do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
315
+ `)}var xl={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function hs(e){return e.filter(t=>t.path!==null&&t.status in xl&&!t.link).map(t=>({path:t.path,label:xl[t.status]}))}function Oo(e){let t=hs(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 Mo(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 Uo(e){return e.filter(t=>t.link).length}function fs(e,t){try{let n=th(e,nh(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=oh(zp(Kp(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 Pl(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("/"),a=o.get(s);a?a.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((a,u)=>a.path.localeCompare(u.path));n.push({kind:"category",label:`${rh(r)} (${s.length})`,paths:s.map(a=>a.path),indent:!1});for(let a of s){let u=a.path.replace(/\\/g,"/").split("/").pop()??a.path;n.push({kind:"article",label:u,paths:[a.path],indent:!0,note:a.label})}}for(let r of[...t].sort((s,a)=>s.path.localeCompare(a.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 Wo(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(`
316
+ `)}function ms(e,t,n){let o=x=>t[x.index]?.paths.length??0,r=e.filter(x=>x.ok),s=e.filter(x=>!x.ok),a=e.reduce((x,_)=>x+o(_),0),u=r.reduce((x,_)=>x+o(_),0),g=n==="api"?`${xe(e.reduce((x,_)=>x+_.costUsd,0))} total`:at(e.reduce((x,_)=>x+_.outputTokens,0)),b=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,y=x=>`${x} article${x===1?"":"s"}`,P=[];if(s.length===0)P.push(`Published ${y(a)} (${b}) successfully \xB7 ${g}.`),P.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{P.push(`Published ${u}/${y(a)} (${b}) \xB7 ${g}.`),P.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)P.push(` \u2717 ${x.label}${x.error?` \u2014 ${x.error}`:""}`)}return P}async function Rt(e,t){let{model:n}=Zp(e.cwd,"standard"),o=async(r,s)=>{let a=Qp(r);console.log(m(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 ${a.length} partition${a.length===1?"":"s"} (\u2264${En} agents at once) on ${n}\u2026`)),s||console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let u=!1;for await(let g of eh({cwd:e.cwd,partitions:a,promptFor:b=>Wo(b.paths),concurrency:En,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(g.type==="partition_status")g.status==="running"?console.log(m(` \u25B8 ${g.label} \u2014 publishing\u2026`)):g.status==="done"?console.log(E(` \u2713 ${g.label}`)):console.log(v(` \u2717 ${g.label}`));else if(g.type==="run_done"){u=g.aborted,console.log("");let b=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let P of ms(g.results,a,b))console.log(g.ok?E(P):M(P));let y=fs(e.cwd,e.profileName);y&&console.log(m(y));try{let P=Cl(await vl({cwd:e.cwd,profileName:e.profileName}));P&&console.log(m(P))}catch{}try{let P=Sl(await Rl({cwd:e.cwd,profileName:e.profileName}));P&&console.log(m(P))}catch{}}return u};try{if(!await o(t,!1)){let s=await gs(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(v(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Fo(e,t,n){let o=Jp(e,n);if(o.length===0)return[];let r=new Set(hs((await Lo({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function gs(e,t,n){try{let o=new Set(n),r=await Lo({cwd:e,profileName:t});return hs(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function Tl(e,t){let n=_e(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Fo(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 Rt(t,r)}if(o==="--all"){console.log(m("Checking what needs publishing\u2026"));try{let r=await Lo({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:a}=Oo(r.entries),u=Uo(r.entries),g=e.includes("--force")&&a.length>0;u>0&&console.log(M(`\u26A0 ${u} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),a.length>0&&!g&&console.log(M(Mo(a.length)));let b=g?[...s,...a]:s;if(b.length===0){if(a.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(E(u>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let y=Cl(await vl({cwd:t.cwd,profileName:t.profileName}));y&&console.log(m(y));let P=Sl(await Rl({cwd:t.cwd,profileName:t.profileName}));P&&console.log(m(P))}catch{}return{kind:"continue"}}return t?await Rt(t,b.map(y=>y.path)):{kind:"forward-to-agent",prompt:Wo(b.map(y=>y.path)),display:"/publish --all"}}catch(r){return console.log(v(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(m("Checking what needs publishing\u2026"));let r;try{let s=await Lo({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:u}=Oo(s.entries);r=a;let g=Uo(s.entries);if(g>0&&console.log(M(`\u26A0 ${g} 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.`)),u.length>0&&console.log(M(Mo(u.length))),r.length===0&&u.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(v(`Could not compute sync status: ${s.message}`)),console.log(m("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(m(" (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} ${m(`(${s.label})`)}`);return console.log(m("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>Xp({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(m("Cancelled.")),{kind:"continue"}}if(o==="--all")return await Rt(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:ps(o),display:`/publish ${o}`}}async function Nn(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
317
+ `),display:"/audit"}}q();import{readProjectConfig as sh}from"document360-engine";function ws(){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(`
318
+ `)}async function Dl(e,t){let n=t?.cwd??process.cwd();return sh(n)?{kind:"forward-to-agent",prompt:ws(),display:"/discover"}:(console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}q();import{checkbox as ih}from"@inquirer/prompts";import{inventoryRepo as ah,readProjectConfig as Al,writeProjectConfig as lh}from"document360-engine";function ys(e,t){let n=Al(e);n&&(n.authoritativeSourceFiles=t,lh(n,e))}function qo(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 jl(e,t){let n=t?.cwd??process.cwd();if(!Al(n))return console.log(v("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=ah(n);if(o.length===0)return console.log(m('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} ${m(qo(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>ih({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${qo(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(m("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};ys(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"}}q();import{confirm as yh}from"@inquirer/prompts";import{applyPull as $s,computeSyncStatus as Wl,compareRemoteSources as kh,planPull as Fl,planImport as bh,applyImport as $h,establishBaselines as xh,rebaselineServerMeta as vh,D360AuthError as Ch}from"document360-engine";q();var El=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:v,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint: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:v,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:v,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ae,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:m,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:m,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 ch(e){return e.path?e.path:`${e.title??"(untitled)"} ${ae(`[${e.articleId}]`)}`}function dh(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60);return`${n}m ${Math.round(t-n*60)}s`}function Ho(e,t){let n=[],o=e.entries.filter(y=>y.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 y of o)n.push(` ${M("~")} ${M(y.path??"")} ${ae(`\u2192 "${y.link.title}"`)}`)}for(let y of El){let P=e.entries.filter(x=>x.status===y.status&&!(y.status==="untracked-local"&&x.link));if(P.length!==0){n.push(""),n.push($e(y.header));for(let x of P)n.push(` ${y.paint(y.mark)} ${y.paint(ch(x))}${x.detail?ae(` (${x.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let a={"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"},u=o.length,g=s===r?E("\u2713 everything up to date"):[r>0?E(`\u2713 ${r} up to date`):null,u>0?`${u} to link`:null,...El.map(y=>{let P=(e.counts[y.status]??0)-(y.status==="untracked-local"?u:0);return P>0?`${P} ${a[y.status]}`:null})].filter(Boolean).join(ae(" \xB7 ")),b=t!==void 0?` \xB7 synced in ${dh(t)}`:"";return n.push(g+ae(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${b}`)),n}import{structuredPatch as uh}from"diff";import Nl from"picocolors";var Il=80,ph="\x1B[48;2;74;28;28m",hh="\x1B[48;2;24;66;24m",_l="\x1B[49m",ks=e=>String(e).padStart(5);function Ll(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function Ol(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 Xe(e,t,n){let o=x=>{let _=x.replace(/\r\n/g,`
319
319
  `);return _.endsWith(`
320
320
  `)||_===""?_:_+`
321
- `},r=o(e),s=o(t);if(r===s)return null;let a=Math.max(20,n-10),u=dh("a","b",r,s,"","",{context:3}),g=0,b=0,y=[];u.hunks.forEach((x,_)=>{_>0&&y.push(El.gray(" \u2026"));let C=x.oldStart,N=x.newStart,D=[],W=[],z=()=>{for(let K=0;K<D.length;K++){let X=K<W.length?_l(D[K],W[K]):void 0;b++,y.push(`${uh}${ys(C++)} - ${Ll(D[K],a,X)}${Il}`)}for(let K=0;K<W.length;K++){let X=K<D.length?_l(D[K],W[K]):void 0;g++,y.push(`${ph}${ys(N++)} + ${Ll(W[K],a,X)}${Il}`)}D=[],W=[]};for(let K of x.lines){let X=K[0],he=K.slice(1);X==="-"?D.push(he):X==="+"?W.push(he):(z(),y.push(El.gray(ys(N))+" "+he.slice(0,a)),C++,N++)}z()});let P=y.slice(0,Nl);return{added:g,removed:b,lines:P,hidden:Math.max(0,y.length-Nl)}}H();import{select as hh}from"@inquirer/prompts";import{applyPull as fh,computeSyncStatus as mh,planPull as gh}from"document360-engine";var Ol=e=>e===1?"":"s";async function ks(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=Xe(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${Ol(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(m(` \u2026 +${n.hidden} more diff lines`))}else console.log(m(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>hh({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"?(fh({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(m(" Skipped \u2014 still a conflict.")),"skipped")}async function Ml(e,t){let n=_e(t.cwd,t.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await mh({cwd:t.cwd,profileName:t.profileName})).entries.filter(u=>u.status==="conflict"&&u.path).map(u=>u.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 a=[];for(let u of s){let g=await gh({cwd:t.cwd,profileName:t.profileName,relPath:u});await ks(t,g)==="keep-local"&&a.push(u)}if(a.length>0)return console.log(m(`Publishing ${a.length} kept-local article${Ol(a.length)} over the portal\u2026`)),await Rt(t,a)}catch(r){console.log(v(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Fl(e,t){let n=_e(t.cwd,t.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Ch(t),{kind:"continue"};if(o==="--baseline")return await Rh(t,e.filter(a=>a!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Sh(t),{kind:"continue"};if(o)return console.log(v(`Unknown option: ${o}`)),console.log(m("Usage: /pull pull portal edits + import new portal articles")),console.log(m(" /pull <path> pull one article (or resolve a conflict)")),console.log(m(" /pull --status drift report only (no writes)")),console.log(m(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Ph(t,r),{kind:"continue"};console.log(m("Pulling changes from Document360\u2026"));let s=await $s({cwd:t.cwd,profileName:t.profileName});for(let a of xs(s))console.log(a.tone==="ok"?E(a.text):a.tone==="warn"?M(a.text):m(a.text));console.log("")}catch(r){r instanceof vh?console.log(v(r.message)):console.log(v(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function $s(e){let t=await Ul({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 Wl({cwd:e.cwd,profileName:e.profileName,relPath:o.path});bs({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 kh({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});bh({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 qo=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,St=e=>e===1?"":"s";function xs(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${St(e.pulled.length)} into local: ${qo(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${St(e.imported.length)}: ${qo(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${St(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${St(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). (${qo(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${St(e.failed.length)} failed: ${qo(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 Ch(e){console.log(m("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Ul({cwd:e.cwd,profileName:e.profileName});for(let o of Ho(n,Date.now()-t))console.log(o);console.log("")}async function Rh(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(m(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await $h({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await xh({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(m(` - ${s.path} (${s.reason})`))}}async function Sh(e){console.log(m("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await yh({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(E("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(v(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(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(m(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Ph(e,t){let n=t.replace(/\\/g,"/"),o=await Wl({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await ks(e,o)==="keep-local"&&(console.log(m(`Publishing ${o.path} over the portal\u2026`)),await Rt(e,[o.path]));return}console.log(""),console.log(`${L("\u25CF")} ${$e(o.title)} ${ae(`(${o.path})`)}`);for(let a of o.notes)console.log(M(` \u26A0 ${a}`));let r=Xe(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(m(" Local file already matches the remote content \u2014 advancing the sync base only.")),bs({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ae(` \u23BF Added ${r.added} line${St(r.added)}, removed ${r.removed} line${St(r.removed)}`));for(let a of r.lines)console.log(a);if(r.hidden>0&&console.log(m(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>wh({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(m(" Skipped."));return}bs({cwd:e.cwd,profileName:e.profileName},o),console.log(E(` \u2713 Pulled ${o.path} (sync base advanced).`))}H();import{statSync as Th}from"node:fs";import{resolve as Dh}from"node:path";import{estimateBulkCost as Ah,planPartitions as jh,readProjectConfig as Eh,resolveModelForOperation as Nh,runPartitioned as Ih,trackedArticlePaths as _h}from"document360-engine";var vs=3;function Cs(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 Rs(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Ss(e,t){return t.map(n=>{let o=0;try{o=Th(Dh(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Ps(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:
321
+ `},r=o(e),s=o(t);if(r===s)return null;let a=Math.max(20,n-10),u=uh("a","b",r,s,"","",{context:3}),g=0,b=0,y=[];u.hunks.forEach((x,_)=>{_>0&&y.push(Nl.gray(" \u2026"));let C=x.oldStart,N=x.newStart,D=[],W=[],z=()=>{for(let K=0;K<D.length;K++){let X=K<W.length?Ll(D[K],W[K]):void 0;b++,y.push(`${ph}${ks(C++)} - ${Ol(D[K],a,X)}${_l}`)}for(let K=0;K<W.length;K++){let X=K<D.length?Ll(D[K],W[K]):void 0;g++,y.push(`${hh}${ks(N++)} + ${Ol(W[K],a,X)}${_l}`)}D=[],W=[]};for(let K of x.lines){let X=K[0],he=K.slice(1);X==="-"?D.push(he):X==="+"?W.push(he):(z(),y.push(Nl.gray(ks(N))+" "+he.slice(0,a)),C++,N++)}z()});let P=y.slice(0,Il);return{added:g,removed:b,lines:P,hidden:Math.max(0,y.length-Il)}}q();import{select as fh}from"@inquirer/prompts";import{applyPull as mh,computeSyncStatus as gh,planPull as wh}from"document360-engine";var Ml=e=>e===1?"":"s";async function bs(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=Xe(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${Ml(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(m(` \u2026 +${n.hidden} more diff lines`))}else console.log(m(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>fh({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"?(mh({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(m(" Skipped \u2014 still a conflict.")),"skipped")}async function Ul(e,t){let n=_e(t.cwd,t.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await gh({cwd:t.cwd,profileName:t.profileName})).entries.filter(u=>u.status==="conflict"&&u.path).map(u=>u.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 a=[];for(let u of s){let g=await wh({cwd:t.cwd,profileName:t.profileName,relPath:u});await bs(t,g)==="keep-local"&&a.push(u)}if(a.length>0)return console.log(m(`Publishing ${a.length} kept-local article${Ml(a.length)} over the portal\u2026`)),await Rt(t,a)}catch(r){console.log(v(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function ql(e,t){let n=_e(t.cwd,t.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Rh(t),{kind:"continue"};if(o==="--baseline")return await Sh(t,e.filter(a=>a!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Ph(t),{kind:"continue"};if(o)return console.log(v(`Unknown option: ${o}`)),console.log(m("Usage: /pull pull portal edits + import new portal articles")),console.log(m(" /pull <path> pull one article (or resolve a conflict)")),console.log(m(" /pull --status drift report only (no writes)")),console.log(m(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Th(t,r),{kind:"continue"};console.log(m("Pulling changes from Document360\u2026"));let s=await xs({cwd:t.cwd,profileName:t.profileName});for(let a of vs(s))console.log(a.tone==="ok"?E(a.text):a.tone==="warn"?M(a.text):m(a.text));console.log("")}catch(r){r instanceof Ch?console.log(v(r.message)):console.log(v(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function xs(e){let t=await Wl({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 Fl({cwd:e.cwd,profileName:e.profileName,relPath:o.path});$s({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 bh({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});$h({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 Bo=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,St=e=>e===1?"":"s";function vs(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${St(e.pulled.length)} into local: ${Bo(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${St(e.imported.length)}: ${Bo(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${St(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${St(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). (${Bo(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${St(e.failed.length)} failed: ${Bo(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 Rh(e){console.log(m("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Wl({cwd:e.cwd,profileName:e.profileName});for(let o of Ho(n,Date.now()-t))console.log(o);console.log("")}async function Sh(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(m(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await xh({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await vh({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(m(` - ${s.path} (${s.reason})`))}}async function Ph(e){console.log(m("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await kh({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(E("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(v(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(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(m(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Th(e,t){let n=t.replace(/\\/g,"/"),o=await Fl({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await bs(e,o)==="keep-local"&&(console.log(m(`Publishing ${o.path} over the portal\u2026`)),await Rt(e,[o.path]));return}console.log(""),console.log(`${L("\u25CF")} ${$e(o.title)} ${ae(`(${o.path})`)}`);for(let a of o.notes)console.log(M(` \u26A0 ${a}`));let r=Xe(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(m(" Local file already matches the remote content \u2014 advancing the sync base only.")),$s({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ae(` \u23BF Added ${r.added} line${St(r.added)}, removed ${r.removed} line${St(r.removed)}`));for(let a of r.lines)console.log(a);if(r.hidden>0&&console.log(m(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>yh({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(m(" Skipped."));return}$s({cwd:e.cwd,profileName:e.profileName},o),console.log(E(` \u2713 Pulled ${o.path} (sync base advanced).`))}q();import{statSync as Dh}from"node:fs";import{resolve as Ah}from"node:path";import{estimateBulkCost as jh,planPartitions as Eh,readProjectConfig as Nh,resolveModelForOperation as Ih,runPartitioned as _h,trackedArticlePaths as Lh}from"document360-engine";var Cs=3;function Rs(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 Ss(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Ps(e,t){return t.map(n=>{let o=0;try{o=Dh(Ah(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Ts(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:
322
322
  - 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.
323
323
  - 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.
324
324
  - 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.
325
325
  - Work only on these files:
326
326
  `+e.paths.map(t=>`- ${t}`).join(`
327
- `)}function Ts(e,t,n){let o=e.reduce((u,g)=>u+g.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(u=>` \u2022 ${u.label} \u2014 ${u.paths.length} article${u.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 Ds(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),a=e.reduce((C,N)=>C+o(N),0),u=r.reduce((C,N)=>C+o(N),0),g=e.reduce((C,N)=>C+N.costUsd,0),b=e.reduce((C,N)=>C+N.outputTokens,0),y=n==="api"?`${xe(g)} total`:at(b),P=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=C=>`${C} article${C===1?"":"s"}`,_=[];if(s.length===0)_.push(`Converted ${x(a)} (${P}) successfully \xB7 ${y}.`);else{_.push(`Converted ${u}/${x(a)} (${P}) \xB7 ${y}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)_.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return _}async function Hl(e,t){if(!Eh(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Cs(e),r=_h(t.cwd,t.profileName);if(r.length===0)return console.log(v("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Rs(r,n);if(s.length===0)return console.log(v(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let a=jh(s),u=`/convert${n?` --scope ${n}`:""} --run`,{model:g,forced:b}=Nh(t.cwd,"light");if(!o){let y=Ah({files:Ss(t.cwd,s),op:"convert",model:g});n&&console.log(m(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let P of Ts(a,y,vs))console.log(P);return console.log(m(`Model: ${g}${b?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(m(`Run ${u} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Converting ${s.length} articles across ${a.length} partitions (\u2264${vs} agents at once) on ${g}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let y of Ih({cwd:t.cwd,partitions:a,promptFor:Ps,concurrency:vs,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:g}))if(y.type==="partition_status")y.status==="running"?console.log(m(` \u25B8 ${y.label} \u2014 converting\u2026`)):y.status==="done"?console.log(E(` \u2713 ${y.label}`)):console.log(v(` \u2717 ${y.label}`));else if(y.type==="run_done"){console.log("");let P=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let x of Ds(y.results,a,P))console.log(y.ok?E(x):M(x))}}catch(y){console.log(v(`Convert run failed: ${y.message}`))}return console.log(""),{kind:"continue"}}H();import{statSync as Vl}from"node:fs";import{resolve as Gl}from"node:path";import{estimateBulkCost as Bh,lintDocs as Vh,planPartitions as Gh,readDocsPlan as Yh,readProjectConfig as Yl,DEFAULT_DOCS_DIR as zh,resolveModelForOperation as Kh,runPartitioned as Xh,stampArticles as Qh,CONTENT_CAP_VERSION as Jh}from"document360-engine";import{readProjectConfig as Lh,loadProfileMap as Oh,resolveActiveProfile as Mh,desiredCategoryOrder as Uh,desiredArticleOrder as Wh,DEFAULT_DOCS_DIR as Fh}from"document360-engine";var As=e=>e.replace(/\\/g,"/"),Hh=e=>As(e).split("/").pop()??e;function qh(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function In(e,t){try{let n=Lh(e);if(!n)return[];let o=Mh(e,t),r=Oh(e,o.name);if(!r)return[];let s=As(n.docsDir??Fh).replace(/\/+$/,""),a=new Map;for(let g of Wh(r))a.set(g.categoryPath,(a.get(g.categoryPath)??0)+1);let u=[];for(let g of Uh(r)){let b=As(g.path),y=b.startsWith(`${s}/`)?b.slice(s.length+1):b===s?"":b;y&&u.push({token:y,label:qh(Hh(b)),count:a.get(g.path)??0})}return u}catch{return[]}}function ql(e,t){let n=In(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 lt(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function rn(e,t,n,o){let r=In(e,o);if(r.length<=1)return[];let s=n.filter(b=>b.startsWith("--")).join(" "),a=s?` ${s}`:"",u=`/${t}${a} --all`.replace(/\s+/g," "),g=b=>t==="write"?`/write --scope ${b}${a}`:`/${t} ${b}${a}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((b,y)=>b+y.count,0)} articles). Pick a target:`,` ${u} (everything)`,...r.map(b=>` ${g(b.token)} (${b.label} \xB7 ${b.count} article${b.count===1?"":"s"})`)]}function Bo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Bl(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 Zh=3,ef=8;function js(e){return e===void 0||!Number.isFinite(e)?Zh:Math.max(1,Math.min(Math.floor(e),ef))}function Es(e){let t,n,o=!1,r=!1,s,a=g=>{let b=Number(g);return g!==void 0&&Number.isFinite(b)?b:void 0};for(let g=0;g<e.length;g++){let b=e[g];if(b==="--preview"||b==="--dry-run")o=!0;else if(b==="--rewrite"||b==="--force")r=!0;else{if(b==="--run"||b==="--yes"||b==="--all")continue;b==="--scope"?t=e[++g]:b?.startsWith("--scope=")?t=b.slice(8):b==="--concurrency"?s=a(e[++g]):b?.startsWith("--concurrency=")?s=a(b.slice(14)):b&&!b.startsWith("--")&&(n=b)}}let u=g=>g?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:u(t),path:u(n),preview:o,concurrency:s,rewrite:r}}function tf(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function nf(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Ns(e,t,n){return n.filter(o=>{try{return Vl(Gl(e,t,o)).size===0}catch{return!0}})}function Is(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let a of o.get(r)?.sources??[])try{s+=Vl(Gl(e,a)).size}catch{}return{path:r,bytes:s}})}function _s(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.
327
+ `)}function Ds(e,t,n){let o=e.reduce((u,g)=>u+g.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(u=>` \u2022 ${u.label} \u2014 ${u.paths.length} article${u.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 As(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),a=e.reduce((C,N)=>C+o(N),0),u=r.reduce((C,N)=>C+o(N),0),g=e.reduce((C,N)=>C+N.costUsd,0),b=e.reduce((C,N)=>C+N.outputTokens,0),y=n==="api"?`${xe(g)} total`:at(b),P=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=C=>`${C} article${C===1?"":"s"}`,_=[];if(s.length===0)_.push(`Converted ${x(a)} (${P}) successfully \xB7 ${y}.`);else{_.push(`Converted ${u}/${x(a)} (${P}) \xB7 ${y}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)_.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return _}async function Hl(e,t){if(!Nh(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Rs(e),r=Lh(t.cwd,t.profileName);if(r.length===0)return console.log(v("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Ss(r,n);if(s.length===0)return console.log(v(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let a=Eh(s),u=`/convert${n?` --scope ${n}`:""} --run`,{model:g,forced:b}=Ih(t.cwd,"light");if(!o){let y=jh({files:Ps(t.cwd,s),op:"convert",model:g});n&&console.log(m(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let P of Ds(a,y,Cs))console.log(P);return console.log(m(`Model: ${g}${b?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(m(`Run ${u} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Converting ${s.length} articles across ${a.length} partitions (\u2264${Cs} agents at once) on ${g}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let y of _h({cwd:t.cwd,partitions:a,promptFor:Ts,concurrency:Cs,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:g}))if(y.type==="partition_status")y.status==="running"?console.log(m(` \u25B8 ${y.label} \u2014 converting\u2026`)):y.status==="done"?console.log(E(` \u2713 ${y.label}`)):console.log(v(` \u2717 ${y.label}`));else if(y.type==="run_done"){console.log("");let P=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let x of As(y.results,a,P))console.log(y.ok?E(x):M(x))}}catch(y){console.log(v(`Convert run failed: ${y.message}`))}return console.log(""),{kind:"continue"}}q();import{statSync as Gl}from"node:fs";import{resolve as Yl}from"node:path";import{estimateBulkCost as Vh,lintDocs as Gh,planPartitions as Yh,readDocsPlan as zh,readProjectConfig as zl,DEFAULT_DOCS_DIR as Kh,resolveModelForOperation as Xh,runPartitioned as Qh,stampArticles as Jh,CONTENT_CAP_VERSION as Zh}from"document360-engine";import{readProjectConfig as Oh,loadProfileMap as Mh,resolveActiveProfile as Uh,desiredCategoryOrder as Wh,desiredArticleOrder as Fh,DEFAULT_DOCS_DIR as qh}from"document360-engine";var js=e=>e.replace(/\\/g,"/"),Hh=e=>js(e).split("/").pop()??e;function Bh(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function In(e,t){try{let n=Oh(e);if(!n)return[];let o=Uh(e,t),r=Mh(e,o.name);if(!r)return[];let s=js(n.docsDir??qh).replace(/\/+$/,""),a=new Map;for(let g of Fh(r))a.set(g.categoryPath,(a.get(g.categoryPath)??0)+1);let u=[];for(let g of Wh(r)){let b=js(g.path),y=b.startsWith(`${s}/`)?b.slice(s.length+1):b===s?"":b;y&&u.push({token:y,label:Bh(Hh(b)),count:a.get(g.path)??0})}return u}catch{return[]}}function Bl(e,t){let n=In(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 lt(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function rn(e,t,n,o){let r=In(e,o);if(r.length<=1)return[];let s=n.filter(b=>b.startsWith("--")).join(" "),a=s?` ${s}`:"",u=`/${t}${a} --all`.replace(/\s+/g," "),g=b=>t==="write"?`/write --scope ${b}${a}`:`/${t} ${b}${a}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((b,y)=>b+y.count,0)} articles). Pick a target:`,` ${u} (everything)`,...r.map(b=>` ${g(b.token)} (${b.label} \xB7 ${b.count} article${b.count===1?"":"s"})`)]}function Vo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Vl(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 ef=3,tf=8;function Es(e){return e===void 0||!Number.isFinite(e)?ef:Math.max(1,Math.min(Math.floor(e),tf))}function Ns(e){let t,n,o=!1,r=!1,s,a=g=>{let b=Number(g);return g!==void 0&&Number.isFinite(b)?b:void 0};for(let g=0;g<e.length;g++){let b=e[g];if(b==="--preview"||b==="--dry-run")o=!0;else if(b==="--rewrite"||b==="--force")r=!0;else{if(b==="--run"||b==="--yes"||b==="--all")continue;b==="--scope"?t=e[++g]:b?.startsWith("--scope=")?t=b.slice(8):b==="--concurrency"?s=a(e[++g]):b?.startsWith("--concurrency=")?s=a(b.slice(14)):b&&!b.startsWith("--")&&(n=b)}}let u=g=>g?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:u(t),path:u(n),preview:o,concurrency:s,rewrite:r}}function nf(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function of(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Is(e,t,n){return n.filter(o=>{try{return Gl(Yl(e,t,o)).size===0}catch{return!0}})}function _s(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let a of o.get(r)?.sources??[])try{s+=Gl(Yl(e,a)).size}catch{}return{path:r,bytes:s}})}function Ls(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.
328
328
  `:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
329
329
  - 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).
330
330
  - 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).
@@ -334,90 +334,91 @@ ${s}${g}`).join("")}).join(`
334
334
  - 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.
335
335
  Articles:
336
336
  `+e.paths.map(r=>`- ${r}`).join(`
337
- `)}function Ls(e,t,n){let o=e.reduce((a,u)=>a+u.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(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.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 Os(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),a=e.reduce((C,N)=>C+o(N),0),u=r.reduce((C,N)=>C+o(N),0),g=e.reduce((C,N)=>C+N.costUsd,0),b=e.reduce((C,N)=>C+N.outputTokens,0),y=n==="api"?`${xe(g)} total`:at(b),P=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=C=>`${C} article${C===1?"":"s"}`,_=[];if(s.length===0)_.push(`Wrote ${x(a)} (${P}) 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 ${u}/${x(a)} (${P}) \xB7 ${y}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)_.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return _}function Ms(e,t,n){try{let o=Vh({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 Us(e,t,n){let o=(Yl(e)?.docsDir??zh).replace(/\/+$/,""),r=t.map(u=>u.path);if(n.path){let u=tf(n.path,o);return r.includes(u)?{docsDir:o,targets:[u],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${u}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=nf(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 a=Ns(e,o,s);if(a.length===0){let u=n.scope?` under "${n.scope}"`:"",g=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${u} are already written. Use /write <path> to rewrite one, or /write${g} --rewrite to regenerate them all.`}}return{docsDir:o,targets:a,planCount:r.length}}async function zl(e,t){if(!Yl(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Bo(e)){for(let W of ql(t.cwd,t.profileName))console.log(m(W));return{kind:"continue"}}if(lt("write",e)){let W=rn(t.cwd,"write",e,t.profileName);if(W.length>0){for(let z of W)console.log(m(z));return{kind:"continue"}}}let n=Yh(t.cwd);if(n.length===0)return console.log(v("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:a,rewrite:u}=Es(e),{docsDir:g,targets:b,reason:y,rewriting:P}=Us(t.cwd,n,{scope:o,path:r,rewrite:u});if(b.length===0)return console.log(y?M(y):M("Nothing to write.")),{kind:"continue"};P&&console.log(M(`--rewrite: regenerating ${b.length} already-written article${b.length===1?"":"s"} (overwrites them; git has your baseline).`));let x=Gh(b),_=js(a),{model:C,forced:N}=Kh(t.cwd,"standard"),D=!!r;if(s&&!D){let W=Bh({files:Is(t.cwd,n,b),op:"write",model:C});o&&console.log(m(`Scope: ${o} (${b.length} pending).`));for(let z of Ls(x,W,_))console.log(z);return console.log(m(`Model: ${C}${N?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(m(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Writing ${b.length} article${b.length===1?"":"s"} across ${x.length} partition${x.length===1?"":"s"} (\u2264${_} agents at once) on ${C}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let W of Xh({cwd:t.cwd,partitions:x,promptFor:z=>_s(z,g,{rewrite:P||D}),concurrency:_,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(W.type==="partition_status")W.status==="running"?console.log(m(` \u25B8 ${W.label} \u2014 writing\u2026`)):W.status==="done"?console.log(E(` \u2713 ${W.label}`)):console.log(v(` \u2717 ${W.label}`));else if(W.type==="run_done"){console.log("");let z=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let X of Os(W.results,x,z))console.log(W.ok?E(X):M(X));if(W.ok)try{Qh(t.cwd,b.map(X=>`${g}/${X}`),{writtenCap:Jh})}catch{}let K=Ms(t.cwd,g,b);K&&console.log(M(K))}}catch(W){console.log(v(`Write run failed: ${W.message}`))}return console.log(""),{kind:"continue"}}H();import{existsSync as of,readdirSync as Kl,statSync as Xl}from"node:fs";import{join as Ql}from"node:path";import{inputDir as rf,readProjectConfig as sf}from"document360-engine";var Jl=/\.(md|markdown|pdf|txt)$/i;function Ws(e){let t=rf(e);if(!of(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Kl(t)){let s=Ql(t,r),a=!1;try{a=Xl(s).isDirectory()}catch{continue}if(a){if(r.startsWith("."))continue;let u=af(s);u>0&&n.push({name:r,docCount:u})}else Jl.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function af(e){let t=0;for(let n of Kl(e))try{Xl(Ql(e,n)).isFile()&&Jl.test(n)&&t++}catch{}return t}function Fs(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 Vo(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(`
338
- `)}var Hs="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Zl(e,t){let n=t?.cwd??process.cwd();if(!sf(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Ws(n);if(o.length===0&&r===0)return console.log(m(Hs)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(m("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let g of o)console.log(` ${g.name} ${m(`(${g.docCount} doc${g.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let u=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Vo(u),display:u?`/draft ${u}`:"/draft"}}let a=Fs(o,s);return{kind:"forward-to-agent",prompt:Vo(a??"",a?void 0:s),display:`/draft ${s}`}}H();import{listOpenForDocs as lf,readProjectConfig as cf}from"document360-engine";function qs(e){try{return lf(e).filter(t=>t.kind==="request").length}catch{return 0}}function Bs(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Vs(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(`
339
- `)}var Gs="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 ec(e,t){let n=t?.cwd??process.cwd();if(!cf(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Bs(e);if(!r&&qs(n)===0)return console.log(m(Gs)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Vs(r,o),display:s}}H();import{search as df}from"@inquirer/prompts";import{findByName as uf,getSession as pf,listSessions as hf,relativeTime as nc}from"document360-engine";async function oc(e,t){let n=hf(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(m("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=uf(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(v(`No session matches "${o}".`)),tc(n),{kind:"continue"})}if(!process.stdin.isTTY)return tc(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>df({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let a=(s??"").toLowerCase();return n.filter(u=>!a||u.name.toLowerCase().includes(a)||u.firstPrompt.toLowerCase().includes(a)).map(u=>({name:`${u.name} ${nc(u.updatedAt)}`,value:u.uuid,description:u.firstPrompt.slice(0,100)}))}})),r=pf(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function tc(e){console.log("");for(let t of e.slice(0,15))console.log(` ${L(t.name)} ${m(nc(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}H();import{renameSession as ff}from"document360-engine";function Ys(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=Ys(e.join(" "));if(!n)return console.log(v("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(ff(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log(v("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(E(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as sc,readProjectConfig as mf,writeProjectConfig as gf}from"document360-engine";H();function zs(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=mf(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}},gf(o,e),null):`Unknown environment "${r}". Known: ${sc().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function ic(e,t){let n=e[0];if(!n)return Ro(t.cwd),{kind:"continue"};if(n==="add"){let o=zs(t.cwd,e[1],e[2]);return o?(console.log(v(o)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${L(`/profile ${e[1]}`)} then ${L("/login")}`),{kind:"continue"})}return So(t.cwd,n),Po(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}H();import{select as wf}from"@inquirer/prompts";import{readProjectConfig as yf,readUserConfig as ac,resolveModelSetting as Ks,writeUserConfig as lc}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 Go(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 kf(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 _n(e,t){let n=()=>Ks(e).model;if(t==="default"){let s=ac();return s.defaultModel?(delete s.defaultModel,lc(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Ks(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}}lc({...ac(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=yf(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 cc(e,t){let n=e[0]?.trim();if(!n){let a=Ks(t.cwd);if(!process.stdin.isTTY)return console.log(`${$e("Model:")} ${L(a.model)}${a.source==="auto"?m(" (auto)"):""}`),console.log(m(` source: ${kf(a)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let u=Go(a),g;try{g=await t.withPausedInput(()=>wf({message:`Select model (current: ${a.model}${a.source==="auto"?" \xB7 auto":""})`,default:He[u].value,choices:He.map((x,_)=>({name:`${x.label}${_===u?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:b,changed:y,effective:P}=_n(t.cwd,g??"default");for(let x of b)console.log(x.startsWith("\u26A0")?M(x):x.startsWith("\u2713")?E(x):m(x));return y&&await t.setModel(P),{kind:"continue"}}let{lines:o,changed:r,effective:s}=_n(t.cwd,n);for(let a of o)console.log(a.startsWith("\u26A0")?M(a):a.startsWith("\u2713")?E(a):m(a));return r&&await t.setModel(s),{kind:"continue"}}Yo();async function mc(e,t){return await t.withPausedInput(()=>Xt(t.cwd)),{kind:"clear"}}async function gc(e,t){return await t.withPausedInput(()=>$o(t.cwd,t.profileName)),{kind:"clear"}}H();import{resolveActiveProfile as Of}from"document360-engine";async function wc(e,t){let n=!1;try{n=Of(t.cwd).production}catch{}return n?(console.log(M("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(m("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}H();var yc=async(e,t)=>{try{await t.withPausedInput(()=>Co({}))}catch(n){console.log(v(`Login failed: ${n.message}`))}return{kind:"continue"}};H();import{resolveActiveProfile as Mf,clearTokens as Uf,clearProfileProject as Wf}from"document360-engine";async function kc(e,t){let n;try{n=Mf(t.cwd,t.profileName).name}catch(r){return console.log(v(r.message)),{kind:"continue"}}let o=Uf(n);return Wf(t.cwd,n),console.log(o?E(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):m(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(m("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as Js}from"node:fs";import{isAbsolute as bc,join as $c,resolve as xc}from"node:path";import{readProjectConfig as vc,screenshotPlaceholderIds as Ff,DEFAULT_CAPTURE_DIR as Cc,DEFAULT_OUTPUT_DIR as Hf}from"document360-engine";var Qs=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function On(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="setup")return{mode:"setup"};if(t==="list")return{mode:"list",scope:e[1]?Qs(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]?Qs(o[1]):void 0};let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:Qs(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function Pt(e,t){let n=vc(e),o=n?.captureDir??Cc,r=n?.outputDir??Hf,s=(a,u)=>bc(a)?$c(a,u):xc(e,a,u);return Ff(e,{scope:t}).map(({id:a,file:u})=>{let g=Js(s(r,`${a}.png`))?"captured":Js(s(o,`${a}.spec.ts`))?"spec":"placeholder";return{id:a,file:u,state:g}})}function Rc(e,t){let n=vc(e)?.captureDir??Cc;return Js(bc(n)?$c(n,`${t}.spec.ts`):xc(e,n,`${t}.spec.ts`))}var qf={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Bf={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function zo(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 a of e.filter(u=>u.file===s))r.push(` ${qf[a.state]} ${a.id.padEnd(34)} ${Bf[a.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Sc(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),indent:!1});let r=new Map;for(let s of t){let a=r.get(s.file);a?a.push(s):r.set(s.file,[s])}for(let s of[...r.keys()].sort()){let a=r.get(s);if(a.length===1){o.push({kind:"shot",action:"author",label:a[0].id,ids:[a[0].id],indent:!1,note:` ${s}`});continue}o.push({kind:"article",action:"author",label:`${s} (${a.length})`,ids:a.map(u=>u.id),indent:!1});for(let u of a)o.push({kind:"shot",action:"author",label:u.id,ids:[u.id],indent:!0})}n.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${n.length} ready specs`,ids:n.map(s=>s.id),indent:!1});for(let s of n)o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],indent:n.length>1,note:" \u25D0 ready \u2014 enter captures"});return o}function Pc(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(`
337
+ `)}function Os(e,t,n){let o=e.reduce((a,u)=>a+u.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(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.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 Ms(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),a=e.reduce((C,N)=>C+o(N),0),u=r.reduce((C,N)=>C+o(N),0),g=e.reduce((C,N)=>C+N.costUsd,0),b=e.reduce((C,N)=>C+N.outputTokens,0),y=n==="api"?`${xe(g)} total`:at(b),P=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=C=>`${C} article${C===1?"":"s"}`,_=[];if(s.length===0)_.push(`Wrote ${x(a)} (${P}) 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 ${u}/${x(a)} (${P}) \xB7 ${y}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)_.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return _}function Us(e,t,n){try{let o=Gh({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 Ws(e,t,n){let o=(zl(e)?.docsDir??Kh).replace(/\/+$/,""),r=t.map(u=>u.path);if(n.path){let u=nf(n.path,o);return r.includes(u)?{docsDir:o,targets:[u],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${u}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=of(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 a=Is(e,o,s);if(a.length===0){let u=n.scope?` under "${n.scope}"`:"",g=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${u} are already written. Use /write <path> to rewrite one, or /write${g} --rewrite to regenerate them all.`}}return{docsDir:o,targets:a,planCount:r.length}}async function Kl(e,t){if(!zl(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Vo(e)){for(let W of Bl(t.cwd,t.profileName))console.log(m(W));return{kind:"continue"}}if(lt("write",e)){let W=rn(t.cwd,"write",e,t.profileName);if(W.length>0){for(let z of W)console.log(m(z));return{kind:"continue"}}}let n=zh(t.cwd);if(n.length===0)return console.log(v("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:a,rewrite:u}=Ns(e),{docsDir:g,targets:b,reason:y,rewriting:P}=Ws(t.cwd,n,{scope:o,path:r,rewrite:u});if(b.length===0)return console.log(y?M(y):M("Nothing to write.")),{kind:"continue"};P&&console.log(M(`--rewrite: regenerating ${b.length} already-written article${b.length===1?"":"s"} (overwrites them; git has your baseline).`));let x=Yh(b),_=Es(a),{model:C,forced:N}=Xh(t.cwd,"standard"),D=!!r;if(s&&!D){let W=Vh({files:_s(t.cwd,n,b),op:"write",model:C});o&&console.log(m(`Scope: ${o} (${b.length} pending).`));for(let z of Os(x,W,_))console.log(z);return console.log(m(`Model: ${C}${N?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(m(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Writing ${b.length} article${b.length===1?"":"s"} across ${x.length} partition${x.length===1?"":"s"} (\u2264${_} agents at once) on ${C}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let W of Qh({cwd:t.cwd,partitions:x,promptFor:z=>Ls(z,g,{rewrite:P||D}),concurrency:_,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(W.type==="partition_status")W.status==="running"?console.log(m(` \u25B8 ${W.label} \u2014 writing\u2026`)):W.status==="done"?console.log(E(` \u2713 ${W.label}`)):console.log(v(` \u2717 ${W.label}`));else if(W.type==="run_done"){console.log("");let z=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let X of Ms(W.results,x,z))console.log(W.ok?E(X):M(X));if(W.ok)try{Jh(t.cwd,b.map(X=>`${g}/${X}`),{writtenCap:Zh})}catch{}let K=Us(t.cwd,g,b);K&&console.log(M(K))}}catch(W){console.log(v(`Write run failed: ${W.message}`))}return console.log(""),{kind:"continue"}}q();import{existsSync as rf,readdirSync as Xl,statSync as Ql}from"node:fs";import{join as Jl}from"node:path";import{inputDir as sf,readProjectConfig as af}from"document360-engine";var Zl=/\.(md|markdown|pdf|txt)$/i;function Fs(e){let t=sf(e);if(!rf(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Xl(t)){let s=Jl(t,r),a=!1;try{a=Ql(s).isDirectory()}catch{continue}if(a){if(r.startsWith("."))continue;let u=lf(s);u>0&&n.push({name:r,docCount:u})}else Zl.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function lf(e){let t=0;for(let n of Xl(e))try{Ql(Jl(e,n)).isFile()&&Zl.test(n)&&t++}catch{}return t}function qs(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 Go(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(`
338
+ `)}var Hs="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function ec(e,t){let n=t?.cwd??process.cwd();if(!af(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Fs(n);if(o.length===0&&r===0)return console.log(m(Hs)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(m("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let g of o)console.log(` ${g.name} ${m(`(${g.docCount} doc${g.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let u=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Go(u),display:u?`/draft ${u}`:"/draft"}}let a=qs(o,s);return{kind:"forward-to-agent",prompt:Go(a??"",a?void 0:s),display:`/draft ${s}`}}q();import{listOpenForDocs as cf,readProjectConfig as df}from"document360-engine";function Bs(e){try{return cf(e).filter(t=>t.kind==="request").length}catch{return 0}}function Vs(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Gs(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(`
339
+ `)}var Ys="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 tc(e,t){let n=t?.cwd??process.cwd();if(!df(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Vs(e);if(!r&&Bs(n)===0)return console.log(m(Ys)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Gs(r,o),display:s}}q();import{search as uf}from"@inquirer/prompts";import{findByName as pf,getSession as hf,listSessions as ff,relativeTime as oc}from"document360-engine";async function rc(e,t){let n=ff(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(m("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=pf(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(v(`No session matches "${o}".`)),nc(n),{kind:"continue"})}if(!process.stdin.isTTY)return nc(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>uf({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let a=(s??"").toLowerCase();return n.filter(u=>!a||u.name.toLowerCase().includes(a)||u.firstPrompt.toLowerCase().includes(a)).map(u=>({name:`${u.name} ${oc(u.updatedAt)}`,value:u.uuid,description:u.firstPrompt.slice(0,100)}))}})),r=hf(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function nc(e){console.log("");for(let t of e.slice(0,15))console.log(` ${L(t.name)} ${m(oc(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}q();import{renameSession as mf}from"document360-engine";function zs(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 sc(e,t){let n=zs(e.join(" "));if(!n)return console.log(v("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(mf(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log(v("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(E(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as ic,readProjectConfig as gf,writeProjectConfig as wf}from"document360-engine";q();function Ks(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=gf(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 ic().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},wf(o,e),null):`Unknown environment "${r}". Known: ${ic().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function ac(e,t){let n=e[0];if(!n)return So(t.cwd),{kind:"continue"};if(n==="add"){let o=Ks(t.cwd,e[1],e[2]);return o?(console.log(v(o)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${L(`/profile ${e[1]}`)} then ${L("/login")}`),{kind:"continue"})}return Po(t.cwd,n),To(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}q();import{select as yf}from"@inquirer/prompts";import{readProjectConfig as kf,readUserConfig as lc,resolveModelSetting as Xs,writeUserConfig as cc}from"document360-engine";var qe=[{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 Yo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=qe.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function bf(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 _n(e,t){let n=()=>Xs(e).model;if(t==="default"){let s=lc();return s.defaultModel?(delete s.defaultModel,cc(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Xs(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}}cc({...lc(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=kf(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 dc(e,t){let n=e[0]?.trim();if(!n){let a=Xs(t.cwd);if(!process.stdin.isTTY)return console.log(`${$e("Model:")} ${L(a.model)}${a.source==="auto"?m(" (auto)"):""}`),console.log(m(` source: ${bf(a)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let u=Yo(a),g;try{g=await t.withPausedInput(()=>yf({message:`Select model (current: ${a.model}${a.source==="auto"?" \xB7 auto":""})`,default:qe[u].value,choices:qe.map((x,_)=>({name:`${x.label}${_===u?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:b,changed:y,effective:P}=_n(t.cwd,g??"default");for(let x of b)console.log(x.startsWith("\u26A0")?M(x):x.startsWith("\u2713")?E(x):m(x));return y&&await t.setModel(P),{kind:"continue"}}let{lines:o,changed:r,effective:s}=_n(t.cwd,n);for(let a of o)console.log(a.startsWith("\u26A0")?M(a):a.startsWith("\u2713")?E(a):m(a));return r&&await t.setModel(s),{kind:"continue"}}zo();async function gc(e,t){return await t.withPausedInput(()=>Xt(t.cwd)),{kind:"clear"}}async function wc(e,t){return await t.withPausedInput(()=>xo(t.cwd,t.profileName)),{kind:"clear"}}q();import{resolveActiveProfile as Mf}from"document360-engine";async function yc(e,t){let n=!1;try{n=Mf(t.cwd).production}catch{}return n?(console.log(M("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(m("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}q();var kc=async(e,t)=>{try{await t.withPausedInput(()=>Ro({}))}catch(n){console.log(v(`Login failed: ${n.message}`))}return{kind:"continue"}};q();import{resolveActiveProfile as Uf,clearTokens as Wf,clearProfileProject as Ff}from"document360-engine";async function bc(e,t){let n;try{n=Uf(t.cwd,t.profileName).name}catch(r){return console.log(v(r.message)),{kind:"continue"}}let o=Wf(n);return Ff(t.cwd,n),console.log(o?E(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):m(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(m("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as Zs}from"node:fs";import{isAbsolute as $c,join as xc,resolve as vc}from"node:path";import{readProjectConfig as Cc,screenshotPlaceholderIds as qf,DEFAULT_CAPTURE_DIR as Rc,DEFAULT_OUTPUT_DIR as Hf}from"document360-engine";var Js=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function On(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]?Js(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]?Js(o[1]):void 0};let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:Js(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function Pt(e,t){let n=Cc(e),o=n?.captureDir??Rc,r=n?.outputDir??Hf,s=(a,u)=>$c(a)?xc(a,u):vc(e,a,u);return qf(e,{scope:t}).map(({id:a,file:u})=>{let g=Zs(s(r,`${a}.png`))?"captured":Zs(s(o,`${a}.spec.ts`))?"spec":"placeholder";return{id:a,file:u,state:g}})}function Sc(e,t){let n=Cc(e)?.captureDir??Rc;return Zs($c(n)?xc(n,`${t}.spec.ts`):vc(e,n,`${t}.spec.ts`))}var Bf={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Vf={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Ko(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 a of e.filter(u=>u.file===s))r.push(` ${Bf[a.state]} ${a.id.padEnd(34)} ${Vf[a.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Pc(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),indent:!1});let r=new Map;for(let s of t){let a=r.get(s.file);a?a.push(s):r.set(s.file,[s])}for(let s of[...r.keys()].sort()){let a=r.get(s);if(a.length===1){o.push({kind:"shot",action:"author",label:a[0].id,ids:[a[0].id],indent:!1,note:` ${s}`});continue}o.push({kind:"article",action:"author",label:`${s} (${a.length})`,ids:a.map(u=>u.id),indent:!1});for(let u of a)o.push({kind:"shot",action:"author",label:u.id,ids:[u.id],indent:!0})}n.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${n.length} ready specs`,ids:n.map(s=>s.id),indent:!1});for(let s of n)o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],indent:n.length>1,note:" \u25D0 ready \u2014 enter captures"});return o}function Tc(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(`
340
340
  `),"","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(`
341
- `)}async function Ko(e,t){let n=On(e);if(n.mode==="list"){let a=t?.cwd??process.cwd(),u=Pt(a,n.scope);for(let b of zo(u,n.scope))console.log(b);let g=u.filter(b=>b.state==="placeholder").length;return g>0&&(console.log(""),console.log(`Author specs: /screenshot author <id> (one shot) \xB7 /screenshot author <path> (a folder) \xB7 /screenshot author --all (all ${g} 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(`
342
- `),display:`/screenshot ${n.id}`};if(n.mode==="capture"||n.mode==="setup")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(`
343
- `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{spawn as Vf}from"node:child_process";import{existsSync as Tc,statSync as Gf}from"node:fs";import{isAbsolute as Yf,join as Dc,resolve as zf}from"node:path";import{readProjectConfig as Kf,DEFAULT_OUTPUT_DIR as Xf}from"document360-engine";var Qf=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Zs(e){let t=e.find(n=>!n.startsWith("--"));return e.includes("--all")?{mode:"all"}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:Qf(t)}:{mode:"single",id:t}:{mode:"picker"}}function ei(e,t){let n=Pt(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 Ac(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"),o=[];t.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${t.length} ready specs`,ids:t.map(s=>s.id),indent:!1});let r=new Map;for(let s of t){let a=r.get(s.file);a?a.push(s):r.set(s.file,[s])}for(let s of[...r.keys()].sort()){let a=r.get(s);if(a.length===1){o.push({kind:"shot",action:"capture",label:a[0].id,ids:[a[0].id],indent:!1,note:` ${s}`});continue}o.push({kind:"article",action:"capture",label:`${s} (${a.length})`,ids:a.map(u=>u.id),indent:!1});for(let u of a)o.push({kind:"shot",action:"capture",label:u.id,ids:[u.id],indent:!0})}for(let s of[...n].sort((a,u)=>a.id.localeCompare(u.id)))o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],indent:!1,note:" \u25CF captured \u2014 re-capture"});return o}function Jf(e,t){let n=Kf(e)?.outputDir??Xf;return Yf(n)?Dc(n,`${t}.png`):zf(e,n,`${t}.png`)}function ti(e,t,n,o){let r=Jf(e,t);return Tc(r)&&Gf(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function jc(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}function Ec(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(`
344
- `)}var Zf=/^[A-Za-z0-9._-]+$/;function ni(e){return new Promise((t,n)=>{if(!Zf.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=Vf(`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",a=>{r+=a.toString()}),o.stderr?.on("data",a=>{r+=a.toString()}));let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",a=>{e.signal?.removeEventListener("abort",s),n(a)}),o.on("close",a=>{e.signal?.removeEventListener("abort",s),t({exitCode:a??1,output:r})})})}function Nc(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function Xo(e){return Tc(Dc(e,".d360-writer","capture.json"))}function Ic(e,t){let n=new Map(Pt(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function oi(e,t){let n=t?.cwd??process.cwd(),o=Zs(e);if(!Xo(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}=ei(n,o.mode==="scope"?o.scope:void 0),a=o.mode==="single"?[o.id]:o.mode==="picker"?r:[...r,...s];if(a.length===0)return console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};let u=Date.now(),g=[];for(let y of a){console.log(`\u25B6 ${y}`);try{let{exitCode:P}=await ni({cwd:n,id:y,stdio:"inherit"});g.push({id:y,outcome:ti(n,y,P,u)})}catch(P){if(P.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};g.push({id:y,outcome:"failed",detail:P.message})}}let b=y=>g.filter(P=>P.outcome===y).length;return console.log(`\u2713 ${b("captured")} captured \xB7 \u2298 ${b("skipped")} skipped \xB7 \u2717 ${b("failed")} failed`),{kind:"continue"}}import{existsSync as em,readFileSync as tm}from"node:fs";import{isAbsolute as nm,join as om,resolve as rm}from"node:path";import{readProjectConfig as sm,DEFAULT_CAPTURE_DIR as im}from"document360-engine";async function sn(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-SETUP.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
345
- `),display:"/capture-setup"}}var _c="-".repeat(64);function ri(e){let t=im;try{let y=sm(e);y?.captureDir&&(t=y.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=nm(t)?om(t,"CAPTURE-TESTID-REQUESTS.json"):rm(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!em(n))return null;let o;try{let y=JSON.parse(tm(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,a=`${s} data-testid attribute${s===1?"":"s"}`,u=`${r} source file${r===1?"":"s"}`,g=`${t}/CAPTURE-TESTID-REQUESTS.md`,b=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${a} requested across ${u}.`,"\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.","",_c,`Read ${g} and ${b}. They list ${a} 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.",_c]}st();H();import{listOpenForDocs as am,readProjectConfig as lm}from"document360-engine";function si(e){try{return am(e).length}catch{return 0}}function ii(){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(`
346
- `)}async function Lc(e,t){let n=t?.cwd??process.cwd();return lm(n)?si(n)===0?(console.log(m("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:ii(),display:"/inbox"}:(console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}H();import{listOpenHints as cm,listOpenForDocs as dm,listOpenDirectives as um,readProjectConfig as pm,computeSyncStatus as hm,planPull as fm,applyPull as mm,planImport as gm,applyImport as wm}from"document360-engine";function Mn(e){let t=0,n=0,o=0,r=0;try{t=cm(e).length}catch{}try{let s=dm(e);n=s.filter(a=>a.kind==="request").length,o=s.filter(a=>a.kind==="answer").length}catch{}try{r=um(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function Un(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 li(e){return{publish:e.includes("--publish")}}function ci({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page" \u2014 .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (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(`
347
- `)}var ym={status:hm,plan:fm,apply:mm,planImport:gm,applyImport:wm};async function di(e,t=ym){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 ai=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Qo=e=>e===1?"":"s";function ui(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${Qo(e.pulled.length)} into local: ${ai(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Qo(e.imported.length)} into local drafts: ${ai(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Qo(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${ai(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${Qo(e.failed.length)} failed \u2014 left for /pull.`),t}async function Oc(e,t){let n=t?.cwd??process.cwd();if(!pm(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=_e(n,t?.profileName);if(!o.ok)return console.log(v(o.reason)),{kind:"continue"};let{publish:r}=li(e);console.log(m("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await di({cwd:n,profileName:t?.profileName});for(let u of ui(s))console.log(u.startsWith("\u2713")?E(u):u.startsWith("\u2139")?m(u):M(u));let a=Un(Mn(n));return console.log(m(a?`Catching up on ${a}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:ci({publish:r}),display:`/catch-up${r?" --publish":""}`}}H();import{spawn as km}from"node:child_process";var Tt="document360-writer",Jo=`npm i -g ${Tt}@latest`;async function Zo(){let e=process.platform==="win32";return new Promise(t=>{try{let n=km(`npm i -g ${Tt}@latest`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});n.on("error",o=>t({ok:!1,output:String(o)})),n.on("close",o=>t({ok:o===0,output:""})),e||n.unref()}catch(n){t({ok:!1,output:String(n)})}})}async function Mc(){return console.log(m(`Updating ${Tt}\u2026`)),(await Zo()).ok?console.log(E("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(v(`Update failed \u2014 run manually: ${Jo}`)),{kind:"continue"}}H();st();import{existsSync as pi,rmSync as bm}from"node:fs";import{basename as Uc,resolve as hi}from"node:path";import{execFileSync as $m}from"node:child_process";import{input as xm}from"@inquirer/prompts";import{readProjectConfig as vm,devHintsGuidePath as Cm}from"document360-engine";var Rm=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Sm=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),er=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Wc=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Fc(e){let t=er(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Wc(t)?!0:Sm.has(t)}function fi(e){let t=null;try{t=vm(e)}catch{t=null}let n=new Set(Rm);for(let o of[er(t?.docsDir),er(t?.captureDir),er(t?.outputDir)])o&&Wc(o)&&n.add(o);return[...n].filter(o=>Fc(o)&&pi(hi(e,o)))}function mi(e,t){let n=[],o=[];for(let r of t){if(!Fc(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{bm(hi(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Hc(e,t){try{return $m("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
348
- `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Pm(e){return Hc(e,".d360-writer/hints")}function Tm(e){return Hc(e,".d360-writer/messages")}function gi(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Pm(e),o=Tm(e),r=pi(hi(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: ${Uc(e)}`]}async function qc(e,t){let n=fi(t.cwd);for(let g of gi(t.cwd,n))console.log(n.length===0?m(g):g);if(n.length===0)return{kind:"continue"};let o=Uc(t.cwd);if((await t.withPausedInput(()=>xm({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(M("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=pi(Cm(t.cwd)),{removed:a,failed:u}=mi(t.cwd,n);console.log(E(`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`));for(let g of u)console.log(v(` \u2717 ${g.path}: ${g.error}`));if(s){for(let g of jo())console.log(g);console.log(m("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(m("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}H();import{lintDocs as Dm}from"document360-engine";function tr(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 wi(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
+ `)}async function Xo(e,t){let n=On(e);if(n.mode==="list"){let a=t?.cwd??process.cwd(),u=Pt(a,n.scope);for(let b of Ko(u,n.scope))console.log(b);let g=u.filter(b=>b.state==="placeholder").length;return g>0&&(console.log(""),console.log(`Author specs: /screenshot author <id> (one shot) \xB7 /screenshot author <path> (a folder) \xB7 /screenshot author --all (all ${g} 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(`
342
+ `),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(`
343
+ `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{spawn as Gf}from"node:child_process";import{existsSync as Dc,statSync as Yf}from"node:fs";import{isAbsolute as zf,join as Ac,resolve as Kf}from"node:path";import{readProjectConfig as Xf,DEFAULT_OUTPUT_DIR as Qf}from"document360-engine";var Jf=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function ei(e){let t=e.find(n=>!n.startsWith("--"));return e.includes("--all")?{mode:"all"}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:Jf(t)}:{mode:"single",id:t}:{mode:"picker"}}function ti(e,t){let n=Pt(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 jc(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"),o=[];t.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${t.length} ready specs`,ids:t.map(s=>s.id),indent:!1});let r=new Map;for(let s of t){let a=r.get(s.file);a?a.push(s):r.set(s.file,[s])}for(let s of[...r.keys()].sort()){let a=r.get(s);if(a.length===1){o.push({kind:"shot",action:"capture",label:a[0].id,ids:[a[0].id],indent:!1,note:` ${s}`});continue}o.push({kind:"article",action:"capture",label:`${s} (${a.length})`,ids:a.map(u=>u.id),indent:!1});for(let u of a)o.push({kind:"shot",action:"capture",label:u.id,ids:[u.id],indent:!0})}for(let s of[...n].sort((a,u)=>a.id.localeCompare(u.id)))o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],indent:!1,note:" \u25CF captured \u2014 re-capture"});return o}function Zf(e,t){let n=Xf(e)?.outputDir??Qf;return zf(n)?Ac(n,`${t}.png`):Kf(e,n,`${t}.png`)}function ni(e,t,n,o){let r=Zf(e,t);return Dc(r)&&Yf(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function Ec(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}function Nc(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(`
344
+ `)}var em=/^[A-Za-z0-9._-]+$/;function oi(e){return new Promise((t,n)=>{if(!em.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=Gf(`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",a=>{r+=a.toString()}),o.stderr?.on("data",a=>{r+=a.toString()}));let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",a=>{e.signal?.removeEventListener("abort",s),n(a)}),o.on("close",a=>{e.signal?.removeEventListener("abort",s),t({exitCode:a??1,output:r})})})}function Ic(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function Qo(e){return Dc(Ac(e,".d360-writer","capture.json"))}function ri(){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(`
345
+ `)}function _c(e,t){let n=new Map(Pt(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function si(e,t){let n=t?.cwd??process.cwd(),o=ei(e);if(!Qo(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}=ti(n,o.mode==="scope"?o.scope:void 0),a=o.mode==="single"?[o.id]:o.mode==="picker"?r:[...r,...s];if(a.length===0)return console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};let u=Date.now(),g=[];for(let y of a){console.log(`\u25B6 ${y}`);try{let{exitCode:P}=await oi({cwd:n,id:y,stdio:"inherit"});g.push({id:y,outcome:ni(n,y,P,u)})}catch(P){if(P.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};g.push({id:y,outcome:"failed",detail:P.message})}}let b=y=>g.filter(P=>P.outcome===y).length;return console.log(`\u2713 ${b("captured")} captured \xB7 \u2298 ${b("skipped")} skipped \xB7 \u2717 ${b("failed")} failed`),{kind:"continue"}}import{existsSync as tm,readFileSync as nm}from"node:fs";import{isAbsolute as om,join as rm,resolve as sm}from"node:path";import{readProjectConfig as im,DEFAULT_CAPTURE_DIR as am}from"document360-engine";async function sn(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-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(`
346
+ `),display:"/screenshot checklist"}}var Lc="-".repeat(64);function ii(e){let t=am;try{let y=im(e);y?.captureDir&&(t=y.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=om(t)?rm(t,"CAPTURE-TESTID-REQUESTS.json"):sm(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!tm(n))return null;let o;try{let y=JSON.parse(nm(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,a=`${s} data-testid attribute${s===1?"":"s"}`,u=`${r} source file${r===1?"":"s"}`,g=`${t}/CAPTURE-TESTID-REQUESTS.md`,b=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${a} requested across ${u}.`,"\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.","",Lc,`Read ${g} and ${b}. They list ${a} 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.",Lc]}st();q();import{listOpenForDocs as lm,readProjectConfig as cm}from"document360-engine";function ai(e){try{return lm(e).length}catch{return 0}}function li(){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(`
347
+ `)}async function Oc(e,t){let n=t?.cwd??process.cwd();return cm(n)?ai(n)===0?(console.log(m("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:li(),display:"/inbox"}:(console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}q();import{listOpenHints as dm,listOpenForDocs as um,listOpenDirectives as pm,readProjectConfig as hm,computeSyncStatus as fm,planPull as mm,applyPull as gm,planImport as wm,applyImport as ym}from"document360-engine";function Mn(e){let t=0,n=0,o=0,r=0;try{t=dm(e).length}catch{}try{let s=um(e);n=s.filter(a=>a.kind==="request").length,o=s.filter(a=>a.kind==="answer").length}catch{}try{r=pm(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function Un(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 di(e){return{publish:e.includes("--publish")}}function ui({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(`
348
+ `)}var km={status:fm,plan:mm,apply:gm,planImport:wm,applyImport:ym};async function pi(e,t=km){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 ci=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Jo=e=>e===1?"":"s";function hi(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${Jo(e.pulled.length)} into local: ${ci(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Jo(e.imported.length)} into local drafts: ${ci(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Jo(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${ci(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${Jo(e.failed.length)} failed \u2014 left for /pull.`),t}async function Mc(e,t){let n=t?.cwd??process.cwd();if(!hm(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=_e(n,t?.profileName);if(!o.ok)return console.log(v(o.reason)),{kind:"continue"};let{publish:r}=di(e);console.log(m("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await pi({cwd:n,profileName:t?.profileName});for(let u of hi(s))console.log(u.startsWith("\u2713")?E(u):u.startsWith("\u2139")?m(u):M(u));let a=Un(Mn(n));return console.log(m(a?`Catching up on ${a}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:ui({publish:r}),display:`/catch-up${r?" --publish":""}`}}q();import{spawn as bm}from"node:child_process";var Tt="document360-writer",Zo=`npm i -g ${Tt}@latest`;async function er(){let e=process.platform==="win32";return new Promise(t=>{try{let n=bm(`npm i -g ${Tt}@latest`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});n.on("error",o=>t({ok:!1,output:String(o)})),n.on("close",o=>t({ok:o===0,output:""})),e||n.unref()}catch(n){t({ok:!1,output:String(n)})}})}async function Uc(){return console.log(m(`Updating ${Tt}\u2026`)),(await er()).ok?console.log(E("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(v(`Update failed \u2014 run manually: ${Zo}`)),{kind:"continue"}}q();st();import{existsSync as fi,rmSync as $m}from"node:fs";import{basename as Wc,resolve as mi}from"node:path";import{execFileSync as xm}from"node:child_process";import{input as vm}from"@inquirer/prompts";import{readProjectConfig as Cm,devHintsGuidePath as Rm}from"document360-engine";var Sm=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Pm=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),tr=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Fc=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function qc(e){let t=tr(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Fc(t)?!0:Pm.has(t)}function gi(e){let t=null;try{t=Cm(e)}catch{t=null}let n=new Set(Sm);for(let o of[tr(t?.docsDir),tr(t?.captureDir),tr(t?.outputDir)])o&&Fc(o)&&n.add(o);return[...n].filter(o=>qc(o)&&fi(mi(e,o)))}function wi(e,t){let n=[],o=[];for(let r of t){if(!qc(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{$m(mi(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Hc(e,t){try{return xm("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
349
+ `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Tm(e){return Hc(e,".d360-writer/hints")}function Dm(e){return Hc(e,".d360-writer/messages")}function yi(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Tm(e),o=Dm(e),r=fi(mi(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: ${Wc(e)}`]}async function Bc(e,t){let n=gi(t.cwd);for(let g of yi(t.cwd,n))console.log(n.length===0?m(g):g);if(n.length===0)return{kind:"continue"};let o=Wc(t.cwd);if((await t.withPausedInput(()=>vm({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(M("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=fi(Rm(t.cwd)),{removed:a,failed:u}=wi(t.cwd,n);console.log(E(`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`));for(let g of u)console.log(v(` \u2717 ${g.path}: ${g.error}`));if(s){for(let g of Eo())console.log(g);console.log(m("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(m("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}q();import{lintDocs as Am}from"document360-engine";function nr(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 ki(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(`
349
350
  `)).join(`
350
351
  `)].join(`
351
- `)}async function Bc(e,t){let n=e.includes("--fix"),o=e.find(a=>!a.startsWith("--")),r=o?` ${o}`:"",s=Dm({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(m(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:wi(s),display:`/check${r} --fix`});console.log(m("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let a of tr(s))console.log(s.length===0?E(a):M(a));return s.length>0&&console.log(m("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}H();import{lintDocs as _m,loadStyleGuide as Lm,buildReviewPrompt as Om,readProjectConfig as Mm,DEFAULT_DOCS_DIR as Um}from"document360-engine";H();import{readProjectConfig as Am,loadProfileMap as jm,resolveActiveProfile as Em,desiredCategoryOrder as Nm,desiredArticleOrder as Im}from"document360-engine";function Vc(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Gc=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Wn(e,t){try{if(!Am(e))return[];let n=Em(e,t),o=jm(e,n.name);if(!o)return[];let r=new Map;for(let a of Im(o)){let u=r.get(a.categoryPath);u?u.push(a):r.set(a.categoryPath,[a])}let s=[];for(let a of Nm(o)){s.push(Vc(Gc(a.path)));for(let u of(r.get(a.path)??[]).sort((g,b)=>g.order-b.order))s.push(` ${Vc(Gc(u.path))}`)}return s}catch{return[]}}async function Yc(e,t){let n=Wn(t.cwd,t.profileName);if(n.length===0)return console.log(m("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 yi(e,t){let n=Mm(e);if(!n)return null;let o=(n.docsDir??Um).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(y=>!y.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=_m({cwd:e}),u=s?a.filter(y=>y.path===`${o}/${s}`||y.path.startsWith(`${o}/${s}/`)):a,g=s?"":Wn(e).join(`
352
- `);return{prompt:Om({docsRoot:o,scope:s,styleGuide:Lm(e),deterministicFindings:u,fix:r,structure:g||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function zc(e,t){if(lt("review",e)){let o=rn(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(m(r));return{kind:"continue"}}}let n=yi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}H();import{readProjectConfig as Wm}from"document360-engine";function ki(e,t){if(!Wm(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(`
353
- `),display:`/reorder${n?` ${n}`:""}`}}async function Kc(e,t){if(lt("reorder",e)){let o=rn(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(m(r));return{kind:"continue"}}}let n=ki(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}H();import{readProjectConfig as Fm,writeProjectConfig as Xc,isAppType as Hm,playbookSkillName as qm,detectAppType as Qc}from"document360-engine";var Jc=["web","cli","service","library"],Bm=new Set(["web","cli"]);function bi(e){return Bm.has(e)?`${qm(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function nr(e,t){let n=t.cwd,o=Fm(n);if(!o)return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??Qc(n);if(s){let a=o.appType?"set in config":"auto-detected";console.log(`${L("Genre:")} ${s} (${a}) \u2014 ${bi(s)}`)}else console.log(M("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(m(`Set it: /genre <${Jc.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(m("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...a}=o;Xc(a,n);let u=Qc(n);return console.log(E(`\u2713 Genre reset to auto-detect \u2014 now: ${u?`${u} (${bi(u)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return Hm(r)?(Xc({...o,appType:r},n),console.log(E(`\u2713 Genre set to ${r} \u2014 ${bi(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(v(`Unknown genre "${r}". Choose one of: ${Jc.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}H();import{listRoadmap as or,roadmapProgress as Zc,stampRoadmapDone as Vm}from"document360-engine";function $i(e){let t=or(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=Zc(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 rr(e,t){let n=or(e).filter(b=>b.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=b=>b.trim().toLowerCase(),s=n.find(b=>r(b.title)===r(o)),a=o?s?[s]:n.filter(b=>r(b.title).includes(r(o))):[n[0]];if(a.length>1)return{ok:!1,line:`"${o}" matches ${a.length} open steps \u2014 add a distinguishing word:
352
+ `)}async function Vc(e,t){let n=e.includes("--fix"),o=e.find(a=>!a.startsWith("--")),r=o?` ${o}`:"",s=Am({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(m(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:ki(s),display:`/check${r} --fix`});console.log(m("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let a of nr(s))console.log(s.length===0?E(a):M(a));return s.length>0&&console.log(m("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}q();import{lintDocs as Lm,loadStyleGuide as Om,buildReviewPrompt as Mm,readProjectConfig as Um,DEFAULT_DOCS_DIR as Wm}from"document360-engine";q();import{readProjectConfig as jm,loadProfileMap as Em,resolveActiveProfile as Nm,desiredCategoryOrder as Im,desiredArticleOrder as _m}from"document360-engine";function Gc(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Yc=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Wn(e,t){try{if(!jm(e))return[];let n=Nm(e,t),o=Em(e,n.name);if(!o)return[];let r=new Map;for(let a of _m(o)){let u=r.get(a.categoryPath);u?u.push(a):r.set(a.categoryPath,[a])}let s=[];for(let a of Im(o)){s.push(Gc(Yc(a.path)));for(let u of(r.get(a.path)??[]).sort((g,b)=>g.order-b.order))s.push(` ${Gc(Yc(u.path))}`)}return s}catch{return[]}}async function zc(e,t){let n=Wn(t.cwd,t.profileName);if(n.length===0)return console.log(m("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 bi(e,t){let n=Um(e);if(!n)return null;let o=(n.docsDir??Wm).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(y=>!y.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=Lm({cwd:e}),u=s?a.filter(y=>y.path===`${o}/${s}`||y.path.startsWith(`${o}/${s}/`)):a,g=s?"":Wn(e).join(`
353
+ `);return{prompt:Mm({docsRoot:o,scope:s,styleGuide:Om(e),deterministicFindings:u,fix:r,structure:g||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function Kc(e,t){if(lt("review",e)){let o=rn(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(m(r));return{kind:"continue"}}}let n=bi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}q();import{readProjectConfig as Fm}from"document360-engine";function $i(e,t){if(!Fm(e))return null;let n=t.find(r=>!r.startsWith("--"));return{prompt:[`Reorder the articles within ${n?`the "${n}" category`:"each category"} to the best reading order.`,"Follow the manage-structure skill: decide the ideal order with senior-editor judgment per the doc-genre","playbook (overview / mental-model first; reference and troubleshooting/FAQ last), then APPLY it with the","d360_reorder_articles tool \u2014 one category at a time, all paths in the same category folder.",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(`
354
+ `),display:`/reorder${n?` ${n}`:""}`}}async function Xc(e,t){if(lt("reorder",e)){let o=rn(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(m(r));return{kind:"continue"}}}let n=$i(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}q();import{readProjectConfig as qm,writeProjectConfig as Qc,isAppType as Hm,playbookSkillName as Bm,detectAppType as Jc}from"document360-engine";var Zc=["web","cli","service","library"],Vm=new Set(["web","cli"]);function xi(e){return Vm.has(e)?`${Bm(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function or(e,t){let n=t.cwd,o=qm(n);if(!o)return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??Jc(n);if(s){let a=o.appType?"set in config":"auto-detected";console.log(`${L("Genre:")} ${s} (${a}) \u2014 ${xi(s)}`)}else console.log(M("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(m(`Set it: /genre <${Zc.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(m("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...a}=o;Qc(a,n);let u=Jc(n);return console.log(E(`\u2713 Genre reset to auto-detect \u2014 now: ${u?`${u} (${xi(u)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return Hm(r)?(Qc({...o,appType:r},n),console.log(E(`\u2713 Genre set to ${r} \u2014 ${xi(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(v(`Unknown genre "${r}". Choose one of: ${Zc.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}q();import{listRoadmap as rr,roadmapProgress as ed,stampRoadmapDone as Gm}from"document360-engine";function vi(e){let t=rr(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=ed(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 sr(e,t){let n=rr(e).filter(b=>b.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=b=>b.trim().toLowerCase(),s=n.find(b=>r(b.title)===r(o)),a=o?s?[s]:n.filter(b=>r(b.title).includes(r(o))):[n[0]];if(a.length>1)return{ok:!1,line:`"${o}" matches ${a.length} open steps \u2014 add a distinguishing word:
354
355
  ${a.map(b=>` \u25CB ${b.title}`).join(`
355
356
  `)}`};if(a.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
356
357
  ${n.map(b=>` \u25CB ${b.title}`).join(`
357
- `)}`};let u=a[0].title;Vm(e,u,{doneAt:new Date().toISOString()});let g=Zc(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${u}${g?` \u2014 next up: ${g.title}${g.run?` (${g.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function ed(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?or(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function td(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=or(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
+ `)}`};let u=a[0].title;Gm(e,u,{doneAt:new Date().toISOString()});let g=ed(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${u}${g?` \u2014 next up: ${g.title}${g.run?` (${g.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function td(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?rr(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function nd(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=rr(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
359
  ${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(`
359
- `):null}async function nd(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=rr(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("(")?m(r):r);return{kind:"continue"}}var od={help:Kr,"?":Kr,clear:Ma,exit:Xr,quit:Xr,init:ts,mcp:Io,publish:Pl,audit:Nn,discover:Tl,scope:Al,pull:Fl,resolve:Ml,convert:Hl,write:zl,draft:Zl,document:ec,resume:oc,rename:rc,profile:ic,model:cc,doctor:Ln,workspace:mc,project:gc,"allow-prod":wc,login:yc,logout:kc,screenshot:async(e,t)=>{let n=On(e);return n.mode==="capture"?oi(n.rest,t):n.mode==="setup"?sn():Ko(e,t)},capture:oi,"capture-setup":sn,devhints:Ka,inbox:Lc,"catch-up":Oc,update:Mc,reset:qc,check:Bc,review:zc,reorder:Kc,structure:Yc,genre:nr,roadmap:nd};function rd(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}st();var Gm="Or just tell me what to write or update.",Ym='\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 ue(e){return e===1?"":"s"}function sr(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Fn(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var zm={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 Km(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:zm,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${ue(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${ue(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
360
- \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${ue(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${ue(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ue(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${ue(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${ue(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${ue(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${ue(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${ue(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${ue(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${ue(n)}.`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${ue(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 sd(e){return e.find(t=>t.lead||t.picker)??null}function xi(e,t){let n=t.filter(a=>a.bullet).map(a=>` \u2022 ${a.bullet}`),o=sd(t),r=[];o?.lead?r.push(Fn(o.lead)):o?.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let a of t.filter(u=>u!==o).slice(0,2))a.follow&&r.push(a.follow);let s=[[e,...n].join(`
361
- `)];return r.length&&s.push(r.join(" ")),s.push(Gm),s.join(`
362
-
363
- `)}function Hn(e){if(!e.ready)return{kind:"idle"};let t=Km(e);if(!e.hasDocs){let s=sd(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:xi("\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:Ym,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${ue(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${ue(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${ue(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:xi("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:xi("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as vi,readdirSync as Ri}from"node:fs";import{spawnSync as Xm}from"node:child_process";import{join as ir}from"node:path";import{readProjectConfig as ad,resolveActiveProfile as ld,loadTokens as Qm,isExpired as Jm,loadProfileMap as cd,localAheadPaths as Zm,loadKnownConflicts as eg,readDocsPlan as tg,devHintsGuidePath as ng,DEFAULT_DOCS_DIR as Ci,roadmapProgress as og,listRoadmap as rg,readProductBriefState as sg,reconcileCommitRequest as ig}from"document360-engine";st();function id(e){try{return Ri(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Si(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>id(ir(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&id(ir(e,o)))}function Pi(e,t){try{let n=ad(e);if(!n)return!1;let o=ld(e,t),r=cd(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=ir(e,(n.docsDir??Ci).replace(/\/+$/,""));return!!(vi(s)&&Ri(s).length>0||vi(ng(e)))}catch{return!1}}function qn(e,t,n){try{let o=ad(e);if(!o)return null;let r=ld(e,t),s=Qm(r.name),a=!!s&&(!Jm(s)||!!s.refreshToken),u=Pi(e,t)||!Si(e,o.authoritativeSourceFiles),g=cd(e,r.name),b=g?Object.keys(g.articles).length:0,y=ir(e,(o.docsDir??Ci).replace(/\/+$/,"")),P=!1;try{P=vi(y)&&Ri(y).length>0}catch{}let x=0;if(g?.lastAnalyzedCommit)try{let ve=Xm("git",["rev-list","--count",`${g.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});ve.status===0&&(x=parseInt((ve.stdout||"").trim(),10)||0)}catch{}let _=0;try{let ve=tg(e);if(ve.length>0){let ut=(o.docsDir??Ci).replace(/\/+$/,"");_=Ns(e,ut,ve.map(qe=>qe.path)).length}}catch{}let C=Mn(e),N=Un({...C,directives:0}),D=Zm(e,t),W=new Set(eg(e,r.name)),z=D.filter(ve=>W.has(ve)).length,K=D.length-z,X=Ie(e),he=og(e),Qe=ig(e,new Date().toISOString()),me=sg(e),jt=me?{status:me.status,openQuestions:me.openQuestions}:null;return!jt&&P&&rg(e).some(ut=>ut.status==="open"&&(ut.run??"").trim()==="/discover")&&(jt={status:"pending",openQuestions:0}),{ready:a&&u&&!n.claudeMissing,hasDocs:P,tracked:b,pendingText:N,directives:C.directives,behind:x,pendingWrites:_,localAhead:K,conflicts:z,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:X.status,devhintsCompletedVersion:X.completedVersion,devhintsToVersion:le,builderStarted:Ke(e),genreUnknown:n.genreUnknown,roadmap:he,discovery:jt,uncommittedDocs:Qe.dirty.length}}catch{return null}}function dd(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 ar(e){if(e.length===0)return[];let t=(s,a)=>`${s}${"\u2500".repeat(78)}${a}`,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,a)=>{a>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let u of dd(`${a+1}. ${s.feature}`,76))o.push(n(u));o.push(n());for(let u of dd(s.why,73))o.push(n(` ${u}`));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 ag={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"},pd=160,Di=200,hd=40;function Te(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function ud(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),hd)}`);return t.length>4&&n.push("\u2026"),Te(n.join(", "),pd)}var ct=e=>typeof e=="string"&&e?e:null,Ti=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function lg(e){let t=ct(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 cg(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=ct(t.title);if(!o)return null;let r=lg(t.local_path);return n("Create article",`"${Te(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=ct(t.title),r=Ti(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)",Ti(t.article_id)?`id ${Ti(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",ct(t.name)?`"${Te(ct(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=ct(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 lr(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),a=s.join("__");if(r==="document360"){let b=cg(a,t);if(b)return b}let u=a.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${u}`,sep:" ",arg:ud(t)}}let n=ag[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:Te(o,pd)}:{title:e,sep:"",arg:ud(t)}}function dg(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 ug(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(dg).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Te(r,Di))]}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),hd)}`);return n.length>0?[Te(n.join(" \xB7 "),Di)]:null}return null}function pg(e){let t=ct(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function hg(e,t,n){switch(e){case"d360_create_article":{let o=pg(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=ct(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 cr(e,t=4,n,o){let r=e.replace(/\r\n/g,`
364
- `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let a=hg(n.slice(18),o,r);if(a)return{lines:a,hidden:0}}let s=ug(r)??r.split(`
365
- `);return{lines:s.slice(0,t).map(a=>Te(a,Di)),hidden:Math.max(0,s.length-t)}}function dr(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function ur(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 fd(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 pr(e){return fd(e,"url")}function hr(e){return fd(e,"preview_url")}var Ng=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Ig(e,t,n,o){if(Ng.test(e))try{let r=wd(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,a=ur(t,n),u=pr(n);e.endsWith("publish_article")&&u&&console.log(L(` \u2B95 Live: ${u}`));let g=hr(n);g?console.log(L(` \u2B95 Preview: ${g}`)):a&&s&&console.log(L(` \u2B95 Preview: ${dr(r.connection.portalUrl,s,a,r.project.languageCode??"en")}`))}catch{}}async function yd(e=process.cwd(),t="auto",n,o){let r=mg(t);r.kind==="none"&&(console.error(""),console.error(v("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)),_g(e,n),r.kind==="subscription"&&(r.stored?console.log(m(" Using your Claude subscription (no API key set).")):console.log(m(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,a=Ai({cwd:e,profileName:n,allowProdWrites:s}),u={uuid:null,firstPrompt:null,titleFired:!1},g=fg({input:process.stdin,output:process.stdout}),b=[],y=null,P=!1;g.on("line",C=>{if(y){let N=y;y=null,N(C)}else b.push(C)}),g.on("close",()=>{if(P=!0,y){let C=y;y=null,C(null)}});function x(){return b.length>0?Promise.resolve(b.shift()):P?Promise.resolve(null):(process.stdout.write(L("> ")),new Promise(C=>{y=C}))}let _={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{a.close(),a=Ai({cwd:e,profileName:n,allowProdWrites:s}),u={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>u.uuid,setPendingName:C=>{u.pendingName=C},setModel:async C=>a.setModel(C),withPausedInput:async C=>{g.pause();try{return await C()}finally{g.resume()}}};try{for(;;){let C=await x();if(C===null)break;let N=C.trim();if(N){if(N.startsWith("/")){let D=rd(N);if(!D)continue;let W=od[D.name];if(!W){console.log(v(`Unknown command: /${D.name}`)),console.log(m("Type /help for the list."));continue}let z=await W(D.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"){a.close(),a=Ai({cwd:e,resume:z.uuid,profileName:n,allowProdWrites:s});let K=gg(z.uuid);u={uuid:z.uuid,firstPrompt:K?.firstPrompt??null,titleFired:!0},gd(z.uuid),console.log(E(`\u2713 Resumed "${z.name}"`)),console.log("");continue}if(z.kind==="forward-to-agent"){u.firstPrompt||(u.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(me=>!me.startsWith("--")),Qe=X?jg(e,he):[];if(await ji(a,z.prompt,r,u,e),X)try{Ag(e,Qe,{reviewedCap:Eg})}catch{}}else Lg(e,n);continue}if(Sg(N)){let D=Pg(N);if(D){try{Tg(e,{title:D,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}u.firstPrompt||(u.firstPrompt=N),await ji(a,`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,u,e);continue}}u.firstPrompt||(u.firstPrompt=N),await ji(a,N,r,u,e)}}}finally{a.close(),g.close()}}function _g(e,t){console.log(""),console.log(Cn("document360-writer")),console.log(m(` cwd: ${e}`));let n=$g(e);if(console.log(m(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Og(e,t)),!xg(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(Do(e),!Ke(e))for(let r of Ao(e))console.log(M(` ${r}`))}catch{}try{let r=vg(e);r.persisted&&r.appType?console.log(m(` \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=Dg(e);for(let s of ar(r.applied))console.log(M(` ${s}`))}catch{}try{let r=qn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Hn(r):null;if(s?.kind==="recommend"&&s.rec.note){let a=s.rec.tone==="warn"?M:m;for(let u of cs(s.rec.note).split(`
366
- `))console.log(a(` ${u}`));s.rec.picker&&console.log(L(` Pick one: ${s.rec.picker.options.map(u=>u.cmd).join(" \xB7 ")}`))}}catch{}}console.log(m(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Lg(e,t){try{let n=qn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Hn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(m(` Next: ${Fn(o.rec.lead)}`))}catch{}}function Og(e,t){try{let n=wd(e,t),o=n.production?M(" \u26A0 PRODUCTION"):"",r=Rg(n.name);if(!r)return m(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...md(r.idToken)??{},...md(r.accessToken)??{}},a=s.email??s.preferred_username??"signed in";return Cg(r)&&!r.refreshToken?M(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):m(` Document360: ${a} \xB7 profile "${n.name}"${o}`)}catch(n){return m(` Document360: ${n.message.split(".")[0]}`)}}function Mg(){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 Ug(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;kg({uuid:t,name:r??yg(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Wg(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||bg(o,t).then(r=>{r&&wg(n,r)}).catch(()=>{})}async function ji(e,t,n,o,r){let s=new Map;for await(let a of e.send(t))Fg(a,o,r,n,s)}function Fg(e,t,n,o,r){switch(e.type){case"session":t.uuid||Ug(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=lr(e.name,e.input);s&&(process.stdout.write(`
367
-
368
- `),console.log(`${E("\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=Xe(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let a=u=>u===1?"":"s";console.log(ae(` \u23BF Added ${s.added} line${a(s.added)}, removed ${s.removed} line${a(s.removed)}`));for(let u of s.lines)console.log(u);s.hidden>0&&console.log(m(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let a=cr(e.output,4,e.isError?void 0:s.name,s.input),u=e.isError?v:ae;a.lines.forEach((g,b)=>console.log(u((b===0?" \u23BF ":" ")+g))),a.hidden>0&&console.log(m(` \u2026 +${a.hidden} lines`)),e.isError||Ig(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
369
- `);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(m(` (${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&&(gd(t.uuid),t.titleFired||Wg(t,n));break}case"error":console.error(""),console.error(v(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Mg();break}}import{render as ny}from"ink";import{resolveAuth as oy}from"document360-engine";import{useCallback as G,useEffect as Ae,useMemo as Oi,useRef as ee,useState as q}from"react";import{Box as se,Text as A,useApp as nw,useInput as ow,useStdout as rw}from"ink";import{existsSync as ln,readFileSync as $r,readdirSync as sw}from"node:fs";import{basename as Vn,isAbsolute as iw,join as Mi}from"node:path";import{createSession as qd,classifyClaudeAuth as Bi,CLAUDE_CODE_SETUP_HINT as aw,loginPkce as lw,toStoredTokens as cw,saveTokens as dw,getAccessToken as uw,resolveActiveProfile as De,resolveProjectId as pw,getArticle as hw,decodeJwtClaims as dn,isExpired as dt,loadTokens as At,clearTokens as fw,clearProfileProject as mw,setTitle as gw,slugify as ww,touchSession as Ui,upsertSession as yw,generateTitle as Bd,findByName as kw,listSessions as bw,renameSession as $w,suggestNextAction as xw,readProjectConfig as re,writeProjectConfig as Vd,resolveAndPersistAppType as vw,detectAppType as Cw,resolveModelSetting as Vi,loadProfileMap as Gd,applyPull as Yd,computeSyncStatus as Wi,lintDocs as zd,compareRemoteSources as Rw,planPull as Kd,establishBaselines as Sw,rebaselineServerMeta as Pw,inventoryRepo as Tw,knownEnvironments as Dw,resolveEnvironment as Aw,planPartitions as Fi,partitionEvenly as jw,screenshotPlaceholderIds as Ew,trackedArticlePaths as Nw,runPartitioned as xr,estimateBulkCost as Xd,resolveModelForOperation as vr,readDocsPlan as Iw,checkForUpdate as _w,detectInstallKind as Lw,isSelfUpdatable as Ow,devHintsGuidePath as Qd,toolFeedbackPath as Jd,reconcileToolFeedback as Mw,reconcileUpgradeActions as Uw,stampArticles as Hi,listArticleFiles as Zd,CONTENT_CAP_VERSION as qi,ENGINE_VERSION as au,DEFAULT_DOCS_DIR as lu,setProfileProject as Ww,writeCrashLog as Fw,applyStructureOrder as eu,orderSyncLine as tu,applyRelatedArticles as nu,relatedSyncLine as ou}from"document360-engine";st();import{spawn as kd}from"node:child_process";function Hg(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function qg(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?kd([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):kd(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",a=>o(a===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 Ei(e){for(let[t,n]of Hg())if(await qg(t,n,e))return!0;return!1}var Bg=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Ni(e,t){if(t.closed)return e;let n=e.split(`
370
- `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){Bg.test(s)&&(t.cueSeen=!0);continue}let a=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);a?(n[r]=`${a[1]}${++t.num}. ${a[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
371
- `)}import{existsSync as Vg,mkdirSync as Gg,readFileSync as Yg,writeFileSync as zg}from"node:fs";import{join as bd}from"node:path";import{writerDir as Kg}from"document360-engine";function $d(e){return bd(Kg(e),".sessions")}function xd(e,t){return bd($d(e),`${t}.json`)}function vd(e,t,n){try{Gg($d(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");zg(xd(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Ii(e,t){try{let n=xd(e,t);if(!Vg(n))return[];let o=JSON.parse(Yg(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Xg=e=>`\x1B]0;${e}\x07`,Qg=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Cd(e){process.stdout.isTTY&&process.stdout.write(e)}function an(e){Cd(Xg(e))}function fr(e){Cd(Qg(e))}var mr=["\xB7 "," \xB7"],gr="\u{1F7E3}";Yo();No();H();import{Box as Rd,Text as de}from"ink";import{jsx as pe,jsxs as wr}from"react/jsx-runtime";function Jg({row:e}){switch(e.t){case"head":return pe(de,{color:V,bold:!0,children:e.s});case"text":return pe(de,{children:e.s});case"dim":return pe(de,{dimColor:!0,children:e.s});case"sub":return pe(de,{bold:!0,dimColor:!0,children:e.s});case"good":return pe(de,{color:"green",children:e.s});case"step":return wr(de,{children:[pe(de,{color:V,children:`${e.n}. `}),e.s]});case"cmd":return wr(de,{children:[" ",pe(de,{color:V,children:e.name.padEnd(20)}),pe(de,{dimColor:!0,children:e.s})]});case"gap":return pe(de,{children:" "})}}function Sd({tab:e,width:t,version:n,engineVersion:o}){let r=Ne[e]??Ne[0],s=6+Ne.reduce((u,g)=>u+g.label.length+4,0),a="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return wr(Rd,{flexDirection:"column",paddingX:1,children:[wr(de,{children:[pe(de,{color:V,bold:!0,children:"Help "}),Ne.map((u,g)=>g===e?pe(de,{color:"white",backgroundColor:V,bold:!0,children:` ${u.label} `},u.key):pe(de,{dimColor:!0,children:` ${u.label} `},u.key))]}),pe(de,{color:V,children:a}),pe(Rd,{flexDirection:"column",marginTop:1,children:r.rows.map((u,g)=>pe(Jg,{row:u},g))}),pe(de,{dimColor:!0,children:`
372
- \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var Zg=/^(?:\d+[.)]|[-*•])\s+/;function Pd(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
373
- `)){let a=s.trim().replace(Zg,""),u=a.match(/^`([^`]+)`$/);u&&(a=u[1].trim());let g=a.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!g||!o.has(g[1].toLowerCase()))continue;let b=`/${g[1].toLowerCase()}${g[2]?` ${g[2]}`:""}`;if(r.includes(b)||r.push(b),r.length>=n)break}return r}H();function Bn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Le(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Td(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var ew=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Dd(e,t,n){if(!ew.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 a=s.replace(/\\/g,"/");return r===a||r.endsWith(`/${a}`)})??null}function _i(e){return e.replace(/^[\w.-]+\//,"")}var yr=16,Ad={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Dt(e){return typeof e=="string"?e:e.cmd}function jd(e){return typeof e=="string"?void 0:e.desc}function Li(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Ed(e,t){let n=Li(t);return e.some(r=>Dt(r).trim()===t.trim()||!!n&&Li(Dt(r))===n)?e.filter(r=>Dt(r).trim()!==t.trim()&&!(n&&Li(Dt(r))===n)):[]}import{isDirectiveMention as Hw,stripDirectiveMention as qw,appendDirective as Bw}from"document360-engine";var tw=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Nd(e){return e.replace(/\r\n?/g,`
374
- `)}function Id(e){return e.includes(`
375
- `)||e.length>200}function _d(e,t){let n=t.split(`
376
- `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Ld(e,t){return e.replace(tw,n=>t.get(n)??n)}function Od(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function kr(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
377
- `)){if(s.length===0)o.push({start:r,end:r});else for(let a=0;a<s.length;a+=n)o.push({start:r+a,end:r+Math.min(a+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function br(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Md(e,t,n){let o=br(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 Ud(e,t,n){let o=e[br(e,t)];return n==="start"?o.start:o.end}function Wd(e,t,n){let o=Math.max(1,n),r=e.split(`
360
+ `):null}async function od(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=sr(n,e.slice(1).join(" ").trim());return console.log(r.ok?E(r.line):M(r.line)),{kind:"continue"}}let o=vi(n);console.log(L(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?m(r):r);return{kind:"continue"}}var rd={help:Xr,"?":Xr,clear:Ua,exit:Qr,quit:Qr,init:ns,mcp:_o,publish:Tl,audit:Nn,discover:Dl,scope:jl,pull:ql,resolve:Ul,convert:Hl,write:Kl,draft:ec,document:tc,resume:rc,rename:sc,profile:ac,model:dc,doctor:Ln,workspace:gc,project:wc,"allow-prod":yc,login:kc,logout:bc,screenshot:async(e,t)=>{let n=On(e);return n.mode==="capture"?si(n.rest,t):n.mode==="checklist"?sn():Xo(e,t)},capture:si,"capture-setup":sn,devhints:Xa,inbox:Oc,"catch-up":Mc,update:Uc,reset:Bc,check:Vc,review:Kc,reorder:Xc,structure:zc,genre:or,roadmap:od};function sd(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}st();var Ym="Or just tell me what to write or update.",zm='\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 ue(e){return e===1?"":"s"}function ir(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Fn(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var Km={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 Xm(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:Km,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${ue(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${ue(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
361
+ \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${ue(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${ue(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ue(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${ue(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${ue(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${ue(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${ue(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${ue(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${ue(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${ue(n)}.`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${ue(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 id(e){return e.find(t=>t.lead||t.picker)??null}function Ci(e,t){let n=t.filter(a=>a.bullet).map(a=>` \u2022 ${a.bullet}`),o=id(t),r=[];o?.lead?r.push(Fn(o.lead)):o?.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let a of t.filter(u=>u!==o).slice(0,2))a.follow&&r.push(a.follow);let s=[[e,...n].join(`
362
+ `)];return r.length&&s.push(r.join(" ")),s.push(Ym),s.join(`
363
+
364
+ `)}function qn(e){if(!e.ready)return{kind:"idle"};let t=Xm(e);if(!e.hasDocs){let s=id(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:Ci("\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:zm,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${ue(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${ue(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${ue(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:Ci("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:Ci("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as Ri,readdirSync as Pi}from"node:fs";import{spawnSync as Qm}from"node:child_process";import{join as ar}from"node:path";import{readProjectConfig as ld,resolveActiveProfile as cd,loadTokens as Jm,isExpired as Zm,loadProfileMap as dd,localAheadPaths as eg,loadKnownConflicts as tg,readDocsPlan as ng,devHintsGuidePath as og,DEFAULT_DOCS_DIR as Si,roadmapProgress as rg,listRoadmap as sg,readProductBriefState as ig,reconcileCommitRequest as ag}from"document360-engine";st();function ad(e){try{return Pi(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Ti(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>ad(ar(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&ad(ar(e,o)))}function Di(e,t){try{let n=ld(e);if(!n)return!1;let o=cd(e,t),r=dd(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=ar(e,(n.docsDir??Si).replace(/\/+$/,""));return!!(Ri(s)&&Pi(s).length>0||Ri(og(e)))}catch{return!1}}function Hn(e,t,n){try{let o=ld(e);if(!o)return null;let r=cd(e,t),s=Jm(r.name),a=!!s&&(!Zm(s)||!!s.refreshToken),u=Di(e,t)||!Ti(e,o.authoritativeSourceFiles),g=dd(e,r.name),b=g?Object.keys(g.articles).length:0,y=ar(e,(o.docsDir??Si).replace(/\/+$/,"")),P=!1;try{P=Ri(y)&&Pi(y).length>0}catch{}let x=0;if(g?.lastAnalyzedCommit)try{let ve=Qm("git",["rev-list","--count",`${g.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});ve.status===0&&(x=parseInt((ve.stdout||"").trim(),10)||0)}catch{}let _=0;try{let ve=ng(e);if(ve.length>0){let ut=(o.docsDir??Si).replace(/\/+$/,"");_=Is(e,ut,ve.map(He=>He.path)).length}}catch{}let C=Mn(e),N=Un({...C,directives:0}),D=eg(e,t),W=new Set(tg(e,r.name)),z=D.filter(ve=>W.has(ve)).length,K=D.length-z,X=Ie(e),he=rg(e),Qe=ag(e,new Date().toISOString()),me=ig(e),jt=me?{status:me.status,openQuestions:me.openQuestions}:null;return!jt&&P&&sg(e).some(ut=>ut.status==="open"&&(ut.run??"").trim()==="/discover")&&(jt={status:"pending",openQuestions:0}),{ready:a&&u&&!n.claudeMissing,hasDocs:P,tracked:b,pendingText:N,directives:C.directives,behind:x,pendingWrites:_,localAhead:K,conflicts:z,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:X.status,devhintsCompletedVersion:X.completedVersion,devhintsToVersion:le,builderStarted:Ke(e),genreUnknown:n.genreUnknown,roadmap:he,discovery:jt,uncommittedDocs:Qe.dirty.length}}catch{return null}}function ud(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 lr(e){if(e.length===0)return[];let t=(s,a)=>`${s}${"\u2500".repeat(78)}${a}`,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,a)=>{a>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let u of ud(`${a+1}. ${s.feature}`,76))o.push(n(u));o.push(n());for(let u of ud(s.why,73))o.push(n(` ${u}`));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}q();var lg={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"},hd=160,ji=200,fd=40;function Te(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function pd(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),fd)}`);return t.length>4&&n.push("\u2026"),Te(n.join(", "),hd)}var ct=e=>typeof e=="string"&&e?e:null,Ai=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function cg(e){let t=ct(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 dg(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=ct(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=ct(t.title),r=Ai(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)",Ai(t.article_id)?`id ${Ai(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",ct(t.name)?`"${Te(ct(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=ct(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 cr(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),a=s.join("__");if(r==="document360"){let b=dg(a,t);if(b)return b}let u=a.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${u}`,sep:" ",arg:pd(t)}}let n=lg[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:Te(o,hd)}:{title:e,sep:"",arg:pd(t)}}function ug(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(ug).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Te(r,ji))]}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),fd)}`);return n.length>0?[Te(n.join(" \xB7 "),ji)]:null}return null}function hg(e){let t=ct(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function fg(e,t,n){switch(e){case"d360_create_article":{let o=hg(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=ct(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 dr(e,t=4,n,o){let r=e.replace(/\r\n/g,`
365
+ `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let a=fg(n.slice(18),o,r);if(a)return{lines:a,hidden:0}}let s=pg(r)??r.split(`
366
+ `);return{lines:s.slice(0,t).map(a=>Te(a,ji)),hidden:Math.max(0,s.length-t)}}function ur(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function pr(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 md(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 hr(e){return md(e,"url")}function fr(e){return md(e,"preview_url")}var Ig=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function _g(e,t,n,o){if(Ig.test(e))try{let r=yd(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,a=pr(t,n),u=hr(n);e.endsWith("publish_article")&&u&&console.log(L(` \u2B95 Live: ${u}`));let g=fr(n);g?console.log(L(` \u2B95 Preview: ${g}`)):a&&s&&console.log(L(` \u2B95 Preview: ${ur(r.connection.portalUrl,s,a,r.project.languageCode??"en")}`))}catch{}}async function kd(e=process.cwd(),t="auto",n,o){let r=gg(t);r.kind==="none"&&(console.error(""),console.error(v("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)),Lg(e,n),r.kind==="subscription"&&(r.stored?console.log(m(" Using your Claude subscription (no API key set).")):console.log(m(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,a=Ei({cwd:e,profileName:n,allowProdWrites:s}),u={uuid:null,firstPrompt:null,titleFired:!1},g=mg({input:process.stdin,output:process.stdout}),b=[],y=null,P=!1;g.on("line",C=>{if(y){let N=y;y=null,N(C)}else b.push(C)}),g.on("close",()=>{if(P=!0,y){let C=y;y=null,C(null)}});function x(){return b.length>0?Promise.resolve(b.shift()):P?Promise.resolve(null):(process.stdout.write(L("> ")),new Promise(C=>{y=C}))}let _={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{a.close(),a=Ei({cwd:e,profileName:n,allowProdWrites:s}),u={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>u.uuid,setPendingName:C=>{u.pendingName=C},setModel:async C=>a.setModel(C),withPausedInput:async C=>{g.pause();try{return await C()}finally{g.resume()}}};try{for(;;){let C=await x();if(C===null)break;let N=C.trim();if(N){if(N.startsWith("/")){let D=sd(N);if(!D)continue;let W=rd[D.name];if(!W){console.log(v(`Unknown command: /${D.name}`)),console.log(m("Type /help for the list."));continue}let z=await W(D.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"){a.close(),a=Ei({cwd:e,resume:z.uuid,profileName:n,allowProdWrites:s});let K=wg(z.uuid);u={uuid:z.uuid,firstPrompt:K?.firstPrompt??null,titleFired:!0},wd(z.uuid),console.log(E(`\u2713 Resumed "${z.name}"`)),console.log("");continue}if(z.kind==="forward-to-agent"){u.firstPrompt||(u.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(me=>!me.startsWith("--")),Qe=X?Eg(e,he):[];if(await Ni(a,z.prompt,r,u,e),X)try{jg(e,Qe,{reviewedCap:Ng})}catch{}}else Og(e,n);continue}if(Pg(N)){let D=Tg(N);if(D){try{Dg(e,{title:D,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}u.firstPrompt||(u.firstPrompt=N),await Ni(a,`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,u,e);continue}}u.firstPrompt||(u.firstPrompt=N),await Ni(a,N,r,u,e)}}}finally{a.close(),g.close()}}function Lg(e,t){console.log(""),console.log(Cn("document360-writer")),console.log(m(` cwd: ${e}`));let n=xg(e);if(console.log(m(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Mg(e,t)),!vg(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(Ao(e),!Ke(e))for(let r of jo(e))console.log(M(` ${r}`))}catch{}try{let r=Cg(e);r.persisted&&r.appType?console.log(m(` \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=Ag(e);for(let s of lr(r.applied))console.log(M(` ${s}`))}catch{}try{let r=Hn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?qn(r):null;if(s?.kind==="recommend"&&s.rec.note){let a=s.rec.tone==="warn"?M:m;for(let u of ds(s.rec.note).split(`
367
+ `))console.log(a(` ${u}`));s.rec.picker&&console.log(L(` Pick one: ${s.rec.picker.options.map(u=>u.cmd).join(" \xB7 ")}`))}}catch{}}console.log(m(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Og(e,t){try{let n=Hn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?qn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(m(` Next: ${Fn(o.rec.lead)}`))}catch{}}function Mg(e,t){try{let n=yd(e,t),o=n.production?M(" \u26A0 PRODUCTION"):"",r=Sg(n.name);if(!r)return m(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...gd(r.idToken)??{},...gd(r.accessToken)??{}},a=s.email??s.preferred_username??"signed in";return Rg(r)&&!r.refreshToken?M(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):m(` Document360: ${a} \xB7 profile "${n.name}"${o}`)}catch(n){return m(` Document360: ${n.message.split(".")[0]}`)}}function Ug(){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 Wg(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;bg({uuid:t,name:r??kg(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Fg(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||$g(o,t).then(r=>{r&&yg(n,r)}).catch(()=>{})}async function Ni(e,t,n,o,r){let s=new Map;for await(let a of e.send(t))qg(a,o,r,n,s)}function qg(e,t,n,o,r){switch(e.type){case"session":t.uuid||Wg(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=cr(e.name,e.input);s&&(process.stdout.write(`
368
+
369
+ `),console.log(`${E("\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=Xe(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let a=u=>u===1?"":"s";console.log(ae(` \u23BF Added ${s.added} line${a(s.added)}, removed ${s.removed} line${a(s.removed)}`));for(let u of s.lines)console.log(u);s.hidden>0&&console.log(m(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let a=dr(e.output,4,e.isError?void 0:s.name,s.input),u=e.isError?v:ae;a.lines.forEach((g,b)=>console.log(u((b===0?" \u23BF ":" ")+g))),a.hidden>0&&console.log(m(` \u2026 +${a.hidden} lines`)),e.isError||_g(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
370
+ `);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(m(` (${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&&(wd(t.uuid),t.titleFired||Fg(t,n));break}case"error":console.error(""),console.error(v(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Ug();break}}import{render as oy}from"ink";import{resolveAuth as ry}from"document360-engine";import{useCallback as G,useEffect as Ae,useMemo as Ui,useRef as ee,useState as H}from"react";import{Box as se,Text as A,useApp as ow,useInput as rw,useStdout as sw}from"ink";import{existsSync as ln,readFileSync as xr,readdirSync as iw}from"node:fs";import{basename as Vn,isAbsolute as aw,join as Wi}from"node:path";import{createSession as Bd,classifyClaudeAuth as Gi,CLAUDE_CODE_SETUP_HINT as lw,loginPkce as cw,toStoredTokens as dw,saveTokens as uw,getAccessToken as pw,resolveActiveProfile as De,resolveProjectId as hw,getArticle as fw,decodeJwtClaims as dn,isExpired as dt,loadTokens as At,clearTokens as mw,clearProfileProject as gw,setTitle as ww,slugify as yw,touchSession as Fi,upsertSession as kw,generateTitle as Vd,findByName as bw,listSessions as $w,renameSession as xw,suggestNextAction as vw,readProjectConfig as re,writeProjectConfig as Gd,resolveAndPersistAppType as Cw,detectAppType as Rw,resolveModelSetting as Yi,loadProfileMap as Yd,applyPull as zd,computeSyncStatus as qi,lintDocs as Kd,compareRemoteSources as Sw,planPull as Xd,establishBaselines as Pw,rebaselineServerMeta as Tw,inventoryRepo as Dw,knownEnvironments as Aw,resolveEnvironment as jw,planPartitions as Hi,partitionEvenly as Ew,screenshotPlaceholderIds as Nw,trackedArticlePaths as Iw,runPartitioned as vr,estimateBulkCost as Qd,resolveModelForOperation as Cr,readDocsPlan as _w,checkForUpdate as Lw,detectInstallKind as Ow,isSelfUpdatable as Mw,devHintsGuidePath as Jd,toolFeedbackPath as Zd,reconcileToolFeedback as Uw,reconcileUpgradeActions as Ww,stampArticles as Bi,listArticleFiles as eu,CONTENT_CAP_VERSION as Vi,ENGINE_VERSION as lu,DEFAULT_DOCS_DIR as cu,setProfileProject as Fw,writeCrashLog as qw,applyStructureOrder as tu,orderSyncLine as nu,applyRelatedArticles as ou,relatedSyncLine as ru}from"document360-engine";st();import{spawn as bd}from"node:child_process";function Hg(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Bg(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?bd([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):bd(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",a=>o(a===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 Ii(e){for(let[t,n]of Hg())if(await Bg(t,n,e))return!0;return!1}var Vg=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function _i(e,t){if(t.closed)return e;let n=e.split(`
371
+ `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){Vg.test(s)&&(t.cueSeen=!0);continue}let a=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);a?(n[r]=`${a[1]}${++t.num}. ${a[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
372
+ `)}import{existsSync as Gg,mkdirSync as Yg,readFileSync as zg,writeFileSync as Kg}from"node:fs";import{join as $d}from"node:path";import{writerDir as Xg}from"document360-engine";function xd(e){return $d(Xg(e),".sessions")}function vd(e,t){return $d(xd(e),`${t}.json`)}function Cd(e,t,n){try{Yg(xd(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Kg(vd(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Li(e,t){try{let n=vd(e,t);if(!Gg(n))return[];let o=JSON.parse(zg(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Qg=e=>`\x1B]0;${e}\x07`,Jg=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Rd(e){process.stdout.isTTY&&process.stdout.write(e)}function an(e){Rd(Qg(e))}function mr(e){Rd(Jg(e))}var gr=["\xB7 "," \xB7"],wr="\u{1F7E3}";zo();Io();q();import{Box as Sd,Text as de}from"ink";import{jsx as pe,jsxs as yr}from"react/jsx-runtime";function Zg({row:e}){switch(e.t){case"head":return pe(de,{color:V,bold:!0,children:e.s});case"text":return pe(de,{children:e.s});case"dim":return pe(de,{dimColor:!0,children:e.s});case"sub":return pe(de,{bold:!0,dimColor:!0,children:e.s});case"good":return pe(de,{color:"green",children:e.s});case"step":return yr(de,{children:[pe(de,{color:V,children:`${e.n}. `}),e.s]});case"cmd":return yr(de,{children:[" ",pe(de,{color:V,children:e.name.padEnd(20)}),pe(de,{dimColor:!0,children:e.s})]});case"gap":return pe(de,{children:" "})}}function Pd({tab:e,width:t,version:n,engineVersion:o}){let r=Ne[e]??Ne[0],s=6+Ne.reduce((u,g)=>u+g.label.length+4,0),a="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return yr(Sd,{flexDirection:"column",paddingX:1,children:[yr(de,{children:[pe(de,{color:V,bold:!0,children:"Help "}),Ne.map((u,g)=>g===e?pe(de,{color:"white",backgroundColor:V,bold:!0,children:` ${u.label} `},u.key):pe(de,{dimColor:!0,children:` ${u.label} `},u.key))]}),pe(de,{color:V,children:a}),pe(Sd,{flexDirection:"column",marginTop:1,children:r.rows.map((u,g)=>pe(Zg,{row:u},g))}),pe(de,{dimColor:!0,children:`
373
+ \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var ew=/^(?:\d+[.)]|[-*•])\s+/;function Td(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
374
+ `)){let a=s.trim().replace(ew,""),u=a.match(/^`([^`]+)`$/);u&&(a=u[1].trim());let g=a.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!g||!o.has(g[1].toLowerCase()))continue;let b=`/${g[1].toLowerCase()}${g[2]?` ${g[2]}`:""}`;if(r.includes(b)||r.push(b),r.length>=n)break}return r}q();function Bn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Le(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Dd(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var tw=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Ad(e,t,n){if(!tw.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 a=s.replace(/\\/g,"/");return r===a||r.endsWith(`/${a}`)})??null}function Oi(e){return e.replace(/^[\w.-]+\//,"")}var kr=16,jd={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Dt(e){return typeof e=="string"?e:e.cmd}function Ed(e){return typeof e=="string"?void 0:e.desc}function Mi(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Nd(e,t){let n=Mi(t);return e.some(r=>Dt(r).trim()===t.trim()||!!n&&Mi(Dt(r))===n)?e.filter(r=>Dt(r).trim()!==t.trim()&&!(n&&Mi(Dt(r))===n)):[]}import{isDirectiveMention as Hw,stripDirectiveMention as Bw,appendDirective as Vw}from"document360-engine";var nw=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Id(e){return e.replace(/\r\n?/g,`
375
+ `)}function _d(e){return e.includes(`
376
+ `)||e.length>200}function Ld(e,t){let n=t.split(`
377
+ `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Od(e,t){return e.replace(nw,n=>t.get(n)??n)}function Md(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function br(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
378
+ `)){if(s.length===0)o.push({start:r,end:r});else for(let a=0;a<s.length;a+=n)o.push({start:r+a,end:r+Math.min(a+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function $r(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Ud(e,t,n){let o=$r(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 Wd(e,t,n){let o=e[$r(e,t)];return n==="start"?o.start:o.end}function Fd(e,t,n){let o=Math.max(1,n),r=e.split(`
378
379
  `),s=0;for(let a=r.length-1;a>=0;a--){let u=r[a];if(s+=Math.max(1,Math.ceil(u.length/o)),s>=t){let g=s-t;return{text:[g>0?u.slice(g*o):u,...r.slice(a+1)].join(`
379
- `),truncated:a>0||g>0}}}return{text:e,truncated:!1}}function Fd(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 Hd(e){let t=!1,n=0,o=0;for(let r of e.split(`
380
- `)){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 Gn,jsx as j,jsxs as Y}from"react/jsx-runtime";var Vw={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},ru=` 1. /init \u2014 pick your Document360 environment & scaffold config
380
+ `),truncated:a>0||g>0}}}return{text:e,truncated:!1}}function qd(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 Hd(e){let t=!1,n=0,o=0;for(let r of e.split(`
381
+ `)){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 Gn,jsx as j,jsxs as Y}from"react/jsx-runtime";var Gw={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},su=` 1. /init \u2014 pick your Document360 environment & scaffold config
381
382
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
382
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Gw(e,t,n,o){let r=Bi(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)",a=Vi(e),u=re(e),g=(u?.docsDir??lu).replace(/\/+$/,""),b=u?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${g}/ + config`,y={version:t,engineVersion:au,claude:s,model:a.model,modelSource:Vw[a.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:u!==null,mode:b};if(u===null)return y;try{let P=De(e,o);y.profile=P.name,y.apiUrl=P.connection.apiUrl,y.prod=P.production,y.project=P.project.projectName??P.project.projectId??"(chosen at login)";let x=At(P.name);if(x){let _={...dn(x.idToken)??{},...dn(x.accessToken)??{}},C=_.email??_.preferred_username??"signed in";dt(x)?x.refreshToken&&(y.who=C,y.loggedOut=!1,y.sessionHint="session expired \u2014 refreshing\u2026"):(y.who=C,y.loggedOut=!1,y.sessionHint=`session valid until ${new Date(x.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return y}function Yw(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={...dn(o.idToken)??{},...dn(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return dt(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 su=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],un=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],zw="Ask me to write or update an article\u2026";function cn({ch:e,dim:t}){let[n,o]=q(!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 Kw=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function iu(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Xw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Qw({startTime:e,chars:t}){let[n,o]=q(0);Ae(()=>{let g=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(g)},[]);let r=un[n%un.length],s=su[Math.floor(n/16)%su.length],a=Math.floor((Date.now()-e)/1e3),u=Math.round(t/4);return Y(se,{children:[j(A,{color:V,children:` ${r} ${s}\u2026 `}),j(A,{color:"gray",children:`(${jn(a)} \xB7 ~${u} tokens \xB7 esc to interrupt)`})]})}function Jw({text:e}){let[t,n]=q(0);return Ae(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),j(se,{paddingX:1,children:j(A,{color:V,children:`${un[t%un.length]} ${e}`})})}var Zw=12e4;function ey({p:e}){let[t,n]=q(0);Ae(()=>{let D=setInterval(()=>n(W=>W+1),150);return()=>clearInterval(D)},[]);let o=un[t%un.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),a=Math.round(e.chars/4),u=Date.now()-e.lastAt>=Zw,g=e.verb??"Converting",b=e.unit??"article",y=e.rows.reduce((D,W)=>D+W.items,0),P=g.toLowerCase(),x=e.rows,_=0;if(x.length>yr){let D=x.findIndex(z=>z.status==="active"||z.status==="pending"),W=Math.max(0,Math.min(D-2,x.length-yr));_=x.slice(0,W).filter(z=>z.status==="done").length,x=x.slice(W,W+yr)}let C=Math.min(40,Math.max(...x.map(D=>_i(D.label).length),0)),N=D=>D==="failed"?"red":D==="active"?V:void 0;return Y(se,{flexDirection:"column",children:[Y(se,{children:[j(A,{color:V,children:` ${o} ${g} ${y} ${b}${y===1?"":"s"} `}),j(A,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${a} tokens \xB7 ${jn(r)} \xB7 esc to stop`})]}),_>0&&j(A,{dimColor:!0,children:` \u2714 +${_} done`}),x.map(D=>Y(A,{color:N(D.status),dimColor:D.status==="done"||D.status==="pending",children:[` ${Ad[D.status]} ${_i(D.label).padEnd(C)}`,D.status==="active"&&D.itemsDone!==void 0?` (${D.itemsDone}/${D.items} ${b}${D.items===1?"":"s"})`:D.status!=="pending"?` (${D.items} ${b}${D.items===1?"":"s"})`:"",D.status==="active"?` \u2190 ${P}\u2026`:""]},D.label)),u&&j(A,{color:"yellow",children:` \u26A0 no activity for ${jn(s)} \u2014 press esc to stop if it's wedged`})]})}var ty=10800*1e3;function cu({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=nw(),[s,a]=q(n),[u,g]=q(null),[b,y]=q({text:"",pos:0}),P=b.text,x=G(c=>{y(l=>{let i=typeof c=="function"?c(l.text):c;return{text:i,pos:i.length}})},[]),_=G(c=>{y(l=>({text:l.text.slice(0,l.pos)+c+l.text.slice(l.pos),pos:l.pos+c.length}))},[]),C=G(()=>{y(c=>{if(c.pos===0)return c;let l=c.text.slice(0,c.pos),i=Od(l)??l.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[N,D]=q(!1),[W,z]=q(!1),[K,X]=q(0),[he,Qe]=q(!1),[me,jt]=q(null),[ve,ut]=q(null),[qe,pt]=q([]),Yn=ee(!1),Rr=ee(!1),[Sr,Ki]=q(!1),zn=ee(0),[gu,Kn]=q(!1),[wu,Xn]=q(!1),[Pr,Xi]=q(null),[yu,Et]=q(0),ht=ee(0),[pn,Nt]=q(0),[It,Qn]=q(null),Qi=ee(new Map),ku=ee(0),_t=ee([]),je=ee(null);je.current===null&&(je.current=qd({cwd:e,profileName:s,allowProdWrites:!1}));let Be=ee({uuid:null,firstPrompt:null,titleFired:!1}),Jn=ee(new Map),Lt=ee(!1),Tr=ee([]),ce=ee([]),Ot=ee([]),Zn=ee(null),[Ji,ft]=q(null),Dr=ee(null),[mt,gt]=q(null),[Ve,Mt]=q(null),[Ge,Ut]=q(null),[ge,Wt]=q(null),[Ce,wt]=q(null),[Je,Ft]=q(null),[Ze,yt]=q(null),[Ye,kt]=q(null),[Zi,hn]=q(null),[Re,bt]=q(null),[ye,Ht]=q(null),[ea,Ar]=q([]),$t=ee([]),fn=ee(!1),ke=ee(null),[eo,ne]=q(null),[ta,na]=q(null),to=ee(!1),mn=ee(null),gn=ee(null),[Se,xt]=q(null),[no,wn]=q(null),jr=!!(Ge||ge||Ce||Je||Ze||Ye||Re||ye||Se||no),[oa,qt]=q(0),[ra,Bt]=q(0),[bu,sa]=q(0),Er=Oi(()=>{try{let c=Vi(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,bu]),{stdout:Me}=rw(),[,$u]=q(0),ia=ee(`${Me.columns??80}x${Me.rows??24}`),et=G(()=>Math.max(20,(Me.columns??80)-1),[Me]),d=G(c=>{_t.current.push(c),console.log(ds(c,et()))},[et]),we=G((c,l)=>{zn.current++,jt(c),ut(l??null)},[]),Ue=G(()=>{zn.current++,jt(null),ut(null)},[]),Q=G(c=>we(c,sr({kind:"cmd",cmd:c,reason:""})),[we]),oo=G((c,l)=>{!l?.silent&&c.note&&d({kind:"note",tone:c.tone,text:c.note}),c.picker&&(pt(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),hn(c.picker.title)),c.lead&&we(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,sr(c.lead))},[d,we]),be=G((c,l,i="info")=>{c&&d({kind:"note",tone:i,text:c}),l&&we(l.kind==="cmd"?l.cmd:l.text,sr(l))},[d,we]),[yn,Nr]=q(null),[xu,aa]=q(!1),Vt=G(c=>{Nr(c),aa(!1),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),Ir=ee(!1),_r=G(async()=>{try{if(Ir.current||!Ow(Lw())||re(e)?.mode==="engineer")return;let c=await _w({pkg:Tt,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;Ir.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${Tt} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),Xn(!0),(await Zo().finally(()=>Xn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),Q("/exit"),Xi(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${Jo}`})}catch{}},[e,o,d,Q]),ro=G(c=>{let l=_e(e,s);return l.ok?!0:(d({kind:"note",tone:"warn",text:l.reason}),gn.current=c,Q("/login"),!1)},[e,s,d,Q]),[so,Lr]=q(null),vt=G(c=>{let l=qn(e,s,{claudeMissing:Bi(t).state==="missing",allowAutoAudit:c,genreUnknown:Rr.current});return l?Hn(l):{kind:"idle"}},[e,s,t]),kn=ee(!0),Gt=ee(!1),io=ee(0),bn=ee(0);Ae(()=>{let c=setInterval(()=>{if(kn.current){io.current=0,bn.current=0;return}if(!N)try{if(!ln(Qd(e)))return;if(Ie(e).status==="current"){kn.current=!0,io.current=0,bn.current=0;let i=vt(!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.";d({kind:"note",tone:"ok",text:`${R}${f?.lead?` ${Fn(f.lead)}`:""}`}),Nr(null),f&&(f.lead||f.picker)?oo(f,{silent:!0}):Gt.current||we("write the docs for this repo"),X(O=>O+1);return}if(Gt.current)return;io.current+=1;let l=io.current;if((l===4||l%15===0)&&bn.current<3){bn.current+=1;let i=bn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Ke(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${i}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${i}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,N,d,vt,oo,we]),Ae(()=>{let c=Ji??Vn(e);if(!N){fr(0),an(`${gr} ${c}`);return}fr(3);let l=0;an(`${mr[0]} ${c}`);let i=setInterval(()=>{l=(l+1)%mr.length,an(`${mr[l]} ${c}`)},400);return()=>clearInterval(i)},[N,e,Ji]),Ae(()=>()=>fr(0),[]),Ae(()=>{let c=performance.now(),l=[],i=(p,w)=>{let k=performance.now();try{return w()}finally{let $=Math.round(performance.now()-k);$>=80&&l.push(`${p}: ${$}ms`)}};d({kind:"banner",info:i("banner",()=>Gw(e,o,t,s))});let f=Bi(t).state==="missing";if(f&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
383
- ${aw}
383
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Yw(e,t,n,o){let r=Gi(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)",a=Yi(e),u=re(e),g=(u?.docsDir??cu).replace(/\/+$/,""),b=u?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${g}/ + config`,y={version:t,engineVersion:lu,claude:s,model:a.model,modelSource:Gw[a.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:u!==null,mode:b};if(u===null)return y;try{let P=De(e,o);y.profile=P.name,y.apiUrl=P.connection.apiUrl,y.prod=P.production,y.project=P.project.projectName??P.project.projectId??"(chosen at login)";let x=At(P.name);if(x){let _={...dn(x.idToken)??{},...dn(x.accessToken)??{}},C=_.email??_.preferred_username??"signed in";dt(x)?x.refreshToken&&(y.who=C,y.loggedOut=!1,y.sessionHint="session expired \u2014 refreshing\u2026"):(y.who=C,y.loggedOut=!1,y.sessionHint=`session valid until ${new Date(x.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return y}function zw(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={...dn(o.idToken)??{},...dn(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return dt(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 iu=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],un=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Kw="Ask me to write or update an article\u2026";function cn({ch:e,dim:t}){let[n,o]=H(!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 Xw=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function au(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Qw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Jw({startTime:e,chars:t}){let[n,o]=H(0);Ae(()=>{let g=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(g)},[]);let r=un[n%un.length],s=iu[Math.floor(n/16)%iu.length],a=Math.floor((Date.now()-e)/1e3),u=Math.round(t/4);return Y(se,{children:[j(A,{color:V,children:` ${r} ${s}\u2026 `}),j(A,{color:"gray",children:`(${jn(a)} \xB7 ~${u} tokens \xB7 esc to interrupt)`})]})}function Zw({text:e}){let[t,n]=H(0);return Ae(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),j(se,{paddingX:1,children:j(A,{color:V,children:`${un[t%un.length]} ${e}`})})}var ey=12e4;function ty({p:e}){let[t,n]=H(0);Ae(()=>{let D=setInterval(()=>n(W=>W+1),150);return()=>clearInterval(D)},[]);let o=un[t%un.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),a=Math.round(e.chars/4),u=Date.now()-e.lastAt>=ey,g=e.verb??"Converting",b=e.unit??"article",y=e.rows.reduce((D,W)=>D+W.items,0),P=g.toLowerCase(),x=e.rows,_=0;if(x.length>kr){let D=x.findIndex(z=>z.status==="active"||z.status==="pending"),W=Math.max(0,Math.min(D-2,x.length-kr));_=x.slice(0,W).filter(z=>z.status==="done").length,x=x.slice(W,W+kr)}let C=Math.min(40,Math.max(...x.map(D=>Oi(D.label).length),0)),N=D=>D==="failed"?"red":D==="active"?V:void 0;return Y(se,{flexDirection:"column",children:[Y(se,{children:[j(A,{color:V,children:` ${o} ${g} ${y} ${b}${y===1?"":"s"} `}),j(A,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${a} tokens \xB7 ${jn(r)} \xB7 esc to stop`})]}),_>0&&j(A,{dimColor:!0,children:` \u2714 +${_} done`}),x.map(D=>Y(A,{color:N(D.status),dimColor:D.status==="done"||D.status==="pending",children:[` ${jd[D.status]} ${Oi(D.label).padEnd(C)}`,D.status==="active"&&D.itemsDone!==void 0?` (${D.itemsDone}/${D.items} ${b}${D.items===1?"":"s"})`:D.status!=="pending"?` (${D.items} ${b}${D.items===1?"":"s"})`:"",D.status==="active"?` \u2190 ${P}\u2026`:""]},D.label)),u&&j(A,{color:"yellow",children:` \u26A0 no activity for ${jn(s)} \u2014 press esc to stop if it's wedged`})]})}var ny=10800*1e3;function du({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=ow(),[s,a]=H(n),[u,g]=H(null),[b,y]=H({text:"",pos:0}),P=b.text,x=G(c=>{y(l=>{let i=typeof c=="function"?c(l.text):c;return{text:i,pos:i.length}})},[]),_=G(c=>{y(l=>({text:l.text.slice(0,l.pos)+c+l.text.slice(l.pos),pos:l.pos+c.length}))},[]),C=G(()=>{y(c=>{if(c.pos===0)return c;let l=c.text.slice(0,c.pos),i=Md(l)??l.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[N,D]=H(!1),[W,z]=H(!1),[K,X]=H(0),[he,Qe]=H(!1),[me,jt]=H(null),[ve,ut]=H(null),[He,pt]=H([]),Yn=ee(!1),Sr=ee(!1),[Pr,Qi]=H(!1),zn=ee(0),[wu,Kn]=H(!1),[yu,Xn]=H(!1),[Tr,Ji]=H(null),[ku,Et]=H(0),ht=ee(0),[pn,Nt]=H(0),[It,Qn]=H(null),Zi=ee(new Map),bu=ee(0),_t=ee([]),je=ee(null);je.current===null&&(je.current=Bd({cwd:e,profileName:s,allowProdWrites:!1}));let Be=ee({uuid:null,firstPrompt:null,titleFired:!1}),Jn=ee(new Map),Lt=ee(!1),Dr=ee([]),ce=ee([]),Ot=ee([]),Zn=ee(null),[ea,ft]=H(null),Ar=ee(null),[mt,gt]=H(null),[Ve,Mt]=H(null),[Ge,Ut]=H(null),[ge,Wt]=H(null),[Ce,wt]=H(null),[Je,Ft]=H(null),[Ze,yt]=H(null),[Ye,kt]=H(null),[ta,hn]=H(null),[Re,bt]=H(null),[ye,qt]=H(null),[na,jr]=H([]),$t=ee([]),fn=ee(!1),ke=ee(null),[eo,oe]=H(null),[oa,ra]=H(null),to=ee(!1),mn=ee(null),gn=ee(null),[Se,xt]=H(null),[no,wn]=H(null),Er=!!(Ge||ge||Ce||Je||Ze||Ye||Re||ye||Se||no),[sa,Ht]=H(0),[ia,Bt]=H(0),[$u,aa]=H(0),Nr=Ui(()=>{try{let c=Yi(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,$u]),{stdout:Me}=sw(),[,xu]=H(0),la=ee(`${Me.columns??80}x${Me.rows??24}`),et=G(()=>Math.max(20,(Me.columns??80)-1),[Me]),d=G(c=>{_t.current.push(c),console.log(us(c,et()))},[et]),we=G((c,l)=>{zn.current++,jt(c),ut(l??null)},[]),Ue=G(()=>{zn.current++,jt(null),ut(null)},[]),Q=G(c=>we(c,ir({kind:"cmd",cmd:c,reason:""})),[we]),oo=G((c,l)=>{!l?.silent&&c.note&&d({kind:"note",tone:c.tone,text:c.note}),c.picker&&(pt(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),hn(c.picker.title)),c.lead&&we(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,ir(c.lead))},[d,we]),be=G((c,l,i="info")=>{c&&d({kind:"note",tone:i,text:c}),l&&we(l.kind==="cmd"?l.cmd:l.text,ir(l))},[d,we]),[yn,Ir]=H(null),[vu,ca]=H(!1),Vt=G(c=>{Ir(c),ca(!1),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),_r=ee(!1),Lr=G(async()=>{try{if(_r.current||!Mw(Ow())||re(e)?.mode==="engineer")return;let c=await Lw({pkg:Tt,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;_r.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${Tt} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),Xn(!0),(await er().finally(()=>Xn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),Q("/exit"),Ji(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${Zo}`})}catch{}},[e,o,d,Q]),ro=G(c=>{let l=_e(e,s);return l.ok?!0:(d({kind:"note",tone:"warn",text:l.reason}),gn.current=c,Q("/login"),!1)},[e,s,d,Q]),[so,Or]=H(null),vt=G(c=>{let l=Hn(e,s,{claudeMissing:Gi(t).state==="missing",allowAutoAudit:c,genreUnknown:Sr.current});return l?qn(l):{kind:"idle"}},[e,s,t]),kn=ee(!0),Gt=ee(!1),io=ee(0),bn=ee(0);Ae(()=>{let c=setInterval(()=>{if(kn.current){io.current=0,bn.current=0;return}if(!N)try{if(!ln(Jd(e)))return;if(Ie(e).status==="current"){kn.current=!0,io.current=0,bn.current=0;let i=vt(!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.";d({kind:"note",tone:"ok",text:`${R}${f?.lead?` ${Fn(f.lead)}`:""}`}),Ir(null),f&&(f.lead||f.picker)?oo(f,{silent:!0}):Gt.current||we("write the docs for this repo"),X(O=>O+1);return}if(Gt.current)return;io.current+=1;let l=io.current;if((l===4||l%15===0)&&bn.current<3){bn.current+=1;let i=bn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Ke(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${i}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${i}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,N,d,vt,oo,we]),Ae(()=>{let c=ea??Vn(e);if(!N){mr(0),an(`${wr} ${c}`);return}mr(3);let l=0;an(`${gr[0]} ${c}`);let i=setInterval(()=>{l=(l+1)%gr.length,an(`${gr[l]} ${c}`)},400);return()=>clearInterval(i)},[N,e,ea]),Ae(()=>()=>mr(0),[]),Ae(()=>{let c=performance.now(),l=[],i=(p,w)=>{let k=performance.now();try{return w()}finally{let $=Math.round(performance.now()-k);$>=80&&l.push(`${p}: ${$}ms`)}};d({kind:"banner",info:i("banner",()=>Yw(e,o,t,s))});let f=Gi(t).state==="missing";if(f&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
384
+ ${lw}
384
385
  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)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
385
- ${ru}`}),Q(f?"/doctor":"/init");return}f&&Q("/doctor");try{let p=De(e,s),w=At(p.name);w&&dt(w)&&w.refreshToken?uw({profile:p.name,connection:p.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),X(k=>k+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Q("/login")}):(!w||dt(w))&&(d({kind:"note",tone:"warn",text:`Profile "${p.name}" is not signed in \u2014 sign in with /login.`}),Q("/login"))}catch{}try{let p=re(e),w=De(e,s),k=At(w.name);p&&k&&!dt(k)&&Si(e,p.authoritativeSourceFiles)&&!Pi(e,s)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),Q("/scope"))}catch{}try{let p=i("resolve-genre",()=>vw(e));p.persisted&&p.appType?d({kind:"note",tone:"ok",text:`\u2713 Detected a ${p.appType} app \u2014 enabled the ${p.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):p.source==="unknown"&&re(e)&&(Rr.current=!0)}catch{}let R=Ie(e);try{if(i("reconcile-devhints",()=>Do(e)),R.status!=="current"&&!Ke(e)){let p=Ao(e);p.length&&(d({kind:"note",tone:"warn",text:p.join(`
386
- `)}),Vt(Ct()),kn.current=!1,Gt.current=!1)}}catch{}try{let p=i("reconcile-feedback",()=>Mw(e));p.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${p.archived} resolved item${p.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${p.open>0?`; ${p.open} still open`:""}.`})}catch{}try{let p=i("upgrade-actions",()=>Uw(e));p.applied.length>0&&d({kind:"note",tone:"warn",text:ar(p.applied).join(`
387
- `)})}catch{}let O=i("ready-decision",()=>vt(!0));O.kind==="autoAudit"?(d({kind:"note",tone:"info",text:O.note}),Nn().then(p=>{p.kind==="forward-to-agent"&&p.prompt&&oe(p.prompt,{display:p.display,quietUser:!0})})):O.kind==="recommend"&&oo(O.rec);let h=Math.round(performance.now()-c);h>=800&&Fw({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${h}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${l.length?l.join(`
386
+ ${su}`}),Q(f?"/doctor":"/init");return}f&&Q("/doctor");try{let p=De(e,s),w=At(p.name);w&&dt(w)&&w.refreshToken?pw({profile:p.name,connection:p.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),X(k=>k+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Q("/login")}):(!w||dt(w))&&(d({kind:"note",tone:"warn",text:`Profile "${p.name}" is not signed in \u2014 sign in with /login.`}),Q("/login"))}catch{}try{let p=re(e),w=De(e,s),k=At(w.name);p&&k&&!dt(k)&&Ti(e,p.authoritativeSourceFiles)&&!Di(e,s)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),Q("/scope"))}catch{}try{let p=i("resolve-genre",()=>Cw(e));p.persisted&&p.appType?d({kind:"note",tone:"ok",text:`\u2713 Detected a ${p.appType} app \u2014 enabled the ${p.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):p.source==="unknown"&&re(e)&&(Sr.current=!0)}catch{}let R=Ie(e);try{if(i("reconcile-devhints",()=>Ao(e)),R.status!=="current"&&!Ke(e)){let p=jo(e);p.length&&(d({kind:"note",tone:"warn",text:p.join(`
387
+ `)}),Vt(Ct()),kn.current=!1,Gt.current=!1)}}catch{}try{let p=i("reconcile-feedback",()=>Uw(e));p.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${p.archived} resolved item${p.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${p.open>0?`; ${p.open} still open`:""}.`})}catch{}try{let p=i("upgrade-actions",()=>Ww(e));p.applied.length>0&&d({kind:"note",tone:"warn",text:lr(p.applied).join(`
388
+ `)})}catch{}let O=i("ready-decision",()=>vt(!0));O.kind==="autoAudit"?(d({kind:"note",tone:"info",text:O.note}),Nn().then(p=>{p.kind==="forward-to-agent"&&p.prompt&&te(p.prompt,{display:p.display,quietUser:!0})})):O.kind==="recommend"&&oo(O.rec);let h=Math.round(performance.now()-c);h>=800&&qw({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${h}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${l.length?l.join(`
388
389
  `):"no single phase \u226580ms"}
389
- cwd: ${e}`}),_r()},[]),Ae(()=>{let c=setInterval(()=>{_r()},ty);return()=>clearInterval(c)},[_r]),Ae(()=>{if(N||he||Sr||Yn.current||me!==null||qe.length>0||P!==""||yn!==null||ce.current.length>0||Zn.current||jr)return;let c=vt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&oo(c.rec,{silent:!0})},[N,he,me,qe,P,yn,jr,K,vt,Sr]),Ae(()=>{let c=null,l=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let f=`${Me.columns??80}x${Me.rows??24}`;f!==ia.current&&(ia.current=f,$u(R=>R+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+kl(_t.current,et())+"\x1B[?2026l")},80))},400)};return Me.on("resize",i),()=>{c&&clearTimeout(c),l&&clearTimeout(l),Me.off("resize",i)}},[Me,et]);let Ee=Math.max(20,(Me.columns??80)-1),la=Oi(()=>Yw(e,s),[e,s,K]),Or=(()=>{if(wu)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Pr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Pr?` v${Pr}`:""}\u2026`,isSetup:!0};if(so)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 xu?{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 l=Mi(e,(c.docsDir??lu).replace(/\/+$/,"")),i=(()=>{try{return ln(l)&&sw(l).length>0}catch{return!1}})();try{let f=De(e,s),R=At(f.name);if(!(!!R&&!(dt(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:zw,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),$n=dl(P),ca=$n.length>0&&!N,Mr=u!==null?Wd(u,8,Ee):null,ao=Re?Re.paths.filter(c=>!Re.query||c.toLowerCase().includes(Re.query.toLowerCase())).slice(0,8):[],lo=Se?Se.sessions.filter(c=>{let l=Se.query.toLowerCase();return!l||c.name.toLowerCase().includes(l)||c.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],Pe=G((c,l)=>{je.current?.close(),je.current=qd({cwd:e,resume:c,profileName:l??s,allowProdWrites:Lt.current}),c||(Be.current={uuid:null,firstPrompt:null,titleFired:!1},ft(null)),qt(0),Bt(0)},[e,s]),da=G((c,l,i)=>{if(Kw.test(c))try{let f=De(e,s),R=typeof l.project_id=="string"&&l.project_id||f.project.projectId,O=ur(l,i),h=[],p=pr(i);c.endsWith("publish_article")&&p&&h.push(`Live: ${p}`);let w=hr(i);w?h.push(`Preview: ${w}`):O&&R&&h.push(`Preview: ${dr(f.connection.portalUrl,R,O,f.project.languageCode??"en")}`),h.length>0&&d({kind:"link",lines:h})}catch{}},[e,s,d]),oe=G(async(c,l)=>{Kn(!0),Yn.current=!1,Ue(),pt([]),hn(null),Nr(null);let i=zn.current;l?.quietUser||d({kind:"user",text:l?.echoDisplay&&l.display?l.display:c});let f=Be.current;f.firstPrompt||(f.firstPrompt=l?.display??c),ht.current=Date.now(),Et(0),D(!0),Jn.current.clear();let R="",O=!1,h=!1,p="",w={num:0,closed:!1,cueSeen:!1},k=null,$=()=>{k||(k=setTimeout(()=>{k=null,g(p.length>0?p:null)},60))},S=()=>{k&&clearTimeout(k),k=null,g(null)},U=(T=!1)=>{let{head:B,keep:I}=Fd(p,T);B.trim()&&d({kind:"assistant",text:Ni(B.trimEnd(),w)}),p=I,S()};try{for await(let T of je.current.send(c))if(T.type==="session"){if(!f.uuid){f.uuid=T.sessionId;let B=new Date().toISOString(),I=Dr.current,F=I??ww(f.firstPrompt??"session");yw({uuid:T.sessionId,name:F,renamed:!!I,titled:!1,cwd:e,firstPrompt:f.firstPrompt??"",createdAt:B,updatedAt:B}),ft(F),Dr.current=null}}else if(T.type==="text"){p+=T.delta,R+=T.delta;let B=Hd(p);if(B>0){let I=p.slice(0,B).trimEnd();I&&d({kind:"assistant",text:Ni(I,w)}),p=p.slice(B)}$(),Et(I=>I+T.delta.length)}else if(T.type==="tool"){O=!0;let B=lr(T.name,T.input);B&&(U(),d({kind:"tool",title:B.title,sep:B.sep,arg:B.arg}),Jn.current.set(T.id,{name:T.name,input:T.input}))}else if(T.type==="article_diff"){let B=Xe(T.oldContent,T.newContent,et());B&&(U(),d({kind:"diff",added:B.added,removed:B.removed,lines:B.lines,hidden:B.hidden}))}else if(T.type==="tool_result"){T.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(T.output)&&(to.current=!0);let B=Jn.current.get(T.id);if(B){Jn.current.delete(T.id),U();let I=cr(T.output,4,T.isError?void 0:B.name,B.input);d({kind:"tool-result",lines:I.lines,hidden:I.hidden,isError:T.isError}),T.isError||da(B.name,B.input,T.output)}}else if(T.type==="result"){U(!0),qt(I=>I+T.outputTokens),Bt(I=>I+T.costUsd);let B=T.inputTokens+T.cacheReadTokens+T.cacheCreationTokens;if(d({kind:"done",seconds:Math.round((Date.now()-ht.current)/1e3),tokens:T.outputTokens,costUsd:T.costUsd,ok:T.ok,...B>0?{inTokens:B,cachedPct:Math.round(T.cacheReadTokens/B*100)}:{}}),!h&&!O&&!R.trim()&&!fn.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),T.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(R))try{let I=Jd(e);if(ln(I)){let F=$r(I,"utf8").trim();F&&(Lr(F),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(T.ok&&w.cueSeen)Ki(!0),pt([]);else{let I=T.ok?Pd(R,nn.map(F=>F.name)):[];if(I.length>0)Q(I[0]);else if(T.ok&&R.trim()){let F=vt(!1);F.kind==="recommend"&&(F.rec.lead||F.rec.picker)||xw(c,R,e).then(te=>{te&&zn.current===i&&we(te)}).catch(()=>{})}}if(f.uuid&&(Ui(f.uuid),!f.titleFired)){f.titleFired=!0;let I=f.uuid,F=f.firstPrompt;F&&Bd(F,e).then(te=>{te&&(gw(I,te),ft(te))}).catch(()=>{})}}else T.type==="error"&&(U(!0),h=!0,T.kind==="auth"&&(to.current=!0),d({kind:"note",text:`agent error: ${T.message}`,tone:"error"}))}finally{D(!1),S(),X(T=>T+1),Be.current.uuid&&vd(e,Be.current.uuid,_t.current),to.current?(to.current=!1,mn.current=l?.display??c,we("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):mn.current=null,fn.current&&(fn.current=!1,$t.current.length>0&&(d({kind:"note",tone:"info",text:`(${$t.current.length} queued message(s) discarded)`}),$t.current=[],Ar([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,da,et,we,Q,Ue,vt]),Yt=G(async c=>{let l=vr(e,"standard");ht.current=Date.now(),Et(0),D(!0);let i=new AbortController;ke.current=i;let f=async(R,O)=>{let h=Fi(R);ne({verb:"Publishing",total:h.length,done:0,active:[],rows:Bn(h),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:O?`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 ${h.length} partition${h.length===1?"":"s"} (\u2264${En} agents at once) on ${l.model}\u2026 (esc to stop)`});let p=!1;for await(let w of xr({cwd:e,partitions:h,promptFor:k=>Uo(k.paths),concurrency:En,profileName:s,allowProdWrites:Lt.current,model:l.model,signal:i.signal}))if(w.type==="partition_status")w.status==="running"?ne(k=>k&&{...k,active:[...k.active,w.label],rows:Le(k.rows,w.label,"active"),lastAt:Date.now()}):ne(k=>k&&{...k,active:k.active.filter($=>$!==w.label),done:k.done+1,rows:Le(k.rows,w.label,w.status==="done"?"done":"failed"),lastAt:Date.now()});else if(w.type==="partition_event")ne(k=>{if(!k)return k;let $={...k,lastAt:Date.now()};return w.event.type==="tool"?$.tools=k.tools+1:w.event.type==="text"&&($.chars=k.chars+w.event.delta.length),$});else if(w.type==="run_done"){p=w.aborted,Bt(U=>U+w.totalCostUsd),qt(U=>U+w.results.reduce((T,B)=>T+B.outputTokens,0));let k=w.aborted?"Stopped. ":"",$=t.kind==="api"?"api":"subscription";d({kind:"note",tone:w.aborted?"warn":w.ok?"ok":"warn",text:k+fs(w.results,h,$).join(`
390
- `)});let S=hs(e,s);if(S&&d({kind:"note",tone:"info",text:S}),!w.aborted){try{let U=await eu({cwd:e,profileName:s}),T=tu(U);T?d({kind:"note",tone:"info",text:T}):U.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${U.skipped}`})}catch(U){d({kind:"note",tone:"warn",text:`Order sync failed: ${U.message}`})}try{let U=ou(await nu({cwd:e,profileName:s}));U&&d({kind:"note",tone:"info",text:U})}catch(U){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${U.message}`})}}}return p};try{if(!await f(c,!1)){let O=await ms(e,s,c);O.length>0&&await f(O,!0)}}catch(R){d({kind:"note",tone:"error",text:`Publish run failed: ${R.message}`})}finally{ke.current=null,ne(null),D(!1),X(R=>R+1)}},[e,s,d,t]),Ur=G(async c=>{await oe(us(c),{display:`/publish ${c}`,quietUser:!0});try{let l=await Wo(e,s,c.replace(/\\/g,"/"));l.length>0&&(hn(`Related articles not yet published (${l.length}):`),pt([`/publish --related ${c}`,...l.map(i=>`/publish ${i}`)]))}catch{}},[e,s,oe]),ua=G(c=>{if(c)try{for(let l of Array.isArray(c)?c:[c]){let i=ed(e,l);if(!i)continue;rr(e,i.title).ok&&d({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${i.title}`});return}}catch{}},[e,d]),pa=G(async(c,l)=>{let f=jw(c,3),R=vr(e,"standard");ht.current=Date.now(),Et(0),D(!0);let O=new AbortController;ke.current=O,ne({verb:"Authoring",unit:"spec",total:f.length,done:0,active:[],rows:Bn(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({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 h=!1;try{for await(let p of xr({cwd:e,partitions:f,promptFor:Pc,concurrency:6,profileName:s,allowProdWrites:Lt.current,model:R.model,signal:O.signal}))if(p.type==="partition_status")p.status==="running"?ne(w=>w&&{...w,active:[...w.active,p.label],rows:Le(w.rows,p.label,"active"),lastAt:Date.now()}):ne(w=>w&&{...w,active:w.active.filter(k=>k!==p.label),done:w.done+1,rows:Le(w.rows,p.label,p.status==="done"?"done":"failed"),lastAt:Date.now()});else if(p.type==="partition_event")ne(w=>{if(!w)return w;let k={...w,lastAt:Date.now()};return p.event.type==="tool"?k.tools=w.tools+1:p.event.type==="text"&&(k.chars=w.chars+p.event.delta.length),k});else if(p.type==="run_done"){Bt(S=>S+p.totalCostUsd),qt(S=>S+p.results.reduce((U,T)=>U+T.outputTokens,0));let w=p.results.filter(S=>S.ok).length,k=p.aborted?"Stopped. ":"";h=!p.aborted&&l.setup;let $=p.aborted?"":h?" Refreshing the capture-setup checklist\u2026":" Next: /screenshot capture --all (or /screenshot setup first for the staging checklist).";d({kind:"note",tone:p.aborted?"warn":p.ok?"ok":"warn",text:`${k}Authored specs \u2014 ${w}/${p.results.length} batches ok.${$}`}),!p.aborted&&p.ok&&ua(l.runLine)}}catch(p){d({kind:"note",tone:"error",text:`Spec authoring failed: ${p.message}`})}finally{ke.current=null,ne(null),D(!1),X(p=>p+1)}if(h){let p=await sn();p.kind==="forward-to-agent"&&p.prompt&&await oe(p.prompt,{display:p.display,quietUser:!0});let w=ri(e);w&&d({kind:"note",tone:"info",text:w.join(`
391
- `)})}},[e,s,d,oe]),ha=G(async c=>{let l=await Ko([c]);l.kind==="forward-to-agent"&&l.prompt&&await oe(l.prompt,{display:l.display,quietUser:!0}),Rc(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,oe,be]),Wr=G(async(c,l)=>{if(!Xo(e)){d({kind:"note",tone:"warn",text:"Screenshot capture is not set up in this repo yet \u2014 run d360-capture init in this repo's terminal, then d360-capture auth (once per machine)."});return}D(!0);let i=new AbortController;ke.current=i;let f=c.map($=>({label:$,items:1,status:"pending"}));ne({verb:"Capturing",unit:"screenshot",total:c.length,done:0,active:[],rows:f,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({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 R=Date.now(),O=[];try{for(let $ of c){if(i.signal.aborted)break;ne(I=>I&&{...I,active:[$],rows:Le(I.rows,$,"active"),lastAt:Date.now()});let{exitCode:S,output:U}=await ni({cwd:e,id:$,signal:i.signal,stdio:"pipe"});if(Nc(S,U)){d({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 T=i.signal.aborted&&S!==0?"failed":ti(e,$,S,R),B=T==="captured"?void 0:T==="skipped"?jc(U)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Ec(U);O.push({id:$,outcome:T,detail:B}),ne(I=>I&&{...I,active:[],done:I.done+1,rows:Le(I.rows,$,T==="captured"?"done":"failed"),lastAt:Date.now()})}}catch($){d({kind:"note",tone:"error",text:`Capture run failed: ${$.message}`})}finally{ke.current=null,ne(null),D(!1),X($=>$+1)}if(O.length===0)return;let h=O.filter($=>$.outcome==="captured"),p=O.filter($=>$.outcome==="skipped"),w=O.filter($=>$.outcome==="failed"),k=c.length-O.length;d({kind:"note",tone:w.length?"warn":h.length?"ok":"info",text:`\u2713 ${h.length} captured`+(p.length?` \xB7 \u2298 ${p.length} skipped`:"")+(w.length?` \xB7 \u2717 ${w.length} failed`:"")+(k?` \xB7 ${k} not run (stopped)`:"")});for(let $ of p)d({kind:"note",tone:"info",text:`\u2298 ${$.id} \u2014 ${$.detail}`});for(let $ of w)$.detail&&d({kind:"note",tone:"error",text:`\u2717 ${$.id}
392
- ${$.detail}`});if(h.length>0){let $=Ic(e,h.map(U=>U.id)),S=$.length===1?`/publish ${$[0]}`:"/publish";be(`PNG${h.length===1?"":"s"} saved to the screenshots folder \u2014 publish to put ${h.length===1?"it":"them"} in the article${$.length===1?"":"s"}: ${S}`,{kind:"cmd",cmd:S,reason:""})}else if(p.length>0){let $=c.length===1?`/screenshot capture ${c[0]}`:"/screenshot capture";be(null,{kind:"cmd",cmd:$,reason:""})}O.length===c.length&&w.length===0&&p.length===0&&ua(l?.runLine)},[e,d,be]),Fr=G(c=>{let l=At(c);if(!l||dt(l)&&!l.refreshToken)return null;let i={...dn(l.idToken)??{},...dn(l.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),Hr=G((c,l)=>{if(l){let i=re(e);i&&(i.defaultProfile=c,Vd(i,e))}a(c),Pe(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${l?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Fr(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),Q("/login")),X(i=>i+1)},[e,d,Pe,Fr,Q]),co=G((c,l,i)=>{ko(e,c,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Pe(),Gd(e,c)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:en(Zt(e)).join(`
393
- `)}),Vt(Ct()),kn.current=Ie(e).status==="current",Gt.current=Ke(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,Pe,Vt]),uo=G(async c=>{let l;try{l=await Rn(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Q("/workspace");return}if(l.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=l.workspaces.filter(R=>(R.workspace_type??"").toLowerCase()!=="apidocumentation"),f=i.length>0?i:l.workspaces;if(f.length===1){let R=f[0],O=l.workspaces.length-f.length;d({kind:"note",tone:"ok",text:`Selected the "${R.name??R.id}" workspace${O>0?" (skipped the API-documentation workspace)":""}.`}),co(l.profile,l.projectId,R);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${f.length} available).`}),Q("/workspace")},[e,d,co,Q]),po=G((c,l)=>{bo(e,c,l.id,l.name),d({kind:"note",tone:"ok",text:`Project set to "${l.name??l.id}" (agent restarted).`}),Pe(),uo(c)},[e,d,Pe,uo]),fa=G(async c=>{let l;try{l=De(e,c)}catch{return}if(!l.project.workspaceId){if(l.project.projectId){if(!l.project.projectName)try{let{projects:i}=await ot(e,l.name),f=i.find(R=>R.id===l.project.projectId);f?.name&&Ww(e,l.name,{projectName:f.name})}catch{}await uo(l.name);return}try{let{projects:i}=await ot(e,l.name);if(i.length===1){let f=i[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${f.name??f.id}".`}),po(l.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}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),wt({cursor:0,current:-1,rows:f,profile:l.name,environment:l.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Q("/project")}},[e,d,uo,po,Q]),zt=G(()=>{let c=ce.current[0];if(!c)return;Ue();let{plan:l,mode:i}=c;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let R of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${R}`});l.overwritesLocalChanges&&i==="pull"&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let f=Xe(l.oldContent,l.newContent,et());d(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"?(d({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),d({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,et,Ue]),qr=G(()=>{if(ce.current.length>0){zt();return}let c=Ot.current;Ot.current=[],c.length>0?(d({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),Yt(c)):Q("/pull")},[zt,d,Yt,Q]),ma=G(c=>{if(ce.current.length===0)return!1;let l=c.trim().toLowerCase(),i=ce.current[0];if(i.mode==="conflict"){if(l==="l"||l==="local")ce.current.shift(),Ot.current.push(i.plan.path),d({kind:"note",tone:"info",text:`Keeping local ${i.plan.path} \u2014 will publish over the portal.`});else if(l==="p"||l==="portal"){ce.current.shift();try{Yd({cwd:e,profileName:s},i.plan),d({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(f){d({kind:"note",tone:"error",text:`Take-portal failed: ${f.message}`})}}else if(l==="s"||l==="skip"||l==="n")ce.current.shift(),d({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let f=ce.current.length;return ce.current=[],Ot.current=[],d({kind:"note",tone:"info",text:`Resolve cancelled (${f} conflict${f===1?"":"s"} left untouched).`}),!0}return qr(),!0}if(l==="y"||l==="yes"){let f=ce.current.shift().plan;try{Yd({cwd:e,profileName:s},f),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${f.path} (sync base advanced).`})}catch(R){d({kind:"note",tone:"error",text:`Pull failed: ${R.message}`})}}else if(l==="n"||l==="no"){let f=ce.current.shift().plan;d({kind:"note",tone:"info",text:`Skipped ${f.path}.`})}else{let f=ce.current.length;return ce.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${f} article(s) left untouched).`}),!0}return qr(),!0},[e,s,qr,d]),Br=G(async c=>{d({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let l=await Wi({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),f=l.entries.filter(O=>O.status==="conflict"&&O.path).map(O=>O.path);if(i){if(!f.includes(i)){d({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}f=[i]}if(f.length===0){d({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let R=[];for(let O of f)try{R.push({plan:await Kd({cwd:e,profileName:s,relPath:O}),mode:"conflict"})}catch(h){d({kind:"note",tone:"error",text:`Could not load ${O} from Document360: ${h.message}`})}if(R.length===0)return;d({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=[],zt()}catch(l){d({kind:"note",tone:"error",text:`Could not compute sync status: ${l.message}`})}},[e,s,d,zt]),ga=G(c=>{let l=Zn.current;if(!l)return!1;if(Zn.current=null,Ue(),c.trim()!==l.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:f}=mi(e,l.targets);d({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)d({kind:"note",tone:"error",text:` \u2717 ${R.path}: ${R.error}`});return l.hadDevhints&&(d({kind:"note",tone:"warn",text:jo().join(`
394
- `)}),Vt(Zr())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
395
- ${ru}`}),Q("/init"),Kn(!1),!0},[e,d,Vt,Ue,Q]),xn=G(async c=>{let l=c.slice(1).trim().split(/\s+/),i=(l[0]??"").toLowerCase(),f=l.slice(1);if(Kn(!0),Bo(f)&&["write","check","review","reorder"].includes(i)){let h=In(e,s);if(h.length===0){d({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let p=w=>i==="write"?`/write ${Bl(f,w).join(" ")}`.trim():`/${i} ${[w,...f.filter(k=>k!=="--scope")].join(" ")}`.trim();if(h.length===1){xn(p(h[0].token));return}kt({cursor:0,rows:h,run:w=>{xn(p(w))}});return}if(lt(i,f)){let h=In(e,s);if(h.length>1){let p=f.filter(S=>S.startsWith("--")).join(" "),w=S=>`/${i}${S?` ${i==="write"?`--scope ${S}`:S}`:""}${p?` ${p}`:""} ${S?"":"--all"}`.replace(/\s+/g," ").trim(),k=h.reduce((S,U)=>S+U.count,0),$={token:"",label:i==="review"?`Everything \u2014 all ${k} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${h.length} categories`:`Everything \u2014 rewrite all ${k} planned articles`,count:k};kt({cursor:0,rows:[$,...h],run:S=>{xn(w(S))}});return}}let R=async h=>{let p=Zs(h);if(!Xo(e)){d({kind:"note",tone:"warn",text:"Screenshot capture is not set up in this repo yet \u2014 run d360-capture init in this repo's terminal, then d360-capture auth (once per machine)."});return}if(p.mode==="single"){await Wr([p.id],{runLine:[`/screenshot capture ${p.id}`,`/capture ${p.id}`]});return}if(p.mode==="all"||p.mode==="scope"){let{ready:k,captured:$}=ei(e,p.mode==="scope"?p.scope:void 0),S=[...k,...$];if(S.length===0){d({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Q("/screenshot");return}let U=p.mode==="scope"?[`/screenshot capture ${p.scope}`,`/capture ${p.scope}`]:["/screenshot capture --all","/capture --all"];await Wr(S,{runLine:U});return}let w=Ac(Pt(e));if(w.length===0){d({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Q("/screenshot");return}yt({cursor:0,rows:w,title:"Capture screenshots \u2014 pick what to shoot:"})},O=async()=>{let h=await sn();h.kind==="forward-to-agent"&&h.prompt&&await oe(h.prompt,{display:h.display,quietUser:!0});let p=ri(e);p&&d({kind:"note",tone:"info",text:p.join(`
396
- `)})};switch(i){case"help":wn({tab:0});return;case"exit":case"quit":je.current?.close(),r();return;case"clear":Pe(),_t.current=[],Kn(!1),Ue(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let h;try{h=De(e,s)}catch(p){d({kind:"note",tone:"error",text:p.message});return}d({kind:"note",tone:"info",text:`Profile "${h.name}" \u2192 ${h.connection.name} (${h.connection.apiUrl})${h.production?" \u26A0 PRODUCTION":""}`}),z(!0);try{let p=await lw(h.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},k=>d({kind:"note",tone:"info",text:k})),w=cw(h.name,p);if(dw(w),await zr(w,h.name,k=>d({kind:"note",tone:"info",text:k})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${h.name}" as ${vo(w)}`}),await fa(s),gn.current){let k=gn.current;gn.current=null;let $=_e(e,s);$.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${k}.`}),Q(k)):(d({kind:"note",tone:"warn",text:`${$.reason} (then ${k}.)`}),Q("/login"),gn.current=k)}else mn.current&&(we(mn.current,"\u21E5 tab to re-send your last prompt\u2026"),mn.current=null)}catch(p){d({kind:"note",tone:"error",text:`Login failed: ${p.message}`})}finally{z(!1),X(p=>p+1)}return}case"allow-prod":{let h=!1;try{h=De(e,s).production}catch{}if(!h){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Lt.current=!0,Pe(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let h=Ys(f.join(" ")),p=Be.current.uuid;if(!p){if(!h){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Dr.current=h,ft(h),an(`${gr} ${h}`),d({kind:"note",tone:"ok",text:`Session will be named "${h}" once it starts.`});return}if(!h){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Be.current.firstPrompt??"";Bd(w,e).then(k=>{k?(we(`/rename ${k}`),d({kind:"note",tone:"info",text:`Suggestion: "${k}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}$w(p,h),ft(h),an(`${gr} ${h}`),d({kind:"note",tone:"ok",text:`Session renamed to "${h}".`});return}case"profile":{let h=f[0],p=re(e);if(!h){let w=Object.entries(p?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let k=w.map(([U,T])=>({name:U,env:T.connection?.environment??"custom",prod:T.production===!0,who:Fr(U)})),$=s??p?.defaultProfile,S=Math.max(0,k.findIndex(U=>U.name===$));Mt({cursor:S,current:S,rows:k});return}if(h==="add"){let w=zs(e,f[1],f[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${f[1]}" created (environment: ${f[2]??f[1]}).`}),Hr(f[1],!1);return}if(!p?.profiles?.[h]){d({kind:"note",tone:"error",text:`Unknown profile "${h}". Create it: /profile add ${h} <environment>`});return}Hr(h,!0);return}case"doctor":await Ln(f,{cwd:e,version:o});return;case"genre":{await nr(f,{cwd:e});try{Rr.current=!(re(e)?.appType??Cw(e))}catch{}X(h=>h+1);return}case"roadmap":{if(f[0]?.toLowerCase()==="done"){let h=rr(e,f.slice(1).join(" ").trim());d({kind:"note",tone:h.ok?"ok":"warn",text:h.line}),X(p=>p+1);return}d({kind:"note",tone:"info",text:$i(e).join(`
397
- `)});return}case"mcp":await Io(f);return;case"init":{if(re(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let h=Dw().map(p=>({name:p,apiUrl:Aw(p).apiUrl}));Ut({cursor:0,rows:h});return}case"resume":{let h=f.join(" ").trim(),p=bw(e).filter($=>$.uuid!==Be.current.uuid);if(!h){if(!p.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}xt({query:"",cursor:0,sessions:p});return}let w=kw(e,h);if(!w){d({kind:"note",tone:"error",text:`No session matches "${h}".`});return}Pe(w.uuid),Be.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},ft(w.name),Ui(w.uuid),_t.current=[];let k=Ii(e,w.uuid);for(let $ of k)d($);d({kind:"note",tone:"ok",text:k.length?`Resumed "${w.name}" \u2014 restored ${k.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let h=f.join(" ").trim(),p;try{p=await Rn(e,s)}catch(k){d({kind:"note",tone:"error",text:`Could not list workspaces: ${k.message}`});return}if(!h){let k=p.workspaces.map(S=>({id:S.id,name:S.name??S.id,type:S.workspace_type}));if(k.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let $=Math.max(0,k.findIndex(S=>S.id===p.current));Wt({cursor:$,current:$,rows:k,profile:p.profile,projectId:p.projectId,projectName:p.projectName,environment:p.environment});return}let w=Gr(p.workspaces,h);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${h}".`});return}co(p.profile,p.projectId,w);return}case"project":{let h=f.join(" ").trim(),p;try{p=await ot(e,s)}catch(k){d({kind:"note",tone:"error",text:`Could not list projects: ${k.message} (signed in? try /login)`});return}if(!h){let k=p.projects.map(S=>({id:S.id,name:S.name??S.id,sub:S.sub_domain}));if(k.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let $=k.findIndex(S=>S.id===p.current);wt({cursor:Math.max(0,$),current:$,rows:k,profile:p.profile,environment:p.environment});return}let w=Yr(p.projects,h);if(!w){d({kind:"note",tone:"error",text:`No project matches "${h}". Available: ${p.projects.map(k=>k.name??k.id).join(", ")}`});return}po(p.profile,w);return}case"logout":{let h;try{h=De(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let p=fw(h);mw(e,h),Pe(),X(w=>w+1),d({kind:"note",tone:p?"ok":"info",text:p?`\u2713 Signed out of "${h}" and cleared its project/workspace selection.`:`Profile "${h}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Q("/login");return}case"publish":{if(!ro(c.trim()))return;if(f[0]==="--related"&&f[1]){let k=await Wo(e,s,f[1].replace(/\\/g,"/"));if(k.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Yt(k);return}let h=f.filter(k=>!k.startsWith("--"));if(h[0]){await Ur(h[0]);return}let p=f.includes("--all"),w=f.includes("--force");d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let k=await Wi({cwd:e,profileName:s}),{clean:$,conflicts:S}=Lo(k.entries),U=p&&w&&S.length>0,T=Mo(k.entries);if(T>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${T} article${T===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.`}),S.length>0&&!U&&d({kind:"note",tone:"warn",text:Oo(S.length)}),$.length===0&&!U){if(S.length>0){Q("/resolve");return}d({kind:"note",tone:"ok",text:T>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let B=k.counts["unknown-base"]??0;B>0&&d({kind:"note",tone:"info",text:`(${B} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),na("Reconciling structure on Document360 (order + related articles)\u2026");try{let I=await eu({cwd:e,profileName:s}),F=ou(await nu({cwd:e,profileName:s})),te=tu(I);te?d({kind:"note",tone:"info",text:te}):I.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${I.skipped}`}),F&&d({kind:"note",tone:"info",text:F}),d({kind:"note",tone:"ok",text:te||F?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(te||F)&&Q("/structure")}catch(I){d({kind:"note",tone:"warn",text:`Structure sync failed: ${I.message}`})}finally{na(null)}return}if(p){let B=(U?[...$,...S]:$).map(I=>I.path);await Yt(B),S.length>0&&!U&&Q("/resolve");return}Ft({cursor:0,rows:Sl($,S)})}catch(k){d({kind:"note",tone:"error",text:`Could not compute sync status: ${k.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!ro(c.trim()))return;await Br(f.find(h=>!h.startsWith("--")));return}case"preview":{let h=f.join(" ").trim();if(!h){let w=[];try{w=Object.keys(Gd(e,De(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}bt({query:"",cursor:0,paths:w});return}let p=iw(h)?h:Mi(e,h);if(ln(p)){try{d({kind:"preview",name:Vn(p),text:iu($r(p,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${p}: ${w.message}`})}return}if(Xw.test(h)){try{let w=De(e,s),k={profile:w.name,connection:w.connection},$=w.project.projectId??pw(k),S=await hw(k,$,h);d({kind:"preview",name:S.title??h,text:S.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${h}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let h=f[0]?.trim();if(!h){let $=Go(Vi(e));gt({cursor:$,current:$});return}let{lines:p,changed:w,effective:k}=_n(e,h);for(let $ of p)d({kind:"note",tone:$.startsWith("\u26A0")?"warn":$.startsWith("\u2713")?"ok":"info",text:$});w&&(sa($=>$+1),je.current?.setModel(k));return}case"convert":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:h,run:p}=Cs(f),w=Nw(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let k=Rs(w,h);if(k.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${h}". (${w.length} are tracked overall.)`});return}let $=Fi(k),S=3,U=`/convert${h?` --scope ${h}`:""} --run`,T=vr(e,"light");if(!p){let I=Xd({files:Ss(e,k),op:"convert",model:T.model}),F=h?`Scope: ${h} (${k.length} of ${w.length} tracked)
398
- `:"",te=`
399
- Model: ${T.model}${T.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:F+Ts($,I,S).join(`
400
- `)+te}),Q(U);return}ht.current=Date.now(),Et(0),D(!0);let B=new AbortController;ke.current=B,ne({verb:"Converting",total:$.length,done:0,active:[],rows:Bn($),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${k.length} articles across ${$.length} partitions (\u2264${S} agents at once) on ${T.model}\u2026 (esc to stop)`});try{for await(let I of xr({cwd:e,partitions:$,promptFor:Ps,concurrency:S,profileName:s,allowProdWrites:Lt.current,model:T.model,signal:B.signal}))if(I.type==="partition_status")I.status==="running"?ne(F=>F&&{...F,active:[...F.active,I.label],rows:Le(F.rows,I.label,"active"),lastAt:Date.now()}):ne(F=>F&&{...F,active:F.active.filter(te=>te!==I.label),done:F.done+1,rows:Le(F.rows,I.label,I.status==="done"?"done":"failed"),lastAt:Date.now()});else if(I.type==="partition_event")ne(F=>{if(!F)return F;let te={...F,lastAt:Date.now()};return I.event.type==="tool"?te.tools=F.tools+1:I.event.type==="text"&&(te.chars=F.chars+I.event.delta.length),te});else if(I.type==="run_done"){Bt(We=>We+I.totalCostUsd),qt(We=>We+I.results.reduce((mo,go)=>mo+go.outputTokens,0));let F=I.aborted?"Stopped. ":"",te=t.kind==="api"?"api":"subscription";d({kind:"note",tone:I.aborted?"warn":I.ok?"ok":"warn",text:F+Ds(I.results,$,te).join(`
401
- `)})}}catch(I){d({kind:"note",tone:"error",text:`Convert run failed: ${I.message}`})}finally{ke.current=null,ne(null),D(!1),X(I=>I+1)}return}case"write":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=Iw(e);if(h.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:p,path:w,preview:k,concurrency:$,rewrite:S}=Es(f),{docsDir:U,targets:T,reason:B,rewriting:I}=Us(e,h,{scope:p,path:w,rewrite:S});if(T.length===0){d({kind:"note",tone:"warn",text:B??"Nothing to write."});return}I&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${T.length} already-written article${T.length===1?"":"s"} (overwrites them; git has your baseline).`});let F=Fi(T),te=js($),We=vr(e,"standard"),mo=!!w;if(k&&!mo){let J=Xd({files:Is(e,h,T),op:"write",model:We.model}),ie=p?`Scope: ${p} (${T.length} pending)
390
+ cwd: ${e}`}),Lr()},[]),Ae(()=>{let c=setInterval(()=>{Lr()},ny);return()=>clearInterval(c)},[Lr]),Ae(()=>{if(N||he||Pr||Yn.current||me!==null||He.length>0||P!==""||yn!==null||ce.current.length>0||Zn.current||Er)return;let c=vt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&oo(c.rec,{silent:!0})},[N,he,me,He,P,yn,Er,K,vt,Pr]),Ae(()=>{let c=null,l=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let f=`${Me.columns??80}x${Me.rows??24}`;f!==la.current&&(la.current=f,xu(R=>R+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+bl(_t.current,et())+"\x1B[?2026l")},80))},400)};return Me.on("resize",i),()=>{c&&clearTimeout(c),l&&clearTimeout(l),Me.off("resize",i)}},[Me,et]);let Ee=Math.max(20,(Me.columns??80)-1),da=Ui(()=>zw(e,s),[e,s,K]),Mr=(()=>{if(yu)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Tr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Tr?` v${Tr}`:""}\u2026`,isSetup:!0};if(so)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 vu?{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 l=Wi(e,(c.docsDir??cu).replace(/\/+$/,"")),i=(()=>{try{return ln(l)&&iw(l).length>0}catch{return!1}})();try{let f=De(e,s),R=At(f.name);if(!(!!R&&!(dt(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:Kw,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),$n=ul(P),ua=$n.length>0&&!N,Ur=u!==null?Fd(u,8,Ee):null,ao=Re?Re.paths.filter(c=>!Re.query||c.toLowerCase().includes(Re.query.toLowerCase())).slice(0,8):[],lo=Se?Se.sessions.filter(c=>{let l=Se.query.toLowerCase();return!l||c.name.toLowerCase().includes(l)||c.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],Pe=G((c,l)=>{je.current?.close(),je.current=Bd({cwd:e,resume:c,profileName:l??s,allowProdWrites:Lt.current}),c||(Be.current={uuid:null,firstPrompt:null,titleFired:!1},ft(null)),Ht(0),Bt(0)},[e,s]),pa=G((c,l,i)=>{if(Xw.test(c))try{let f=De(e,s),R=typeof l.project_id=="string"&&l.project_id||f.project.projectId,O=pr(l,i),h=[],p=hr(i);c.endsWith("publish_article")&&p&&h.push(`Live: ${p}`);let w=fr(i);w?h.push(`Preview: ${w}`):O&&R&&h.push(`Preview: ${ur(f.connection.portalUrl,R,O,f.project.languageCode??"en")}`),h.length>0&&d({kind:"link",lines:h})}catch{}},[e,s,d]),te=G(async(c,l)=>{Kn(!0),Yn.current=!1,Ue(),pt([]),hn(null),Ir(null);let i=zn.current;l?.quietUser||d({kind:"user",text:l?.echoDisplay&&l.display?l.display:c});let f=Be.current;f.firstPrompt||(f.firstPrompt=l?.display??c),ht.current=Date.now(),Et(0),D(!0),Jn.current.clear();let R="",O=!1,h=!1,p="",w={num:0,closed:!1,cueSeen:!1},k=null,$=()=>{k||(k=setTimeout(()=>{k=null,g(p.length>0?p:null)},60))},S=()=>{k&&clearTimeout(k),k=null,g(null)},U=(T=!1)=>{let{head:B,keep:I}=qd(p,T);B.trim()&&d({kind:"assistant",text:_i(B.trimEnd(),w)}),p=I,S()};try{for await(let T of je.current.send(c))if(T.type==="session"){if(!f.uuid){f.uuid=T.sessionId;let B=new Date().toISOString(),I=Ar.current,F=I??yw(f.firstPrompt??"session");kw({uuid:T.sessionId,name:F,renamed:!!I,titled:!1,cwd:e,firstPrompt:f.firstPrompt??"",createdAt:B,updatedAt:B}),ft(F),Ar.current=null}}else if(T.type==="text"){p+=T.delta,R+=T.delta;let B=Hd(p);if(B>0){let I=p.slice(0,B).trimEnd();I&&d({kind:"assistant",text:_i(I,w)}),p=p.slice(B)}$(),Et(I=>I+T.delta.length)}else if(T.type==="tool"){O=!0;let B=cr(T.name,T.input);B&&(U(),d({kind:"tool",title:B.title,sep:B.sep,arg:B.arg}),Jn.current.set(T.id,{name:T.name,input:T.input}))}else if(T.type==="article_diff"){let B=Xe(T.oldContent,T.newContent,et());B&&(U(),d({kind:"diff",added:B.added,removed:B.removed,lines:B.lines,hidden:B.hidden}))}else if(T.type==="tool_result"){T.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(T.output)&&(to.current=!0);let B=Jn.current.get(T.id);if(B){Jn.current.delete(T.id),U();let I=dr(T.output,4,T.isError?void 0:B.name,B.input);d({kind:"tool-result",lines:I.lines,hidden:I.hidden,isError:T.isError}),T.isError||pa(B.name,B.input,T.output)}}else if(T.type==="result"){U(!0),Ht(I=>I+T.outputTokens),Bt(I=>I+T.costUsd);let B=T.inputTokens+T.cacheReadTokens+T.cacheCreationTokens;if(d({kind:"done",seconds:Math.round((Date.now()-ht.current)/1e3),tokens:T.outputTokens,costUsd:T.costUsd,ok:T.ok,...B>0?{inTokens:B,cachedPct:Math.round(T.cacheReadTokens/B*100)}:{}}),!h&&!O&&!R.trim()&&!fn.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),T.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(R))try{let I=Zd(e);if(ln(I)){let F=xr(I,"utf8").trim();F&&(Or(F),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(T.ok&&w.cueSeen)Qi(!0),pt([]);else{let I=T.ok?Td(R,nn.map(F=>F.name)):[];if(I.length>0)Q(I[0]);else if(T.ok&&R.trim()){let F=vt(!1);F.kind==="recommend"&&(F.rec.lead||F.rec.picker)||vw(c,R,e).then(ne=>{ne&&zn.current===i&&we(ne)}).catch(()=>{})}}if(f.uuid&&(Fi(f.uuid),!f.titleFired)){f.titleFired=!0;let I=f.uuid,F=f.firstPrompt;F&&Vd(F,e).then(ne=>{ne&&(ww(I,ne),ft(ne))}).catch(()=>{})}}else T.type==="error"&&(U(!0),h=!0,T.kind==="auth"&&(to.current=!0),d({kind:"note",text:`agent error: ${T.message}`,tone:"error"}))}finally{D(!1),S(),X(T=>T+1),Be.current.uuid&&Cd(e,Be.current.uuid,_t.current),to.current?(to.current=!1,mn.current=l?.display??c,we("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):mn.current=null,fn.current&&(fn.current=!1,$t.current.length>0&&(d({kind:"note",tone:"info",text:`(${$t.current.length} queued message(s) discarded)`}),$t.current=[],jr([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,pa,et,we,Q,Ue,vt]),Yt=G(async c=>{let l=Cr(e,"standard");ht.current=Date.now(),Et(0),D(!0);let i=new AbortController;ke.current=i;let f=async(R,O)=>{let h=Hi(R);oe({verb:"Publishing",total:h.length,done:0,active:[],rows:Bn(h),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:O?`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 ${h.length} partition${h.length===1?"":"s"} (\u2264${En} agents at once) on ${l.model}\u2026 (esc to stop)`});let p=!1;for await(let w of vr({cwd:e,partitions:h,promptFor:k=>Wo(k.paths),concurrency:En,profileName:s,allowProdWrites:Lt.current,model:l.model,signal:i.signal}))if(w.type==="partition_status")w.status==="running"?oe(k=>k&&{...k,active:[...k.active,w.label],rows:Le(k.rows,w.label,"active"),lastAt:Date.now()}):oe(k=>k&&{...k,active:k.active.filter($=>$!==w.label),done:k.done+1,rows:Le(k.rows,w.label,w.status==="done"?"done":"failed"),lastAt:Date.now()});else if(w.type==="partition_event")oe(k=>{if(!k)return k;let $={...k,lastAt:Date.now()};return w.event.type==="tool"?$.tools=k.tools+1:w.event.type==="text"&&($.chars=k.chars+w.event.delta.length),$});else if(w.type==="run_done"){p=w.aborted,Bt(U=>U+w.totalCostUsd),Ht(U=>U+w.results.reduce((T,B)=>T+B.outputTokens,0));let k=w.aborted?"Stopped. ":"",$=t.kind==="api"?"api":"subscription";d({kind:"note",tone:w.aborted?"warn":w.ok?"ok":"warn",text:k+ms(w.results,h,$).join(`
391
+ `)});let S=fs(e,s);if(S&&d({kind:"note",tone:"info",text:S}),!w.aborted){try{let U=await tu({cwd:e,profileName:s}),T=nu(U);T?d({kind:"note",tone:"info",text:T}):U.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${U.skipped}`})}catch(U){d({kind:"note",tone:"warn",text:`Order sync failed: ${U.message}`})}try{let U=ru(await ou({cwd:e,profileName:s}));U&&d({kind:"note",tone:"info",text:U})}catch(U){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${U.message}`})}}}return p};try{if(!await f(c,!1)){let O=await gs(e,s,c);O.length>0&&await f(O,!0)}}catch(R){d({kind:"note",tone:"error",text:`Publish run failed: ${R.message}`})}finally{ke.current=null,oe(null),D(!1),X(R=>R+1)}},[e,s,d,t]),Wr=G(async c=>{await te(ps(c),{display:`/publish ${c}`,quietUser:!0});try{let l=await Fo(e,s,c.replace(/\\/g,"/"));l.length>0&&(hn(`Related articles not yet published (${l.length}):`),pt([`/publish --related ${c}`,...l.map(i=>`/publish ${i}`)]))}catch{}},[e,s,te]),co=G(c=>{if(c)try{for(let l of Array.isArray(c)?c:[c]){let i=td(e,l);if(!i)continue;sr(e,i.title).ok&&d({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${i.title}`});return}}catch{}},[e,d]),ha=G(async(c,l)=>{let f=Ew(c,3),R=Cr(e,"standard");ht.current=Date.now(),Et(0),D(!0);let O=new AbortController;ke.current=O,oe({verb:"Authoring",unit:"spec",total:f.length,done:0,active:[],rows:Bn(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({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 h=!1;try{for await(let p of vr({cwd:e,partitions:f,promptFor:Tc,concurrency:6,profileName:s,allowProdWrites:Lt.current,model:R.model,signal:O.signal}))if(p.type==="partition_status")p.status==="running"?oe(w=>w&&{...w,active:[...w.active,p.label],rows:Le(w.rows,p.label,"active"),lastAt:Date.now()}):oe(w=>w&&{...w,active:w.active.filter(k=>k!==p.label),done:w.done+1,rows:Le(w.rows,p.label,p.status==="done"?"done":"failed"),lastAt:Date.now()});else if(p.type==="partition_event")oe(w=>{if(!w)return w;let k={...w,lastAt:Date.now()};return p.event.type==="tool"?k.tools=w.tools+1:p.event.type==="text"&&(k.chars=w.chars+p.event.delta.length),k});else if(p.type==="run_done"){Bt(S=>S+p.totalCostUsd),Ht(S=>S+p.results.reduce((U,T)=>U+T.outputTokens,0));let w=p.results.filter(S=>S.ok).length,k=p.aborted?"Stopped. ":"";h=!p.aborted&&l.setup;let $=p.aborted?"":h?" Refreshing the capture-setup checklist\u2026":" Next: /screenshot capture --all (or /screenshot checklist first for the staging checklist).";d({kind:"note",tone:p.aborted?"warn":p.ok?"ok":"warn",text:`${k}Authored specs \u2014 ${w}/${p.results.length} batches ok.${$}`}),!p.aborted&&p.ok&&co(l.runLine)}}catch(p){d({kind:"note",tone:"error",text:`Spec authoring failed: ${p.message}`})}finally{ke.current=null,oe(null),D(!1),X(p=>p+1)}if(h){let p=await sn();p.kind==="forward-to-agent"&&p.prompt&&await te(p.prompt,{display:p.display,quietUser:!0});let w=ii(e);w&&d({kind:"note",tone:"info",text:w.join(`
392
+ `)})}},[e,s,d,te,co]),fa=G(async c=>{let l=await Xo([c]);l.kind==="forward-to-agent"&&l.prompt&&await te(l.prompt,{display:l.display,quietUser:!0}),Sc(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]),Fr=G(async(c,l)=>{if(!Qo(e)){await te(ri(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}D(!0);let i=new AbortController;ke.current=i;let f=c.map($=>({label:$,items:1,status:"pending"}));oe({verb:"Capturing",unit:"screenshot",total:c.length,done:0,active:[],rows:f,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({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 R=Date.now(),O=[];try{for(let $ of c){if(i.signal.aborted)break;oe(I=>I&&{...I,active:[$],rows:Le(I.rows,$,"active"),lastAt:Date.now()});let{exitCode:S,output:U}=await oi({cwd:e,id:$,signal:i.signal,stdio:"pipe"});if(Ic(S,U)){d({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 T=i.signal.aborted&&S!==0?"failed":ni(e,$,S,R),B=T==="captured"?void 0:T==="skipped"?Ec(U)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Nc(U);O.push({id:$,outcome:T,detail:B}),oe(I=>I&&{...I,active:[],done:I.done+1,rows:Le(I.rows,$,T==="captured"?"done":"failed"),lastAt:Date.now()})}}catch($){d({kind:"note",tone:"error",text:`Capture run failed: ${$.message}`})}finally{ke.current=null,oe(null),D(!1),X($=>$+1)}if(O.length===0)return;let h=O.filter($=>$.outcome==="captured"),p=O.filter($=>$.outcome==="skipped"),w=O.filter($=>$.outcome==="failed"),k=c.length-O.length;d({kind:"note",tone:w.length?"warn":h.length?"ok":"info",text:`\u2713 ${h.length} captured`+(p.length?` \xB7 \u2298 ${p.length} skipped`:"")+(w.length?` \xB7 \u2717 ${w.length} failed`:"")+(k?` \xB7 ${k} not run (stopped)`:"")});for(let $ of p)d({kind:"note",tone:"info",text:`\u2298 ${$.id} \u2014 ${$.detail}`});for(let $ of w)$.detail&&d({kind:"note",tone:"error",text:`\u2717 ${$.id}
393
+ ${$.detail}`});if(h.length>0){let $=_c(e,h.map(U=>U.id)),S=$.length===1?`/publish ${$[0]}`:"/publish";be(`PNG${h.length===1?"":"s"} saved to the screenshots folder \u2014 publish to put ${h.length===1?"it":"them"} in the article${$.length===1?"":"s"}: ${S}`,{kind:"cmd",cmd:S,reason:""})}else if(p.length>0){let $=c.length===1?`/screenshot capture ${c[0]}`:"/screenshot capture";be(null,{kind:"cmd",cmd:$,reason:""})}O.length===c.length&&w.length===0&&p.length===0&&co(l?.runLine)},[e,d,be,te,co]),qr=G(c=>{let l=At(c);if(!l||dt(l)&&!l.refreshToken)return null;let i={...dn(l.idToken)??{},...dn(l.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),Hr=G((c,l)=>{if(l){let i=re(e);i&&(i.defaultProfile=c,Gd(i,e))}a(c),Pe(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${l?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),qr(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),Q("/login")),X(i=>i+1)},[e,d,Pe,qr,Q]),uo=G((c,l,i)=>{bo(e,c,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Pe(),Yd(e,c)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:en(Zt(e)).join(`
394
+ `)}),Vt(Ct()),kn.current=Ie(e).status==="current",Gt.current=Ke(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,Pe,Vt]),po=G(async c=>{let l;try{l=await Rn(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Q("/workspace");return}if(l.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=l.workspaces.filter(R=>(R.workspace_type??"").toLowerCase()!=="apidocumentation"),f=i.length>0?i:l.workspaces;if(f.length===1){let R=f[0],O=l.workspaces.length-f.length;d({kind:"note",tone:"ok",text:`Selected the "${R.name??R.id}" workspace${O>0?" (skipped the API-documentation workspace)":""}.`}),uo(l.profile,l.projectId,R);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${f.length} available).`}),Q("/workspace")},[e,d,uo,Q]),ho=G((c,l)=>{$o(e,c,l.id,l.name),d({kind:"note",tone:"ok",text:`Project set to "${l.name??l.id}" (agent restarted).`}),Pe(),po(c)},[e,d,Pe,po]),ma=G(async c=>{let l;try{l=De(e,c)}catch{return}if(!l.project.workspaceId){if(l.project.projectId){if(!l.project.projectName)try{let{projects:i}=await ot(e,l.name),f=i.find(R=>R.id===l.project.projectId);f?.name&&Fw(e,l.name,{projectName:f.name})}catch{}await po(l.name);return}try{let{projects:i}=await ot(e,l.name);if(i.length===1){let f=i[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${f.name??f.id}".`}),ho(l.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}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),wt({cursor:0,current:-1,rows:f,profile:l.name,environment:l.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Q("/project")}},[e,d,po,ho,Q]),zt=G(()=>{let c=ce.current[0];if(!c)return;Ue();let{plan:l,mode:i}=c;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let R of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${R}`});l.overwritesLocalChanges&&i==="pull"&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let f=Xe(l.oldContent,l.newContent,et());d(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"?(d({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),d({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,et,Ue]),Br=G(()=>{if(ce.current.length>0){zt();return}let c=Ot.current;Ot.current=[],c.length>0?(d({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),Yt(c)):Q("/pull")},[zt,d,Yt,Q]),ga=G(c=>{if(ce.current.length===0)return!1;let l=c.trim().toLowerCase(),i=ce.current[0];if(i.mode==="conflict"){if(l==="l"||l==="local")ce.current.shift(),Ot.current.push(i.plan.path),d({kind:"note",tone:"info",text:`Keeping local ${i.plan.path} \u2014 will publish over the portal.`});else if(l==="p"||l==="portal"){ce.current.shift();try{zd({cwd:e,profileName:s},i.plan),d({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(f){d({kind:"note",tone:"error",text:`Take-portal failed: ${f.message}`})}}else if(l==="s"||l==="skip"||l==="n")ce.current.shift(),d({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let f=ce.current.length;return ce.current=[],Ot.current=[],d({kind:"note",tone:"info",text:`Resolve cancelled (${f} conflict${f===1?"":"s"} left untouched).`}),!0}return Br(),!0}if(l==="y"||l==="yes"){let f=ce.current.shift().plan;try{zd({cwd:e,profileName:s},f),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${f.path} (sync base advanced).`})}catch(R){d({kind:"note",tone:"error",text:`Pull failed: ${R.message}`})}}else if(l==="n"||l==="no"){let f=ce.current.shift().plan;d({kind:"note",tone:"info",text:`Skipped ${f.path}.`})}else{let f=ce.current.length;return ce.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${f} article(s) left untouched).`}),!0}return Br(),!0},[e,s,Br,d]),Vr=G(async c=>{d({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let l=await qi({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),f=l.entries.filter(O=>O.status==="conflict"&&O.path).map(O=>O.path);if(i){if(!f.includes(i)){d({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}f=[i]}if(f.length===0){d({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let R=[];for(let O of f)try{R.push({plan:await Xd({cwd:e,profileName:s,relPath:O}),mode:"conflict"})}catch(h){d({kind:"note",tone:"error",text:`Could not load ${O} from Document360: ${h.message}`})}if(R.length===0)return;d({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=[],zt()}catch(l){d({kind:"note",tone:"error",text:`Could not compute sync status: ${l.message}`})}},[e,s,d,zt]),wa=G(c=>{let l=Zn.current;if(!l)return!1;if(Zn.current=null,Ue(),c.trim()!==l.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:f}=wi(e,l.targets);d({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)d({kind:"note",tone:"error",text:` \u2717 ${R.path}: ${R.error}`});return l.hadDevhints&&(d({kind:"note",tone:"warn",text:Eo().join(`
395
+ `)}),Vt(es())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
396
+ ${su}`}),Q("/init"),Kn(!1),!0},[e,d,Vt,Ue,Q]),xn=G(async c=>{let l=c.slice(1).trim().split(/\s+/),i=(l[0]??"").toLowerCase(),f=l.slice(1);if(Kn(!0),Vo(f)&&["write","check","review","reorder"].includes(i)){let h=In(e,s);if(h.length===0){d({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let p=w=>i==="write"?`/write ${Vl(f,w).join(" ")}`.trim():`/${i} ${[w,...f.filter(k=>k!=="--scope")].join(" ")}`.trim();if(h.length===1){xn(p(h[0].token));return}kt({cursor:0,rows:h,run:w=>{xn(p(w))}});return}if(lt(i,f)){let h=In(e,s);if(h.length>1){let p=f.filter(S=>S.startsWith("--")).join(" "),w=S=>`/${i}${S?` ${i==="write"?`--scope ${S}`:S}`:""}${p?` ${p}`:""} ${S?"":"--all"}`.replace(/\s+/g," ").trim(),k=h.reduce((S,U)=>S+U.count,0),$={token:"",label:i==="review"?`Everything \u2014 all ${k} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${h.length} categories`:`Everything \u2014 rewrite all ${k} planned articles`,count:k};kt({cursor:0,rows:[$,...h],run:S=>{xn(w(S))}});return}}let R=async h=>{let p=ei(h);if(!Qo(e)){await te(ri(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(p.mode==="single"){await Fr([p.id],{runLine:[`/screenshot capture ${p.id}`,`/capture ${p.id}`]});return}if(p.mode==="all"||p.mode==="scope"){let{ready:k,captured:$}=ti(e,p.mode==="scope"?p.scope:void 0),S=[...k,...$];if(S.length===0){d({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Q("/screenshot");return}let U=p.mode==="scope"?[`/screenshot capture ${p.scope}`,`/capture ${p.scope}`]:["/screenshot capture --all","/capture --all"];await Fr(S,{runLine:U});return}let w=jc(Pt(e));if(w.length===0){d({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Q("/screenshot");return}yt({cursor:0,rows:w,title:"Capture screenshots \u2014 pick what to shoot:"})},O=async()=>{let h=await sn();h.kind==="forward-to-agent"&&h.prompt&&await te(h.prompt,{display:h.display,quietUser:!0});let p=ii(e);p&&d({kind:"note",tone:"info",text:p.join(`
397
+ `)})};switch(i){case"help":wn({tab:0});return;case"exit":case"quit":je.current?.close(),r();return;case"clear":Pe(),_t.current=[],Kn(!1),Ue(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let h;try{h=De(e,s)}catch(p){d({kind:"note",tone:"error",text:p.message});return}d({kind:"note",tone:"info",text:`Profile "${h.name}" \u2192 ${h.connection.name} (${h.connection.apiUrl})${h.production?" \u26A0 PRODUCTION":""}`}),z(!0);try{let p=await cw(h.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},k=>d({kind:"note",tone:"info",text:k})),w=dw(h.name,p);if(uw(w),await Kr(w,h.name,k=>d({kind:"note",tone:"info",text:k})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${h.name}" as ${Co(w)}`}),await ma(s),gn.current){let k=gn.current;gn.current=null;let $=_e(e,s);$.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${k}.`}),Q(k)):(d({kind:"note",tone:"warn",text:`${$.reason} (then ${k}.)`}),Q("/login"),gn.current=k)}else mn.current&&(we(mn.current,"\u21E5 tab to re-send your last prompt\u2026"),mn.current=null)}catch(p){d({kind:"note",tone:"error",text:`Login failed: ${p.message}`})}finally{z(!1),X(p=>p+1)}return}case"allow-prod":{let h=!1;try{h=De(e,s).production}catch{}if(!h){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Lt.current=!0,Pe(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let h=zs(f.join(" ")),p=Be.current.uuid;if(!p){if(!h){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Ar.current=h,ft(h),an(`${wr} ${h}`),d({kind:"note",tone:"ok",text:`Session will be named "${h}" once it starts.`});return}if(!h){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Be.current.firstPrompt??"";Vd(w,e).then(k=>{k?(we(`/rename ${k}`),d({kind:"note",tone:"info",text:`Suggestion: "${k}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}xw(p,h),ft(h),an(`${wr} ${h}`),d({kind:"note",tone:"ok",text:`Session renamed to "${h}".`});return}case"profile":{let h=f[0],p=re(e);if(!h){let w=Object.entries(p?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let k=w.map(([U,T])=>({name:U,env:T.connection?.environment??"custom",prod:T.production===!0,who:qr(U)})),$=s??p?.defaultProfile,S=Math.max(0,k.findIndex(U=>U.name===$));Mt({cursor:S,current:S,rows:k});return}if(h==="add"){let w=Ks(e,f[1],f[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${f[1]}" created (environment: ${f[2]??f[1]}).`}),Hr(f[1],!1);return}if(!p?.profiles?.[h]){d({kind:"note",tone:"error",text:`Unknown profile "${h}". Create it: /profile add ${h} <environment>`});return}Hr(h,!0);return}case"doctor":await Ln(f,{cwd:e,version:o});return;case"genre":{await or(f,{cwd:e});try{Sr.current=!(re(e)?.appType??Rw(e))}catch{}X(h=>h+1);return}case"roadmap":{if(f[0]?.toLowerCase()==="done"){let h=sr(e,f.slice(1).join(" ").trim());d({kind:"note",tone:h.ok?"ok":"warn",text:h.line}),X(p=>p+1);return}d({kind:"note",tone:"info",text:vi(e).join(`
398
+ `)});return}case"mcp":await _o(f);return;case"init":{if(re(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let h=Aw().map(p=>({name:p,apiUrl:jw(p).apiUrl}));Ut({cursor:0,rows:h});return}case"resume":{let h=f.join(" ").trim(),p=$w(e).filter($=>$.uuid!==Be.current.uuid);if(!h){if(!p.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}xt({query:"",cursor:0,sessions:p});return}let w=bw(e,h);if(!w){d({kind:"note",tone:"error",text:`No session matches "${h}".`});return}Pe(w.uuid),Be.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},ft(w.name),Fi(w.uuid),_t.current=[];let k=Li(e,w.uuid);for(let $ of k)d($);d({kind:"note",tone:"ok",text:k.length?`Resumed "${w.name}" \u2014 restored ${k.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let h=f.join(" ").trim(),p;try{p=await Rn(e,s)}catch(k){d({kind:"note",tone:"error",text:`Could not list workspaces: ${k.message}`});return}if(!h){let k=p.workspaces.map(S=>({id:S.id,name:S.name??S.id,type:S.workspace_type}));if(k.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let $=Math.max(0,k.findIndex(S=>S.id===p.current));Wt({cursor:$,current:$,rows:k,profile:p.profile,projectId:p.projectId,projectName:p.projectName,environment:p.environment});return}let w=Yr(p.workspaces,h);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${h}".`});return}uo(p.profile,p.projectId,w);return}case"project":{let h=f.join(" ").trim(),p;try{p=await ot(e,s)}catch(k){d({kind:"note",tone:"error",text:`Could not list projects: ${k.message} (signed in? try /login)`});return}if(!h){let k=p.projects.map(S=>({id:S.id,name:S.name??S.id,sub:S.sub_domain}));if(k.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let $=k.findIndex(S=>S.id===p.current);wt({cursor:Math.max(0,$),current:$,rows:k,profile:p.profile,environment:p.environment});return}let w=zr(p.projects,h);if(!w){d({kind:"note",tone:"error",text:`No project matches "${h}". Available: ${p.projects.map(k=>k.name??k.id).join(", ")}`});return}ho(p.profile,w);return}case"logout":{let h;try{h=De(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let p=mw(h);gw(e,h),Pe(),X(w=>w+1),d({kind:"note",tone:p?"ok":"info",text:p?`\u2713 Signed out of "${h}" and cleared its project/workspace selection.`:`Profile "${h}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Q("/login");return}case"publish":{if(!ro(c.trim()))return;if(f[0]==="--related"&&f[1]){let k=await Fo(e,s,f[1].replace(/\\/g,"/"));if(k.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Yt(k);return}let h=f.filter(k=>!k.startsWith("--"));if(h[0]){await Wr(h[0]);return}let p=f.includes("--all"),w=f.includes("--force");d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let k=await qi({cwd:e,profileName:s}),{clean:$,conflicts:S}=Oo(k.entries),U=p&&w&&S.length>0,T=Uo(k.entries);if(T>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${T} article${T===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.`}),S.length>0&&!U&&d({kind:"note",tone:"warn",text:Mo(S.length)}),$.length===0&&!U){if(S.length>0){Q("/resolve");return}d({kind:"note",tone:"ok",text:T>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let B=k.counts["unknown-base"]??0;B>0&&d({kind:"note",tone:"info",text:`(${B} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),ra("Reconciling structure on Document360 (order + related articles)\u2026");try{let I=await tu({cwd:e,profileName:s}),F=ru(await ou({cwd:e,profileName:s})),ne=nu(I);ne?d({kind:"note",tone:"info",text:ne}):I.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${I.skipped}`}),F&&d({kind:"note",tone:"info",text:F}),d({kind:"note",tone:"ok",text:ne||F?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(ne||F)&&Q("/structure")}catch(I){d({kind:"note",tone:"warn",text:`Structure sync failed: ${I.message}`})}finally{ra(null)}return}if(p){let B=(U?[...$,...S]:$).map(I=>I.path);await Yt(B),S.length>0&&!U&&Q("/resolve");return}Ft({cursor:0,rows:Pl($,S)})}catch(k){d({kind:"note",tone:"error",text:`Could not compute sync status: ${k.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!ro(c.trim()))return;await Vr(f.find(h=>!h.startsWith("--")));return}case"preview":{let h=f.join(" ").trim();if(!h){let w=[];try{w=Object.keys(Yd(e,De(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}bt({query:"",cursor:0,paths:w});return}let p=aw(h)?h:Wi(e,h);if(ln(p)){try{d({kind:"preview",name:Vn(p),text:au(xr(p,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${p}: ${w.message}`})}return}if(Qw.test(h)){try{let w=De(e,s),k={profile:w.name,connection:w.connection},$=w.project.projectId??hw(k),S=await fw(k,$,h);d({kind:"preview",name:S.title??h,text:S.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${h}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let h=f[0]?.trim();if(!h){let $=Yo(Yi(e));gt({cursor:$,current:$});return}let{lines:p,changed:w,effective:k}=_n(e,h);for(let $ of p)d({kind:"note",tone:$.startsWith("\u26A0")?"warn":$.startsWith("\u2713")?"ok":"info",text:$});w&&(aa($=>$+1),je.current?.setModel(k));return}case"convert":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:h,run:p}=Rs(f),w=Iw(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let k=Ss(w,h);if(k.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${h}". (${w.length} are tracked overall.)`});return}let $=Hi(k),S=3,U=`/convert${h?` --scope ${h}`:""} --run`,T=Cr(e,"light");if(!p){let I=Qd({files:Ps(e,k),op:"convert",model:T.model}),F=h?`Scope: ${h} (${k.length} of ${w.length} tracked)
399
+ `:"",ne=`
400
+ Model: ${T.model}${T.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:F+Ds($,I,S).join(`
401
+ `)+ne}),Q(U);return}ht.current=Date.now(),Et(0),D(!0);let B=new AbortController;ke.current=B,oe({verb:"Converting",total:$.length,done:0,active:[],rows:Bn($),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${k.length} articles across ${$.length} partitions (\u2264${S} agents at once) on ${T.model}\u2026 (esc to stop)`});try{for await(let I of vr({cwd:e,partitions:$,promptFor:Ts,concurrency:S,profileName:s,allowProdWrites:Lt.current,model:T.model,signal:B.signal}))if(I.type==="partition_status")I.status==="running"?oe(F=>F&&{...F,active:[...F.active,I.label],rows:Le(F.rows,I.label,"active"),lastAt:Date.now()}):oe(F=>F&&{...F,active:F.active.filter(ne=>ne!==I.label),done:F.done+1,rows:Le(F.rows,I.label,I.status==="done"?"done":"failed"),lastAt:Date.now()});else if(I.type==="partition_event")oe(F=>{if(!F)return F;let ne={...F,lastAt:Date.now()};return I.event.type==="tool"?ne.tools=F.tools+1:I.event.type==="text"&&(ne.chars=F.chars+I.event.delta.length),ne});else if(I.type==="run_done"){Bt(We=>We+I.totalCostUsd),Ht(We=>We+I.results.reduce((go,wo)=>go+wo.outputTokens,0));let F=I.aborted?"Stopped. ":"",ne=t.kind==="api"?"api":"subscription";d({kind:"note",tone:I.aborted?"warn":I.ok?"ok":"warn",text:F+As(I.results,$,ne).join(`
402
+ `)})}}catch(I){d({kind:"note",tone:"error",text:`Convert run failed: ${I.message}`})}finally{ke.current=null,oe(null),D(!1),X(I=>I+1)}return}case"write":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=_w(e);if(h.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:p,path:w,preview:k,concurrency:$,rewrite:S}=Ns(f),{docsDir:U,targets:T,reason:B,rewriting:I}=Ws(e,h,{scope:p,path:w,rewrite:S});if(T.length===0){d({kind:"note",tone:"warn",text:B??"Nothing to write."});return}I&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${T.length} already-written article${T.length===1?"":"s"} (overwrites them; git has your baseline).`});let F=Hi(T),ne=Es($),We=Cr(e,"standard"),go=!!w;if(k&&!go){let J=Qd({files:_s(e,h,T),op:"write",model:We.model}),ie=p?`Scope: ${p} (${T.length} pending)
402
403
  `:"",fe=`
403
- Model: ${We.model}${We.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:ie+Ls(F,J,te).join(`
404
- `)+fe}),Q(`/write${p?` --scope ${p}`:""}`);return}ht.current=Date.now(),Et(0),D(!0);let go=new AbortController;ke.current=go,ne({verb:"Writing",total:F.length,done:0,active:[],rows:Bn(F),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${T.length} article${T.length===1?"":"s"} across ${F.length} partition${F.length===1?"":"s"} (\u2264${te} agents at once) on ${We.model}${We.forced?" (forced)":""}\u2026 (esc to stop)`});let wo=new Set;try{for await(let J of xr({cwd:e,partitions:F,promptFor:ie=>_s(ie,U,{rewrite:I||mo}),concurrency:te,profileName:s,allowProdWrites:Lt.current,model:We.model,signal:go.signal}))if(J.type==="partition_status")J.status==="running"?ne(ie=>ie&&{...ie,active:[...ie.active,J.label],rows:Le(ie.rows,J.label,"active"),lastAt:Date.now()}):ne(ie=>ie&&{...ie,active:ie.active.filter(fe=>fe!==J.label),done:ie.done+1,rows:Le(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 fe=Dd(J.event.name,J.event.input,F[J.index]?.paths??[]);fe&&!wo.has(fe)&&(wo.add(fe),ie=J.label)}ne(fe=>{if(!fe)return fe;let Fe={...fe,lastAt:Date.now()};return J.event.type==="tool"?Fe.tools=fe.tools+1:J.event.type==="text"&&(Fe.chars=fe.chars+J.event.delta.length),ie&&(Fe.rows=Td(Fe.rows,ie)),Fe})}else if(J.type==="run_done"){Bt(tt=>tt+J.totalCostUsd),qt(tt=>tt+J.results.reduce((ze,Ru)=>ze+Ru.outputTokens,0));let ie=J.aborted?"Stopped. ":"",fe=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:J.aborted?"warn":J.ok?"ok":"warn",text:ie+Os(J.results,F,fe).join(`
405
- `)}),!J.aborted&&J.ok)try{let tt=(wo.size>0?[...wo]:T).map(ze=>`${U}/${ze}`);Hi(e,tt,{writtenCap:qi})}catch{}let Fe=J.aborted?null:Ms(e,U,T);if(Fe&&d({kind:"note",tone:"warn",text:Fe}),!J.aborted&&J.ok){let tt=p??w??"",ze=tt?` ${tt}`:"";be(Fe?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${ze} --fix, then /review${ze} --fix for editorial quality, then /publish --all (add /screenshot author --all first if you want images).`:`Written. I\u2019d run /review${ze} --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${ze} --fix`:`/review${ze} --fix`,reason:""})}}}catch(J){d({kind:"note",tone:"error",text:`Write run failed: ${J.message}`})}finally{ke.current=null,ne(null),D(!1),X(J=>J+1)}return}case"draft":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:h,looseDocs:p}=Ws(e);if(h.length===0&&p===0){d({kind:"note",tone:"info",text:Hs});return}let w=f.join(" ").trim();if(!w&&h.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
404
+ Model: ${We.model}${We.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:ie+Os(F,J,ne).join(`
405
+ `)+fe}),Q(`/write${p?` --scope ${p}`:""}`);return}ht.current=Date.now(),Et(0),D(!0);let wo=new AbortController;ke.current=wo,oe({verb:"Writing",total:F.length,done:0,active:[],rows:Bn(F),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${T.length} article${T.length===1?"":"s"} across ${F.length} partition${F.length===1?"":"s"} (\u2264${ne} agents at once) on ${We.model}${We.forced?" (forced)":""}\u2026 (esc to stop)`});let yo=new Set;try{for await(let J of vr({cwd:e,partitions:F,promptFor:ie=>Ls(ie,U,{rewrite:I||go}),concurrency:ne,profileName:s,allowProdWrites:Lt.current,model:We.model,signal:wo.signal}))if(J.type==="partition_status")J.status==="running"?oe(ie=>ie&&{...ie,active:[...ie.active,J.label],rows:Le(ie.rows,J.label,"active"),lastAt:Date.now()}):oe(ie=>ie&&{...ie,active:ie.active.filter(fe=>fe!==J.label),done:ie.done+1,rows:Le(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 fe=Ad(J.event.name,J.event.input,F[J.index]?.paths??[]);fe&&!yo.has(fe)&&(yo.add(fe),ie=J.label)}oe(fe=>{if(!fe)return fe;let Fe={...fe,lastAt:Date.now()};return J.event.type==="tool"?Fe.tools=fe.tools+1:J.event.type==="text"&&(Fe.chars=fe.chars+J.event.delta.length),ie&&(Fe.rows=Dd(Fe.rows,ie)),Fe})}else if(J.type==="run_done"){Bt(tt=>tt+J.totalCostUsd),Ht(tt=>tt+J.results.reduce((ze,Su)=>ze+Su.outputTokens,0));let ie=J.aborted?"Stopped. ":"",fe=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:J.aborted?"warn":J.ok?"ok":"warn",text:ie+Ms(J.results,F,fe).join(`
406
+ `)}),!J.aborted&&J.ok)try{let tt=(yo.size>0?[...yo]:T).map(ze=>`${U}/${ze}`);Bi(e,tt,{writtenCap:Vi})}catch{}let Fe=J.aborted?null:Us(e,U,T);if(Fe&&d({kind:"note",tone:"warn",text:Fe}),!J.aborted&&J.ok){let tt=p??w??"",ze=tt?` ${tt}`:"";be(Fe?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${ze} --fix, then /review${ze} --fix for editorial quality, then /publish --all (add /screenshot author --all first if you want images).`:`Written. I\u2019d run /review${ze} --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${ze} --fix`:`/review${ze} --fix`,reason:""})}}}catch(J){d({kind:"note",tone:"error",text:`Write run failed: ${J.message}`})}finally{ke.current=null,oe(null),D(!1),X(J=>J+1)}return}case"draft":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:h,looseDocs:p}=Fs(e);if(h.length===0&&p===0){d({kind:"note",tone:"info",text:Hs});return}let w=f.join(" ").trim();if(!w&&h.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
406
407
  ${h.map(S=>` \u2022 ${S.name} (${S.docCount} doc${S.docCount===1?"":"s"})`).join(`
407
- `)}`}),pt(h.map(S=>`/draft ${S.name}`));return}let k="",$;if(w){let S=Fs(h,w);S?k=S:$=w}else k=h[0]?.name??"";await oe(Vo(k,$),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!ro(c.trim()))return;let h=f.find(p=>p.startsWith("--"));try{if(h==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let k=Date.now(),$=await Wi({cwd:e,profileName:s});d({kind:"note",tone:"info",text:Ho($,Date.now()-k).join(`
408
- `)});return}if(h==="--baseline"){let k=f.find(T=>!T.startsWith("--")),$=k?k.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:$?`Setting the sync baseline for ${$}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let S=await Sw({cwd:e,profileName:s,relPaths:$?[$]:void 0}),U=$?{rebaselined:[],skipped:[]}:await Pw({cwd:e,profileName:s});if(S.baselined.length===0&&S.skipped.length===0&&U.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}S.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${S.baselined.length} article${S.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),U.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${U.rebaselined.length} article${U.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),S.skipped.length>0&&d({kind:"note",tone:"warn",text:`${S.skipped.length} skipped:
408
+ `)}`}),pt(h.map(S=>`/draft ${S.name}`));return}let k="",$;if(w){let S=qs(h,w);S?k=S:$=w}else k=h[0]?.name??"";await te(Go(k,$),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!ro(c.trim()))return;let h=f.find(p=>p.startsWith("--"));try{if(h==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let k=Date.now(),$=await qi({cwd:e,profileName:s});d({kind:"note",tone:"info",text:Ho($,Date.now()-k).join(`
409
+ `)});return}if(h==="--baseline"){let k=f.find(T=>!T.startsWith("--")),$=k?k.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:$?`Setting the sync baseline for ${$}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let S=await Pw({cwd:e,profileName:s,relPaths:$?[$]:void 0}),U=$?{rebaselined:[],skipped:[]}:await Tw({cwd:e,profileName:s});if(S.baselined.length===0&&S.skipped.length===0&&U.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}S.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${S.baselined.length} article${S.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),U.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${U.rebaselined.length} article${U.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),S.skipped.length>0&&d({kind:"note",tone:"warn",text:`${S.skipped.length} skipped:
409
410
  ${S.skipped.map(T=>` - ${T.path} (${T.reason})`).join(`
410
- `)}`}),X(T=>T+1);return}if(h==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let k=await Rw({cwd:e,profileName:s}),$=k.onlyInLegacy.length===0&&k.onlyInManifest.length===0&&k.mappedMissingFromManifest.length===0,S=[`Legacy listing: ${k.legacyCount} \xB7 Manifest: ${k.manifestCount} \xB7 in both: ${k.inBoth}`];$?S.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(k.mappedMissingFromManifest.length&&S.push(`\u2717 ${k.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${k.mappedMissingFromManifest.slice(0,5).join(", ")}`),k.onlyInLegacy.length&&S.push(`\u26A0 ${k.onlyInLegacy.length} only in the legacy listing: ${k.onlyInLegacy.slice(0,5).join(", ")}`),k.onlyInManifest.length&&S.push(`\u26A0 ${k.onlyInManifest.length} only in the manifest: ${k.onlyInManifest.slice(0,5).join(", ")}`),S.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:$?"ok":"warn",text:S.join(`
411
- `)});return}if(h){d({kind:"note",tone:"error",text:`Unknown option: ${h} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let p=f[0];if(p){let k=await Kd({cwd:e,profileName:s,relPath:p.replace(/\\/g,"/")});ce.current=[{plan:k,mode:k.overwritesLocalChanges?"conflict":"pull"}],Ot.current=[],zt();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let w=await $s({cwd:e,profileName:s});for(let k of xs(w))d({kind:"note",tone:k.tone,text:k.text});X(k=>k+1)}catch(p){d({kind:"note",tone:"error",text:`Pull failed: ${p.message}`})}return}case"scope":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=Tw(e);if(h.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Ht({cursor:0,rows:h.map(p=>({...p,checked:p.recommended}))});return}case"audit":{if(f[0]==="--auto"){let p=re(e);if(!p){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=f[1]!=="off";Vd({...p,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let h=await Nn();h.kind==="forward-to-agent"&&h.prompt&&await oe(h.prompt,{display:h.display,quietUser:!0});return}case"check":{let h=f.find(k=>!k.startsWith("--")),p=h?` ${h}`:"",w=zd({cwd:e,scope:h});if(f.includes("--fix")){if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}d({kind:"note",tone:"info",text:`Fixing ${w.length} doc issue${w.length===1?"":"s"}\u2026`});let k=Zd(e,h);await oe(wi(w),{display:`/check${p} --fix`,quietUser:!0});try{Hi(e,k,{reviewedCap:qi})}catch{}let $=zd({cwd:e,scope:h});d({kind:"note",tone:$.length===0?"ok":"warn",text:$.length===0?"\u2713 Doc-checker: all issues resolved.":tr($).join(`
412
- `)}),be($.length===0?`Deterministic issues fixed. Next: /review${p} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${p} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${p} --fix`,reason:""});return}d({kind:"note",tone:w.length===0?"ok":"warn",text:tr(w).join(`
411
+ `)}`}),X(T=>T+1);return}if(h==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let k=await Sw({cwd:e,profileName:s}),$=k.onlyInLegacy.length===0&&k.onlyInManifest.length===0&&k.mappedMissingFromManifest.length===0,S=[`Legacy listing: ${k.legacyCount} \xB7 Manifest: ${k.manifestCount} \xB7 in both: ${k.inBoth}`];$?S.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(k.mappedMissingFromManifest.length&&S.push(`\u2717 ${k.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${k.mappedMissingFromManifest.slice(0,5).join(", ")}`),k.onlyInLegacy.length&&S.push(`\u26A0 ${k.onlyInLegacy.length} only in the legacy listing: ${k.onlyInLegacy.slice(0,5).join(", ")}`),k.onlyInManifest.length&&S.push(`\u26A0 ${k.onlyInManifest.length} only in the manifest: ${k.onlyInManifest.slice(0,5).join(", ")}`),S.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:$?"ok":"warn",text:S.join(`
412
+ `)});return}if(h){d({kind:"note",tone:"error",text:`Unknown option: ${h} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let p=f[0];if(p){let k=await Xd({cwd:e,profileName:s,relPath:p.replace(/\\/g,"/")});ce.current=[{plan:k,mode:k.overwritesLocalChanges?"conflict":"pull"}],Ot.current=[],zt();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let w=await xs({cwd:e,profileName:s});for(let k of vs(w))d({kind:"note",tone:k.tone,text:k.text});X(k=>k+1)}catch(p){d({kind:"note",tone:"error",text:`Pull failed: ${p.message}`})}return}case"scope":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=Dw(e);if(h.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}qt({cursor:0,rows:h.map(p=>({...p,checked:p.recommended}))});return}case"audit":{if(f[0]==="--auto"){let p=re(e);if(!p){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=f[1]!=="off";Gd({...p,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let h=await Nn();h.kind==="forward-to-agent"&&h.prompt&&await te(h.prompt,{display:h.display,quietUser:!0});return}case"check":{let h=f.find(k=>!k.startsWith("--")),p=h?` ${h}`:"",w=Kd({cwd:e,scope:h});if(f.includes("--fix")){if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}d({kind:"note",tone:"info",text:`Fixing ${w.length} doc issue${w.length===1?"":"s"}\u2026`});let k=eu(e,h);await te(ki(w),{display:`/check${p} --fix`,quietUser:!0});try{Bi(e,k,{reviewedCap:Vi})}catch{}let $=Kd({cwd:e,scope:h});d({kind:"note",tone:$.length===0?"ok":"warn",text:$.length===0?"\u2713 Doc-checker: all issues resolved.":nr($).join(`
413
+ `)}),be($.length===0?`Deterministic issues fixed. Next: /review${p} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${p} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${p} --fix`,reason:""});return}d({kind:"note",tone:w.length===0?"ok":"warn",text:nr(w).join(`
413
414
  `)}),w.length>0&&be(`Found ${w.length} doc issue${w.length===1?"":"s"} above. /check${p} --fix has the agent fix them in place (or /review${p} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${p} --fix`,reason:""});return}case"structure":{let h=Wn(e,s);if(h.length===0){d({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}d({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...h].join(`
414
- `)});return}case"reorder":{let h=ki(e,f);if(!h){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await oe(h.prompt,{display:h.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 h=yi(e,f);if(!h){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=f.includes("--fix"),w=f.find($=>!$.startsWith("--")),k=p?Zd(e,w):[];if(await oe(h.prompt,{display:h.display,quietUser:!0}),p)try{Hi(e,k,{reviewedCap:qi})}catch{}if(p)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 $=f.filter(S=>S!=="--fix").join(" ");be(`The review listed issues above. /review${$?` ${$}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${$?` ${$}`:""} --fix`,reason:""})}return}case"capture-setup":{await O();return}case"devhints":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:en(Zt(e)).join(`
415
- `)}),Vt(Ct()),kn.current=Ie(e).status==="current",Gt.current=Ke(e);return}case"discover":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await oe(gs(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(si(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await oe(ii(),{display:"/inbox",quietUser:!0});return}case"feedback":{let h=Jd(e),p="";try{p=ln(h)?$r(h,"utf8"):""}catch{p=""}if(!/^## /m.test(p)){d({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let w=await Ei(p.trim());d({kind:"note",tone:w?"ok":"warn",text:w?"\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 ${h} and copy it manually.`}),w&&Lr(null);return}case"document":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:h,what:p}=Bs(f);if(!p&&qs(e)===0){d({kind:"note",tone:"info",text:Gs});return}let w=`/document${p?` ${p}`:""}${h?" --publish":""}`;await oe(Vs(p,h),{display:w,quietUser:!0});return}case"catch-up":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!ro(c.trim()))return;let{publish:h}=li(f);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let p=await di({cwd:e,profileName:s});for(let k of ui(p))d({kind:"note",tone:k.startsWith("\u2713")?"ok":k.startsWith("\u2139")?"info":"warn",text:k});let w=Un(Mn(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await oe(ci({publish:h}),{display:`/catch-up${h?" --publish":""}`,quietUser:!0});return}case"update":{Ir.current=!0,d({kind:"note",tone:"info",text:`Updating ${Tt}\u2026 (don\u2019t close this window)`}),Xn(!0),(await Zo().finally(()=>Xn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),Q("/exit"),Xi("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Jo}`});return}case"screenshot":{let h=On(f);if(h.mode==="capture"){await R(h.rest);return}if(h.mode==="setup"){await O();return}if(h.mode==="list"){if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=Pt(e,h.scope);if(h.picker){if(k.length===0){d({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let S=Sc(k);if(S.length===0){d({kind:"note",tone:"info",text:zo(k,h.scope).join(`
416
- `)}),be(`\u2713 All ${k.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}yt({cursor:0,rows:S,title:"Screenshots \u2014 pick what to author or capture:"});return}d({kind:"note",tone:"info",text:zo(k,h.scope).join(`
417
- `)});let $=k.filter(S=>S.state==="placeholder").length;if($>0){let S=h.scope?`/screenshot author ${h.scope}`:"/screenshot author --all";be(`${$} of ${k.length} still need${$===1?"s":""} a spec \u2014 /screenshot author <id> authors one, ${S} authors them all in parallel.`,{kind:"cmd",cmd:S,reason:""})}return}if(h.mode==="single"){await ha(h.id);return}if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=h.mode==="scope"?h.scope:void 0,w=Ew(e,{scope:p}).map(k=>k.id);if(w.length===0){d({kind:"note",tone:"info",text:p?`No screenshot placeholders under ${p}.`:"No screenshot placeholders found in the docs."});return}await pa(w,{setup:h.setup,runLine:h.mode==="scope"?[`/screenshot author ${h.scope}`,`/screenshot ${h.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await R(f);return}case"reset":{let h=fi(e);if(h.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Zn.current={repoName:Vn(e),targets:h,hadDevhints:ln(Qd(e))},d({kind:"note",tone:"warn",text:gi(e,h).join(`
418
- `)}),we(Vn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,zt,Br,d,Pe,oe,Yt,Ur,fa]),ho=G(c=>{let l=(c??P).trim();if(x(""),Qn(null),Nt(0),l.startsWith("/")&&(Yn.current=!1,Ue(),hn(null),pt(f=>Ed(f,l))),!l||(Ki(!1),ga(l))||ma(l))return;Tr.current.push(l);let i=Ld(l,Qi.current);if(l.startsWith("/"))d({kind:"user",text:l}),Qe(!0),xn(i).finally(()=>Qe(!1));else if(Hw(i)){d({kind:"user",text:l});let f=qw(i);if(!f)oe(i,{display:l,quietUser:!0});else{try{Bw(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}oe(`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:l,quietUser:!0})}}else{let f=td(e,i);oe(f??i,{display:l})}},[P,ga,ma,xn,oe]),wa=G(c=>{if(c.length>1){if(c.includes("\x1B"))return;let l=Nd(c);if(Id(l)){let i=_d(++ku.current,l);Qi.current.set(i,l),_(i)}else _(l);return}_(c)},[_]),Kt=Math.max(10,Ee-6),ya=Oi(()=>kr(b.text,Kt),[b.text,Kt]),Vr=G(c=>y(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+c))})),[]),fo=G(c=>y(l=>({...l,pos:Md(kr(l.text,Kt),l.pos,c)})),[Kt]),vn=G(c=>y(l=>({...l,pos:Ud(kr(l.text,Kt),l.pos,c)})),[Kt]),vu=["\x1B[H","\x1B[1~","\x1BOH"],Cu=["\x1B[F","\x1B[4~","\x1BOF"],ka=G((c,l)=>l.leftArrow?(Vr(-1),!0):l.rightArrow?(Vr(1),!0):c&&vu.includes(c)?(vn("start"),!0):c&&Cu.includes(c)?(vn("end"),!0):l.ctrl&&c==="a"?(vn("start"),!0):l.ctrl&&c==="e"?(vn("end"),!0):!1,[Vr,vn]);return ow((c,l)=>{if(l.ctrl&&c==="c"){je.current?.close(),r();return}if(!W){if(N){if(l.escape){if(ke.current){if(!ke.current.signal.aborted){let i=(eo?.verb??"work").toLowerCase(),f=eo?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${f}s)\u2026`}),ke.current.abort()}return}fn.current||(fn.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),je.current?.interrupt());return}if(l.return){let i=P.trim();if(!i)return;$t.current.push(i),Ar([...$t.current]),x("");return}if(ka(c,l))return;if(l.upArrow){fo(-1);return}if(l.downArrow){fo(1);return}if(l.backspace||l.delete){C();return}c&&!l.ctrl&&!l.meta&&wa(c);return}if(mt){if(l.upArrow){gt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){gt(i=>i&&{...i,cursor:Math.min(He.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=He.length){gt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=He[mt.cursor];gt(null);let{lines:f,changed:R,effective:O}=_n(e,i.value??"default");for(let h of f)d({kind:"note",tone:h.startsWith("\u26A0")?"warn":h.startsWith("\u2713")?"ok":"info",text:h});R&&(sa(h=>h+1),je.current?.setModel(O));return}if(c==="s"){let i=He[mt.cursor];gt(null),je.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(l.escape){gt(null);return}return}if(Ve){if(l.upArrow){Mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Mt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ve.rows.length){Mt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return||c==="s"){let i=Ve.rows[Ve.cursor];Mt(null),Hr(i.name,l.return===!0);return}if(l.escape){Mt(null);return}return}if(no){if(l.escape){wn(null);return}if(l.leftArrow||l.tab&&l.shift){wn(i=>i&&{tab:(i.tab-1+Ne.length)%Ne.length});return}if(l.rightArrow||l.tab){wn(i=>i&&{tab:(i.tab+1)%Ne.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ne.length){wn({tab:Number(c)-1});return}return}if(Ge){if(l.upArrow){Ut(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ut(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){Ut(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ge.rows[Ge.cursor].name;if(Ut(null),!es(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let R=!1;try{let O=At(i);R=!!O&&!(dt(O)&&!O.refreshToken)}catch{R=!1}d({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(O=>O+1);return}if(l.escape){Ut(null);return}return}if(ge){if(l.upArrow){Wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Wt(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){Wt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=ge.rows[ge.cursor],{profile:f,projectId:R}=ge;Wt(null),co(f,R,i);return}if(l.escape){Wt(null);return}return}if(Ce){if(l.upArrow){wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){wt(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){wt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ce.rows[Ce.cursor],{profile:f}=Ce;wt(null),po(f,i);return}if(l.escape){wt(null);return}return}if(ye){if(l.upArrow){Ht(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ht(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){Ht(i=>i&&{...i,rows:i.rows.map((f,R)=>R===i.cursor?{...f,checked:!f.checked}:f)});return}if(l.return){let i=ye.rows.filter(f=>f.checked).map(f=>f.path);if(Ht(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}ws(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of i)d({kind:"note",tone:"info",text:` ${f}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){Ht(null);return}return}if(Ye){if(l.upArrow){kt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){kt(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){kt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ye.rows[Ye.cursor],f=Ye.run;kt(null),f(i.token);return}if(l.escape){kt(null);return}return}if(Je){if(l.upArrow){Ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ft(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Je.rows.length){Ft(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Je.rows[Je.cursor];Ft(null),i.conflict?Br(i.paths[0]):i.kind==="article"?Ur(i.paths[0]):Yt(i.paths);return}if(l.escape){Ft(null);return}return}if(Ze){if(l.upArrow){yt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){yt(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){yt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ze.rows[Ze.cursor];yt(null),i.action==="capture"?Wr(i.ids,{runLine:i.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):i.kind==="shot"?ha(i.ids[0]):pa(i.ids,{setup:!0,runLine:i.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(l.escape){yt(null);return}return}if(Re){if(l.escape){bt(null);return}if(l.upArrow){bt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){bt(i=>i&&{...i,cursor:Math.min(Math.max(0,ao.length-1),i.cursor+1)});return}if(l.return){let i=ao[Re.cursor];if(i){bt(null);try{d({kind:"preview",name:Vn(i),text:iu($r(Mi(e,i),"utf8"))})}catch(f){d({kind:"note",tone:"error",text:`Could not read ${i}: ${f.message}`})}}return}if(l.backspace||l.delete){bt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){bt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(Se){if(l.escape){xt(null);return}if(l.upArrow){xt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){xt(i=>i&&{...i,cursor:Math.min(Math.max(0,lo.length-1),i.cursor+1)});return}if(l.return){let i=lo[Se.cursor];if(i){xt(null),Pe(i.uuid),Be.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},ft(i.name),Ui(i.uuid),_t.current=[];let f=Ii(e,i.uuid);for(let R of f)d(R);d({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(l.backspace||l.delete){xt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){xt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(l.tab&&!P&&me){x(me),Ue();return}if(!P&&qe.length>0&&!Sr&&c&&/^[1-9]$/.test(c)){let i=qe[Number(c)-1];if(i){x(Dt(i));return}}if(!P&&(so||yn)&&c==="c"&&!l.ctrl&&!l.meta&&!l.return&&!l.tab){let i=so!=null;Ei(so??yn).then(R=>{d({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&&Lr(null),R&&!i&&aa(!0)});return}if(!ka(c,l)){if(ca){if(l.upArrow){Nt(i=>Math.max(0,i-1));return}if(l.downArrow){Nt(i=>Math.min($n.length-1,i+1));return}if(l.tab){x("/"+($n[pn]?.name??"")+" "),Nt(0);return}if(l.return){let i=$n[pn];if(i){let f=P.trim().slice(1).split(/\s+/).slice(1).join(" ");if(ul(i.usage)&&!f){x("/"+i.name+" "),Nt(0);return}ho("/"+i.name+(f?" "+f:""));return}}}else{if(l.upArrow){if(P!==""&&It===null){fo(-1);return}let i=Tr.current;if(!i.length)return;let f=It===null?i.length-1:Math.max(0,It-1);Qn(f),x(i[f]??"");return}if(l.downArrow){if(P!==""&&It===null){fo(1);return}let i=Tr.current;if(It===null)return;let f=It+1;f>=i.length?(Qn(null),x("")):(Qn(f),x(i[f]??""));return}}if(l.return){ho();return}if(l.backspace||l.delete){C();return}if(l.escape){x(""),Nt(0),Ue(),pt([]),hn(null),Yn.current=!0;return}c&&!l.ctrl&&!l.meta&&wa(c)}}}),Ae(()=>{if(N||W)return;let c=$t.current.shift();c!==void 0&&(Ar([...$t.current]),ho(c))},[N,W,ho]),Y(se,{flexDirection:"column",width:Ee,children:[Mr!==null&&Y(se,{marginTop:1,flexDirection:"column",children:[Mr.truncated&&j(A,{dimColor:!0,children:"\u2026"}),j(A,{children:Mr.text})]}),N&&(eo?j(ey,{p:eo}):j(Qw,{startTime:ht.current,chars:yu})),!N&&ta?j(Jw,{text:ta}):null,j(se,{borderStyle:"round",borderColor:la.prod?"yellow":V,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:P?ya.map((c,l)=>{let i=b.text.slice(c.start,c.end),f=l===br(ya,b.pos),R=Math.min(b.pos,c.end)-c.start;return Y(A,{children:[j(A,{color:V,children:l===0?"> ":" "}),f?Y(Gn,{children:[i.slice(0,R),j(cn,{ch:i[R]??" "}),i.slice(R+1)]}):i||" "]},`${l}-${c.start}`)}):Y(A,{children:[j(A,{color:V,children:"> "}),jr?j(cn,{ch:" "}):me&&!N&&ve?Y(Gn,{children:[j(cn,{ch:ve[0],dim:!0}),j(A,{color:"gray",children:ve.slice(1)})]}):me&&!N?Y(Gn,{children:[j(cn,{ch:me[0],dim:!0}),j(A,{color:"gray",children:me.slice(1)}),j(A,{dimColor:!0,children:" (tab)"})]}):(Or.isSetup||!gu)&&!N?Y(Gn,{children:[j(cn,{ch:Or.text[0],dim:!0}),j(A,{color:"gray",children:Or.text.slice(1)})]}):j(cn,{ch:" "})]})}),ea.length>0&&j(se,{flexDirection:"column",paddingX:1,children:ea.map((c,l)=>j(A,{color:"gray",children:`\u29D7 queued: ${c}`},`${l}-${c.slice(0,24)}`))}),no?j(Sd,{tab:no.tab,width:Ee,version:o,engineVersion:au}):mt?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,l)=>Y(A,{color:l===mt.cursor?V:void 0,children:[l===mt.cursor?"\u276F ":" ",`${l+1}. ${c.label}${l===mt.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"})]}):Ve?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Switch connection profile"}),Ve.rows.map((c,l)=>Y(A,{color:l===Ve.cursor?V:void 0,children:[l===Ve.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Ve.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"})]}):Ge?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Pick your Document360 environment"}),Ge.rows.map((c,l)=>Y(A,{color:l===Ge.cursor?V:void 0,children:[l===Ge.cursor?"\u276F ":" ",`${l+1}. ${c.name}`.padEnd(16),j(A,{color:"gray",children:c.apiUrl})]},c.name)),j(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ge?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Switch workspace"}),j(A,{dimColor:!0,children:`environment ${ge.environment} \xB7 project ${ge.projectName??`${ge.projectId.slice(0,8)}\u2026`}`}),ge.rows.map((c,l)=>Y(A,{color:l===ge.cursor?V:void 0,children:[l===ge.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===ge.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,l)=>Y(A,{color:l===Ce.cursor?V:void 0,children:[l===Ce.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Ce.current?" \u2714":""}`.padEnd(30),j(A,{color:"gray",children:c.sub??""})]},c.id)),j(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ye?(()=>{let l=Math.min(Math.max(0,ye.cursor-Math.floor(7)),Math.max(0,ye.rows.length-14)),i=ye.rows.slice(l,l+14),f=ye.rows.filter(R=>R.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 ${ye.rows.length})`}),l>0?j(A,{dimColor:!0,children:` \u2191 ${l} more`}):null,i.map((R,O)=>{let h=l+O;return Y(A,{color:h===ye.cursor?V:void 0,children:[h===ye.cursor?"\u276F ":" ",R.checked?"\u25C9 ":"\u25CB ",R.path.padEnd(Math.min(48,Ee-34)),j(A,{color:"gray",children:Fo(R)})]},R.path)}),l+14<ye.rows.length?j(A,{dimColor:!0,children:` \u2193 ${ye.rows.length-l-14} more`}):null,j(A,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Ye?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Which category? (pick one to scope to)"}),Ye.rows.map((c,l)=>{let i=l===Ye.cursor,f=`${l+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,Ee-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"})]}):Je?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:"}),Je.rows.map((c,l)=>{let i=l===Je.cursor,f=c.indent?" ":" ",R=`${l+1}.`.padEnd(3);return Y(A,{color:i?V:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${f}${R} ${c.label}`.padEnd(Math.min(56,Ee-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"})]}):Ze?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:Ze.title}),(()=>{let{rows:l,cursor:i}=Ze,f=Math.max(0,Math.min(i-Math.floor(12/2),l.length-12)),R=l.slice(f,f+12);return Y(Gn,{children:[f>0?j(A,{color:"gray",children:` \u2026 ${f} more above`}):null,R.map((O,h)=>{let p=f+h,w=p===i,k=O.indent?" ":" ",$=p<9?`${p+1}.`.padEnd(3):" ";return Y(A,{color:w?V:void 0,bold:O.kind!=="shot"&&!w,children:[w?"\u276F ":" ",`${k}${$} ${O.label}`.padEnd(Math.min(56,Ee-24)),O.note?j(A,{color:"gray",children:O.note}):null]},`${O.kind}:${O.ids.join(",")}`)}),f+12<l.length?j(A,{color:"gray",children:` \u2026 ${l.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)"}`}),ao.length===0?j(A,{color:"gray",children:"no articles match"}):ao.map((c,l)=>Y(A,{color:l===Re.cursor?V:void 0,children:[l===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)"}`}),lo.length===0?j(A,{color:"gray",children:"no sessions match"}):lo.map((c,l)=>Y(A,{color:l===Se.cursor?V:void 0,children:[l===Se.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),j(A,{color:l===Se.cursor?V:"gray",children:c.firstPrompt.slice(0,Math.max(10,Ee-40))})]},c.uuid)),j(A,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):ca?Y(se,{flexDirection:"column",children:[$n.map((c,l)=>Y(A,{color:l===pn?V:void 0,children:[l===pn?"\u276F ":" ",c.usage.padEnd(22)," ",j(A,{color:l===pn?V:"gray",children:c.name==="model"&&Er?`${c.desc} (currently ${Er})`:c.desc})]},c.name)),j(A,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!P&&qe.length>0?Y(se,{flexDirection:"column",paddingX:1,children:[Zi?j(A,{color:V,children:Zi}):null,qe.map((c,l)=>{let i=Dt(c),f=i.slice(0,Math.max(20,Ee-5)),R=Ee-f.length-7,O=R>=12?(jd(c)??cl(i)).slice(0,R):"";return Y(A,{children:[j(A,{color:V,children:l+1})," ",f,O?j(A,{dimColor:!0,children:` \u2014 ${O}`}):null]},i)}),j(A,{dimColor:!0,children:`press 1-${qe.length} to fill \xB7 esc cancel`})]}):j(se,{paddingX:1,children:Y(A,{color:"gray",children:[la.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Er??"model n/a"}${t.kind==="api"?ra>0?` \xB7 ${xe(ra)}`:"":oa>0?` \xB7 ${at(oa)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}H();import{jsx as ry}from"react/jsx-runtime";async function du(e=process.cwd(),t="auto",n,o="0.0.0"){let r=oy(t);r.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${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}=ny(ry(cu,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
419
- `),process.exit(0)}H();import{writeCrashLog as uu,isBenignTransportError as sy}from"document360-engine";var pu=!1;function Gi(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function hu(e){if(pu)return;pu=!0;let t=(n,o)=>{if(sy(o)){uu({kind:n,level:"transport",message:Gi(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=uu({kind:n,level:"fatal",message:Gi(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
420
- `+v(`\u2717 d360-writer crashed: ${Gi(o)}`)+`
415
+ `)});return}case"reorder":{let h=$i(e,f);if(!h){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await te(h.prompt,{display:h.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 h=bi(e,f);if(!h){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=f.includes("--fix"),w=f.find($=>!$.startsWith("--")),k=p?eu(e,w):[];if(await te(h.prompt,{display:h.display,quietUser:!0}),p)try{Bi(e,k,{reviewedCap:Vi})}catch{}if(p)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 $=f.filter(S=>S!=="--fix").join(" ");be(`The review listed issues above. /review${$?` ${$}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${$?` ${$}`:""} --fix`,reason:""})}return}case"capture-setup":{await O();return}case"devhints":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:en(Zt(e)).join(`
416
+ `)}),Vt(Ct()),kn.current=Ie(e).status==="current",Gt.current=Ke(e);return}case"discover":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await te(ws(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(ai(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await te(li(),{display:"/inbox",quietUser:!0});return}case"feedback":{let h=Zd(e),p="";try{p=ln(h)?xr(h,"utf8"):""}catch{p=""}if(!/^## /m.test(p)){d({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let w=await Ii(p.trim());d({kind:"note",tone:w?"ok":"warn",text:w?"\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 ${h} and copy it manually.`}),w&&Or(null);return}case"document":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:h,what:p}=Vs(f);if(!p&&Bs(e)===0){d({kind:"note",tone:"info",text:Ys});return}let w=`/document${p?` ${p}`:""}${h?" --publish":""}`;await te(Gs(p,h),{display:w,quietUser:!0});return}case"catch-up":{if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!ro(c.trim()))return;let{publish:h}=di(f);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let p=await pi({cwd:e,profileName:s});for(let k of hi(p))d({kind:"note",tone:k.startsWith("\u2713")?"ok":k.startsWith("\u2139")?"info":"warn",text:k});let w=Un(Mn(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await te(ui({publish:h}),{display:`/catch-up${h?" --publish":""}`,quietUser:!0});return}case"update":{_r.current=!0,d({kind:"note",tone:"info",text:`Updating ${Tt}\u2026 (don\u2019t close this window)`}),Xn(!0),(await er().finally(()=>Xn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),Q("/exit"),Ji("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Zo}`});return}case"screenshot":{let h=On(f);if(h.mode==="capture"){await R(h.rest);return}if(h.mode==="checklist"){await O();return}if(h.mode==="list"){if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=Pt(e,h.scope);if(h.picker){if(k.length===0){d({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let S=Pc(k);if(S.length===0){d({kind:"note",tone:"info",text:Ko(k,h.scope).join(`
417
+ `)}),be(`\u2713 All ${k.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}yt({cursor:0,rows:S,title:"Screenshots \u2014 pick what to author or capture:"});return}d({kind:"note",tone:"info",text:Ko(k,h.scope).join(`
418
+ `)});let $=k.filter(S=>S.state==="placeholder").length;if($>0){let S=h.scope?`/screenshot author ${h.scope}`:"/screenshot author --all";be(`${$} of ${k.length} still need${$===1?"s":""} a spec \u2014 /screenshot author <id> authors one, ${S} authors them all in parallel.`,{kind:"cmd",cmd:S,reason:""})}return}if(h.mode==="single"){await fa(h.id);return}if(!re(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=h.mode==="scope"?h.scope:void 0,w=Nw(e,{scope:p}).map(k=>k.id);if(w.length===0){d({kind:"note",tone:"info",text:p?`No screenshot placeholders under ${p}.`:"No screenshot placeholders found in the docs."});return}await ha(w,{setup:h.setup,runLine:h.mode==="scope"?[`/screenshot author ${h.scope}`,`/screenshot ${h.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await R(f);return}case"reset":{let h=gi(e);if(h.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Zn.current={repoName:Vn(e),targets:h,hadDevhints:ln(Jd(e))},d({kind:"note",tone:"warn",text:yi(e,h).join(`
419
+ `)}),we(Vn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,zt,Vr,d,Pe,te,Yt,Wr,ma]),fo=G(c=>{let l=(c??P).trim();if(x(""),Qn(null),Nt(0),l.startsWith("/")&&(Yn.current=!1,Ue(),hn(null),pt(f=>Nd(f,l))),!l||(Qi(!1),wa(l))||ga(l))return;Dr.current.push(l);let i=Od(l,Zi.current);if(l.startsWith("/"))d({kind:"user",text:l}),Qe(!0),xn(i).finally(()=>Qe(!1));else if(Hw(i)){d({kind:"user",text:l});let f=Bw(i);if(!f)te(i,{display:l,quietUser:!0});else{try{Vw(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:l,quietUser:!0})}}else{let f=nd(e,i);te(f??i,{display:l})}},[P,wa,ga,xn,te]),ya=G(c=>{if(c.length>1){if(c.includes("\x1B"))return;let l=Id(c);if(_d(l)){let i=Ld(++bu.current,l);Zi.current.set(i,l),_(i)}else _(l);return}_(c)},[_]),Kt=Math.max(10,Ee-6),ka=Ui(()=>br(b.text,Kt),[b.text,Kt]),Gr=G(c=>y(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+c))})),[]),mo=G(c=>y(l=>({...l,pos:Ud(br(l.text,Kt),l.pos,c)})),[Kt]),vn=G(c=>y(l=>({...l,pos:Wd(br(l.text,Kt),l.pos,c)})),[Kt]),Cu=["\x1B[H","\x1B[1~","\x1BOH"],Ru=["\x1B[F","\x1B[4~","\x1BOF"],ba=G((c,l)=>l.leftArrow?(Gr(-1),!0):l.rightArrow?(Gr(1),!0):c&&Cu.includes(c)?(vn("start"),!0):c&&Ru.includes(c)?(vn("end"),!0):l.ctrl&&c==="a"?(vn("start"),!0):l.ctrl&&c==="e"?(vn("end"),!0):!1,[Gr,vn]);return rw((c,l)=>{if(l.ctrl&&c==="c"){je.current?.close(),r();return}if(!W){if(N){if(l.escape){if(ke.current){if(!ke.current.signal.aborted){let i=(eo?.verb??"work").toLowerCase(),f=eo?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${f}s)\u2026`}),ke.current.abort()}return}fn.current||(fn.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),je.current?.interrupt());return}if(l.return){let i=P.trim();if(!i)return;$t.current.push(i),jr([...$t.current]),x("");return}if(ba(c,l))return;if(l.upArrow){mo(-1);return}if(l.downArrow){mo(1);return}if(l.backspace||l.delete){C();return}c&&!l.ctrl&&!l.meta&&ya(c);return}if(mt){if(l.upArrow){gt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){gt(i=>i&&{...i,cursor:Math.min(qe.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=qe.length){gt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=qe[mt.cursor];gt(null);let{lines:f,changed:R,effective:O}=_n(e,i.value??"default");for(let h of f)d({kind:"note",tone:h.startsWith("\u26A0")?"warn":h.startsWith("\u2713")?"ok":"info",text:h});R&&(aa(h=>h+1),je.current?.setModel(O));return}if(c==="s"){let i=qe[mt.cursor];gt(null),je.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(l.escape){gt(null);return}return}if(Ve){if(l.upArrow){Mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Mt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ve.rows.length){Mt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return||c==="s"){let i=Ve.rows[Ve.cursor];Mt(null),Hr(i.name,l.return===!0);return}if(l.escape){Mt(null);return}return}if(no){if(l.escape){wn(null);return}if(l.leftArrow||l.tab&&l.shift){wn(i=>i&&{tab:(i.tab-1+Ne.length)%Ne.length});return}if(l.rightArrow||l.tab){wn(i=>i&&{tab:(i.tab+1)%Ne.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ne.length){wn({tab:Number(c)-1});return}return}if(Ge){if(l.upArrow){Ut(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ut(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){Ut(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ge.rows[Ge.cursor].name;if(Ut(null),!ts(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let R=!1;try{let O=At(i);R=!!O&&!(dt(O)&&!O.refreshToken)}catch{R=!1}d({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(O=>O+1);return}if(l.escape){Ut(null);return}return}if(ge){if(l.upArrow){Wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Wt(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){Wt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=ge.rows[ge.cursor],{profile:f,projectId:R}=ge;Wt(null),uo(f,R,i);return}if(l.escape){Wt(null);return}return}if(Ce){if(l.upArrow){wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){wt(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){wt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ce.rows[Ce.cursor],{profile:f}=Ce;wt(null),ho(f,i);return}if(l.escape){wt(null);return}return}if(ye){if(l.upArrow){qt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.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(l.return){let i=ye.rows.filter(f=>f.checked).map(f=>f.path);if(qt(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}ys(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of i)d({kind:"note",tone:"info",text:` ${f}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){qt(null);return}return}if(Ye){if(l.upArrow){kt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){kt(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){kt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ye.rows[Ye.cursor],f=Ye.run;kt(null),f(i.token);return}if(l.escape){kt(null);return}return}if(Je){if(l.upArrow){Ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ft(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Je.rows.length){Ft(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Je.rows[Je.cursor];Ft(null),i.conflict?Vr(i.paths[0]):i.kind==="article"?Wr(i.paths[0]):Yt(i.paths);return}if(l.escape){Ft(null);return}return}if(Ze){if(l.upArrow){yt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){yt(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){yt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ze.rows[Ze.cursor];yt(null),i.action==="capture"?Fr(i.ids,{runLine:i.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):i.kind==="shot"?fa(i.ids[0]):ha(i.ids,{setup:!0,runLine:i.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(l.escape){yt(null);return}return}if(Re){if(l.escape){bt(null);return}if(l.upArrow){bt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){bt(i=>i&&{...i,cursor:Math.min(Math.max(0,ao.length-1),i.cursor+1)});return}if(l.return){let i=ao[Re.cursor];if(i){bt(null);try{d({kind:"preview",name:Vn(i),text:au(xr(Wi(e,i),"utf8"))})}catch(f){d({kind:"note",tone:"error",text:`Could not read ${i}: ${f.message}`})}}return}if(l.backspace||l.delete){bt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){bt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(Se){if(l.escape){xt(null);return}if(l.upArrow){xt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){xt(i=>i&&{...i,cursor:Math.min(Math.max(0,lo.length-1),i.cursor+1)});return}if(l.return){let i=lo[Se.cursor];if(i){xt(null),Pe(i.uuid),Be.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},ft(i.name),Fi(i.uuid),_t.current=[];let f=Li(e,i.uuid);for(let R of f)d(R);d({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(l.backspace||l.delete){xt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){xt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(l.tab&&!P&&me){x(me),Ue();return}if(!P&&He.length>0&&!Pr&&c&&/^[1-9]$/.test(c)){let i=He[Number(c)-1];if(i){x(Dt(i));return}}if(!P&&(so||yn)&&c==="c"&&!l.ctrl&&!l.meta&&!l.return&&!l.tab){let i=so!=null;Ii(so??yn).then(R=>{d({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&&Or(null),R&&!i&&ca(!0)});return}if(!ba(c,l)){if(ua){if(l.upArrow){Nt(i=>Math.max(0,i-1));return}if(l.downArrow){Nt(i=>Math.min($n.length-1,i+1));return}if(l.tab){x("/"+($n[pn]?.name??"")+" "),Nt(0);return}if(l.return){let i=$n[pn];if(i){let f=P.trim().slice(1).split(/\s+/).slice(1).join(" ");if(pl(i.usage)&&!f){x("/"+i.name+" "),Nt(0);return}fo("/"+i.name+(f?" "+f:""));return}}}else{if(l.upArrow){if(P!==""&&It===null){mo(-1);return}let i=Dr.current;if(!i.length)return;let f=It===null?i.length-1:Math.max(0,It-1);Qn(f),x(i[f]??"");return}if(l.downArrow){if(P!==""&&It===null){mo(1);return}let i=Dr.current;if(It===null)return;let f=It+1;f>=i.length?(Qn(null),x("")):(Qn(f),x(i[f]??""));return}}if(l.return){fo();return}if(l.backspace||l.delete){C();return}if(l.escape){x(""),Nt(0),Ue(),pt([]),hn(null),Yn.current=!0;return}c&&!l.ctrl&&!l.meta&&ya(c)}}}),Ae(()=>{if(N||W)return;let c=$t.current.shift();c!==void 0&&(jr([...$t.current]),fo(c))},[N,W,fo]),Y(se,{flexDirection:"column",width:Ee,children:[Ur!==null&&Y(se,{marginTop:1,flexDirection:"column",children:[Ur.truncated&&j(A,{dimColor:!0,children:"\u2026"}),j(A,{children:Ur.text})]}),N&&(eo?j(ty,{p:eo}):j(Jw,{startTime:ht.current,chars:ku})),!N&&oa?j(Zw,{text:oa}):null,j(se,{borderStyle:"round",borderColor:da.prod?"yellow":V,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:P?ka.map((c,l)=>{let i=b.text.slice(c.start,c.end),f=l===$r(ka,b.pos),R=Math.min(b.pos,c.end)-c.start;return Y(A,{children:[j(A,{color:V,children:l===0?"> ":" "}),f?Y(Gn,{children:[i.slice(0,R),j(cn,{ch:i[R]??" "}),i.slice(R+1)]}):i||" "]},`${l}-${c.start}`)}):Y(A,{children:[j(A,{color:V,children:"> "}),Er?j(cn,{ch:" "}):me&&!N&&ve?Y(Gn,{children:[j(cn,{ch:ve[0],dim:!0}),j(A,{color:"gray",children:ve.slice(1)})]}):me&&!N?Y(Gn,{children:[j(cn,{ch:me[0],dim:!0}),j(A,{color:"gray",children:me.slice(1)}),j(A,{dimColor:!0,children:" (tab)"})]}):(Mr.isSetup||!wu)&&!N?Y(Gn,{children:[j(cn,{ch:Mr.text[0],dim:!0}),j(A,{color:"gray",children:Mr.text.slice(1)})]}):j(cn,{ch:" "})]})}),na.length>0&&j(se,{flexDirection:"column",paddingX:1,children:na.map((c,l)=>j(A,{color:"gray",children:`\u29D7 queued: ${c}`},`${l}-${c.slice(0,24)}`))}),no?j(Pd,{tab:no.tab,width:Ee,version:o,engineVersion:lu}):mt?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)."}),qe.map((c,l)=>Y(A,{color:l===mt.cursor?V:void 0,children:[l===mt.cursor?"\u276F ":" ",`${l+1}. ${c.label}${l===mt.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"})]}):Ve?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Switch connection profile"}),Ve.rows.map((c,l)=>Y(A,{color:l===Ve.cursor?V:void 0,children:[l===Ve.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Ve.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"})]}):Ge?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Pick your Document360 environment"}),Ge.rows.map((c,l)=>Y(A,{color:l===Ge.cursor?V:void 0,children:[l===Ge.cursor?"\u276F ":" ",`${l+1}. ${c.name}`.padEnd(16),j(A,{color:"gray",children:c.apiUrl})]},c.name)),j(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ge?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Switch workspace"}),j(A,{dimColor:!0,children:`environment ${ge.environment} \xB7 project ${ge.projectName??`${ge.projectId.slice(0,8)}\u2026`}`}),ge.rows.map((c,l)=>Y(A,{color:l===ge.cursor?V:void 0,children:[l===ge.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===ge.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,l)=>Y(A,{color:l===Ce.cursor?V:void 0,children:[l===Ce.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Ce.current?" \u2714":""}`.padEnd(30),j(A,{color:"gray",children:c.sub??""})]},c.id)),j(A,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ye?(()=>{let l=Math.min(Math.max(0,ye.cursor-Math.floor(7)),Math.max(0,ye.rows.length-14)),i=ye.rows.slice(l,l+14),f=ye.rows.filter(R=>R.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 ${ye.rows.length})`}),l>0?j(A,{dimColor:!0,children:` \u2191 ${l} more`}):null,i.map((R,O)=>{let h=l+O;return Y(A,{color:h===ye.cursor?V:void 0,children:[h===ye.cursor?"\u276F ":" ",R.checked?"\u25C9 ":"\u25CB ",R.path.padEnd(Math.min(48,Ee-34)),j(A,{color:"gray",children:qo(R)})]},R.path)}),l+14<ye.rows.length?j(A,{dimColor:!0,children:` \u2193 ${ye.rows.length-l-14} more`}):null,j(A,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Ye?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:"Which category? (pick one to scope to)"}),Ye.rows.map((c,l)=>{let i=l===Ye.cursor,f=`${l+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,Ee-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"})]}):Je?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:"}),Je.rows.map((c,l)=>{let i=l===Je.cursor,f=c.indent?" ":" ",R=`${l+1}.`.padEnd(3);return Y(A,{color:i?V:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${f}${R} ${c.label}`.padEnd(Math.min(56,Ee-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"})]}):Ze?Y(se,{flexDirection:"column",paddingX:1,children:[j(A,{color:V,bold:!0,children:Ze.title}),(()=>{let{rows:l,cursor:i}=Ze,f=Math.max(0,Math.min(i-Math.floor(12/2),l.length-12)),R=l.slice(f,f+12);return Y(Gn,{children:[f>0?j(A,{color:"gray",children:` \u2026 ${f} more above`}):null,R.map((O,h)=>{let p=f+h,w=p===i,k=O.indent?" ":" ",$=p<9?`${p+1}.`.padEnd(3):" ";return Y(A,{color:w?V:void 0,bold:O.kind!=="shot"&&!w,children:[w?"\u276F ":" ",`${k}${$} ${O.label}`.padEnd(Math.min(56,Ee-24)),O.note?j(A,{color:"gray",children:O.note}):null]},`${O.kind}:${O.ids.join(",")}`)}),f+12<l.length?j(A,{color:"gray",children:` \u2026 ${l.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)"}`}),ao.length===0?j(A,{color:"gray",children:"no articles match"}):ao.map((c,l)=>Y(A,{color:l===Re.cursor?V:void 0,children:[l===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)"}`}),lo.length===0?j(A,{color:"gray",children:"no sessions match"}):lo.map((c,l)=>Y(A,{color:l===Se.cursor?V:void 0,children:[l===Se.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),j(A,{color:l===Se.cursor?V:"gray",children:c.firstPrompt.slice(0,Math.max(10,Ee-40))})]},c.uuid)),j(A,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):ua?Y(se,{flexDirection:"column",children:[$n.map((c,l)=>Y(A,{color:l===pn?V:void 0,children:[l===pn?"\u276F ":" ",c.usage.padEnd(22)," ",j(A,{color:l===pn?V:"gray",children:c.name==="model"&&Nr?`${c.desc} (currently ${Nr})`:c.desc})]},c.name)),j(A,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!P&&He.length>0?Y(se,{flexDirection:"column",paddingX:1,children:[ta?j(A,{color:V,children:ta}):null,He.map((c,l)=>{let i=Dt(c),f=i.slice(0,Math.max(20,Ee-5)),R=Ee-f.length-7,O=R>=12?(Ed(c)??dl(i)).slice(0,R):"";return Y(A,{children:[j(A,{color:V,children:l+1})," ",f,O?j(A,{dimColor:!0,children:` \u2014 ${O}`}):null]},i)}),j(A,{dimColor:!0,children:`press 1-${He.length} to fill \xB7 esc cancel`})]}):j(se,{paddingX:1,children:Y(A,{color:"gray",children:[da.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Nr??"model n/a"}${t.kind==="api"?ia>0?` \xB7 ${xe(ia)}`:"":sa>0?` \xB7 ${at(sa)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}q();import{jsx as sy}from"react/jsx-runtime";async function uu(e=process.cwd(),t="auto",n,o="0.0.0"){let r=ry(t);r.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${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}=oy(sy(du,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
420
+ `),process.exit(0)}q();import{writeCrashLog as pu,isBenignTransportError as iy}from"document360-engine";var hu=!1;function zi(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function fu(e){if(hu)return;hu=!0;let t=(n,o)=>{if(iy(o)){pu({kind:n,level:"transport",message:zi(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=pu({kind:n,level:"fatal",message:zi(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
421
+ `+v(`\u2717 d360-writer crashed: ${zi(o)}`)+`
421
422
  `),r&&process.stderr.write(m(` Crash details: ${r}`)+`
422
423
  `+m(" Run: d360-writer logs")+`
423
- `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var cy=ay(import.meta.url),Cr=cy("../package.json");hu("d360-writer");var Oe=new iy;function Yi(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Oe.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=>{Yi(e),await Co({profile:e.profile,manual:e.manual})});Oe.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Yi(e),await ja({profile:e.profile})});Oe.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Yi(e),await Aa({profile:e.profile})});var zi=Oe.command("profile").description("Manage connection profiles for the current repo");zi.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Ro(process.cwd()));zi.command("use <name>").description("Set the default profile for this repo").action(e=>So(process.cwd(),e));zi.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Po(process.cwd(),e));var fu=Oe.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");fu.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Xt(process.cwd(),e.profile));fu.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await va(process.cwd(),e,t.profile)});var mu=Oe.command("project").description("Choose the Document360 project for this repo (active profile's identity)");mu.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>$o(process.cwd(),e.profile));mu.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Ra(process.cwd(),e,t.profile)});Oe.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(No(),il));await e()});Oe.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>_a());Oe.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(()=>(Yo(),fc)),n=await t(process.cwd(),Cr.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Oe.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Cr.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(ly.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 La(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 yd(e.cwd,e.auth,e.profile,Cr.version):await du(e.cwd,e.auth,e.profile,Cr.version)});Oe.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
424
+ `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var dy=ly(import.meta.url),Rr=dy("../package.json");fu("d360-writer");var Oe=new ay;function Ki(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Oe.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=>{Ki(e),await Ro({profile:e.profile,manual:e.manual})});Oe.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ki(e),await Ea({profile:e.profile})});Oe.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ki(e),await ja({profile:e.profile})});var Xi=Oe.command("profile").description("Manage connection profiles for the current repo");Xi.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>So(process.cwd()));Xi.command("use <name>").description("Set the default profile for this repo").action(e=>Po(process.cwd(),e));Xi.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>To(process.cwd(),e));var mu=Oe.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");mu.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Xt(process.cwd(),e.profile));mu.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Ca(process.cwd(),e,t.profile)});var gu=Oe.command("project").description("Choose the Document360 project for this repo (active profile's identity)");gu.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>xo(process.cwd(),e.profile));gu.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Sa(process.cwd(),e,t.profile)});Oe.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Io(),al));await e()});Oe.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>La());Oe.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(()=>(zo(),mc)),n=await t(process.cwd(),Rr.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Oe.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Rr.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 Oa(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 kd(e.cwd,e.auth,e.profile,Rr.version):await uu(e.cwd,e.auth,e.profile,Rr.version)});Oe.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});