document360-writer 0.5.121 → 0.5.122

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 +92 -90
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var Kd=Object.defineProperty;var uo=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var na=(e,t)=>{for(var n in t)Kd(e,n,{get:t[n],enumerable:!0})};import Ze from"picocolors";var q,Xd,Qd,Jd,oa,kn,f,R,L,D,O,ie,ke,W=uo(()=>{"use strict";q="#7f56d9",[Xd,Qd,Jd]=[127,86,217],oa=e=>Ze.isColorSupported?`\x1B[38;2;${Xd};${Qd};${Jd}m${e}\x1B[39m`:e,kn=e=>Ze.bold(oa(e)),f=e=>Ze.dim(e),R=e=>Ze.red(e),L=e=>Ze.yellow(e),D=e=>Ze.green(e),O=oa,ie=e=>Ze.gray(e),ke=e=>Ze.bold(e)});import{existsSync as Yt,writeFileSync as tt,readFileSync as Lu,readdirSync as Mu}from"node:fs";import{join as va}from"node:path";import{devHintsGuidePath as vo,hintsDir as $a,hooksDir as xa,architectureDir as Sa,messagesDir as Wr,creatorNotesPath as Ca,devhintsStatePath as Da,directivesPath as Ra,DIRECTIVES_HEADER as Uu,roadmapPath as Pa,ROADMAP_HEADER as Wu,ensureDir as $n,writeMessage as Fu,listOpenForDev as Hu}from"document360-engine";function ja(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var Xd=Object.defineProperty;var uo=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var oa=(e,t)=>{for(var n in t)Xd(e,n,{get:t[n],enumerable:!0})};import Ze from"picocolors";var q,Qd,Jd,Zd,ra,kn,f,R,O,D,L,ie,ke,W=uo(()=>{"use strict";q="#7f56d9",[Qd,Jd,Zd]=[127,86,217],ra=e=>Ze.isColorSupported?`\x1B[38;2;${Qd};${Jd};${Zd}m${e}\x1B[39m`:e,kn=e=>Ze.bold(ra(e)),f=e=>Ze.dim(e),R=e=>Ze.red(e),O=e=>Ze.yellow(e),D=e=>Ze.green(e),L=ra,ie=e=>Ze.gray(e),ke=e=>Ze.bold(e)});import{existsSync as Yt,writeFileSync as tt,readFileSync as Mu,readdirSync as Uu}from"node:fs";import{join as $a}from"node:path";import{devHintsGuidePath as vo,hintsDir as xa,hooksDir as Ca,architectureDir as Da,messagesDir as Wr,creatorNotesPath as Ra,devhintsStatePath as ja,directivesPath as Pa,DIRECTIVES_HEADER as Wu,roadmapPath as Sa,ROADMAP_HEADER as Fu,ensureDir as $n,writeMessage as Hu,listOpenForDev as qu}from"document360-engine";function Aa(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
3
3
 
4
4
  <!-- devhints script v${ae} \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 Bu(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
221
+ `}function Vu(){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 Kt(e){$n($a(e)),$n(Sa(e)),$n(Wr(e));for(let n of[$a(e),Wr(e)]){let o=va(n,".gitkeep");Yt(o)||tt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
236
- `)}Yt(Ca(e))||tt(Ca(e),Bu()),Yt(Ra(e))||tt(Ra(e),Uu),Yt(Pa(e))||tt(Pa(e),Wu),tt(vo(e),ja()),$n(xa(e)),tt(va(xa(e),"open-questions.mjs"),qu);let t=Ee(e);return Ea(e,new Date().toISOString()),t}async function Aa(e,t){for(let n of Xt(Kt(t.cwd)))console.log(n);return{kind:"continue"}}function bt(){return[`This is document360-writer's dev hand-off setup (v${ae}).`,'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": ${ae},`,' "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 Fr(e){try{let t=Lu(Da(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Ea(e,t){let o={...Fr(e)??{},emittedVersion:ae,emittedAt:t};tt(Da(e),`${JSON.stringify(o,null,2)}
238
- `)}function Ge(e){try{return Mu(Sa(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ee(e){let n=Fr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ae?"stale":"current",completedVersion:n}}function $o(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ae};try{if(!Yt(vo(e)))return n;let o=Fr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;ae>r&&($n(Wr(e)),tt(vo(e),ja()),Ea(e,t),n.guideRefreshed=!0),ae>s&&(Hu(e).some(p=>p.kind==="request"&&p.subject.startsWith(Ta))||(Fu(e,{id:`onb${ae}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Ta}${ae})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${ae}${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:","",bt()].join(`
235
+ `}function Kt(e){$n(xa(e)),$n(Da(e)),$n(Wr(e));for(let n of[xa(e),Wr(e)]){let o=$a(n,".gitkeep");Yt(o)||tt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
236
+ `)}Yt(Ra(e))||tt(Ra(e),Vu()),Yt(Pa(e))||tt(Pa(e),Wu),Yt(Sa(e))||tt(Sa(e),Fu),tt(vo(e),Aa()),$n(Ca(e)),tt($a(Ca(e),"open-questions.mjs"),Bu);let t=Ee(e);return Na(e,new Date().toISOString()),t}async function Ea(e,t){for(let n of Xt(Kt(t.cwd)))console.log(n);return{kind:"continue"}}function bt(){return[`This is document360-writer's dev hand-off setup (v${ae}).`,'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": ${ae},`,' "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 Fr(e){try{let t=Mu(ja(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Na(e,t){let o={...Fr(e)??{},emittedVersion:ae,emittedAt:t};tt(ja(e),`${JSON.stringify(o,null,2)}
238
+ `)}function Ge(e){try{return Uu(Da(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ee(e){let n=Fr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ae?"stale":"current",completedVersion:n}}function $o(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ae};try{if(!Yt(vo(e)))return n;let o=Fr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;ae>r&&($n(Wr(e)),tt(vo(e),Aa()),Na(e,t),n.guideRefreshed=!0),ae>s&&(qu(e).some(p=>p.kind==="request"&&p.subject.startsWith(Ta))||(Hu(e,{id:`onb${ae}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Ta}${ae})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${ae}${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:","",bt()].join(`
239
239
  `)}),n.notifiedBuilder=!0))}catch{}return n}function xo(e){if(!Yt(vo(e)))return[];let t=Ee(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${ae}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,zt,bt(),zt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Hr(){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 Co(){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):",zt,Hr(),zt]}function Xt(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${ae}.`," 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):",zt,bt(),zt,"","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 zt,ae,qu,Ta,nt=uo(()=>{"use strict";zt="-".repeat(64),ae=10,qu=`#!/usr/bin/env node
240
+ `)}function Co(){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):",zt,Hr(),zt]}function Xt(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${ae}.`," 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):",zt,bt(),zt,"","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 zt,ae,Bu,Ta,nt=uo(()=>{"use strict";zt="-".repeat(64),ae=10,Bu=`#!/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
- `;Ta="Re-run dev\u2194docs onboarding (protocol v"});var Ha={};na(Ha,{initCommand:()=>Br,scaffoldInit:()=>qr});import{input as xn,confirm as Vu}from"@inquirer/prompts";import{basename as Na,join as Ro}from"node:path";import{existsSync as Qt,readFileSync as Gu,readdirSync as Yu,writeFileSync as zu}from"node:fs";import{writeProjectConfig as Ia,readProjectConfig as Ku,projectConfigPath as _a,writerDir as Xu,DEFAULT_DOCS_DIR as Oa,DEFAULT_CAPTURE_DIR as La,DEFAULT_OUTPUT_DIR as Ma}from"document360-engine";function qr(e,t="berlin"){let n=_a(e);if(Qt(n))return{created:!1,path:n,profileName:""};let o={projectId:Wa(e)??Na(e),docsDir:Oa,captureDir:La,outputDir:Ma,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Fa(e)};return Ia(o,e),Ua(e),{created:!0,path:n,profileName:t}}function Ua(e){let t=Ro(Xu(e),".gitignore");Qt(t)||zu(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
279
- `),"utf8")}async function Br(){let e=process.cwd(),t=_a(e);if(Qt(t)&&!await Vu({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Wa(e)??Na(e),o=await xn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await xn({message:"Capture directory (where document360-capture .spec.ts files live):",default:La}),s=await xn({message:"Screenshot output directory:",default:Ma}),l=await xn({message:"Default connection profile name:",default:"berlin"}),p=await xn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),m={projectId:o,docsDir:Oa,captureDir:r,outputDir:s,profiles:{[l]:{connection:{environment:p},production:!1}},defaultProfile:l,authoritativeSourceFiles:Fa(e)},k=Ku(e);k?.terminologyGlossary&&(m.terminologyGlossary=k.terminologyGlossary),Ia(m,e),Ua(e);let g=Kt(e);console.log(""),console.log(D(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${O(`d360-writer login --profile ${l}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let T of Xt(g))console.log(T);return console.log(""),console.log(`${f("Then ask:")} ${O('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Wa(e){let t=Ro(e,"package.json");if(!Qt(t))return null;try{return JSON.parse(Gu(t,"utf8")).name??null}catch{return null}}function Fa(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Qt(Ro(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Ro(e,n);Qt(o)&&!Qu(o)&&t.push(n)}return t}function Qu(e){try{return Yu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Po=uo(()=>{"use strict";W();nt()});var Xl={};na(Xl,{doctorCommand:()=>An,renderDoctorChecks:()=>Kl,runDoctorChecks:()=>zl});import{existsSync as Bf}from"node:fs";import{d360GetAll as Vf,getAccessToken as Gf,isExpired as Ms,loadProfileMap as Yf,loadTokens as zf,packageSkillsDir as Gl,ENGINE_VERSION as Kf,projectConfigPath as Xf,readProjectConfig as Qf,DEFAULT_DOCS_DIR as Jf,fetchManifestSummary as Zf,resolveActiveProfile as eh,classifyClaudeAuth as th,CLAUDE_CODE_SETUP_HINT as Yl,resolveModelSetting as nh,probeModel as oh,detectAppType as rh,playbookSkillName as sh,D360AuthError as ih}from"document360-engine";async function zl(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Kf}`});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=th();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. ${Yl}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Yl});let s=nh(e);if(n.push({level:"ok",label:`Model: ${s.model} (${s.source==="auto"?"auto \u2014 right-sized for docs; /model to change":s.source})`}),r.state==="ready"){let P=await oh(e,s.model??void 0);P.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(P.latencyMs/1e3).toFixed(1)}s`}):P.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${P.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let l=Qf(e);if(!l)return n.push({level:"fail",label:`No ${Xf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${l.projectId}`});let p=(l.docsDir??Jf).replace(/\/+$/,"");n.push(l.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let m=l.authoritativeSourceFiles??[];n.push(m.length>0?{level:"ok",label:`Sources: docs grounded in ${m.length} path(s) (${m.slice(0,3).join(", ")}${m.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let k=l.appType??rh(e);if(k){let P=l.appType?"from config":"auto-detected",N=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${P})${N?` \u2192 ${sh(k)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let g;try{g=eh(e),n.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(P){return n.push({level:"fail",label:`Profile config: ${P.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let T=zf(g.name);T?Ms(T)&&!T.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Ms(T)?n.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(T.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${g.name})`}),n.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let v=Yf(e,g.name);v?v.projectId&&g.project.projectId&&v.projectId!==g.project.projectId?n.push({level:"fail",label:`Category map projectId (${v.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(v.articles).length} articles, ${Object.keys(v.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),n.push(Bf(Gl())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Gl()}`,fix:"Reinstall document360-writer (broken install)"});let _=Ee(e);if(_.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ae})`}):_.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${_.completedVersion}, current is v${ae}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),T&&(!Ms(T)||T.refreshToken)){let P={profile:g.name,connection:g.connection};try{await Gf(P);let S=await Vf(P,"/v3/projects");n.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${S.length} project(s) visible`})}catch(S){n.push({level:"fail",label:`API call failed: ${S.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=v?.projectId??g.project.projectId;if(N&&g.project.workspaceId)try{let S=await Zf(P,N,g.project.workspaceId);if(S){let M=(S.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${g.connection.name} (${S.languages?.length??0} language${(S.languages?.length??0)===1?"":"s"}) \xB7 hash ${M||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${g.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(S){S instanceof ih||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(S.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??N})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${S.message.slice(0,80)})`})}}return n}function Kl(e){let t=[""];for(let r of e){let s=r.level==="ok"?D("\u2713"):r.level==="warn"?L("\u26A0"):R("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${O(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?D(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):R(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function An(e,t){console.log(f("Running checks\u2026"));for(let n of Kl(await zl(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Wo=uo(()=>{"use strict";nt();W()});import{Command as Rw}from"commander";import{createRequire as Pw}from"node:module";import{AUTH_MODES as Tw}from"document360-engine";import{input as pu}from"@inquirer/prompts";import{loginPkce as fu,refreshTokens as hu,toStoredTokens as ca,clearTokens as mu,decodeJwtClaims as la,isExpired as gu,loadTokens as wu,saveTokens as da,resolveActiveProfile as mo,setProfileProject as yu,readProjectConfig as ku}from"document360-engine";W();import{select as Zd}from"@inquirer/prompts";import{resolveActiveProfile as eu,setProfileProject as tu,resolveProjectId as nu,listWorkspaces as ou}from"document360-engine";async function bn(e,t){let n=eu(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??nu(o);return{workspaces:await ou(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var ra=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function _r(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 po(e,t,n,o,r){tu(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function sa(e,t,n){let o;try{o=await bn(e,n)}catch(s){return console.log(R(`Could not list workspaces: ${s.message}`)),1}let r=_r(o.workspaces,t);return r?(po(e,o.profile,o.projectId,r.id,r.name),console.log(D(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(R(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Gt(e,t){let n;try{n=await bn(e,t)}catch(k){console.log(R(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:l}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===l?O("\u25CF"):" "} ${ra(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Zd({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${ra(k)}${k.id===l?" (current)":""}`,value:k.id}))}),m=o.find(k=>k.id===p);po(e,s,r,p,m?.name),console.log(D(`\u2713 Workspace set to "${m?.name??p}" for profile "${s}".`))}W();import{select as ru}from"@inquirer/prompts";import{resolveActiveProfile as su,setProfileProject as iu,listProjects as au}from"document360-engine";async function et(e,t){let n=su(e,t),o={profile:n.name,connection:n.connection};return{projects:await au(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ia=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Or(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 fo(e,t,n,o){iu(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function aa(e,t,n){let o;try{o=await et(e,n)}catch(s){return console.log(R(`Could not list projects: ${s.message}`)),1}let r=Or(o.projects,t);return r?(fo(e,o.profile,r.id,r.name),console.log(D(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(R(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function ho(e,t){let n;try{n=await et(e,t)}catch(m){console.log(R(`Could not list projects: ${m.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let m of o)console.log(` ${m.id===s?O("\u25CF"):" "} ${ia(m)} ${f(m.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let l=await ru({message:"Select the Document360 project for this repo:",choices:o.map(m=>({name:`${ia(m)}${m.id===s?" (current)":""}`,value:m.id}))}),p=o.find(m=>m.id===l);fo(e,r,l,p?.name),console.log(D(`\u2713 Project set to "${p?.name??l}" for profile "${r}". Next: pick a workspace.`))}W();import lu from"picocolors";function cu(e=process.env){return e.FORCE_HYPERLINK==="0"||!lu.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 du(e,t=e,n){return cu(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var uu=/https?:\/\/[^\s\x1b]+/g;function vn(e,t){return e.replace(uu,n=>du(n,n,t))}function ua(e){return{...la(e.idToken)??{},...la(e.accessToken)??{}}}function go(e){let t=ua(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 wo(e){let t=mo(process.cwd(),e.profile),n=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await fu(n,{manual:e.manual,promptForRedirect:s=>pu({message:s})},s=>console.log(vn(s))),r=ca(t.name,o);if(da(r),await Lr(r,t.name,s=>console.log(f(s))),console.log(""),console.log(D(`\u2713 Logged in to "${t.name}" as ${go(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{ku(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Gt(process.cwd(),t.name))}catch{}}async function Lr(e,t,n){let r=ua(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(mo(process.cwd(),t).project.projectId)return;let l;try{let{projects:p}=await et(process.cwd(),t);l=p.find(m=>m.id===r)?.name}catch{}yu(process.cwd(),t,{projectId:r,projectName:l}),n(` Project "${l??r}" written to profile "${t}".`)}catch{}}async function pa(e){let t=mo(process.cwd(),e.profile),n=t.connection,o=wu(t.name);if(!o){console.log(R(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${O(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${go(o)}`),gu(o))if(o.refreshToken)try{let r=ca(t.name,await hu(n,o.refreshToken));da(r),console.log(D(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(L("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function fa(e){let t=mo(process.cwd(),e.profile);mu(t.name)?console.log(D(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as ha,writeProjectConfig as bu,resolveActiveProfile as vu,loadTokens as $u,isExpired as xu}from"document360-engine";function yo(e){let t=ha(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(R("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?O("\u25CF "):" ",s=o.production?L(" \u26A0 PRODUCTION"):"",l=o.connection.environment??"(inline)",p=$u(n),m=p?xu(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${O(n)} \u2192 ${l}${s} [${m}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function ko(e,t){let n=ha(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(R(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,bu(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(D(`\u2713 Default profile is now "${t}"${o}`))}function bo(e,t){try{let n=vu(e,t);console.log(""),console.log(`Profile ${O(n.name)}${n.production?L(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(R(n.message)),process.exitCode=1}}W();import{existsSync as Cu,readdirSync as Ru,statSync as ma}from"node:fs";import{join as ga}from"node:path";import{apiLogDir as Pu}from"document360-engine";function wa(){let e=Pu();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!Cu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Ru(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(ma(ga(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(ma(ga(e,r)).size/1024).toFixed(1);console.log(` ${R(r)} ${f(`${s} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as Tu,resolveAuth as Su,findByName as Du,slugify as ju,touchSession as Au,upsertSession as Eu,resolveActiveProfile as Nu}from"document360-engine";async function ya(e,t,n,o,r,s){let l=Su(n);l.kind==="none"&&(console.error(""),console.error(R("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2)),l.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Nu(e,r)}catch(v){console.error(R(`Document360 profile error: ${v.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(R("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let m;if(o){let v=Du(e,o);v||(console.error(R(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),m=v.uuid,console.error(f(`Resuming "${v.name}"`))}let k=Tu({cwd:e,resume:m,profileName:r,allowProdWrites:s===!0}),g=m??null,T=1;for await(let v of k.send(t))switch(v.type){case"session":if(!g){g=v.sessionId;let _=new Date().toISOString();Eu({uuid:g,name:ju(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:_,updatedAt:_})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(ie(` \u2699 ${v.name}`));break;case"result":T=v.ok?0:1,console.error(f(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(R("agent finished with an error result"));break;case"error":console.error(""),console.error(R(`agent error: ${v.message}`)),process.exit(1)}g&&Au(g),process.stdout.write(`
280
- `),process.exit(T)}import{createInterface as Nm}from"node:readline/promises";import{createSession as mi,resolveAuth as Im,getSession as _m,setTitle as Om,slugify as Lm,touchSession as Uc,upsertSession as Mm,generateTitle as Um,resolveActiveProfile as Wc,resolveModelSetting as Wm,readProjectConfig as Fm,resolveAndPersistAppType as Hm,decodeJwtClaims as Mc,isExpired as qm,loadTokens as Bm,isDirectiveMention as Vm,stripDirectiveMention as Gm,appendDirective as Ym,reconcileUpgradeActions as zm,stampArticles as Km,listArticleFiles as Xm,CONTENT_CAP_VERSION as Qm}from"document360-engine";import{ENGINE_VERSION as _u}from"document360-engine";var Ae=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --all to author capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then run d360-capture in your app's repo \u2014 it signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot --list",s:"See capture status \u2014 which specs exist and which are done."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"d360-capture is a separate Playwright CLI \u2014 run it in the app's repo (needs its URL + a login)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress + the next step (`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:"Author capture specs (--all / --list)."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function Iu(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 ka(e){let n=[e?`document360-writer \u2014 help \xB7 v${e.version} \xB7 engine v${e.engineVersion}`:"document360-writer \u2014 help",""];for(let o of Ae){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(Iu(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function Mr(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:_u}:void 0;for(let o of ka(n))console.log(o);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}W();import{getSession as Ou}from"document360-engine";async function ba(e,t){let n=t.currentUuid(),o=n?Ou(n):void 0;return console.log(o?f(`
278
+ `;Ta="Re-run dev\u2194docs onboarding (protocol v"});var qa={};oa(qa,{initCommand:()=>Br,scaffoldInit:()=>qr});import{input as xn,confirm as Gu}from"@inquirer/prompts";import{basename as Ia,join as Ro}from"node:path";import{existsSync as Qt,readFileSync as Yu,readdirSync as zu,writeFileSync as Ku}from"node:fs";import{writeProjectConfig as _a,readProjectConfig as Xu,projectConfigPath as La,writerDir as Qu,DEFAULT_DOCS_DIR as Oa,DEFAULT_CAPTURE_DIR as Ma,DEFAULT_OUTPUT_DIR as Ua}from"document360-engine";function qr(e,t="berlin"){let n=La(e);if(Qt(n))return{created:!1,path:n,profileName:""};let o={projectId:Fa(e)??Ia(e),docsDir:Oa,captureDir:Ma,outputDir:Ua,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Ha(e)};return _a(o,e),Wa(e),{created:!0,path:n,profileName:t}}function Wa(e){let t=Ro(Qu(e),".gitignore");Qt(t)||Ku(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
279
+ `),"utf8")}async function Br(){let e=process.cwd(),t=La(e);if(Qt(t)&&!await Gu({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Fa(e)??Ia(e),o=await xn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await xn({message:"Capture directory (where document360-capture .spec.ts files live):",default:Ma}),s=await xn({message:"Screenshot output directory:",default:Ua}),l=await xn({message:"Default connection profile name:",default:"berlin"}),p=await xn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),m={projectId:o,docsDir:Oa,captureDir:r,outputDir:s,profiles:{[l]:{connection:{environment:p},production:!1}},defaultProfile:l,authoritativeSourceFiles:Ha(e)},k=Xu(e);k?.terminologyGlossary&&(m.terminologyGlossary=k.terminologyGlossary),_a(m,e),Wa(e);let g=Kt(e);console.log(""),console.log(D(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${L(`d360-writer login --profile ${l}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let S of Xt(g))console.log(S);return console.log(""),console.log(`${f("Then ask:")} ${L('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Fa(e){let t=Ro(e,"package.json");if(!Qt(t))return null;try{return JSON.parse(Yu(t,"utf8")).name??null}catch{return null}}function Ha(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Qt(Ro(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Ro(e,n);Qt(o)&&!Ju(o)&&t.push(n)}return t}function Ju(e){try{return zu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Po=uo(()=>{"use strict";W();nt()});var Ql={};oa(Ql,{doctorCommand:()=>An,renderDoctorChecks:()=>Xl,runDoctorChecks:()=>Kl});import{existsSync as Vf}from"node:fs";import{d360GetAll as Gf,getAccessToken as Yf,isExpired as Ms,loadProfileMap as zf,loadTokens as Kf,packageSkillsDir as Yl,ENGINE_VERSION as Xf,projectConfigPath as Qf,readProjectConfig as Jf,DEFAULT_DOCS_DIR as Zf,fetchManifestSummary as eh,resolveActiveProfile as th,classifyClaudeAuth as nh,CLAUDE_CODE_SETUP_HINT as zl,resolveModelSetting as oh,probeModel as rh,detectAppType as sh,playbookSkillName as ih,D360AuthError as ah}from"document360-engine";async function Kl(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Xf}`});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=nh();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. ${zl}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:zl});let s=oh(e);if(n.push({level:"ok",label:`Model: ${s.model} (${s.source==="auto"?"auto \u2014 right-sized for docs; /model to change":s.source})`}),r.state==="ready"){let P=await rh(e,s.model??void 0);P.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(P.latencyMs/1e3).toFixed(1)}s`}):P.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${P.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let l=Jf(e);if(!l)return n.push({level:"fail",label:`No ${Qf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${l.projectId}`});let p=(l.docsDir??Zf).replace(/\/+$/,"");n.push(l.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let m=l.authoritativeSourceFiles??[];n.push(m.length>0?{level:"ok",label:`Sources: docs grounded in ${m.length} path(s) (${m.slice(0,3).join(", ")}${m.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let k=l.appType??sh(e);if(k){let P=l.appType?"from config":"auto-detected",N=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${P})${N?` \u2192 ${ih(k)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let g;try{g=th(e),n.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(P){return n.push({level:"fail",label:`Profile config: ${P.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let S=Kf(g.name);S?Ms(S)&&!S.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Ms(S)?n.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(S.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${g.name})`}),n.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let v=zf(e,g.name);v?v.projectId&&g.project.projectId&&v.projectId!==g.project.projectId?n.push({level:"fail",label:`Category map projectId (${v.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(v.articles).length} articles, ${Object.keys(v.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),n.push(Vf(Yl())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Yl()}`,fix:"Reinstall document360-writer (broken install)"});let _=Ee(e);if(_.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ae})`}):_.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${_.completedVersion}, current is v${ae}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),S&&(!Ms(S)||S.refreshToken)){let P={profile:g.name,connection:g.connection};try{await Yf(P);let T=await Gf(P,"/v3/projects");n.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${T.length} project(s) visible`})}catch(T){n.push({level:"fail",label:`API call failed: ${T.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=v?.projectId??g.project.projectId;if(N&&g.project.workspaceId)try{let T=await eh(P,N,g.project.workspaceId);if(T){let M=(T.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${g.connection.name} (${T.languages?.length??0} language${(T.languages?.length??0)===1?"":"s"}) \xB7 hash ${M||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${g.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(T){T instanceof ah||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(T.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??N})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${T.message.slice(0,80)})`})}}return n}function Xl(e){let t=[""];for(let r of e){let s=r.level==="ok"?D("\u2713"):r.level==="warn"?O("\u26A0"):R("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("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?D(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):R(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function An(e,t){console.log(f("Running checks\u2026"));for(let n of Xl(await Kl(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Wo=uo(()=>{"use strict";nt();W()});import{Command as Pw}from"commander";import{createRequire as Sw}from"node:module";import{AUTH_MODES as Tw}from"document360-engine";import{input as fu}from"@inquirer/prompts";import{loginPkce as hu,refreshTokens as mu,toStoredTokens as da,clearTokens as gu,decodeJwtClaims as ca,isExpired as wu,loadTokens as yu,saveTokens as ua,resolveActiveProfile as mo,setProfileProject as ku,readProjectConfig as bu}from"document360-engine";W();import{select as eu}from"@inquirer/prompts";import{resolveActiveProfile as tu,setProfileProject as nu,resolveProjectId as ou,listWorkspaces as ru}from"document360-engine";async function bn(e,t){let n=tu(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??ou(o);return{workspaces:await ru(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var sa=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function _r(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 po(e,t,n,o,r){nu(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ia(e,t,n){let o;try{o=await bn(e,n)}catch(s){return console.log(R(`Could not list workspaces: ${s.message}`)),1}let r=_r(o.workspaces,t);return r?(po(e,o.profile,o.projectId,r.id,r.name),console.log(D(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(R(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Gt(e,t){let n;try{n=await bn(e,t)}catch(k){console.log(R(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:l}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===l?L("\u25CF"):" "} ${sa(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await eu({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${sa(k)}${k.id===l?" (current)":""}`,value:k.id}))}),m=o.find(k=>k.id===p);po(e,s,r,p,m?.name),console.log(D(`\u2713 Workspace set to "${m?.name??p}" for profile "${s}".`))}W();import{select as su}from"@inquirer/prompts";import{resolveActiveProfile as iu,setProfileProject as au,listProjects as lu}from"document360-engine";async function et(e,t){let n=iu(e,t),o={profile:n.name,connection:n.connection};return{projects:await lu(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var aa=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Lr(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 fo(e,t,n,o){au(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function la(e,t,n){let o;try{o=await et(e,n)}catch(s){return console.log(R(`Could not list projects: ${s.message}`)),1}let r=Lr(o.projects,t);return r?(fo(e,o.profile,r.id,r.name),console.log(D(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(R(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function ho(e,t){let n;try{n=await et(e,t)}catch(m){console.log(R(`Could not list projects: ${m.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let m of o)console.log(` ${m.id===s?L("\u25CF"):" "} ${aa(m)} ${f(m.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let l=await su({message:"Select the Document360 project for this repo:",choices:o.map(m=>({name:`${aa(m)}${m.id===s?" (current)":""}`,value:m.id}))}),p=o.find(m=>m.id===l);fo(e,r,l,p?.name),console.log(D(`\u2713 Project set to "${p?.name??l}" for profile "${r}". Next: pick a workspace.`))}W();import cu from"picocolors";function du(e=process.env){return e.FORCE_HYPERLINK==="0"||!cu.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 uu(e,t=e,n){return du(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var pu=/https?:\/\/[^\s\x1b]+/g;function vn(e,t){return e.replace(pu,n=>uu(n,n,t))}function pa(e){return{...ca(e.idToken)??{},...ca(e.accessToken)??{}}}function go(e){let t=pa(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 wo(e){let t=mo(process.cwd(),e.profile),n=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await hu(n,{manual:e.manual,promptForRedirect:s=>fu({message:s})},s=>console.log(vn(s))),r=da(t.name,o);if(ua(r),await Or(r,t.name,s=>console.log(f(s))),console.log(""),console.log(D(`\u2713 Logged in to "${t.name}" as ${go(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{bu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Gt(process.cwd(),t.name))}catch{}}async function Or(e,t,n){let r=pa(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(mo(process.cwd(),t).project.projectId)return;let l;try{let{projects:p}=await et(process.cwd(),t);l=p.find(m=>m.id===r)?.name}catch{}ku(process.cwd(),t,{projectId:r,projectName:l}),n(` Project "${l??r}" written to profile "${t}".`)}catch{}}async function fa(e){let t=mo(process.cwd(),e.profile),n=t.connection,o=yu(t.name);if(!o){console.log(R(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${L(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${go(o)}`),wu(o))if(o.refreshToken)try{let r=da(t.name,await mu(n,o.refreshToken));ua(r),console.log(D(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(O(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(O("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function ha(e){let t=mo(process.cwd(),e.profile);gu(t.name)?console.log(D(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as ma,writeProjectConfig as vu,resolveActiveProfile as $u,loadTokens as xu,isExpired as Cu}from"document360-engine";function yo(e){let t=ma(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(R("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?L("\u25CF "):" ",s=o.production?O(" \u26A0 PRODUCTION"):"",l=o.connection.environment??"(inline)",p=xu(n),m=p?Cu(p)&&!p.refreshToken?O("expired"):f("logged in"):f("not logged in");console.log(`${r}${L(n)} \u2192 ${l}${s} [${m}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function ko(e,t){let n=ma(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(R(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,vu(n,e);let o=n.profiles[t].production?O(" \u26A0 PRODUCTION"):"";console.log(D(`\u2713 Default profile is now "${t}"${o}`))}function bo(e,t){try{let n=$u(e,t);console.log(""),console.log(`Profile ${L(n.name)}${n.production?O(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(R(n.message)),process.exitCode=1}}W();import{existsSync as Ru,readdirSync as Pu,statSync as ga}from"node:fs";import{join as wa}from"node:path";import{apiLogDir as Su}from"document360-engine";function ya(){let e=Su();if(console.log(""),console.log(`Document360 API logs: ${L(e)}`),!Ru(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Pu(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(ga(wa(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(ga(wa(e,r)).size/1024).toFixed(1);console.log(` ${R(r)} ${f(`${s} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as Tu,resolveAuth as Du,findByName as ju,slugify as Au,touchSession as Eu,upsertSession as Nu,resolveActiveProfile as Iu}from"document360-engine";async function ka(e,t,n,o,r,s){let l=Du(n);l.kind==="none"&&(console.error(""),console.error(R("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),process.exit(2)),l.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Iu(e,r)}catch(v){console.error(R(`Document360 profile error: ${v.message}`)),process.exit(2)}p.production&&(console.error(O(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(R("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let m;if(o){let v=ju(e,o);v||(console.error(R(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),m=v.uuid,console.error(f(`Resuming "${v.name}"`))}let k=Tu({cwd:e,resume:m,profileName:r,allowProdWrites:s===!0}),g=m??null,S=1;for await(let v of k.send(t))switch(v.type){case"session":if(!g){g=v.sessionId;let _=new Date().toISOString();Nu({uuid:g,name:Au(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:_,updatedAt:_})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(ie(` \u2699 ${v.name}`));break;case"result":S=v.ok?0:1,console.error(f(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(R("agent finished with an error result"));break;case"error":console.error(""),console.error(R(`agent error: ${v.message}`)),process.exit(1)}g&&Eu(g),process.stdout.write(`
280
+ `),process.exit(S)}import{createInterface as Im}from"node:readline/promises";import{createSession as gi,resolveAuth as _m,getSession as Lm,setTitle as Om,slugify as Mm,touchSession as Wc,upsertSession as Um,generateTitle as Wm,resolveActiveProfile as Fc,resolveModelSetting as Fm,readProjectConfig as Hm,resolveAndPersistAppType as qm,decodeJwtClaims as Uc,isExpired as Bm,loadTokens as Vm,isDirectiveMention as Gm,stripDirectiveMention as Ym,appendDirective as zm,reconcileUpgradeActions as Km,stampArticles as Xm,listArticleFiles as Qm,CONTENT_CAP_VERSION as Jm}from"document360-engine";import{ENGINE_VERSION as Lu}from"document360-engine";var Ae=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --all to author capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then run d360-capture in your app's repo \u2014 it signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot --list",s:"See capture status \u2014 which specs exist and which are done."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"d360-capture is a separate Playwright CLI \u2014 run it in the app's repo (needs its URL + a login)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress + the next step (`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:"Author capture specs (--all / --list)."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function _u(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 ba(e){let n=[e?`document360-writer \u2014 help \xB7 v${e.version} \xB7 engine v${e.engineVersion}`:"document360-writer \u2014 help",""];for(let o of Ae){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(_u(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function Mr(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:Lu}:void 0;for(let o of ba(n))console.log(o);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}W();import{getSession as Ou}from"document360-engine";async function va(e,t){let n=t.currentUuid(),o=n?Ou(n):void 0;return console.log(o?f(`
281
281
  (conversation reset \u2014 "${o.name}" is still available via /resume)
282
282
  `):f(`
283
283
  (conversation reset \u2014 agent will start fresh on the next prompt)
284
- `)),{kind:"clear"}}async function Ur(){return{kind:"exit"}}Po();W();import{readMcpConfig as Vr,writeMcpConfig as qa}from"document360-engine";async function To(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Ju(),{kind:"continue"}):t==="add"?(Zu(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(ep(e.slice(1)),{kind:"continue"}):(console.log(R(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Ju(){let e=Vr(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
284
+ `)),{kind:"clear"}}async function Ur(){return{kind:"exit"}}Po();W();import{readMcpConfig as Vr,writeMcpConfig as Ba}from"document360-engine";async function So(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Zu(),{kind:"continue"}):t==="add"?(ep(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(tp(e.slice(1)),{kind:"continue"}):(console.log(R(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Zu(){let e=Vr(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
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(` ${O(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${O(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Zu(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(R("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(R(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Vr(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let l={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let m=o[++p],k=m?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(R(`-H expects key:value (no spaces). Got: ${m??"(nothing)"}`));return}l[k[1].trim()]=k[2].trim()}else{console.log(R(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(l).length>0?l:void 0}}r.servers[t]=s,qa(r),console.log(""),console.log(D(`\u2713 Registered "${t}" (${n})`)),console.log(L(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function ep(e){let t=e[0];if(!t){console.log(R("Usage: /mcp remove <name>"));return}let n=Vr();if(!n.servers[t]){console.log(R(`No server named "${t}".`));return}delete n.servers[t],qa(n),console.log(D(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as wp}from"node:fs";import{join as yp}from"node:path";import{select as kp}from"@inquirer/prompts";import{computeSyncStatus as So,planPartitions as bp,relatedArticlePaths as vp,resolveModelForOperation as $p,runPartitioned as xp,loadProfileMap as Cp,resolveActiveProfile as Rp,resolveCrossLinks as Pp,applyStructureOrder as rl,orderSyncLine as sl,applyRelatedArticles as il,relatedSyncLine as al}from"document360-engine";import Z from"picocolors";import el from"wrap-ansi";import Qr from"string-width";W();import ot from"picocolors";import Gr from"wrap-ansi";import Yr from"string-width";var Jt=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"roadmap",usage:"/roadmap [done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done` 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"}],Ba={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function Va(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Ba[n])return Ba[n];let o=Jt.find(r=>r.name===t);return o?o.desc:""}function Ga(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Jt.filter(n=>n.name.startsWith(t))}function Ya(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var tp=new RegExp(`^\\s*/(?:${Jt.map(e=>e.name).join("|")})(?:\\s|$)`),za=e=>tp.test(e),Ka=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Xa=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Qa=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 p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(Ka(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Xa(t[o+1])){let p=Qa(r);o+=2;let m=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)m.push(Qa(t[o++]));n.push({kind:"table",header:p,rows:m});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let m=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(m),text:m.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}if(za(r)){n.push({kind:"para",text:r.trim()}),o++;continue}let l=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!za(t[o])&&!Ka(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Xa(t[o+1]));)l.push(t[o++]);n.push({kind:"para",text:l.join(" ")})}return n}function zr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?ot.bold(t.slice(2,-2)):t.startsWith("`")?O(t.slice(1,-1)):ot.italic(t.slice(1,-1)))}var op=(e,t)=>e+" ".repeat(Math.max(0,t-Yr(e)));function rp(e,t,n){let o=e.length,r=e.map((P,N)=>Math.max(Yr(P),...t.map(S=>Yr(S[N]??"")))),s=Math.max(24,n),l=3*o+1,p=[...r],m=()=>p.reduce((P,N)=>P+N,0)+l,k=0;for(;m()>s&&k++<1e4;){let P=-1,N=6;for(let S=0;S<o;S++)p[S]>N&&(N=p[S],P=S);if(P===-1)break;p[P]-=1}let g=(P,N,S)=>ot.gray(P+p.map(M=>"\u2500".repeat(M+2)).join(N)+S),T=ot.gray("\u2502"),v=(P,N)=>{let S=p.map((V,Y)=>{let ue=P[Y]??"",_e=N?ot.bold(ue):zr(ue);return Gr(_e,V,{hard:!0}).split(`
288
- `)}),M=Math.max(...S.map(V=>V.length)),B=[];for(let V=0;V<M;V++)B.push(p.map((Y,ue)=>`${T} ${op(S[ue][V]??"",Y)} `).join("")+T);return B.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)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${L(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function ep(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(R("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(R(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Vr(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let l={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let m=o[++p],k=m?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(R(`-H expects key:value (no spaces). Got: ${m??"(nothing)"}`));return}l[k[1].trim()]=k[2].trim()}else{console.log(R(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(l).length>0?l:void 0}}r.servers[t]=s,Ba(r),console.log(""),console.log(D(`\u2713 Registered "${t}" (${n})`)),console.log(O(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function tp(e){let t=e[0];if(!t){console.log(R("Usage: /mcp remove <name>"));return}let n=Vr();if(!n.servers[t]){console.log(R(`No server named "${t}".`));return}delete n.servers[t],Ba(n),console.log(D(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as yp}from"node:fs";import{join as kp}from"node:path";import{select as bp}from"@inquirer/prompts";import{computeSyncStatus as To,planPartitions as vp,relatedArticlePaths as $p,resolveModelForOperation as xp,runPartitioned as Cp,loadProfileMap as Rp,resolveActiveProfile as Pp,resolveCrossLinks as Sp,applyStructureOrder as sl,orderSyncLine as il,applyRelatedArticles as al,relatedSyncLine as ll}from"document360-engine";import Z from"picocolors";import tl from"wrap-ansi";import Qr from"string-width";W();import ot from"picocolors";import Gr from"wrap-ansi";import Yr from"string-width";var Jt=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"roadmap",usage:"/roadmap [done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done` 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"}],Va={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function Ga(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Va[n])return Va[n];let o=Jt.find(r=>r.name===t);return o?o.desc:""}function Ya(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Jt.filter(n=>n.name.startsWith(t))}function za(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var np=new RegExp(`^\\s*/(?:${Jt.map(e=>e.name).join("|")})(?:\\s|$)`),Ka=e=>np.test(e),Xa=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Qa=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Ja=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function op(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 p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(Xa(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Qa(t[o+1])){let p=Ja(r);o+=2;let m=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)m.push(Ja(t[o++]));n.push({kind:"table",header:p,rows:m});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let m=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(m),text:m.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}if(Ka(r)){n.push({kind:"para",text:r.trim()}),o++;continue}let l=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Ka(t[o])&&!Xa(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Qa(t[o+1]));)l.push(t[o++]);n.push({kind:"para",text:l.join(" ")})}return n}function zr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?ot.bold(t.slice(2,-2)):t.startsWith("`")?L(t.slice(1,-1)):ot.italic(t.slice(1,-1)))}var rp=(e,t)=>e+" ".repeat(Math.max(0,t-Yr(e)));function sp(e,t,n){let o=e.length,r=e.map((P,N)=>Math.max(Yr(P),...t.map(T=>Yr(T[N]??"")))),s=Math.max(24,n),l=3*o+1,p=[...r],m=()=>p.reduce((P,N)=>P+N,0)+l,k=0;for(;m()>s&&k++<1e4;){let P=-1,N=6;for(let T=0;T<o;T++)p[T]>N&&(N=p[T],P=T);if(P===-1)break;p[P]-=1}let g=(P,N,T)=>ot.gray(P+p.map(M=>"\u2500".repeat(M+2)).join(N)+T),S=ot.gray("\u2502"),v=(P,N)=>{let T=p.map((V,Y)=>{let ue=P[Y]??"",_e=N?ot.bold(ue):zr(ue);return Gr(_e,V,{hard:!0}).split(`
288
+ `)}),M=Math.max(...T.map(V=>V.length)),B=[];for(let V=0;V<M;V++)B.push(p.map((Y,ue)=>`${S} ${rp(T[ue][V]??"",Y)} `).join("")+S);return B.join(`
289
289
  `)},_=[g("\u250C","\u252C","\u2510"),v(e,!0)];return _.push(t.length===0?g("\u2514","\u2534","\u2518"):g("\u251C","\u253C","\u2524")),t.forEach((P,N)=>{_.push(v(P,!1)),_.push(N===t.length-1?g("\u2514","\u2534","\u2518"):g("\u251C","\u253C","\u2524"))}),_.join(`
290
- `)}function sp(e,t){switch(e.kind){case"heading":return ot.bold(e.text);case"hr":return ot.gray("\u2500".repeat(t));case"para":return Gr(zr(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",s=" ".repeat(2+r.length+1),[l="",...p]=Gr(zr(o.text),Math.max(10,t-s.length)).split(`
290
+ `)}function ip(e,t){switch(e.kind){case"heading":return ot.bold(e.text);case"hr":return ot.gray("\u2500".repeat(t));case"para":return Gr(zr(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",s=" ".repeat(2+r.length+1),[l="",...p]=Gr(zr(o.text),Math.max(10,t-s.length)).split(`
291
291
  `);return` ${r} ${l}`+p.map(m=>`
292
292
  ${s}${m}`).join("")}).join(`
293
293
  `)}case"code":return e.lines.map(n=>ot.gray(" "+n)).join(`
294
- `);case"table":return rp(e.header,e.rows,t)}}function Kr(e,t){let n=Math.max(20,t);return np(e).map(o=>sp(o,n)).join(`
294
+ `);case"table":return sp(e.header,e.rows,t)}}function Kr(e,t){let n=Math.max(20,t);return op(e).map(o=>ip(o,n)).join(`
295
295
 
296
- `)}W();import ip from"picocolors";var ap=[127,86,217],lp=[22,38,43],Ja={T:ap,E:lp},Cn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Xr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,cp=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Za(){if(!ip.isColorSupported)return[];let e=Cn[0].length,t=[];for(let n=0;n<Cn.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Ja[Cn[n][r]],l=n+1<Cn.length?Ja[Cn[n+1][r]]:void 0;s&&l?o+=`${Xr(s)}${cp(l)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Xr(s)}\u2580\x1B[39m`:l?o+=`${Xr(l)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Rn(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 Pn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function be(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function rt(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Zt=(e,t)=>` ${e.padEnd(13)}${t}`;function dp(e,t){let n=[kn("\u270E document360-writer")+Z.gray(` v${e.version} \xB7 engine v${e.engineVersion}`),Z.gray(" Reads your code, writes your docs."),"",Zt("Claude:",`${e.claude}${Z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Zt("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")),Zt("Profile:",e.configured?`${e.profile}${Z.gray(` (${e.apiUrl})`)}${e.prod?Z.bold(Z.yellow(" \u26A0 PRODUCTION")):""}`:Z.gray("\u2014 (run /init)")),Zt("Project:",e.project),Zt("Mode:",Z.gray(e.mode)),Zt("cwd:",Z.gray(e.cwd))],o=Za();if(o.length===0)return n.join(`
296
+ `)}W();import ap from"picocolors";var lp=[127,86,217],cp=[22,38,43],Za={T:lp,E:cp},Cn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Xr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,dp=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function el(){if(!ap.isColorSupported)return[];let e=Cn[0].length,t=[];for(let n=0;n<Cn.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Za[Cn[n][r]],l=n+1<Cn.length?Za[Cn[n+1][r]]:void 0;s&&l?o+=`${Xr(s)}${dp(l)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Xr(s)}\u2580\x1B[39m`:l?o+=`${Xr(l)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Rn(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 Pn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function be(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function rt(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Zt=(e,t)=>` ${e.padEnd(13)}${t}`;function up(e,t){let n=[kn("\u270E document360-writer")+Z.gray(` v${e.version} \xB7 engine v${e.engineVersion}`),Z.gray(" Reads your code, writes your docs."),"",Zt("Claude:",`${e.claude}${Z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Zt("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")),Zt("Profile:",e.configured?`${e.profile}${Z.gray(` (${e.apiUrl})`)}${e.prod?Z.bold(Z.yellow(" \u26A0 PRODUCTION")):""}`:Z.gray("\u2014 (run /init)")),Zt("Project:",e.project),Zt("Mode:",Z.gray(e.mode)),Zt("cwd:",Z.gray(e.cwd))],o=el();if(o.length===0)return n.join(`
297
297
  `);let r=2,s=3,l=Qr(o[0]);if(!(t>=r+l+s+Math.max(...n.map(g=>Qr(g)))))return[...o.map(g=>" "+g),...n].join(`
298
- `);let m=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let g=0;g<Math.max(o.length+m,n.length);g++){let T=o[g-m]??" ".repeat(l);k.push((" ".repeat(r)+T+" ".repeat(s)+(n[g]??"")).trimEnd())}return k.join(`
299
- `)}var up={error:Z.red,warn:Z.yellow,ok:Z.green,info:Z.gray};function pp(e){return e.replace(/^([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1 ")}function Jr(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return dp(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),l=50,p=e.text.split(`
300
- `).flatMap(k=>el(k,s,{hard:!0}).split(`
298
+ `);let m=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let g=0;g<Math.max(o.length+m,n.length);g++){let S=o[g-m]??" ".repeat(l);k.push((" ".repeat(r)+S+" ".repeat(s)+(n[g]??"")).trimEnd())}return k.join(`
299
+ `)}var pp={error:Z.red,warn:Z.yellow,ok:Z.green,info:Z.gray};function fp(e){return e.replace(/^([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1 ")}function Jr(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return up(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),l=50,p=e.text.split(`
300
+ `).flatMap(k=>tl(k,s,{hard:!0}).split(`
301
301
  `)),m=Math.max(0,p.length-l);return m>0&&(p=[...p.slice(0,l),Z.dim(`\u2026 +${m} more lines`)]),`
302
- `+p.map((k,g)=>o+(g===0?O(" \u276F "):" ")+k+" ".repeat(Math.max(0,s-Qr(k))+1)+r).join(`
302
+ `+p.map((k,g)=>o+(g===0?L(" \u276F "):" ")+k+" ".repeat(Math.max(0,s-Qr(k))+1)+r).join(`
303
303
  `)}case"assistant":return`
304
304
  `+Kr(e.text,n);case"tool":{let o=e.arg!==null?Z.gray(`${e.sep}(${e.arg})`):"";return`
305
- `+el(Z.green("\u25CF ")+Z.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?Z.red:Z.gray,r=e.lines.map((s,l)=>o((l===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(Z.dim(` \u2026 +${e.hidden} lines`)),r.join(`
305
+ `+tl(Z.green("\u25CF ")+Z.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?Z.red:Z.gray,r=e.lines.map((s,l)=>o((l===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(Z.dim(` \u2026 +${e.hidden} lines`)),r.join(`
306
306
  `)}case"diff":{let o=l=>l===1?"":"s",s=[Z.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(Z.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
307
- `)}case"link":return e.lines.map(o=>O(vn(` \u2B95 ${o}`))).join(`
307
+ `)}case"link":return e.lines.map(o=>L(vn(` \u2B95 ${o}`))).join(`
308
308
  `);case"preview":return`
309
309
  `+kn(`\u25A3 Preview \u2014 ${e.name}`)+`
310
310
 
311
311
  `+Kr(e.text,n);case"note":return`
312
- `+up[e.tone](vn(pp(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${Rn(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
313
- `+(e.ok?Z.magenta("\u2736 "):Z.red("\u2736 "))+Z.gray(`Cooked for ${Pn(e.seconds)} \xB7 ${Rn(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${be(e.costUsd)}`:""))}}}function tl(e,t){return e.map(n=>Jr(n,t)).join(`
314
- `)}import{resolveActiveProfile as fp,loadTokens as hp,isExpired as mp,decodeJwtClaims as nl}from"document360-engine";function gp(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ne(e,t){try{let n=fp(e,t),o=hp(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(mp(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let l={...nl(o.idToken)??{},...nl(o.accessToken)??{}}.doc360_project_id;if(typeof l=="string"&&l&&l!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${gp(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var Tn=3;function Zr(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 ol={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function es(e){return e.filter(t=>t.path!==null&&t.status in ol&&!t.link).map(t=>({path:t.path,label:ol[t.status]}))}function Do(e){let t=es(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 jo(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 Ao(e){return e.filter(t=>t.link).length}function ts(e,t){try{let n=Cp(e,Rp(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Pp(wp(yp(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 Tp(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 ll(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let s=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),l=o.get(s);l?l.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((l,p)=>l.path.localeCompare(p.path));n.push({kind:"category",label:`${Tp(r)} (${s.length})`,paths:s.map(l=>l.path),indent:!1});for(let l of s){let p=l.path.replace(/\\/g,"/").split("/").pop()??l.path;n.push({kind:"article",label:p,paths:[l.path],indent:!0,note:l.label})}}for(let r of[...t].sort((s,l)=>s.path.localeCompare(l.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function Eo(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 ns(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),s=e.filter(v=>!v.ok),l=e.reduce((v,_)=>v+o(_),0),p=r.reduce((v,_)=>v+o(_),0),m=n==="api"?`${be(e.reduce((v,_)=>v+_.costUsd,0))} total`:rt(e.reduce((v,_)=>v+_.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,g=v=>`${v} article${v===1?"":"s"}`,T=[];if(s.length===0)T.push(`Published ${g(l)} (${k}) successfully \xB7 ${m}.`),T.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{T.push(`Published ${p}/${g(l)} (${k}) \xB7 ${m}.`),T.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let v of s)T.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return T}async function vt(e,t){let{model:n}=$p(e.cwd,"standard"),o=async(r,s)=>{let l=bp(r);console.log(f(s?`Resolving cross-links in ${r.length} article${r.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${r.length} article${r.length===1?"":"s"} across ${l.length} partition${l.length===1?"":"s"} (\u2264${Tn} agents at once) on ${n}\u2026`)),s||console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let p=!1;for await(let m of xp({cwd:e.cwd,partitions:l,promptFor:k=>Eo(k.paths),concurrency:Tn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(m.type==="partition_status")m.status==="running"?console.log(f(` \u25B8 ${m.label} \u2014 publishing\u2026`)):m.status==="done"?console.log(D(` \u2713 ${m.label}`)):console.log(R(` \u2717 ${m.label}`));else if(m.type==="run_done"){p=m.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let T of ns(m.results,l,k))console.log(m.ok?D(T):L(T));let g=ts(e.cwd,e.profileName);g&&console.log(f(g));try{let T=sl(await rl({cwd:e.cwd,profileName:e.profileName}));T&&console.log(f(T))}catch{}try{let T=al(await il({cwd:e.cwd,profileName:e.profileName}));T&&console.log(f(T))}catch{}}return p};try{if(!await o(t,!1)){let s=await os(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(R(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function No(e,t,n){let o=vp(e,n);if(o.length===0)return[];let r=new Set(es((await So({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function os(e,t,n){try{let o=new Set(n),r=await So({cwd:e,profileName:t});return es(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function cl(e,t){let n=Ne(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await No(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(D("\u2713 All related articles are already published.")),{kind:"continue"}):await vt(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await So({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:l}=Do(r.entries),p=Ao(r.entries),m=e.includes("--force")&&l.length>0;p>0&&console.log(L(`\u26A0 ${p} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),l.length>0&&!m&&console.log(L(jo(l.length)));let k=m?[...s,...l]:s;if(k.length===0){if(l.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(D(p>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let g=sl(await rl({cwd:t.cwd,profileName:t.profileName}));g&&console.log(f(g));let T=al(await il({cwd:t.cwd,profileName:t.profileName}));T&&console.log(f(T))}catch{}return{kind:"continue"}}return t?await vt(t,k.map(g=>g.path)):{kind:"forward-to-agent",prompt:Eo(k.map(g=>g.path)),display:"/publish --all"}}catch(r){return console.log(R(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let s=await So({cwd:t?.cwd??process.cwd()}),{clean:l,conflicts:p}=Do(s.entries);r=l;let m=Ao(s.entries);if(m>0&&console.log(L(`\u26A0 ${m} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),p.length>0&&console.log(L(jo(p.length))),r.length===0&&p.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(R(`Could not compute sync status: ${s.message}`)),console.log(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(D("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(f(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${f(`(${s.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>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(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await vt(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Zr(o),display:`/publish ${o}`}}async function Sn(){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"}}W();import{readProjectConfig as Sp}from"document360-engine";function rs(){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 Sp(n)?{kind:"forward-to-agent",prompt:rs(),display:"/discover"}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{checkbox as Dp}from"@inquirer/prompts";import{inventoryRepo as jp,readProjectConfig as ul,writeProjectConfig as Ap}from"document360-engine";function ss(e,t){let n=ul(e);n&&(n.authoritativeSourceFiles=t,Ap(n,e))}function Io(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 pl(e,t){let n=t?.cwd??process.cwd();if(!ul(n))return console.log(R("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=jp(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(O("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(Io(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Dp({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Io(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(f("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};ss(n,r),console.log(D(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as Fp}from"@inquirer/prompts";import{applyPull as ls,computeSyncStatus as vl,compareRemoteSources as Hp,planPull as $l,planImport as qp,applyImport as Bp,establishBaselines as Vp,rebaselineServerMeta as Gp,D360AuthError as Yp}from"document360-engine";W();var fl=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:R,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:L,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:O,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:R,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:R,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ie,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:f,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:f,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:ie,mark:"\xB7"}];function Ep(e){return e.path?e.path:`${e.title??"(untitled)"} ${ie(`[${e.articleId}]`)}`}function Np(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 _o(e,t){let n=[],o=e.entries.filter(g=>g.link);if(o.length>0){n.push(""),n.push(ke("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let g of o)n.push(` ${L("~")} ${L(g.path??"")} ${ie(`\u2192 "${g.link.title}"`)}`)}for(let g of fl){let T=e.entries.filter(v=>v.status===g.status&&!(g.status==="untracked-local"&&v.link));if(T.length!==0){n.push(""),n.push(ke(g.header));for(let v of T)n.push(` ${g.paint(g.mark)} ${g.paint(Ep(v))}${v.detail?ie(` (${v.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let l={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},p=o.length,m=s===r?D("\u2713 everything up to date"):[r>0?D(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...fl.map(g=>{let T=(e.counts[g.status]??0)-(g.status==="untracked-local"?p:0);return T>0?`${T} ${l[g.status]}`:null})].filter(Boolean).join(ie(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${Np(t)}`:"";return n.push(m+ie(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as Ip}from"diff";import hl from"picocolors";var ml=80,_p="\x1B[48;2;74;28;28m",Op="\x1B[48;2;24;66;24m",gl="\x1B[49m",is=e=>String(e).padStart(5);function wl(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function yl(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 Ye(e,t,n){let o=v=>{let _=v.replace(/\r\n/g,`
312
+ `+pp[e.tone](vn(fp(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${Rn(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
313
+ `+(e.ok?Z.magenta("\u2736 "):Z.red("\u2736 "))+Z.gray(`Cooked for ${Pn(e.seconds)} \xB7 ${Rn(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${be(e.costUsd)}`:""))}}}function nl(e,t){return e.map(n=>Jr(n,t)).join(`
314
+ `)}import{resolveActiveProfile as hp,loadTokens as mp,isExpired as gp,decodeJwtClaims as ol}from"document360-engine";function wp(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ne(e,t){try{let n=hp(e,t),o=mp(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 l={...ol(o.idToken)??{},...ol(o.accessToken)??{}}.doc360_project_id;if(typeof l=="string"&&l&&l!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${wp(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var Sn=3;function Zr(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 rl={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function es(e){return e.filter(t=>t.path!==null&&t.status in rl&&!t.link).map(t=>({path:t.path,label:rl[t.status]}))}function Do(e){let t=es(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 jo(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 Ao(e){return e.filter(t=>t.link).length}function ts(e,t){try{let n=Rp(e,Pp(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Sp(yp(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 Tp(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 cl(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let s=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),l=o.get(s);l?l.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((l,p)=>l.path.localeCompare(p.path));n.push({kind:"category",label:`${Tp(r)} (${s.length})`,paths:s.map(l=>l.path),indent:!1});for(let l of s){let p=l.path.replace(/\\/g,"/").split("/").pop()??l.path;n.push({kind:"article",label:p,paths:[l.path],indent:!0,note:l.label})}}for(let r of[...t].sort((s,l)=>s.path.localeCompare(l.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function Eo(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 ns(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),s=e.filter(v=>!v.ok),l=e.reduce((v,_)=>v+o(_),0),p=r.reduce((v,_)=>v+o(_),0),m=n==="api"?`${be(e.reduce((v,_)=>v+_.costUsd,0))} total`:rt(e.reduce((v,_)=>v+_.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,g=v=>`${v} article${v===1?"":"s"}`,S=[];if(s.length===0)S.push(`Published ${g(l)} (${k}) successfully \xB7 ${m}.`),S.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{S.push(`Published ${p}/${g(l)} (${k}) \xB7 ${m}.`),S.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let v of s)S.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return S}async function vt(e,t){let{model:n}=xp(e.cwd,"standard"),o=async(r,s)=>{let l=vp(r);console.log(f(s?`Resolving cross-links in ${r.length} article${r.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${r.length} article${r.length===1?"":"s"} across ${l.length} partition${l.length===1?"":"s"} (\u2264${Sn} agents at once) on ${n}\u2026`)),s||console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let p=!1;for await(let m of Cp({cwd:e.cwd,partitions:l,promptFor:k=>Eo(k.paths),concurrency:Sn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(m.type==="partition_status")m.status==="running"?console.log(f(` \u25B8 ${m.label} \u2014 publishing\u2026`)):m.status==="done"?console.log(D(` \u2713 ${m.label}`)):console.log(R(` \u2717 ${m.label}`));else if(m.type==="run_done"){p=m.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let S of ns(m.results,l,k))console.log(m.ok?D(S):O(S));let g=ts(e.cwd,e.profileName);g&&console.log(f(g));try{let S=il(await sl({cwd:e.cwd,profileName:e.profileName}));S&&console.log(f(S))}catch{}try{let S=ll(await al({cwd:e.cwd,profileName:e.profileName}));S&&console.log(f(S))}catch{}}return p};try{if(!await o(t,!1)){let s=await os(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(R(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function No(e,t,n){let o=$p(e,n);if(o.length===0)return[];let r=new Set(es((await To({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function os(e,t,n){try{let o=new Set(n),r=await To({cwd:e,profileName:t});return es(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function dl(e,t){let n=Ne(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await No(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(D("\u2713 All related articles are already published.")),{kind:"continue"}):await vt(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await To({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:l}=Do(r.entries),p=Ao(r.entries),m=e.includes("--force")&&l.length>0;p>0&&console.log(O(`\u26A0 ${p} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),l.length>0&&!m&&console.log(O(jo(l.length)));let k=m?[...s,...l]:s;if(k.length===0){if(l.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(D(p>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let g=il(await sl({cwd:t.cwd,profileName:t.profileName}));g&&console.log(f(g));let S=ll(await al({cwd:t.cwd,profileName:t.profileName}));S&&console.log(f(S))}catch{}return{kind:"continue"}}return t?await vt(t,k.map(g=>g.path)):{kind:"forward-to-agent",prompt:Eo(k.map(g=>g.path)),display:"/publish --all"}}catch(r){return console.log(R(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let s=await To({cwd:t?.cwd??process.cwd()}),{clean:l,conflicts:p}=Do(s.entries);r=l;let m=Ao(s.entries);if(m>0&&console.log(O(`\u26A0 ${m} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),p.length>0&&console.log(O(jo(p.length))),r.length===0&&p.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(R(`Could not compute sync status: ${s.message}`)),console.log(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(D("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(f(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${f(`(${s.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>bp({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await vt(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Zr(o),display:`/publish ${o}`}}async function Tn(){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"}}W();import{readProjectConfig as Dp}from"document360-engine";function rs(){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 ul(e,t){let n=t?.cwd??process.cwd();return Dp(n)?{kind:"forward-to-agent",prompt:rs(),display:"/discover"}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{checkbox as jp}from"@inquirer/prompts";import{inventoryRepo as Ap,readProjectConfig as pl,writeProjectConfig as Ep}from"document360-engine";function ss(e,t){let n=pl(e);n&&(n.authoritativeSourceFiles=t,Ep(n,e))}function Io(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 fl(e,t){let n=t?.cwd??process.cwd();if(!pl(n))return console.log(R("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Ap(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(L("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(Io(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>jp({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Io(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(f("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};ss(n,r),console.log(D(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as Hp}from"@inquirer/prompts";import{applyPull as ls,computeSyncStatus as $l,compareRemoteSources as qp,planPull as xl,planImport as Bp,applyImport as Vp,establishBaselines as Gp,rebaselineServerMeta as Yp,D360AuthError as zp}from"document360-engine";W();var hl=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:R,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:O,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:R,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:R,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ie,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:f,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:f,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:ie,mark:"\xB7"}];function Np(e){return e.path?e.path:`${e.title??"(untitled)"} ${ie(`[${e.articleId}]`)}`}function Ip(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 _o(e,t){let n=[],o=e.entries.filter(g=>g.link);if(o.length>0){n.push(""),n.push(ke("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let g of o)n.push(` ${O("~")} ${O(g.path??"")} ${ie(`\u2192 "${g.link.title}"`)}`)}for(let g of hl){let S=e.entries.filter(v=>v.status===g.status&&!(g.status==="untracked-local"&&v.link));if(S.length!==0){n.push(""),n.push(ke(g.header));for(let v of S)n.push(` ${g.paint(g.mark)} ${g.paint(Np(v))}${v.detail?ie(` (${v.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let l={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},p=o.length,m=s===r?D("\u2713 everything up to date"):[r>0?D(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...hl.map(g=>{let S=(e.counts[g.status]??0)-(g.status==="untracked-local"?p:0);return S>0?`${S} ${l[g.status]}`:null})].filter(Boolean).join(ie(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${Ip(t)}`:"";return n.push(m+ie(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as _p}from"diff";import ml from"picocolors";var gl=80,Lp="\x1B[48;2;74;28;28m",Op="\x1B[48;2;24;66;24m",wl="\x1B[49m",is=e=>String(e).padStart(5);function yl(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function kl(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 Ye(e,t,n){let o=v=>{let _=v.replace(/\r\n/g,`
319
319
  `);return _.endsWith(`
320
320
  `)||_===""?_:_+`
321
- `},r=o(e),s=o(t);if(r===s)return null;let l=Math.max(20,n-10),p=Ip("a","b",r,s,"","",{context:3}),m=0,k=0,g=[];p.hunks.forEach((v,_)=>{_>0&&g.push(hl.gray(" \u2026"));let P=v.oldStart,N=v.newStart,S=[],M=[],B=()=>{for(let V=0;V<S.length;V++){let Y=V<M.length?wl(S[V],M[V]):void 0;k++,g.push(`${_p}${is(P++)} - ${yl(S[V],l,Y)}${gl}`)}for(let V=0;V<M.length;V++){let Y=V<S.length?wl(S[V],M[V]):void 0;m++,g.push(`${Op}${is(N++)} + ${yl(M[V],l,Y)}${gl}`)}S=[],M=[]};for(let V of v.lines){let Y=V[0],ue=V.slice(1);Y==="-"?S.push(ue):Y==="+"?M.push(ue):(B(),g.push(hl.gray(is(N))+" "+ue.slice(0,l)),P++,N++)}B()});let T=g.slice(0,ml);return{added:m,removed:k,lines:T,hidden:Math.max(0,g.length-ml)}}W();import{select as Lp}from"@inquirer/prompts";import{applyPull as Mp,computeSyncStatus as Up,planPull as Wp}from"document360-engine";var kl=e=>e===1?"":"s";async function as(e,t){console.log(""),console.log(`${O("\u25CF")} ${ke(t.title)} ${ie(`(${t.path})`)}`);for(let r of t.notes)console.log(L(` \u26A0 ${r}`));let n=Ye(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(ie(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${kl(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(f(` \u2026 +${n.hidden} more diff lines`))}else console.log(f(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>Lp({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"?(Mp({cwd:e.cwd,profileName:e.profileName},t),console.log(D(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(f(" Skipped \u2014 still a conflict.")),"skipped")}async function bl(e,t){let n=Ne(t.cwd,t.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Up({cwd:t.cwd,profileName:t.profileName})).entries.filter(p=>p.status==="conflict"&&p.path).map(p=>p.path);if(o){if(!s.includes(o))return console.log(D(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(D("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let l=[];for(let p of s){let m=await Wp({cwd:t.cwd,profileName:t.profileName,relPath:p});await as(t,m)==="keep-local"&&l.push(p)}if(l.length>0)return console.log(f(`Publishing ${l.length} kept-local article${kl(l.length)} over the portal\u2026`)),await vt(t,l)}catch(r){console.log(R(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function xl(e,t){let n=Ne(t.cwd,t.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await zp(t),{kind:"continue"};if(o==="--baseline")return await Kp(t,e.filter(l=>l!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Xp(t),{kind:"continue"};if(o)return console.log(R(`Unknown option: ${o}`)),console.log(f("Usage: /pull pull portal edits + import new portal articles")),console.log(f(" /pull <path> pull one article (or resolve a conflict)")),console.log(f(" /pull --status drift report only (no writes)")),console.log(f(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Qp(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await cs({cwd:t.cwd,profileName:t.profileName});for(let l of ds(s))console.log(l.tone==="ok"?D(l.text):l.tone==="warn"?L(l.text):f(l.text));console.log("")}catch(r){r instanceof Yp?console.log(R(r.message)):console.log(R(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function cs(e){let t=await vl({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 $l({cwd:e.cwd,profileName:e.profileName,relPath:o.path});ls({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 qp({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Bp({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 Oo=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,$t=e=>e===1?"":"s";function ds(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${$t(e.pulled.length)} into local: ${Oo(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${$t(e.imported.length)}: ${Oo(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${$t(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${$t(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). (${Oo(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${$t(e.failed.length)} failed: ${Oo(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 zp(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await vl({cwd:e.cwd,profileName:e.profileName});for(let o of _o(n,Date.now()-t))console.log(o);console.log("")}async function Kp(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(f(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Vp({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Gp({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(D("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(D(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(D(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(L(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(f(` - ${s.path} (${s.reason})`))}}async function Xp(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Hp({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${ke(String(t.legacyCount))} \xB7 Manifest: ${ke(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(D("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(R(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(L(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(L(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(f(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Qp(e,t){let n=t.replace(/\\/g,"/"),o=await $l({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await as(e,o)==="keep-local"&&(console.log(f(`Publishing ${o.path} over the portal\u2026`)),await vt(e,[o.path]));return}console.log(""),console.log(`${O("\u25CF")} ${ke(o.title)} ${ie(`(${o.path})`)}`);for(let l of o.notes)console.log(L(` \u26A0 ${l}`));let r=Ye(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(f(" Local file already matches the remote content \u2014 advancing the sync base only.")),ls({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ie(` \u23BF Added ${r.added} line${$t(r.added)}, removed ${r.removed} line${$t(r.removed)}`));for(let l of r.lines)console.log(l);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Fp({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}ls({cwd:e.cwd,profileName:e.profileName},o),console.log(D(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as Jp}from"node:fs";import{resolve as Zp}from"node:path";import{estimateBulkCost as ef,planPartitions as tf,readProjectConfig as nf,resolveModelForOperation as of,runPartitioned as rf,trackedArticlePaths as sf}from"document360-engine";var us=3;function ps(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 fs(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function hs(e,t){return t.map(n=>{let o=0;try{o=Jp(Zp(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ms(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 l=Math.max(20,n-10),p=_p("a","b",r,s,"","",{context:3}),m=0,k=0,g=[];p.hunks.forEach((v,_)=>{_>0&&g.push(ml.gray(" \u2026"));let P=v.oldStart,N=v.newStart,T=[],M=[],B=()=>{for(let V=0;V<T.length;V++){let Y=V<M.length?yl(T[V],M[V]):void 0;k++,g.push(`${Lp}${is(P++)} - ${kl(T[V],l,Y)}${wl}`)}for(let V=0;V<M.length;V++){let Y=V<T.length?yl(T[V],M[V]):void 0;m++,g.push(`${Op}${is(N++)} + ${kl(M[V],l,Y)}${wl}`)}T=[],M=[]};for(let V of v.lines){let Y=V[0],ue=V.slice(1);Y==="-"?T.push(ue):Y==="+"?M.push(ue):(B(),g.push(ml.gray(is(N))+" "+ue.slice(0,l)),P++,N++)}B()});let S=g.slice(0,gl);return{added:m,removed:k,lines:S,hidden:Math.max(0,g.length-gl)}}W();import{select as Mp}from"@inquirer/prompts";import{applyPull as Up,computeSyncStatus as Wp,planPull as Fp}from"document360-engine";var bl=e=>e===1?"":"s";async function as(e,t){console.log(""),console.log(`${L("\u25CF")} ${ke(t.title)} ${ie(`(${t.path})`)}`);for(let r of t.notes)console.log(O(` \u26A0 ${r}`));let n=Ye(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(ie(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${bl(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(f(` \u2026 +${n.hidden} more diff lines`))}else console.log(f(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>Mp({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"?(Up({cwd:e.cwd,profileName:e.profileName},t),console.log(D(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(f(" Skipped \u2014 still a conflict.")),"skipped")}async function vl(e,t){let n=Ne(t.cwd,t.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Wp({cwd:t.cwd,profileName:t.profileName})).entries.filter(p=>p.status==="conflict"&&p.path).map(p=>p.path);if(o){if(!s.includes(o))return console.log(D(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(D("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let l=[];for(let p of s){let m=await Fp({cwd:t.cwd,profileName:t.profileName,relPath:p});await as(t,m)==="keep-local"&&l.push(p)}if(l.length>0)return console.log(f(`Publishing ${l.length} kept-local article${bl(l.length)} over the portal\u2026`)),await vt(t,l)}catch(r){console.log(R(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Cl(e,t){let n=Ne(t.cwd,t.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Kp(t),{kind:"continue"};if(o==="--baseline")return await Xp(t,e.filter(l=>l!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Qp(t),{kind:"continue"};if(o)return console.log(R(`Unknown option: ${o}`)),console.log(f("Usage: /pull pull portal edits + import new portal articles")),console.log(f(" /pull <path> pull one article (or resolve a conflict)")),console.log(f(" /pull --status drift report only (no writes)")),console.log(f(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Jp(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await cs({cwd:t.cwd,profileName:t.profileName});for(let l of ds(s))console.log(l.tone==="ok"?D(l.text):l.tone==="warn"?O(l.text):f(l.text));console.log("")}catch(r){r instanceof zp?console.log(R(r.message)):console.log(R(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function cs(e){let t=await $l({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 xl({cwd:e.cwd,profileName:e.profileName,relPath:o.path});ls({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 Bp({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Vp({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 Lo=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,$t=e=>e===1?"":"s";function ds(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${$t(e.pulled.length)} into local: ${Lo(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${$t(e.imported.length)}: ${Lo(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${$t(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${$t(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). (${Lo(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${$t(e.failed.length)} failed: ${Lo(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 Kp(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await $l({cwd:e.cwd,profileName:e.profileName});for(let o of _o(n,Date.now()-t))console.log(o);console.log("")}async function Xp(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(f(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Gp({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Yp({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(D("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(D(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(D(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(O(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(f(` - ${s.path} (${s.reason})`))}}async function Qp(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await qp({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${ke(String(t.legacyCount))} \xB7 Manifest: ${ke(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(D("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(R(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(O(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(O(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(f(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Jp(e,t){let n=t.replace(/\\/g,"/"),o=await xl({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await as(e,o)==="keep-local"&&(console.log(f(`Publishing ${o.path} over the portal\u2026`)),await vt(e,[o.path]));return}console.log(""),console.log(`${L("\u25CF")} ${ke(o.title)} ${ie(`(${o.path})`)}`);for(let l of o.notes)console.log(O(` \u26A0 ${l}`));let r=Ye(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(f(" Local file already matches the remote content \u2014 advancing the sync base only.")),ls({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ie(` \u23BF Added ${r.added} line${$t(r.added)}, removed ${r.removed} line${$t(r.removed)}`));for(let l of r.lines)console.log(l);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Hp({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}ls({cwd:e.cwd,profileName:e.profileName},o),console.log(D(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as Zp}from"node:fs";import{resolve as ef}from"node:path";import{estimateBulkCost as tf,planPartitions as nf,readProjectConfig as of,resolveModelForOperation as rf,runPartitioned as sf,trackedArticlePaths as af}from"document360-engine";var us=3;function ps(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 fs(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function hs(e,t){return t.map(n=>{let o=0;try{o=Zp(ef(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ms(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 gs(e,t,n){let o=e.reduce((p,m)=>p+m.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${be(r)}\u2013${be(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function ws(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),s=e.filter(P=>!P.ok),l=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),m=e.reduce((P,N)=>P+N.costUsd,0),k=e.reduce((P,N)=>P+N.outputTokens,0),g=n==="api"?`${be(m)} total`:rt(k),T=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=P=>`${P} article${P===1?"":"s"}`,_=[];if(s.length===0)_.push(`Converted ${v(l)} (${T}) successfully \xB7 ${g}.`);else{_.push(`Converted ${p}/${v(l)} (${T}) \xB7 ${g}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let P of s)_.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return _}async function Cl(e,t){if(!nf(t.cwd))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=ps(e),r=sf(t.cwd,t.profileName);if(r.length===0)return console.log(R("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=fs(r,n);if(s.length===0)return console.log(R(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let l=tf(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:m,forced:k}=of(t.cwd,"light");if(!o){let g=ef({files:hs(t.cwd,s),op:"convert",model:m});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let T of gs(l,g,us))console.log(T);return console.log(f(`Model: ${m}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${l.length} partitions (\u2264${us} agents at once) on ${m}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let g of rf({cwd:t.cwd,partitions:l,promptFor:ms,concurrency:us,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:m}))if(g.type==="partition_status")g.status==="running"?console.log(f(` \u25B8 ${g.label} \u2014 converting\u2026`)):g.status==="done"?console.log(D(` \u2713 ${g.label}`)):console.log(R(` \u2717 ${g.label}`));else if(g.type==="run_done"){console.log("");let T=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let v of ws(g.results,l,T))console.log(g.ok?D(v):L(v))}}catch(g){console.log(R(`Convert run failed: ${g.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as Tl}from"node:fs";import{resolve as Sl}from"node:path";import{estimateBulkCost as mf,lintDocs as gf,planPartitions as wf,readDocsPlan as yf,readProjectConfig as Dl,DEFAULT_DOCS_DIR as kf,resolveModelForOperation as bf,runPartitioned as vf,stampArticles as $f,CONTENT_CAP_VERSION as xf}from"document360-engine";import{readProjectConfig as af,loadProfileMap as lf,resolveActiveProfile as cf,desiredCategoryOrder as df,desiredArticleOrder as uf,DEFAULT_DOCS_DIR as pf}from"document360-engine";var ys=e=>e.replace(/\\/g,"/"),ff=e=>ys(e).split("/").pop()??e;function hf(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function Dn(e,t){try{let n=af(e);if(!n)return[];let o=cf(e,t),r=lf(e,o.name);if(!r)return[];let s=ys(n.docsDir??pf).replace(/\/+$/,""),l=new Map;for(let m of uf(r))l.set(m.categoryPath,(l.get(m.categoryPath)??0)+1);let p=[];for(let m of df(r)){let k=ys(m.path),g=k.startsWith(`${s}/`)?k.slice(s.length+1):k===s?"":k;g&&p.push({token:g,label:hf(ff(k)),count:l.get(m.path)??0})}return p}catch{return[]}}function Rl(e,t){let n=Dn(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 st(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function en(e,t,n,o){let r=Dn(e,o);if(r.length<=1)return[];let s=n.filter(k=>k.startsWith("--")).join(" "),l=s?` ${s}`:"",p=`/${t}${l} --all`.replace(/\s+/g," "),m=k=>t==="write"?`/write --scope ${k}${l}`:`/${t} ${k}${l}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((k,g)=>k+g.count,0)} articles). Pick a target:`,` ${p} (everything)`,...r.map(k=>` ${m(k.token)} (${k.label} \xB7 ${k.count} article${k.count===1?"":"s"})`)]}function Lo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Pl(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 Cf=3,Rf=8;function ks(e){return e===void 0||!Number.isFinite(e)?Cf:Math.max(1,Math.min(Math.floor(e),Rf))}function bs(e){let t,n,o=!1,r=!1,s,l=m=>{let k=Number(m);return m!==void 0&&Number.isFinite(k)?k:void 0};for(let m=0;m<e.length;m++){let k=e[m];if(k==="--preview"||k==="--dry-run")o=!0;else if(k==="--rewrite"||k==="--force")r=!0;else{if(k==="--run"||k==="--yes"||k==="--all")continue;k==="--scope"?t=e[++m]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?s=l(e[++m]):k?.startsWith("--concurrency=")?s=l(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=m=>m?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function Pf(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Tf(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function vs(e,t,n){return n.filter(o=>{try{return Tl(Sl(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 l of o.get(r)?.sources??[])try{s+=Tl(Sl(e,l)).size}catch{}return{path:r,bytes:s}})}function xs(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 gs(e,t,n){let o=e.reduce((p,m)=>p+m.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${be(r)}\u2013${be(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function ws(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),s=e.filter(P=>!P.ok),l=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),m=e.reduce((P,N)=>P+N.costUsd,0),k=e.reduce((P,N)=>P+N.outputTokens,0),g=n==="api"?`${be(m)} total`:rt(k),S=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=P=>`${P} article${P===1?"":"s"}`,_=[];if(s.length===0)_.push(`Converted ${v(l)} (${S}) successfully \xB7 ${g}.`);else{_.push(`Converted ${p}/${v(l)} (${S}) \xB7 ${g}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let P of s)_.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return _}async function Rl(e,t){if(!of(t.cwd))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=ps(e),r=af(t.cwd,t.profileName);if(r.length===0)return console.log(R("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=fs(r,n);if(s.length===0)return console.log(R(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let l=nf(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:m,forced:k}=rf(t.cwd,"light");if(!o){let g=tf({files:hs(t.cwd,s),op:"convert",model:m});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let S of gs(l,g,us))console.log(S);return console.log(f(`Model: ${m}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${l.length} partitions (\u2264${us} agents at once) on ${m}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let g of sf({cwd:t.cwd,partitions:l,promptFor:ms,concurrency:us,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:m}))if(g.type==="partition_status")g.status==="running"?console.log(f(` \u25B8 ${g.label} \u2014 converting\u2026`)):g.status==="done"?console.log(D(` \u2713 ${g.label}`)):console.log(R(` \u2717 ${g.label}`));else if(g.type==="run_done"){console.log("");let S=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let v of ws(g.results,l,S))console.log(g.ok?D(v):O(v))}}catch(g){console.log(R(`Convert run failed: ${g.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as Tl}from"node:fs";import{resolve as Dl}from"node:path";import{estimateBulkCost as gf,lintDocs as wf,planPartitions as yf,readDocsPlan as kf,readProjectConfig as jl,DEFAULT_DOCS_DIR as bf,resolveModelForOperation as vf,runPartitioned as $f,stampArticles as xf,CONTENT_CAP_VERSION as Cf}from"document360-engine";import{readProjectConfig as lf,loadProfileMap as cf,resolveActiveProfile as df,desiredCategoryOrder as uf,desiredArticleOrder as pf,DEFAULT_DOCS_DIR as ff}from"document360-engine";var ys=e=>e.replace(/\\/g,"/"),hf=e=>ys(e).split("/").pop()??e;function mf(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function Dn(e,t){try{let n=lf(e);if(!n)return[];let o=df(e,t),r=cf(e,o.name);if(!r)return[];let s=ys(n.docsDir??ff).replace(/\/+$/,""),l=new Map;for(let m of pf(r))l.set(m.categoryPath,(l.get(m.categoryPath)??0)+1);let p=[];for(let m of uf(r)){let k=ys(m.path),g=k.startsWith(`${s}/`)?k.slice(s.length+1):k===s?"":k;g&&p.push({token:g,label:mf(hf(k)),count:l.get(m.path)??0})}return p}catch{return[]}}function Pl(e,t){let n=Dn(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 st(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function en(e,t,n,o){let r=Dn(e,o);if(r.length<=1)return[];let s=n.filter(k=>k.startsWith("--")).join(" "),l=s?` ${s}`:"",p=`/${t}${l} --all`.replace(/\s+/g," "),m=k=>t==="write"?`/write --scope ${k}${l}`:`/${t} ${k}${l}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((k,g)=>k+g.count,0)} articles). Pick a target:`,` ${p} (everything)`,...r.map(k=>` ${m(k.token)} (${k.label} \xB7 ${k.count} article${k.count===1?"":"s"})`)]}function Oo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Sl(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 Rf=3,Pf=8;function ks(e){return e===void 0||!Number.isFinite(e)?Rf:Math.max(1,Math.min(Math.floor(e),Pf))}function bs(e){let t,n,o=!1,r=!1,s,l=m=>{let k=Number(m);return m!==void 0&&Number.isFinite(k)?k:void 0};for(let m=0;m<e.length;m++){let k=e[m];if(k==="--preview"||k==="--dry-run")o=!0;else if(k==="--rewrite"||k==="--force")r=!0;else{if(k==="--run"||k==="--yes"||k==="--all")continue;k==="--scope"?t=e[++m]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?s=l(e[++m]):k?.startsWith("--concurrency=")?s=l(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=m=>m?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function Sf(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Tf(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function vs(e,t,n){return n.filter(o=>{try{return Tl(Dl(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 l of o.get(r)?.sources??[])try{s+=Tl(Dl(e,l)).size}catch{}return{path:r,bytes:s}})}function xs(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,85 +334,87 @@ ${s}${m}`).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 Cs(e,t,n){let o=e.reduce((l,p)=>l+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(l=>` \u2022 ${l.label} \u2014 ${l.paths.length} article${l.paths.length===1?"":"s"}`),"",`Estimated cost: ${be(r)}\u2013${be(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Rs(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),s=e.filter(P=>!P.ok),l=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),m=e.reduce((P,N)=>P+N.costUsd,0),k=e.reduce((P,N)=>P+N.outputTokens,0),g=n==="api"?`${be(m)} total`:rt(k),T=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=P=>`${P} article${P===1?"":"s"}`,_=[];if(s.length===0)_.push(`Wrote ${v(l)} (${T}) successfully \xB7 ${g}.`),_.push("Next \u2014 push them to Document360:"),_.push("/publish --all"),_.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{_.push(`Wrote ${p}/${v(l)} (${T}) \xB7 ${g}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let P of s)_.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return _}function Ps(e,t,n){try{let o=gf({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 Ts(e,t,n){let o=(Dl(e)?.docsDir??kf).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Pf(n.path,o);return r.includes(p)?{docsDir:o,targets:[p],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${p}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=Tf(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let l=vs(e,o,s);if(l.length===0){let p=n.scope?` under "${n.scope}"`:"",m=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${m} --rewrite to regenerate them all.`}}return{docsDir:o,targets:l,planCount:r.length}}async function jl(e,t){if(!Dl(t.cwd))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Lo(e)){for(let M of Rl(t.cwd,t.profileName))console.log(f(M));return{kind:"continue"}}if(st("write",e)){let M=en(t.cwd,"write",e,t.profileName);if(M.length>0){for(let B of M)console.log(f(B));return{kind:"continue"}}}let n=yf(t.cwd);if(n.length===0)return console.log(R("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:l,rewrite:p}=bs(e),{docsDir:m,targets:k,reason:g,rewriting:T}=Ts(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(g?L(g):L("Nothing to write.")),{kind:"continue"};T&&console.log(L(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let v=wf(k),_=ks(l),{model:P,forced:N}=bf(t.cwd,"standard"),S=!!r;if(s&&!S){let M=mf({files:$s(t.cwd,n,k),op:"write",model:P});o&&console.log(f(`Scope: ${o} (${k.length} pending).`));for(let B of Cs(v,M,_))console.log(B);return console.log(f(`Model: ${P}${N?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${k.length} article${k.length===1?"":"s"} across ${v.length} partition${v.length===1?"":"s"} (\u2264${_} agents at once) on ${P}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let M of vf({cwd:t.cwd,partitions:v,promptFor:B=>xs(B,m,{rewrite:T||S}),concurrency:_,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:P}))if(M.type==="partition_status")M.status==="running"?console.log(f(` \u25B8 ${M.label} \u2014 writing\u2026`)):M.status==="done"?console.log(D(` \u2713 ${M.label}`)):console.log(R(` \u2717 ${M.label}`));else if(M.type==="run_done"){console.log("");let B=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let Y of Rs(M.results,v,B))console.log(M.ok?D(Y):L(Y));if(M.ok)try{$f(t.cwd,k.map(Y=>`${m}/${Y}`),{writtenCap:xf})}catch{}let V=Ps(t.cwd,m,k);V&&console.log(L(V))}}catch(M){console.log(R(`Write run failed: ${M.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as Sf,readdirSync as Al,statSync as El}from"node:fs";import{join as Nl}from"node:path";import{inputDir as Df,readProjectConfig as jf}from"document360-engine";var Il=/\.(md|markdown|pdf|txt)$/i;function Ss(e){let t=Df(e);if(!Sf(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Al(t)){let s=Nl(t,r),l=!1;try{l=El(s).isDirectory()}catch{continue}if(l){if(r.startsWith("."))continue;let p=Af(s);p>0&&n.push({name:r,docCount:p})}else Il.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 Al(e))try{El(Nl(e,n)).isFile()&&Il.test(n)&&t++}catch{}return t}function Ds(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 Mo(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 js="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function _l(e,t){let n=t?.cwd??process.cwd();if(!jf(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Ss(n);if(o.length===0&&r===0)return console.log(f(js)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let m of o)console.log(` ${m.name} ${f(`(${m.docCount} doc${m.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Mo(p),display:p?`/draft ${p}`:"/draft"}}let l=Ds(o,s);return{kind:"forward-to-agent",prompt:Mo(l??"",l?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as Ef,readProjectConfig as Nf}from"document360-engine";function As(e){try{return Ef(e).filter(t=>t.kind==="request").length}catch{return 0}}function Es(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Ns(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 Is="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 Ol(e,t){let n=t?.cwd??process.cwd();if(!Nf(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Es(e);if(!r&&As(n)===0)return console.log(f(Is)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Ns(r,o),display:s}}W();import{search as If}from"@inquirer/prompts";import{findByName as _f,getSession as Of,listSessions as Lf,relativeTime as Ml}from"document360-engine";async function Ul(e,t){let n=Lf(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(f("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=_f(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(R(`No session matches "${o}".`)),Ll(n),{kind:"continue"})}if(!process.stdin.isTTY)return Ll(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>If({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let l=(s??"").toLowerCase();return n.filter(p=>!l||p.name.toLowerCase().includes(l)||p.firstPrompt.toLowerCase().includes(l)).map(p=>({name:`${p.name} ${Ml(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Of(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Ll(e){console.log("");for(let t of e.slice(0,15))console.log(` ${O(t.name)} ${f(Ml(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Mf}from"document360-engine";function _s(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 Wl(e,t){let n=_s(e.join(" "));if(!n)return console.log(R("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Mf(o,n)?console.log(D(`\u2713 Session renamed to "${n}"`)):console.log(R("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(D(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Fl,readProjectConfig as Uf,writeProjectConfig as Wf}from"document360-engine";W();function Os(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Uf(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 Fl().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Wf(o,e),null):`Unknown environment "${r}". Known: ${Fl().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function Hl(e,t){let n=e[0];if(!n)return yo(t.cwd),{kind:"continue"};if(n==="add"){let o=Os(t.cwd,e[1],e[2]);return o?(console.log(R(o)),{kind:"continue"}):(console.log(D(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${O(`/profile ${e[1]}`)} then ${O("/login")}`),{kind:"continue"})}return ko(t.cwd,n),bo(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Ff}from"@inquirer/prompts";import{readProjectConfig as Hf,readUserConfig as ql,resolveModelSetting as Ls,writeUserConfig as Bl}from"document360-engine";var We=[{value:null,label:"Auto",desc:"Sonnet (latest) \u2014 right-sized for docs work (recommended); heavier models only when you pin them"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus (latest) \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet (latest) \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku (latest) \xB7 fastest for quick answers"}];function Uo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=We.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function qf(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 jn(e,t){let n=()=>Ls(e).model;if(t==="default"){let s=ql();return s.defaultModel?(delete s.defaultModel,Bl(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Ls(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}}Bl({...ql(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Hf(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 Vl(e,t){let n=e[0]?.trim();if(!n){let l=Ls(t.cwd);if(!process.stdin.isTTY)return console.log(`${ke("Model:")} ${O(l.model)}${l.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${qf(l)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Uo(l),m;try{m=await t.withPausedInput(()=>Ff({message:`Select model (current: ${l.model}${l.source==="auto"?" \xB7 auto":""})`,default:We[p].value,choices:We.map((v,_)=>({name:`${v.label}${_===p?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:g,effective:T}=jn(t.cwd,m??"default");for(let v of k)console.log(v.startsWith("\u26A0")?L(v):v.startsWith("\u2713")?D(v):f(v));return g&&await t.setModel(T),{kind:"continue"}}let{lines:o,changed:r,effective:s}=jn(t.cwd,n);for(let l of o)console.log(l.startsWith("\u26A0")?L(l):l.startsWith("\u2713")?D(l):f(l));return r&&await t.setModel(s),{kind:"continue"}}Wo();async function Ql(e,t){return await t.withPausedInput(()=>Gt(t.cwd)),{kind:"clear"}}async function Jl(e,t){return await t.withPausedInput(()=>ho(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as ah}from"document360-engine";async function Zl(e,t){let n=!1;try{n=ah(t.cwd).production}catch{}return n?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var ec=async(e,t)=>{try{await t.withPausedInput(()=>wo({}))}catch(n){console.log(R(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as lh,clearTokens as ch,clearProfileProject as dh}from"document360-engine";async function tc(e,t){let n;try{n=lh(t.cwd,t.profileName).name}catch(r){return console.log(R(r.message)),{kind:"continue"}}let o=ch(n);return dh(t.cwd,n),console.log(o?D(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):f(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(f("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as nc}from"node:fs";import{isAbsolute as uh,join as ph,resolve as fh}from"node:path";import{readProjectConfig as hh,screenshotPlaceholderIds as mh,DEFAULT_CAPTURE_DIR as gh,DEFAULT_OUTPUT_DIR as wh}from"document360-engine";var oc=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Us(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?oc(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:oc(o),setup:t}:{mode:"single",id:o}}function Ws(e,t){let n=hh(e),o=n?.captureDir??gh,r=n?.outputDir??wh,s=(l,p)=>uh(l)?ph(l,p):fh(e,l,p);return mh(e,{scope:t}).map(({id:l,file:p})=>{let m=nc(s(r,`${l}.png`))?"captured":nc(s(o,`${l}.spec.ts`))?"spec":"placeholder";return{id:l,file:p,state:m}})}var yh={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},kh={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Fs(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(s=>s.file))].sort(),o=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of n){r.push(s);for(let l of e.filter(p=>p.file===s))r.push(` ${yh[l.state]} ${l.id.padEnd(34)} ${kh[l.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function rc(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 Cs(e,t,n){let o=e.reduce((l,p)=>l+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(l=>` \u2022 ${l.label} \u2014 ${l.paths.length} article${l.paths.length===1?"":"s"}`),"",`Estimated cost: ${be(r)}\u2013${be(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Rs(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),s=e.filter(P=>!P.ok),l=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),m=e.reduce((P,N)=>P+N.costUsd,0),k=e.reduce((P,N)=>P+N.outputTokens,0),g=n==="api"?`${be(m)} total`:rt(k),S=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=P=>`${P} article${P===1?"":"s"}`,_=[];if(s.length===0)_.push(`Wrote ${v(l)} (${S}) successfully \xB7 ${g}.`),_.push("Next \u2014 push them to Document360:"),_.push("/publish --all"),_.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{_.push(`Wrote ${p}/${v(l)} (${S}) \xB7 ${g}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let P of s)_.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return _}function Ps(e,t,n){try{let o=wf({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 Ss(e,t,n){let o=(jl(e)?.docsDir??bf).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Sf(n.path,o);return r.includes(p)?{docsDir:o,targets:[p],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${p}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=Tf(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let l=vs(e,o,s);if(l.length===0){let p=n.scope?` under "${n.scope}"`:"",m=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${m} --rewrite to regenerate them all.`}}return{docsDir:o,targets:l,planCount:r.length}}async function Al(e,t){if(!jl(t.cwd))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Oo(e)){for(let M of Pl(t.cwd,t.profileName))console.log(f(M));return{kind:"continue"}}if(st("write",e)){let M=en(t.cwd,"write",e,t.profileName);if(M.length>0){for(let B of M)console.log(f(B));return{kind:"continue"}}}let n=kf(t.cwd);if(n.length===0)return console.log(R("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:l,rewrite:p}=bs(e),{docsDir:m,targets:k,reason:g,rewriting:S}=Ss(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(g?O(g):O("Nothing to write.")),{kind:"continue"};S&&console.log(O(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let v=yf(k),_=ks(l),{model:P,forced:N}=vf(t.cwd,"standard"),T=!!r;if(s&&!T){let M=gf({files:$s(t.cwd,n,k),op:"write",model:P});o&&console.log(f(`Scope: ${o} (${k.length} pending).`));for(let B of Cs(v,M,_))console.log(B);return console.log(f(`Model: ${P}${N?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${k.length} article${k.length===1?"":"s"} across ${v.length} partition${v.length===1?"":"s"} (\u2264${_} agents at once) on ${P}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let M of $f({cwd:t.cwd,partitions:v,promptFor:B=>xs(B,m,{rewrite:S||T}),concurrency:_,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:P}))if(M.type==="partition_status")M.status==="running"?console.log(f(` \u25B8 ${M.label} \u2014 writing\u2026`)):M.status==="done"?console.log(D(` \u2713 ${M.label}`)):console.log(R(` \u2717 ${M.label}`));else if(M.type==="run_done"){console.log("");let B=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let Y of Rs(M.results,v,B))console.log(M.ok?D(Y):O(Y));if(M.ok)try{xf(t.cwd,k.map(Y=>`${m}/${Y}`),{writtenCap:Cf})}catch{}let V=Ps(t.cwd,m,k);V&&console.log(O(V))}}catch(M){console.log(R(`Write run failed: ${M.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as Df,readdirSync as El,statSync as Nl}from"node:fs";import{join as Il}from"node:path";import{inputDir as jf,readProjectConfig as Af}from"document360-engine";var _l=/\.(md|markdown|pdf|txt)$/i;function Ts(e){let t=jf(e);if(!Df(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of El(t)){let s=Il(t,r),l=!1;try{l=Nl(s).isDirectory()}catch{continue}if(l){if(r.startsWith("."))continue;let p=Ef(s);p>0&&n.push({name:r,docCount:p})}else _l.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Ef(e){let t=0;for(let n of El(e))try{Nl(Il(e,n)).isFile()&&_l.test(n)&&t++}catch{}return t}function Ds(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 Mo(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 js="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Ll(e,t){let n=t?.cwd??process.cwd();if(!Af(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Ts(n);if(o.length===0&&r===0)return console.log(f(js)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let m of o)console.log(` ${m.name} ${f(`(${m.docCount} doc${m.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Mo(p),display:p?`/draft ${p}`:"/draft"}}let l=Ds(o,s);return{kind:"forward-to-agent",prompt:Mo(l??"",l?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as Nf,readProjectConfig as If}from"document360-engine";function As(e){try{return Nf(e).filter(t=>t.kind==="request").length}catch{return 0}}function Es(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Ns(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 Is="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 Ol(e,t){let n=t?.cwd??process.cwd();if(!If(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Es(e);if(!r&&As(n)===0)return console.log(f(Is)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Ns(r,o),display:s}}W();import{search as _f}from"@inquirer/prompts";import{findByName as Lf,getSession as Of,listSessions as Mf,relativeTime as Ul}from"document360-engine";async function Wl(e,t){let n=Mf(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(f("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=Lf(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(R(`No session matches "${o}".`)),Ml(n),{kind:"continue"})}if(!process.stdin.isTTY)return Ml(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>_f({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let l=(s??"").toLowerCase();return n.filter(p=>!l||p.name.toLowerCase().includes(l)||p.firstPrompt.toLowerCase().includes(l)).map(p=>({name:`${p.name} ${Ul(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Of(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Ml(e){console.log("");for(let t of e.slice(0,15))console.log(` ${L(t.name)} ${f(Ul(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Uf}from"document360-engine";function _s(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 Fl(e,t){let n=_s(e.join(" "));if(!n)return console.log(R("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Uf(o,n)?console.log(D(`\u2713 Session renamed to "${n}"`)):console.log(R("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(D(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Hl,readProjectConfig as Wf,writeProjectConfig as Ff}from"document360-engine";W();function Ls(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Wf(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 Hl().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Ff(o,e),null):`Unknown environment "${r}". Known: ${Hl().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function ql(e,t){let n=e[0];if(!n)return yo(t.cwd),{kind:"continue"};if(n==="add"){let o=Ls(t.cwd,e[1],e[2]);return o?(console.log(R(o)),{kind:"continue"}):(console.log(D(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${L(`/profile ${e[1]}`)} then ${L("/login")}`),{kind:"continue"})}return ko(t.cwd,n),bo(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Hf}from"@inquirer/prompts";import{readProjectConfig as qf,readUserConfig as Bl,resolveModelSetting as Os,writeUserConfig as Vl}from"document360-engine";var We=[{value:null,label:"Auto",desc:"Sonnet (latest) \u2014 right-sized for docs work (recommended); heavier models only when you pin them"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus (latest) \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet (latest) \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku (latest) \xB7 fastest for quick answers"}];function Uo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=We.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function 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 jn(e,t){let n=()=>Os(e).model;if(t==="default"){let s=Bl();return s.defaultModel?(delete s.defaultModel,Vl(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Os(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}}Vl({...Bl(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=qf(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 Gl(e,t){let n=e[0]?.trim();if(!n){let l=Os(t.cwd);if(!process.stdin.isTTY)return console.log(`${ke("Model:")} ${L(l.model)}${l.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${Bf(l)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Uo(l),m;try{m=await t.withPausedInput(()=>Hf({message:`Select model (current: ${l.model}${l.source==="auto"?" \xB7 auto":""})`,default:We[p].value,choices:We.map((v,_)=>({name:`${v.label}${_===p?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:g,effective:S}=jn(t.cwd,m??"default");for(let v of k)console.log(v.startsWith("\u26A0")?O(v):v.startsWith("\u2713")?D(v):f(v));return g&&await t.setModel(S),{kind:"continue"}}let{lines:o,changed:r,effective:s}=jn(t.cwd,n);for(let l of o)console.log(l.startsWith("\u26A0")?O(l):l.startsWith("\u2713")?D(l):f(l));return r&&await t.setModel(s),{kind:"continue"}}Wo();async function Jl(e,t){return await t.withPausedInput(()=>Gt(t.cwd)),{kind:"clear"}}async function Zl(e,t){return await t.withPausedInput(()=>ho(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as lh}from"document360-engine";async function ec(e,t){let n=!1;try{n=lh(t.cwd).production}catch{}return n?(console.log(O("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var tc=async(e,t)=>{try{await t.withPausedInput(()=>wo({}))}catch(n){console.log(R(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as ch,clearTokens as dh,clearProfileProject as uh}from"document360-engine";async function nc(e,t){let n;try{n=ch(t.cwd,t.profileName).name}catch(r){return console.log(R(r.message)),{kind:"continue"}}let o=dh(n);return uh(t.cwd,n),console.log(o?D(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):f(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(f("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as oc}from"node:fs";import{isAbsolute as ph,join as fh,resolve as hh}from"node:path";import{readProjectConfig as mh,screenshotPlaceholderIds as gh,DEFAULT_CAPTURE_DIR as wh,DEFAULT_OUTPUT_DIR as yh}from"document360-engine";var rc=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Us(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?rc(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:rc(o),setup:t}:{mode:"single",id:o}}function Ws(e,t){let n=mh(e),o=n?.captureDir??wh,r=n?.outputDir??yh,s=(l,p)=>ph(l)?fh(l,p):hh(e,l,p);return gh(e,{scope:t}).map(({id:l,file:p})=>{let m=oc(s(r,`${l}.png`))?"captured":oc(s(o,`${l}.spec.ts`))?"spec":"placeholder";return{id:l,file:p,state:m}})}var kh={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},bh={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Fs(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(s=>s.file))].sort(),o=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of n){r.push(s);for(let l of e.filter(p=>p.file===s))r.push(` ${kh[l.state]} ${l.id.padEnd(34)} ${bh[l.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function sc(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
341
  `)}async function Fo(e,t){let n=Us(e);if(n.mode==="list"){let l=t?.cwd??process.cwd();for(let p of Fs(Ws(l,n.scope),n.scope))console.log(p);return{kind:"continue"}}if(n.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${n.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${n.id}.spec.ts. Report the spec path and any TODO data-testids or data to stage.`].join(`
342
342
  `),display:`/screenshot ${n.id}`};let r=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${n.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${n.scope}`:"every <!-- SCREENSHOT --> placeholder across the docs tree (the configured docsDir)"}.`,"Follow that skill exactly for each: read the SCREENSHOT block; read the product source for EXACT routes","and stable data-testid selectors (never guess); enter the prepared context via captureScope(); guard data",`prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts.${n.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`].join(`
343
- `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as bh,readFileSync as vh}from"node:fs";import{isAbsolute as $h,join as xh,resolve as Ch}from"node:path";import{readProjectConfig as Rh,DEFAULT_CAPTURE_DIR as Ph}from"document360-engine";async function En(){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(`
344
- `),display:"/capture-setup"}}var sc="-".repeat(64);function Hs(e){let t=Ph;try{let g=Rh(e);g?.captureDir&&(t=g.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=$h(t)?xh(t,"CAPTURE-TESTID-REQUESTS.json"):Ch(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!bh(n))return null;let o;try{let g=JSON.parse(vh(n,"utf8").replace(/^/,""));o=Array.isArray(g?.requests)?g.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(g=>g.file).filter(Boolean)).size,s=o.length,l=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,m=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${l} requested across ${p}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",sc,`Read ${m} and ${k}. They list ${l} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",sc]}nt();W();import{listOpenForDocs as Th,readProjectConfig as Sh}from"document360-engine";function qs(e){try{return Th(e).length}catch{return 0}}function Bs(){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(`
345
- `)}async function ic(e,t){let n=t?.cwd??process.cwd();return Sh(n)?qs(n)===0?(console.log(f("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:Bs(),display:"/inbox"}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as Dh,listOpenForDocs as jh,listOpenDirectives as Ah,readProjectConfig as Eh,computeSyncStatus as Nh,planPull as Ih,applyPull as _h,planImport as Oh,applyImport as Lh}from"document360-engine";function Nn(e){let t=0,n=0,o=0,r=0;try{t=Dh(e).length}catch{}try{let s=jh(e);n=s.filter(l=>l.kind==="request").length,o=s.filter(l=>l.kind==="answer").length}catch{}try{r=Ah(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function In(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 Gs(e){return{publish:e.includes("--publish")}}function Ys({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(`
346
- `)}var Mh={status:Nh,plan:Ih,apply:_h,planImport:Oh,applyImport:Lh};async function zs(e,t=Mh){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 Vs=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Ho=e=>e===1?"":"s";function Ks(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${Ho(e.pulled.length)} into local: ${Vs(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Ho(e.imported.length)} into local drafts: ${Vs(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Ho(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Vs(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${Ho(e.failed.length)} failed \u2014 left for /pull.`),t}async function ac(e,t){let n=t?.cwd??process.cwd();if(!Eh(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ne(n,t?.profileName);if(!o.ok)return console.log(R(o.reason)),{kind:"continue"};let{publish:r}=Gs(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await zs({cwd:n,profileName:t?.profileName});for(let p of Ks(s))console.log(p.startsWith("\u2713")?D(p):p.startsWith("\u2139")?f(p):L(p));let l=In(Nn(n));return console.log(f(l?`Catching up on ${l}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Ys({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as Uh}from"node:child_process";var xt="document360-writer",qo=`npm i -g ${xt}@latest`;async function Bo(){let e=process.platform==="win32";return new Promise(t=>{try{let n=Uh(`npm i -g ${xt}@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 lc(){return console.log(f(`Updating ${xt}\u2026`)),(await Bo()).ok?console.log(D("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(R(`Update failed \u2014 run manually: ${qo}`)),{kind:"continue"}}W();nt();import{existsSync as Xs,rmSync as Wh}from"node:fs";import{basename as cc,resolve as Qs}from"node:path";import{execFileSync as Fh}from"node:child_process";import{input as Hh}from"@inquirer/prompts";import{readProjectConfig as qh,devHintsGuidePath as Bh}from"document360-engine";var Vh=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Gh=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Vo=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),dc=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function uc(e){let t=Vo(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:dc(t)?!0:Gh.has(t)}function Js(e){let t=null;try{t=qh(e)}catch{t=null}let n=new Set(Vh);for(let o of[Vo(t?.docsDir),Vo(t?.captureDir),Vo(t?.outputDir)])o&&dc(o)&&n.add(o);return[...n].filter(o=>uc(o)&&Xs(Qs(e,o)))}function Zs(e,t){let n=[],o=[];for(let r of t){if(!uc(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Wh(Qs(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function pc(e,t){try{return Fh("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
347
- `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Yh(e){return pc(e,".d360-writer/hints")}function zh(e){return pc(e,".d360-writer/messages")}function ei(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Yh(e),o=zh(e),r=Xs(Qs(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: ${cc(e)}`]}async function fc(e,t){let n=Js(t.cwd);for(let m of ei(t.cwd,n))console.log(n.length===0?f(m):m);if(n.length===0)return{kind:"continue"};let o=cc(t.cwd);if((await t.withPausedInput(()=>Hh({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Xs(Bh(t.cwd)),{removed:l,failed:p}=Zs(t.cwd,n);console.log(D(`\u2713 Reset complete \u2014 removed ${l.length} item${l.length===1?"":"s"}. The repo is back to its original state.`));for(let m of p)console.log(R(` \u2717 ${m.path}: ${m.error}`));if(s){for(let m of Co())console.log(m);console.log(f("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}W();import{lintDocs as Kh}from"document360-engine";function Go(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 ti(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(`
343
+ `),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as vh,readFileSync as $h}from"node:fs";import{isAbsolute as xh,join as Ch,resolve as Rh}from"node:path";import{readProjectConfig as Ph,DEFAULT_CAPTURE_DIR as Sh}from"document360-engine";async function En(){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(`
344
+ `),display:"/capture-setup"}}var ic="-".repeat(64);function Hs(e){let t=Sh;try{let g=Ph(e);g?.captureDir&&(t=g.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=xh(t)?Ch(t,"CAPTURE-TESTID-REQUESTS.json"):Rh(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!vh(n))return null;let o;try{let g=JSON.parse($h(n,"utf8").replace(/^/,""));o=Array.isArray(g?.requests)?g.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(g=>g.file).filter(Boolean)).size,s=o.length,l=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,m=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${l} requested across ${p}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",ic,`Read ${m} and ${k}. They list ${l} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",ic]}nt();W();import{listOpenForDocs as Th,readProjectConfig as Dh}from"document360-engine";function qs(e){try{return Th(e).length}catch{return 0}}function Bs(){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(`
345
+ `)}async function ac(e,t){let n=t?.cwd??process.cwd();return Dh(n)?qs(n)===0?(console.log(f("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:Bs(),display:"/inbox"}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as jh,listOpenForDocs as Ah,listOpenDirectives as Eh,readProjectConfig as Nh,computeSyncStatus as Ih,planPull as _h,applyPull as Lh,planImport as Oh,applyImport as Mh}from"document360-engine";function Nn(e){let t=0,n=0,o=0,r=0;try{t=jh(e).length}catch{}try{let s=Ah(e);n=s.filter(l=>l.kind==="request").length,o=s.filter(l=>l.kind==="answer").length}catch{}try{r=Eh(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function In(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 Gs(e){return{publish:e.includes("--publish")}}function Ys({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(`
346
+ `)}var Uh={status:Ih,plan:_h,apply:Lh,planImport:Oh,applyImport:Mh};async function zs(e,t=Uh){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 Vs=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Ho=e=>e===1?"":"s";function Ks(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${Ho(e.pulled.length)} into local: ${Vs(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Ho(e.imported.length)} into local drafts: ${Vs(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Ho(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Vs(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${Ho(e.failed.length)} failed \u2014 left for /pull.`),t}async function lc(e,t){let n=t?.cwd??process.cwd();if(!Nh(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ne(n,t?.profileName);if(!o.ok)return console.log(R(o.reason)),{kind:"continue"};let{publish:r}=Gs(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await zs({cwd:n,profileName:t?.profileName});for(let p of Ks(s))console.log(p.startsWith("\u2713")?D(p):p.startsWith("\u2139")?f(p):O(p));let l=In(Nn(n));return console.log(f(l?`Catching up on ${l}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Ys({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as Wh}from"node:child_process";var xt="document360-writer",qo=`npm i -g ${xt}@latest`;async function Bo(){let e=process.platform==="win32";return new Promise(t=>{try{let n=Wh(`npm i -g ${xt}@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 cc(){return console.log(f(`Updating ${xt}\u2026`)),(await Bo()).ok?console.log(D("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(R(`Update failed \u2014 run manually: ${qo}`)),{kind:"continue"}}W();nt();import{existsSync as Xs,rmSync as Fh}from"node:fs";import{basename as dc,resolve as Qs}from"node:path";import{execFileSync as Hh}from"node:child_process";import{input as qh}from"@inquirer/prompts";import{readProjectConfig as Bh,devHintsGuidePath as Vh}from"document360-engine";var Gh=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Yh=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Vo=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),uc=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function pc(e){let t=Vo(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:uc(t)?!0:Yh.has(t)}function Js(e){let t=null;try{t=Bh(e)}catch{t=null}let n=new Set(Gh);for(let o of[Vo(t?.docsDir),Vo(t?.captureDir),Vo(t?.outputDir)])o&&uc(o)&&n.add(o);return[...n].filter(o=>pc(o)&&Xs(Qs(e,o)))}function Zs(e,t){let n=[],o=[];for(let r of t){if(!pc(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Fh(Qs(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function fc(e,t){try{return Hh("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
347
+ `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function zh(e){return fc(e,".d360-writer/hints")}function Kh(e){return fc(e,".d360-writer/messages")}function ei(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=zh(e),o=Kh(e),r=Xs(Qs(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: ${dc(e)}`]}async function hc(e,t){let n=Js(t.cwd);for(let m of ei(t.cwd,n))console.log(n.length===0?f(m):m);if(n.length===0)return{kind:"continue"};let o=dc(t.cwd);if((await t.withPausedInput(()=>qh({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(O("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Xs(Vh(t.cwd)),{removed:l,failed:p}=Zs(t.cwd,n);console.log(D(`\u2713 Reset complete \u2014 removed ${l.length} item${l.length===1?"":"s"}. The repo is back to its original state.`));for(let m of p)console.log(R(` \u2717 ${m.path}: ${m.error}`));if(s){for(let m of Co())console.log(m);console.log(f("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}W();import{lintDocs as Xh}from"document360-engine";function Go(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 ti(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(`
348
348
  `)).join(`
349
349
  `)].join(`
350
- `)}async function hc(e,t){let n=e.includes("--fix"),o=e.find(l=>!l.startsWith("--")),r=o?` ${o}`:"",s=Kh({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(D("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:ti(s),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let l of Go(s))console.log(s.length===0?D(l):L(l));return s.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}W();import{lintDocs as tm,loadStyleGuide as nm,buildReviewPrompt as om,readProjectConfig as rm,DEFAULT_DOCS_DIR as sm}from"document360-engine";W();import{readProjectConfig as Xh,loadProfileMap as Qh,resolveActiveProfile as Jh,desiredCategoryOrder as Zh,desiredArticleOrder as em}from"document360-engine";function mc(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 _n(e,t){try{if(!Xh(e))return[];let n=Jh(e,t),o=Qh(e,n.name);if(!o)return[];let r=new Map;for(let l of em(o)){let p=r.get(l.categoryPath);p?p.push(l):r.set(l.categoryPath,[l])}let s=[];for(let l of Zh(o)){s.push(mc(gc(l.path)));for(let p of(r.get(l.path)??[]).sort((m,k)=>m.order-k.order))s.push(` ${mc(gc(p.path))}`)}return s}catch{return[]}}async function wc(e,t){let n=_n(t.cwd,t.profileName);if(n.length===0)return console.log(f("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(O("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function ni(e,t){let n=rm(e);if(!n)return null;let o=(n.docsDir??sm).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(g=>!g.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),l=tm({cwd:e}),p=s?l.filter(g=>g.path===`${o}/${s}`||g.path.startsWith(`${o}/${s}/`)):l,m=s?"":_n(e).join(`
351
- `);return{prompt:om({docsRoot:o,scope:s,styleGuide:nm(e),deterministicFindings:p,fix:r,structure:m||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function yc(e,t){if(st("review",e)){let o=en(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=ni(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as im}from"document360-engine";function oi(e,t){if(!im(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(`
352
- `),display:`/reorder${n?` ${n}`:""}`}}async function kc(e,t){if(st("reorder",e)){let o=en(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=oi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as am,writeProjectConfig as bc,isAppType as lm,playbookSkillName as cm,detectAppType as vc}from"document360-engine";var $c=["web","cli","service","library"],dm=new Set(["web","cli"]);function ri(e){return dm.has(e)?`${cm(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Yo(e,t){let n=t.cwd,o=am(n);if(!o)return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??vc(n);if(s){let l=o.appType?"set in config":"auto-detected";console.log(`${O("Genre:")} ${s} (${l}) \u2014 ${ri(s)}`)}else console.log(L("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${$c.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(f("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...l}=o;bc(l,n);let p=vc(n);return console.log(D(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${ri(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return lm(r)?(bc({...o,appType:r},n),console.log(D(`\u2713 Genre set to ${r} \u2014 ${ri(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(R(`Unknown genre "${r}". Choose one of: ${$c.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}W();import{listRoadmap as xc,roadmapProgress as Cc,stampRoadmapDone as um}from"document360-engine";function si(e){let t=xc(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=Cc(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 ii(e,t){let n=xc(e).filter(k=>k.status==="open"),o=t.trim();if(n.length===0)return{ok:!1,line:"The roadmap has no open steps \u2014 nothing to mark done."};let r=k=>k.trim().toLowerCase(),s=n.find(k=>r(k.title)===r(o)),l=o?s?[s]:n.filter(k=>r(k.title).includes(r(o))):[n[0]];if(l.length>1)return{ok:!1,line:`"${o}" matches ${l.length} open steps \u2014 add a distinguishing word:
350
+ `)}async function mc(e,t){let n=e.includes("--fix"),o=e.find(l=>!l.startsWith("--")),r=o?` ${o}`:"",s=Xh({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(D("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:ti(s),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let l of Go(s))console.log(s.length===0?D(l):O(l));return s.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}W();import{lintDocs as nm,loadStyleGuide as om,buildReviewPrompt as rm,readProjectConfig as sm,DEFAULT_DOCS_DIR as im}from"document360-engine";W();import{readProjectConfig as Qh,loadProfileMap as Jh,resolveActiveProfile as Zh,desiredCategoryOrder as em,desiredArticleOrder as tm}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 wc=e=>e.replace(/\\/g,"/").split("/").pop()??e;function _n(e,t){try{if(!Qh(e))return[];let n=Zh(e,t),o=Jh(e,n.name);if(!o)return[];let r=new Map;for(let l of tm(o)){let p=r.get(l.categoryPath);p?p.push(l):r.set(l.categoryPath,[l])}let s=[];for(let l of em(o)){s.push(gc(wc(l.path)));for(let p of(r.get(l.path)??[]).sort((m,k)=>m.order-k.order))s.push(` ${gc(wc(p.path))}`)}return s}catch{return[]}}async function yc(e,t){let n=_n(t.cwd,t.profileName);if(n.length===0)return console.log(f("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(L("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function ni(e,t){let n=sm(e);if(!n)return null;let o=(n.docsDir??im).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(g=>!g.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),l=nm({cwd:e}),p=s?l.filter(g=>g.path===`${o}/${s}`||g.path.startsWith(`${o}/${s}/`)):l,m=s?"":_n(e).join(`
351
+ `);return{prompt:rm({docsRoot:o,scope:s,styleGuide:om(e),deterministicFindings:p,fix:r,structure:m||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function kc(e,t){if(st("review",e)){let o=en(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=ni(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as am}from"document360-engine";function oi(e,t){if(!am(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(`
352
+ `),display:`/reorder${n?` ${n}`:""}`}}async function bc(e,t){if(st("reorder",e)){let o=en(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=oi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as lm,writeProjectConfig as vc,isAppType as cm,playbookSkillName as dm,detectAppType as $c}from"document360-engine";var xc=["web","cli","service","library"],um=new Set(["web","cli"]);function ri(e){return um.has(e)?`${dm(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Yo(e,t){let n=t.cwd,o=lm(n);if(!o)return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??$c(n);if(s){let l=o.appType?"set in config":"auto-detected";console.log(`${L("Genre:")} ${s} (${l}) \u2014 ${ri(s)}`)}else console.log(O("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${xc.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(f("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...l}=o;vc(l,n);let p=$c(n);return console.log(D(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${ri(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return cm(r)?(vc({...o,appType:r},n),console.log(D(`\u2713 Genre set to ${r} \u2014 ${ri(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(R(`Unknown genre "${r}". Choose one of: ${xc.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}W();import{listRoadmap as si,roadmapProgress as Cc,stampRoadmapDone as pm}from"document360-engine";function ii(e){let t=si(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=Cc(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 ai(e,t){let n=si(e).filter(k=>k.status==="open"),o=t.trim();if(n.length===0)return{ok:!1,line:"The roadmap has no open steps \u2014 nothing to mark done."};let r=k=>k.trim().toLowerCase(),s=n.find(k=>r(k.title)===r(o)),l=o?s?[s]:n.filter(k=>r(k.title).includes(r(o))):[n[0]];if(l.length>1)return{ok:!1,line:`"${o}" matches ${l.length} open steps \u2014 add a distinguishing word:
353
353
  ${l.map(k=>` \u25CB ${k.title}`).join(`
354
354
  `)}`};if(l.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
355
355
  ${n.map(k=>` \u25CB ${k.title}`).join(`
356
- `)}`};let p=l[0].title;um(e,p,{doneAt:new Date().toISOString()});let m=Cc(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${p}${m?` \u2014 next up: ${m.title}${m.run?` (${m.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}async function Rc(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=ii(n,e.slice(1).join(" ").trim());return console.log(r.ok?D(r.line):L(r.line)),{kind:"continue"}}let o=si(n);console.log(O(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?f(r):r);return{kind:"continue"}}var Pc={help:Mr,"?":Mr,clear:ba,exit:Ur,quit:Ur,init:Br,mcp:To,publish:cl,audit:Sn,discover:dl,scope:pl,pull:xl,resolve:bl,convert:Cl,write:jl,draft:_l,document:Ol,resume:Ul,rename:Wl,profile:Hl,model:Vl,doctor:An,workspace:Ql,project:Jl,"allow-prod":Zl,login:ec,logout:tc,screenshot:Fo,"capture-setup":En,devhints:Aa,inbox:ic,"catch-up":ac,update:lc,reset:fc,check:hc,review:yc,reorder:kc,structure:wc,genre:Yo,roadmap:Rc};function Tc(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}nt();var pm="Or just tell me what to write or update.",fm='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function fe(e){return e===1?"":"s"}function zo(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function On(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var hm={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 mm(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:hm,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.discovery&&e.discovery.status!=="confident"){let n=e.discovery.openQuestions;t.push(e.discovery.status==="pending"?{key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/publish steps)."}:n>0?{key:"discovery",bullet:`product discovery is waiting on ${n} answer${fe(n)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}:{key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.directives>0||e.pendingText){let n=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",o=[];e.directives>0&&o.push(`${e.directives} owner directive${fe(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
357
- \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${fe(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${fe(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${fe(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${fe(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${fe(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${fe(n)} changed both here and on Document360 (conflicts) \u2014 /publish skips these`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each conflict \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${n} conflict${fe(n)} (keep yours / take the portal's / skip).`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${fe(n.total)} done \u2014 next: ${o.title}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${fe(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${fe(n)}.`})}return t}function Sc(e){return e.find(t=>t.lead||t.picker)??null}function ai(e,t){let n=t.filter(l=>l.bullet).map(l=>` \u2022 ${l.bullet}`),o=Sc(t),r=[];o?.lead?r.push(On(o.lead)):o?.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let l of t.filter(p=>p!==o).slice(0,2))l.follow&&r.push(l.follow);let s=[[e,...n].join(`
358
- `)];return r.length&&s.push(r.join(" ")),s.push(pm),s.join(`
359
-
360
- `)}function Ln(e){if(!e.ready)return{kind:"idle"};let t=mm(e);if(!e.hasDocs){let s=Sc(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:ai("\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:fm,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null}}}if(t.length===0){let s=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${fe(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${fe(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${s}`,tone:"info",lead:null,picker:null}}}let n=t.filter(s=>s.lead||s.picker),o=n[0]??null;return o?(o.key==="audit"||o.key==="roadmap"&&n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${fe(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:ai("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:ai("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as li,readdirSync as di}from"node:fs";import{spawnSync as gm}from"node:child_process";import{join as Ko}from"node:path";import{readProjectConfig as jc,resolveActiveProfile as Ac,loadTokens as wm,isExpired as ym,loadProfileMap as Ec,localAheadPaths as km,loadKnownConflicts as bm,readDocsPlan as vm,devHintsGuidePath as $m,DEFAULT_DOCS_DIR as ci,roadmapProgress as xm,listRoadmap as Cm,readProductBriefState as Rm}from"document360-engine";nt();function Dc(e){try{return di(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ui(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Dc(Ko(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Dc(Ko(e,o)))}function pi(e,t){try{let n=jc(e);if(!n)return!1;let o=Ac(e,t),r=Ec(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Ko(e,(n.docsDir??ci).replace(/\/+$/,""));return!!(li(s)&&di(s).length>0||li($m(e)))}catch{return!1}}function Mn(e,t,n){try{let o=jc(e);if(!o)return null;let r=Ac(e,t),s=wm(r.name),l=!!s&&(!ym(s)||!!s.refreshToken),p=pi(e,t)||!ui(e,o.authoritativeSourceFiles),m=Ec(e,r.name),k=m?Object.keys(m.articles).length:0,g=Ko(e,(o.docsDir??ci).replace(/\/+$/,"")),T=!1;try{T=li(g)&&di(g).length>0}catch{}let v=0;if(m?.lastAnalyzedCommit)try{let Se=gm("git",["rev-list","--count",`${m.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});Se.status===0&&(v=parseInt((Se.stdout||"").trim(),10)||0)}catch{}let _=0;try{let Se=vm(e);if(Se.length>0){let Ke=(o.docsDir??ci).replace(/\/+$/,"");_=vs(e,Ke,Se.map(Fn=>Fn.path)).length}}catch{}let P=Nn(e),N=In({...P,directives:0}),S=km(e,t),M=new Set(bm(e,r.name)),B=S.filter(Se=>M.has(Se)).length,V=S.length-B,Y=Ee(e),ue=xm(e),_e=Rm(e),he=_e?{status:_e.status,openQuestions:_e.openQuestions}:null;return!he&&T&&Cm(e).some(Ke=>Ke.status==="open"&&(Ke.run??"").trim()==="/discover")&&(he={status:"pending",openQuestions:0}),{ready:l&&p&&!n.claudeMissing,hasDocs:T,tracked:k,pendingText:N,directives:P.directives,behind:v,pendingWrites:_,localAhead:V,conflicts:B,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:Y.status,devhintsCompletedVersion:Y.completedVersion,devhintsToVersion:ae,builderStarted:Ge(e),genreUnknown:n.genreUnknown,roadmap:ue,discovery:he}}catch{return null}}function Nc(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 Xo(e){if(e.length===0)return[];let t=(s,l)=>`${s}${"\u2500".repeat(78)}${l}`,n=(s="")=>`\u2502 ${s.padEnd(76)} \u2502`,o=[`\u2B06 d360-writer upgraded \u2014 ${e.length===1?"one improvement affects":`${e.length} improvements affect`} the docs you've already written:`,"",t("\u250C","\u2510")];e.forEach((s,l)=>{l>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let p of Nc(`${l+1}. ${s.feature}`,76))o.push(n(p));o.push(n());for(let p of Nc(s.why,73))o.push(n(` ${p}`));o.push(n())}),o.push(t("\u2514","\u2518")),o.push("");let r=e.length>1;return o.push(`\u2713 ${r?"These are":"This is"} now on your docs roadmap \u2014 each launch shows your next step below (/roadmap shows the full campaign).`),o}W();var Pm={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"},_c=160,hi=200,Oc=40;function Re(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Ic(e){let t=Object.entries(e).filter(([,o])=>o!=null&&o!=="");if(t.length===0)return null;let n=t.slice(0,4).map(([o,r])=>`${o}: ${Re(typeof r=="string"?r:JSON.stringify(r),Oc)}`);return t.length>4&&n.push("\u2026"),Re(n.join(", "),_c)}var it=e=>typeof e=="string"&&e?e:null,fi=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Tm(e){let t=it(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 Sm(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=it(t.title);if(!o)return null;let r=Tm(t.local_path);return n("Create article",`"${Re(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=it(t.title),r=fi(t.article_id);return n("Update article",o?`"${Re(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",fi(t.article_id)?`id ${fi(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",it(t.name)?`"${Re(it(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=it(t.file_path);return n("Upload image",o?Re(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Qo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),l=s.join("__");if(r==="document360"){let k=Sm(l,t);if(k)return k}let p=l.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Ic(t)}}let n=Pm[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:Re(o,_c)}:{title:e,sep:"",arg:Ic(t)}}function Dm(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 jm(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Dm).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Re(r,hi))]}if(t!==null&&typeof t=="object"){let n=Object.entries(t).filter(([,o])=>o!==null&&(typeof o=="string"||typeof o=="number"||typeof o=="boolean")).slice(0,6).map(([o,r])=>`${o}: ${Re(String(r),Oc)}`);return n.length>0?[Re(n.join(" \xB7 "),hi)]:null}return null}function Am(e){let t=it(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Em(e,t,n){switch(e){case"d360_create_article":{let o=Am(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=it(t?.name);return[`\u2713 category created${o?` \xB7 "${o}"`:""}`]}case"d360_upload_drive_file":{let o=n.match(/https?:\/\/\S+/);return[`\u2713 uploaded${o?` \xB7 ${Re(o[0],120)}`:""}`]}default:return null}}function Jo(e,t=4,n,o){let r=e.replace(/\r\n/g,`
361
- `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let l=Em(n.slice(18),o,r);if(l)return{lines:l,hidden:0}}let s=jm(r)??r.split(`
362
- `);return{lines:s.slice(0,t).map(l=>Re(l,hi)),hidden:Math.max(0,s.length-t)}}function Zo(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function er(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 Lc(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 tr(e){return Lc(e,"url")}function nr(e){return Lc(e,"preview_url")}var Jm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Zm(e,t,n,o){if(Jm.test(e))try{let r=Wc(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,l=er(t,n),p=tr(n);e.endsWith("publish_article")&&p&&console.log(O(` \u2B95 Live: ${p}`));let m=nr(n);m?console.log(O(` \u2B95 Preview: ${m}`)):l&&s&&console.log(O(` \u2B95 Preview: ${Zo(r.connection.portalUrl,s,l,r.project.languageCode??"en")}`))}catch{}}async function Fc(e=process.cwd(),t="auto",n,o){let r=Im(t);r.kind==="none"&&(console.error(""),console.error(R("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${O("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${O('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),eg(e,n),r.kind==="subscription"&&(r.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,l=mi({cwd:e,profileName:n,allowProdWrites:s}),p={uuid:null,firstPrompt:null,titleFired:!1},m=Nm({input:process.stdin,output:process.stdout}),k=[],g=null,T=!1;m.on("line",P=>{if(g){let N=g;g=null,N(P)}else k.push(P)}),m.on("close",()=>{if(T=!0,g){let P=g;g=null,P(null)}});function v(){return k.length>0?Promise.resolve(k.shift()):T?Promise.resolve(null):(process.stdout.write(O("> ")),new Promise(P=>{g=P}))}let _={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{l.close(),l=mi({cwd:e,profileName:n,allowProdWrites:s}),p={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>p.uuid,setPendingName:P=>{p.pendingName=P},setModel:async P=>l.setModel(P),withPausedInput:async P=>{m.pause();try{return await P()}finally{m.resume()}}};try{for(;;){let P=await v();if(P===null)break;let N=P.trim();if(N){if(N.startsWith("/")){let S=Tc(N);if(!S)continue;let M=Pc[S.name];if(!M){console.log(R(`Unknown command: /${S.name}`)),console.log(f("Type /help for the list."));continue}let B=await M(S.args,_);if(B.kind==="exit")break;if(B.kind==="clear"){_.restartAgent();continue}if(B.kind==="allow-prod"){s=!0,_.restartAgent(),console.log(D("\u2713 Production writes authorized for this session.")),console.log("");continue}if(B.kind==="resume"){l.close(),l=mi({cwd:e,resume:B.uuid,profileName:n,allowProdWrites:s});let V=_m(B.uuid);p={uuid:B.uuid,firstPrompt:V?.firstPrompt??null,titleFired:!0},Uc(B.uuid),console.log(D(`\u2713 Resumed "${B.name}"`)),console.log("");continue}if(B.kind==="forward-to-agent"){p.firstPrompt||(p.firstPrompt=B.display??B.prompt);let V=(B.display??"").trim().split(/\s+/),Y=(V[0]==="/check"||V[0]==="/review")&&V.includes("--fix"),ue=V.slice(1).find(he=>!he.startsWith("--")),_e=Y?Xm(e,ue):[];if(await gi(l,B.prompt,r,p,e),Y)try{Km(e,_e,{reviewedCap:Qm})}catch{}}else tg(e,n);continue}if(Vm(N)){let S=Gm(N);if(S){try{Ym(e,{title:S,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}p.firstPrompt||(p.firstPrompt=N),await gi(l,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${S}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${S}" and the article path(s) you wrote.`,r,p,e);continue}}p.firstPrompt||(p.firstPrompt=N),await gi(l,N,r,p,e)}}}finally{l.close(),m.close()}}function eg(e,t){console.log(""),console.log(kn("document360-writer")),console.log(f(` cwd: ${e}`));let n=Wm(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(ng(e,t)),!Fm(e))console.log(L(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{let o=!1;try{if($o(e),!Ge(e))for(let r of xo(e))console.log(L(` ${r}`))}catch{}try{let r=Hm(e);r.persisted&&r.appType?console.log(f(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=zm(e);for(let s of Xo(r.applied))console.log(L(` ${s}`))}catch{}try{let r=Mn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Ln(r):null;if(s?.kind==="recommend"&&s.rec.note){let l=s.rec.tone==="warn"?L:f;for(let p of s.rec.note.split(`
363
- `))console.log(l(` ${p}`));s.rec.picker&&console.log(O(` Pick one: ${s.rec.picker.options.map(p=>p.cmd).join(" \xB7 ")}`))}}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function tg(e,t){try{let n=Mn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Ln(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(f(` Next: ${On(o.rec.lead)}`))}catch{}}function ng(e,t){try{let n=Wc(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=Bm(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Mc(r.idToken)??{},...Mc(r.accessToken)??{}},l=s.email??s.preferred_username??"signed in";return qm(r)&&!r.refreshToken?L(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${l} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function og(){console.error(""),console.error(`Sign in with your Claude subscription: run ${O("claude")} once, then retry.`),console.error(` (No Claude Code? ${O("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${O("https://console.anthropic.com/settings/keys")}`)}function rg(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Mm({uuid:t,name:r??Lm(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function sg(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Um(o,t).then(r=>{r&&Om(n,r)}).catch(()=>{})}async function gi(e,t,n,o,r){let s=new Map;for await(let l of e.send(t))ig(l,o,r,n,s)}function ig(e,t,n,o,r){switch(e.type){case"session":t.uuid||rg(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Qo(e.name,e.input);s&&(process.stdout.write(`
364
-
365
- `),console.log(`${D("\u25CF")} ${ke(s.title)}${s.arg!==null?ie(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=Ye(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let l=p=>p===1?"":"s";console.log(ie(` \u23BF Added ${s.added} line${l(s.added)}, removed ${s.removed} line${l(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(f(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let l=Jo(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?R:ie;l.lines.forEach((m,k)=>console.log(p((k===0?" \u23BF ":" ")+m))),l.hidden>0&&console.log(f(` \u2026 +${l.hidden} lines`)),e.isError||Zm(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
366
- `);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(f(` (${Rn(s)}\u2192${Rn(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Uc(t.uuid),t.titleFired||sg(t,n));break}case"error":console.error(""),console.error(R(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&og();break}}import{render as vw}from"ink";import{resolveAuth as $w}from"document360-engine";import{useCallback as z,useEffect as Te,useMemo as $i,useRef as ee,useState as F}from"react";import{Box as ne,Text as j,useApp as vg,useInput as $g,useStdout as xg}from"ink";import{existsSync as nn,readFileSync as dr,readdirSync as Cg}from"node:fs";import{basename as Wn,isAbsolute as Rg,join as xi}from"node:path";import{createSession as pd,classifyClaudeAuth as Di,CLAUDE_CODE_SETUP_HINT as Pg,loginPkce as Tg,toStoredTokens as Sg,saveTokens as Dg,getAccessToken as jg,resolveActiveProfile as Pe,resolveProjectId as Ag,getArticle as Eg,decodeJwtClaims as rn,isExpired as at,loadTokens as Rt,clearTokens as Ng,clearProfileProject as Ig,setTitle as _g,slugify as Og,touchSession as Ci,upsertSession as Lg,generateTitle as fd,findByName as Mg,listSessions as Ug,renameSession as Wg,suggestNextAction as Fg,readProjectConfig as te,writeProjectConfig as hd,resolveAndPersistAppType as Hg,detectAppType as qg,resolveModelSetting as ji,loadProfileMap as md,applyPull as gd,computeSyncStatus as Ri,lintDocs as wd,compareRemoteSources as Bg,planPull as yd,establishBaselines as Vg,rebaselineServerMeta as Gg,inventoryRepo as Yg,knownEnvironments as zg,resolveEnvironment as Kg,planPartitions as Pi,partitionEvenly as Xg,screenshotPlaceholderIds as Qg,trackedArticlePaths as Jg,runPartitioned as ur,estimateBulkCost as kd,resolveModelForOperation as pr,readDocsPlan as Zg,checkForUpdate as ew,detectInstallKind as tw,isSelfUpdatable as nw,devHintsGuidePath as bd,toolFeedbackPath as vd,reconcileToolFeedback as ow,reconcileUpgradeActions as rw,stampArticles as Ti,listArticleFiles as $d,CONTENT_CAP_VERSION as Si,ENGINE_VERSION as jd,DEFAULT_DOCS_DIR as Ad,setProfileProject as sw,writeCrashLog as iw,applyStructureOrder as xd,orderSyncLine as Cd,applyRelatedArticles as Rd,relatedSyncLine as Pd}from"document360-engine";nt();import{spawn as Hc}from"node:child_process";function ag(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function lg(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?Hc([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Hc(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",l=>o(l===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function wi(e){for(let[t,n]of ag())if(await lg(t,n,e))return!0;return!1}var cg=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function yi(e,t){if(t.closed)return e;let n=e.split(`
367
- `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){cg.test(s)&&(t.cueSeen=!0);continue}let l=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);l?(n[r]=`${l[1]}${++t.num}. ${l[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
368
- `)}import{existsSync as dg,mkdirSync as ug,readFileSync as pg,writeFileSync as fg}from"node:fs";import{join as qc}from"node:path";import{writerDir as hg}from"document360-engine";function Bc(e){return qc(hg(e),".sessions")}function Vc(e,t){return qc(Bc(e),`${t}.json`)}function Gc(e,t,n){try{ug(Bc(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");fg(Vc(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function ki(e,t){try{let n=Vc(e,t);if(!dg(n))return[];let o=JSON.parse(pg(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var mg=e=>`\x1B]0;${e}\x07`,gg=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Yc(e){process.stdout.isTTY&&process.stdout.write(e)}function tn(e){Yc(mg(e))}function or(e){Yc(gg(e))}var rr=["\xB7 "," \xB7"],sr="\u{1F7E3}";Wo();Po();W();import{Box as zc,Text as ce}from"ink";import{jsx as de,jsxs as ir}from"react/jsx-runtime";function wg({row:e}){switch(e.t){case"head":return de(ce,{color:q,bold:!0,children:e.s});case"text":return de(ce,{children:e.s});case"dim":return de(ce,{dimColor:!0,children:e.s});case"sub":return de(ce,{bold:!0,dimColor:!0,children:e.s});case"good":return de(ce,{color:"green",children:e.s});case"step":return ir(ce,{children:[de(ce,{color:q,children:`${e.n}. `}),e.s]});case"cmd":return ir(ce,{children:[" ",de(ce,{color:q,children:e.name.padEnd(20)}),de(ce,{dimColor:!0,children:e.s})]});case"gap":return de(ce,{children:" "})}}function Kc({tab:e,width:t,version:n,engineVersion:o}){let r=Ae[e]??Ae[0],s=6+Ae.reduce((p,m)=>p+m.label.length+4,0),l="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return ir(zc,{flexDirection:"column",paddingX:1,children:[ir(ce,{children:[de(ce,{color:q,bold:!0,children:"Help "}),Ae.map((p,m)=>m===e?de(ce,{color:"white",backgroundColor:q,bold:!0,children:` ${p.label} `},p.key):de(ce,{dimColor:!0,children:` ${p.label} `},p.key))]}),de(ce,{color:q,children:l}),de(zc,{flexDirection:"column",marginTop:1,children:r.rows.map((p,m)=>de(wg,{row:p},m))}),de(ce,{dimColor:!0,children:`
369
- \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var yg=/^(?:\d+[.)]|[-*•])\s+/;function Xc(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
370
- `)){let l=s.trim().replace(yg,""),p=l.match(/^`([^`]+)`$/);p&&(l=p[1].trim());let m=l.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!m||!o.has(m[1].toLowerCase()))continue;let k=`/${m[1].toLowerCase()}${m[2]?` ${m[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}W();function Un(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function ze(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Qc(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var kg=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Jc(e,t,n){if(!kg.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(s=>{let l=s.replace(/\\/g,"/");return r===l||r.endsWith(`/${l}`)})??null}function bi(e){return e.replace(/^[\w.-]+\//,"")}var ar=16,Zc={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Ct(e){return typeof e=="string"?e:e.cmd}function ed(e){return typeof e=="string"?void 0:e.desc}function vi(e){return e.trim().split(/\s+/).slice(1).join(" ")}function td(e,t){let n=vi(t);return e.some(r=>Ct(r).trim()===t.trim()||!!n&&vi(Ct(r))===n)?e.filter(r=>Ct(r).trim()!==t.trim()&&!(n&&vi(Ct(r))===n)):[]}import{isDirectiveMention as aw,stripDirectiveMention as lw,appendDirective as cw}from"document360-engine";var bg=/\[Pasted text #\d+ \+\d+ lines?\]/g;function nd(e){return e.replace(/\r\n?/g,`
371
- `)}function od(e){return e.includes(`
372
- `)||e.length>200}function rd(e,t){let n=t.split(`
373
- `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function sd(e,t){return e.replace(bg,n=>t.get(n)??n)}function id(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function lr(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
374
- `)){if(s.length===0)o.push({start:r,end:r});else for(let l=0;l<s.length;l+=n)o.push({start:r+l,end:r+Math.min(l+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function cr(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function ad(e,t,n){let o=cr(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 ld(e,t,n){let o=e[cr(e,t)];return n==="start"?o.start:o.end}function cd(e,t,n){let o=Math.max(1,n),r=e.split(`
356
+ `)}`};let p=l[0].title;pm(e,p,{doneAt:new Date().toISOString()});let m=Cc(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${p}${m?` \u2014 next up: ${m.title}${m.run?` (${m.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function Rc(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=si(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:
357
+ ${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(`
358
+ `):null}async function Pc(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=ai(n,e.slice(1).join(" ").trim());return console.log(r.ok?D(r.line):O(r.line)),{kind:"continue"}}let o=ii(n);console.log(L(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?f(r):r);return{kind:"continue"}}var Sc={help:Mr,"?":Mr,clear:va,exit:Ur,quit:Ur,init:Br,mcp:So,publish:dl,audit:Tn,discover:ul,scope:fl,pull:Cl,resolve:vl,convert:Rl,write:Al,draft:Ll,document:Ol,resume:Wl,rename:Fl,profile:ql,model:Gl,doctor:An,workspace:Jl,project:Zl,"allow-prod":ec,login:tc,logout:nc,screenshot:Fo,"capture-setup":En,devhints:Ea,inbox:ac,"catch-up":lc,update:cc,reset:hc,check:mc,review:kc,reorder:bc,structure:yc,genre:Yo,roadmap:Pc};function Tc(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}nt();var fm="Or just tell me what to write or update.",hm='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function fe(e){return e===1?"":"s"}function zo(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Ln(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var mm={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 gm(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:mm,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.discovery&&e.discovery.status!=="confident"){let n=e.discovery.openQuestions;t.push(e.discovery.status==="pending"?{key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/publish steps)."}:n>0?{key:"discovery",bullet:`product discovery is waiting on ${n} answer${fe(n)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}:{key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.directives>0||e.pendingText){let n=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",o=[];e.directives>0&&o.push(`${e.directives} owner directive${fe(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
359
+ \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${fe(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${fe(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${fe(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${fe(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${fe(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${fe(n)} changed both here and on Document360 (conflicts) \u2014 /publish skips these`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each conflict \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${n} conflict${fe(n)} (keep yours / take the portal's / skip).`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${fe(n.total)} done \u2014 next: ${o.title}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${fe(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${fe(n)}.`})}return t}function Dc(e){return e.find(t=>t.lead||t.picker)??null}function li(e,t){let n=t.filter(l=>l.bullet).map(l=>` \u2022 ${l.bullet}`),o=Dc(t),r=[];o?.lead?r.push(Ln(o.lead)):o?.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let l of t.filter(p=>p!==o).slice(0,2))l.follow&&r.push(l.follow);let s=[[e,...n].join(`
360
+ `)];return r.length&&s.push(r.join(" ")),s.push(fm),s.join(`
361
+
362
+ `)}function On(e){if(!e.ready)return{kind:"idle"};let t=gm(e);if(!e.hasDocs){let s=Dc(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:li("\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:hm,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null}}}if(t.length===0){let s=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${fe(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${fe(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${s}`,tone:"info",lead:null,picker:null}}}let n=t.filter(s=>s.lead||s.picker),o=n[0]??null;return o?(o.key==="audit"||o.key==="roadmap"&&n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${fe(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:li("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:li("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as ci,readdirSync as ui}from"node:fs";import{spawnSync as wm}from"node:child_process";import{join as Ko}from"node:path";import{readProjectConfig as Ac,resolveActiveProfile as Ec,loadTokens as ym,isExpired as km,loadProfileMap as Nc,localAheadPaths as bm,loadKnownConflicts as vm,readDocsPlan as $m,devHintsGuidePath as xm,DEFAULT_DOCS_DIR as di,roadmapProgress as Cm,listRoadmap as Rm,readProductBriefState as Pm}from"document360-engine";nt();function jc(e){try{return ui(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function pi(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>jc(Ko(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&jc(Ko(e,o)))}function fi(e,t){try{let n=Ac(e);if(!n)return!1;let o=Ec(e,t),r=Nc(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Ko(e,(n.docsDir??di).replace(/\/+$/,""));return!!(ci(s)&&ui(s).length>0||ci(xm(e)))}catch{return!1}}function Mn(e,t,n){try{let o=Ac(e);if(!o)return null;let r=Ec(e,t),s=ym(r.name),l=!!s&&(!km(s)||!!s.refreshToken),p=fi(e,t)||!pi(e,o.authoritativeSourceFiles),m=Nc(e,r.name),k=m?Object.keys(m.articles).length:0,g=Ko(e,(o.docsDir??di).replace(/\/+$/,"")),S=!1;try{S=ci(g)&&ui(g).length>0}catch{}let v=0;if(m?.lastAnalyzedCommit)try{let Te=wm("git",["rev-list","--count",`${m.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});Te.status===0&&(v=parseInt((Te.stdout||"").trim(),10)||0)}catch{}let _=0;try{let Te=$m(e);if(Te.length>0){let Ke=(o.docsDir??di).replace(/\/+$/,"");_=vs(e,Ke,Te.map(Fn=>Fn.path)).length}}catch{}let P=Nn(e),N=In({...P,directives:0}),T=bm(e,t),M=new Set(vm(e,r.name)),B=T.filter(Te=>M.has(Te)).length,V=T.length-B,Y=Ee(e),ue=Cm(e),_e=Pm(e),he=_e?{status:_e.status,openQuestions:_e.openQuestions}:null;return!he&&S&&Rm(e).some(Ke=>Ke.status==="open"&&(Ke.run??"").trim()==="/discover")&&(he={status:"pending",openQuestions:0}),{ready:l&&p&&!n.claudeMissing,hasDocs:S,tracked:k,pendingText:N,directives:P.directives,behind:v,pendingWrites:_,localAhead:V,conflicts:B,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:Y.status,devhintsCompletedVersion:Y.completedVersion,devhintsToVersion:ae,builderStarted:Ge(e),genreUnknown:n.genreUnknown,roadmap:ue,discovery:he}}catch{return null}}function Ic(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 Xo(e){if(e.length===0)return[];let t=(s,l)=>`${s}${"\u2500".repeat(78)}${l}`,n=(s="")=>`\u2502 ${s.padEnd(76)} \u2502`,o=[`\u2B06 d360-writer upgraded \u2014 ${e.length===1?"one improvement affects":`${e.length} improvements affect`} the docs you've already written:`,"",t("\u250C","\u2510")];e.forEach((s,l)=>{l>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let p of Ic(`${l+1}. ${s.feature}`,76))o.push(n(p));o.push(n());for(let p of Ic(s.why,73))o.push(n(` ${p}`));o.push(n())}),o.push(t("\u2514","\u2518")),o.push("");let r=e.length>1;return o.push(`\u2713 ${r?"These are":"This is"} now on your docs roadmap \u2014 each launch shows your next step below (/roadmap shows the full campaign).`),o}W();var Sm={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"},Lc=160,mi=200,Oc=40;function Re(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function _c(e){let t=Object.entries(e).filter(([,o])=>o!=null&&o!=="");if(t.length===0)return null;let n=t.slice(0,4).map(([o,r])=>`${o}: ${Re(typeof r=="string"?r:JSON.stringify(r),Oc)}`);return t.length>4&&n.push("\u2026"),Re(n.join(", "),Lc)}var it=e=>typeof e=="string"&&e?e:null,hi=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Tm(e){let t=it(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 Dm(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=it(t.title);if(!o)return null;let r=Tm(t.local_path);return n("Create article",`"${Re(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=it(t.title),r=hi(t.article_id);return n("Update article",o?`"${Re(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",hi(t.article_id)?`id ${hi(t.article_id)}\u2026`:null);case"d360_publish_article":{let o=t.version_number;return n("Publish article LIVE",typeof o=="number"?`v${o}`:null)}case"d360_unpublish_article":return n("Unpublish article",null);case"d360_create_category":return n("Create category",it(t.name)?`"${Re(it(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=it(t.file_path);return n("Upload image",o?Re(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Qo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),l=s.join("__");if(r==="document360"){let k=Dm(l,t);if(k)return k}let p=l.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:_c(t)}}let n=Sm[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:Re(o,Lc)}:{title:e,sep:"",arg:_c(t)}}function jm(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 Am(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(jm).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Re(r,mi))]}if(t!==null&&typeof t=="object"){let n=Object.entries(t).filter(([,o])=>o!==null&&(typeof o=="string"||typeof o=="number"||typeof o=="boolean")).slice(0,6).map(([o,r])=>`${o}: ${Re(String(r),Oc)}`);return n.length>0?[Re(n.join(" \xB7 "),mi)]:null}return null}function Em(e){let t=it(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Nm(e,t,n){switch(e){case"d360_create_article":{let o=Em(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=it(t?.name);return[`\u2713 category created${o?` \xB7 "${o}"`:""}`]}case"d360_upload_drive_file":{let o=n.match(/https?:\/\/\S+/);return[`\u2713 uploaded${o?` \xB7 ${Re(o[0],120)}`:""}`]}default:return null}}function Jo(e,t=4,n,o){let r=e.replace(/\r\n/g,`
363
+ `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let l=Nm(n.slice(18),o,r);if(l)return{lines:l,hidden:0}}let s=Am(r)??r.split(`
364
+ `);return{lines:s.slice(0,t).map(l=>Re(l,mi)),hidden:Math.max(0,s.length-t)}}function Zo(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function er(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 Mc(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 tr(e){return Mc(e,"url")}function nr(e){return Mc(e,"preview_url")}var Zm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function eg(e,t,n,o){if(Zm.test(e))try{let r=Fc(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,l=er(t,n),p=tr(n);e.endsWith("publish_article")&&p&&console.log(L(` \u2B95 Live: ${p}`));let m=nr(n);m?console.log(L(` \u2B95 Preview: ${m}`)):l&&s&&console.log(L(` \u2B95 Preview: ${Zo(r.connection.portalUrl,s,l,r.project.languageCode??"en")}`))}catch{}}async function Hc(e=process.cwd(),t="auto",n,o){let r=_m(t);r.kind==="none"&&(console.error(""),console.error(R("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)),tg(e,n),r.kind==="subscription"&&(r.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,l=gi({cwd:e,profileName:n,allowProdWrites:s}),p={uuid:null,firstPrompt:null,titleFired:!1},m=Im({input:process.stdin,output:process.stdout}),k=[],g=null,S=!1;m.on("line",P=>{if(g){let N=g;g=null,N(P)}else k.push(P)}),m.on("close",()=>{if(S=!0,g){let P=g;g=null,P(null)}});function v(){return k.length>0?Promise.resolve(k.shift()):S?Promise.resolve(null):(process.stdout.write(L("> ")),new Promise(P=>{g=P}))}let _={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{l.close(),l=gi({cwd:e,profileName:n,allowProdWrites:s}),p={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>p.uuid,setPendingName:P=>{p.pendingName=P},setModel:async P=>l.setModel(P),withPausedInput:async P=>{m.pause();try{return await P()}finally{m.resume()}}};try{for(;;){let P=await v();if(P===null)break;let N=P.trim();if(N){if(N.startsWith("/")){let T=Tc(N);if(!T)continue;let M=Sc[T.name];if(!M){console.log(R(`Unknown command: /${T.name}`)),console.log(f("Type /help for the list."));continue}let B=await M(T.args,_);if(B.kind==="exit")break;if(B.kind==="clear"){_.restartAgent();continue}if(B.kind==="allow-prod"){s=!0,_.restartAgent(),console.log(D("\u2713 Production writes authorized for this session.")),console.log("");continue}if(B.kind==="resume"){l.close(),l=gi({cwd:e,resume:B.uuid,profileName:n,allowProdWrites:s});let V=Lm(B.uuid);p={uuid:B.uuid,firstPrompt:V?.firstPrompt??null,titleFired:!0},Wc(B.uuid),console.log(D(`\u2713 Resumed "${B.name}"`)),console.log("");continue}if(B.kind==="forward-to-agent"){p.firstPrompt||(p.firstPrompt=B.display??B.prompt);let V=(B.display??"").trim().split(/\s+/),Y=(V[0]==="/check"||V[0]==="/review")&&V.includes("--fix"),ue=V.slice(1).find(he=>!he.startsWith("--")),_e=Y?Qm(e,ue):[];if(await wi(l,B.prompt,r,p,e),Y)try{Xm(e,_e,{reviewedCap:Jm})}catch{}}else ng(e,n);continue}if(Gm(N)){let T=Ym(N);if(T){try{zm(e,{title:T,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}p.firstPrompt||(p.firstPrompt=N),await wi(l,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${T}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${T}" and the article path(s) you wrote.`,r,p,e);continue}}p.firstPrompt||(p.firstPrompt=N),await wi(l,N,r,p,e)}}}finally{l.close(),m.close()}}function tg(e,t){console.log(""),console.log(kn("document360-writer")),console.log(f(` cwd: ${e}`));let n=Fm(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(og(e,t)),!Hm(e))console.log(O(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{let o=!1;try{if($o(e),!Ge(e))for(let r of xo(e))console.log(O(` ${r}`))}catch{}try{let r=qm(e);r.persisted&&r.appType?console.log(f(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=Km(e);for(let s of Xo(r.applied))console.log(O(` ${s}`))}catch{}try{let r=Mn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?On(r):null;if(s?.kind==="recommend"&&s.rec.note){let l=s.rec.tone==="warn"?O:f;for(let p of s.rec.note.split(`
365
+ `))console.log(l(` ${p}`));s.rec.picker&&console.log(L(` Pick one: ${s.rec.picker.options.map(p=>p.cmd).join(" \xB7 ")}`))}}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function ng(e,t){try{let n=Mn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?On(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(f(` Next: ${Ln(o.rec.lead)}`))}catch{}}function og(e,t){try{let n=Fc(e,t),o=n.production?O(" \u26A0 PRODUCTION"):"",r=Vm(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Uc(r.idToken)??{},...Uc(r.accessToken)??{}},l=s.email??s.preferred_username??"signed in";return Bm(r)&&!r.refreshToken?O(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${l} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function rg(){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 sg(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Um({uuid:t,name:r??Mm(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function ig(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Wm(o,t).then(r=>{r&&Om(n,r)}).catch(()=>{})}async function wi(e,t,n,o,r){let s=new Map;for await(let l of e.send(t))ag(l,o,r,n,s)}function ag(e,t,n,o,r){switch(e.type){case"session":t.uuid||sg(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Qo(e.name,e.input);s&&(process.stdout.write(`
366
+
367
+ `),console.log(`${D("\u25CF")} ${ke(s.title)}${s.arg!==null?ie(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=Ye(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let l=p=>p===1?"":"s";console.log(ie(` \u23BF Added ${s.added} line${l(s.added)}, removed ${s.removed} line${l(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(f(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let l=Jo(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?R:ie;l.lines.forEach((m,k)=>console.log(p((k===0?" \u23BF ":" ")+m))),l.hidden>0&&console.log(f(` \u2026 +${l.hidden} lines`)),e.isError||eg(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
368
+ `);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(f(` (${Rn(s)}\u2192${Rn(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Wc(t.uuid),t.titleFired||ig(t,n));break}case"error":console.error(""),console.error(R(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&rg();break}}import{render as $w}from"ink";import{resolveAuth as xw}from"document360-engine";import{useCallback as z,useEffect as Se,useMemo as xi,useRef as ee,useState as F}from"react";import{Box as ne,Text as j,useApp as $g,useInput as xg,useStdout as Cg}from"ink";import{existsSync as nn,readFileSync as dr,readdirSync as Rg}from"node:fs";import{basename as Wn,isAbsolute as Pg,join as Ci}from"node:path";import{createSession as fd,classifyClaudeAuth as ji,CLAUDE_CODE_SETUP_HINT as Sg,loginPkce as Tg,toStoredTokens as Dg,saveTokens as jg,getAccessToken as Ag,resolveActiveProfile as Pe,resolveProjectId as Eg,getArticle as Ng,decodeJwtClaims as rn,isExpired as at,loadTokens as Rt,clearTokens as Ig,clearProfileProject as _g,setTitle as Lg,slugify as Og,touchSession as Ri,upsertSession as Mg,generateTitle as hd,findByName as Ug,listSessions as Wg,renameSession as Fg,suggestNextAction as Hg,readProjectConfig as te,writeProjectConfig as md,resolveAndPersistAppType as qg,detectAppType as Bg,resolveModelSetting as Ai,loadProfileMap as gd,applyPull as wd,computeSyncStatus as Pi,lintDocs as yd,compareRemoteSources as Vg,planPull as kd,establishBaselines as Gg,rebaselineServerMeta as Yg,inventoryRepo as zg,knownEnvironments as Kg,resolveEnvironment as Xg,planPartitions as Si,partitionEvenly as Qg,screenshotPlaceholderIds as Jg,trackedArticlePaths as Zg,runPartitioned as ur,estimateBulkCost as bd,resolveModelForOperation as pr,readDocsPlan as ew,checkForUpdate as tw,detectInstallKind as nw,isSelfUpdatable as ow,devHintsGuidePath as vd,toolFeedbackPath as $d,reconcileToolFeedback as rw,reconcileUpgradeActions as sw,stampArticles as Ti,listArticleFiles as xd,CONTENT_CAP_VERSION as Di,ENGINE_VERSION as Ad,DEFAULT_DOCS_DIR as Ed,setProfileProject as iw,writeCrashLog as aw,applyStructureOrder as Cd,orderSyncLine as Rd,applyRelatedArticles as Pd,relatedSyncLine as Sd}from"document360-engine";nt();import{spawn as qc}from"node:child_process";function lg(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function cg(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?qc([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):qc(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",l=>o(l===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function yi(e){for(let[t,n]of lg())if(await cg(t,n,e))return!0;return!1}var dg=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function ki(e,t){if(t.closed)return e;let n=e.split(`
369
+ `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){dg.test(s)&&(t.cueSeen=!0);continue}let l=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);l?(n[r]=`${l[1]}${++t.num}. ${l[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
370
+ `)}import{existsSync as ug,mkdirSync as pg,readFileSync as fg,writeFileSync as hg}from"node:fs";import{join as Bc}from"node:path";import{writerDir as mg}from"document360-engine";function Vc(e){return Bc(mg(e),".sessions")}function Gc(e,t){return Bc(Vc(e),`${t}.json`)}function Yc(e,t,n){try{pg(Vc(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");hg(Gc(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function bi(e,t){try{let n=Gc(e,t);if(!ug(n))return[];let o=JSON.parse(fg(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var gg=e=>`\x1B]0;${e}\x07`,wg=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function zc(e){process.stdout.isTTY&&process.stdout.write(e)}function tn(e){zc(gg(e))}function or(e){zc(wg(e))}var rr=["\xB7 "," \xB7"],sr="\u{1F7E3}";Wo();Po();W();import{Box as Kc,Text as ce}from"ink";import{jsx as de,jsxs as ir}from"react/jsx-runtime";function yg({row:e}){switch(e.t){case"head":return de(ce,{color:q,bold:!0,children:e.s});case"text":return de(ce,{children:e.s});case"dim":return de(ce,{dimColor:!0,children:e.s});case"sub":return de(ce,{bold:!0,dimColor:!0,children:e.s});case"good":return de(ce,{color:"green",children:e.s});case"step":return ir(ce,{children:[de(ce,{color:q,children:`${e.n}. `}),e.s]});case"cmd":return ir(ce,{children:[" ",de(ce,{color:q,children:e.name.padEnd(20)}),de(ce,{dimColor:!0,children:e.s})]});case"gap":return de(ce,{children:" "})}}function Xc({tab:e,width:t,version:n,engineVersion:o}){let r=Ae[e]??Ae[0],s=6+Ae.reduce((p,m)=>p+m.label.length+4,0),l="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return ir(Kc,{flexDirection:"column",paddingX:1,children:[ir(ce,{children:[de(ce,{color:q,bold:!0,children:"Help "}),Ae.map((p,m)=>m===e?de(ce,{color:"white",backgroundColor:q,bold:!0,children:` ${p.label} `},p.key):de(ce,{dimColor:!0,children:` ${p.label} `},p.key))]}),de(ce,{color:q,children:l}),de(Kc,{flexDirection:"column",marginTop:1,children:r.rows.map((p,m)=>de(yg,{row:p},m))}),de(ce,{dimColor:!0,children:`
371
+ \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var kg=/^(?:\d+[.)]|[-*•])\s+/;function Qc(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
372
+ `)){let l=s.trim().replace(kg,""),p=l.match(/^`([^`]+)`$/);p&&(l=p[1].trim());let m=l.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!m||!o.has(m[1].toLowerCase()))continue;let k=`/${m[1].toLowerCase()}${m[2]?` ${m[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}W();function Un(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function ze(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Jc(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var bg=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Zc(e,t,n){if(!bg.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(s=>{let l=s.replace(/\\/g,"/");return r===l||r.endsWith(`/${l}`)})??null}function vi(e){return e.replace(/^[\w.-]+\//,"")}var ar=16,ed={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Ct(e){return typeof e=="string"?e:e.cmd}function td(e){return typeof e=="string"?void 0:e.desc}function $i(e){return e.trim().split(/\s+/).slice(1).join(" ")}function nd(e,t){let n=$i(t);return e.some(r=>Ct(r).trim()===t.trim()||!!n&&$i(Ct(r))===n)?e.filter(r=>Ct(r).trim()!==t.trim()&&!(n&&$i(Ct(r))===n)):[]}import{isDirectiveMention as lw,stripDirectiveMention as cw,appendDirective as dw}from"document360-engine";var vg=/\[Pasted text #\d+ \+\d+ lines?\]/g;function od(e){return e.replace(/\r\n?/g,`
373
+ `)}function rd(e){return e.includes(`
374
+ `)||e.length>200}function sd(e,t){let n=t.split(`
375
+ `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function id(e,t){return e.replace(vg,n=>t.get(n)??n)}function ad(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function lr(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
376
+ `)){if(s.length===0)o.push({start:r,end:r});else for(let l=0;l<s.length;l+=n)o.push({start:r+l,end:r+Math.min(l+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function cr(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function ld(e,t,n){let o=cr(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 cd(e,t,n){let o=e[cr(e,t)];return n==="start"?o.start:o.end}function dd(e,t,n){let o=Math.max(1,n),r=e.split(`
375
377
  `),s=0;for(let l=r.length-1;l>=0;l--){let p=r[l];if(s+=Math.max(1,Math.ceil(p.length/o)),s>=t){let m=s-t;return{text:[m>0?p.slice(m*o):p,...r.slice(l+1)].join(`
376
- `),truncated:l>0||m>0}}}return{text:e,truncated:!1}}function dd(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 ud(e){let t=!1,n=0,o=0;for(let r of e.split(`
377
- `)){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 fr,jsx as E,jsxs as K}from"react/jsx-runtime";var dw={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},Td=` 1. /init \u2014 pick your Document360 environment & scaffold config
378
+ `),truncated:l>0||m>0}}}return{text:e,truncated:!1}}function ud(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 pd(e){let t=!1,n=0,o=0;for(let r of e.split(`
379
+ `)){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 fr,jsx as E,jsxs as K}from"react/jsx-runtime";var uw={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},Td=` 1. /init \u2014 pick your Document360 environment & scaffold config
378
380
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
379
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function uw(e,t,n,o){let r=Di(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",l=ji(e),p=te(e),m=(p?.docsDir??Ad).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${m}/ + config`,g={version:t,engineVersion:jd,claude:s,model:l.model,modelSource:dw[l.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:k};if(p===null)return g;try{let T=Pe(e,o);g.profile=T.name,g.apiUrl=T.connection.apiUrl,g.prod=T.production,g.project=T.project.projectName??T.project.projectId??"(chosen at login)";let v=Rt(T.name);if(v){let _={...rn(v.idToken)??{},...rn(v.accessToken)??{}},P=_.email??_.preferred_username??"signed in";at(v)?v.refreshToken&&(g.who=P,g.loggedOut=!1,g.sessionHint="session expired \u2014 refreshing\u2026"):(g.who=P,g.loggedOut=!1,g.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return g}function pw(e,t){try{let n=Pe(e,t),o=Rt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...rn(o.idToken)??{},...rn(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return at(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 Sd=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],sn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],fw="Ask me to write or update an article\u2026";function on({ch:e,dim:t}){let[n,o]=F(!0);return Te(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),E(j,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var hw=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Dd(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var mw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function gw({startTime:e,chars:t}){let[n,o]=F(0);Te(()=>{let m=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(m)},[]);let r=sn[n%sn.length],s=Sd[Math.floor(n/16)%Sd.length],l=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return K(ne,{children:[E(j,{color:q,children:` ${r} ${s}\u2026 `}),E(j,{color:"gray",children:`(${Pn(l)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function ww({text:e}){let[t,n]=F(0);return Te(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),E(ne,{paddingX:1,children:E(j,{color:q,children:`${sn[t%sn.length]} ${e}`})})}var yw=12e4;function kw({p:e}){let[t,n]=F(0);Te(()=>{let S=setInterval(()=>n(M=>M+1),150);return()=>clearInterval(S)},[]);let o=sn[t%sn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),l=Math.round(e.chars/4),p=Date.now()-e.lastAt>=yw,m=e.verb??"Converting",k=e.unit??"article",g=e.rows.reduce((S,M)=>S+M.items,0),T=m.toLowerCase(),v=e.rows,_=0;if(v.length>ar){let S=v.findIndex(B=>B.status==="active"||B.status==="pending"),M=Math.max(0,Math.min(S-2,v.length-ar));_=v.slice(0,M).filter(B=>B.status==="done").length,v=v.slice(M,M+ar)}let P=Math.min(40,Math.max(...v.map(S=>bi(S.label).length),0)),N=S=>S==="failed"?"red":S==="active"?q:void 0;return K(ne,{flexDirection:"column",children:[K(ne,{children:[E(j,{color:q,children:` ${o} ${m} ${g} ${k}${g===1?"":"s"} `}),E(j,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${l} tokens \xB7 ${Pn(r)} \xB7 esc to stop`})]}),_>0&&E(j,{dimColor:!0,children:` \u2714 +${_} done`}),v.map(S=>K(j,{color:N(S.status),dimColor:S.status==="done"||S.status==="pending",children:[` ${Zc[S.status]} ${bi(S.label).padEnd(P)}`,S.status==="active"&&S.itemsDone!==void 0?` (${S.itemsDone}/${S.items} ${k}${S.items===1?"":"s"})`:S.status!=="pending"?` (${S.items} ${k}${S.items===1?"":"s"})`:"",S.status==="active"?` \u2190 ${T}\u2026`:""]},S.label)),p&&E(j,{color:"yellow",children:` \u26A0 no activity for ${Pn(s)} \u2014 press esc to stop if it's wedged`})]})}var bw=10800*1e3;function Ed({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=vg(),[s,l]=F(n),[p,m]=F(null),[k,g]=F({text:"",pos:0}),T=k.text,v=z(c=>{g(a=>{let i=typeof c=="function"?c(a.text):c;return{text:i,pos:i.length}})},[]),_=z(c=>{g(a=>({text:a.text.slice(0,a.pos)+c+a.text.slice(a.pos),pos:a.pos+c.length}))},[]),P=z(()=>{g(c=>{if(c.pos===0)return c;let a=c.text.slice(0,c.pos),i=id(a)??a.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[N,S]=F(!1),[M,B]=F(!1),[V,Y]=F(0),[ue,_e]=F(!1),[he,Se]=F(null),[Ke,Fn]=F(null),[lt,ct]=F([]),Hn=ee(!1),mr=ee(!1),[gr,Ii]=F(!1),qn=ee(0),[Ud,Bn]=F(!1),[Wd,Vn]=F(!1),[wr,_i]=F(null),[Fd,Pt]=F(0),dt=ee(0),[an,Tt]=F(0),[St,Gn]=F(null),Oi=ee(new Map),Hd=ee(0),Dt=ee([]),De=ee(null);De.current===null&&(De.current=pd({cwd:e,profileName:s,allowProdWrites:!1}));let Fe=ee({uuid:null,firstPrompt:null,titleFired:!1}),Yn=ee(new Map),jt=ee(!1),yr=ee([]),le=ee([]),At=ee([]),zn=ee(null),[Li,ut]=F(null),kr=ee(null),[pt,ft]=F(null),[He,Et]=F(null),[qe,Nt]=F(null),[me,It]=F(null),[ve,ht]=F(null),[Xe,_t]=F(null),[Be,mt]=F(null),[Mi,ln]=F(null),[$e,gt]=F(null),[we,Ot]=F(null),[Ui,br]=F([]),wt=ee([]),cn=ee(!1),je=ee(null),[Kn,oe]=F(null),[Wi,Fi]=F(null),Xn=ee(!1),dn=ee(null),un=ee(null),[xe,yt]=F(null),[Qn,pn]=F(null),vr=!!(qe||me||ve||Xe||Be||$e||we||xe||Qn),[Hi,Lt]=F(0),[qi,Mt]=F(0),[qd,Bi]=F(0),$r=$i(()=>{try{let c=ji(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,qd]),{stdout:Oe}=xg(),[,Bd]=F(0),Vi=ee(`${Oe.columns??80}x${Oe.rows??24}`),Qe=z(()=>Math.max(20,(Oe.columns??80)-1),[Oe]),d=z(c=>{Dt.current.push(c),console.log(Jr(c,Qe()))},[Qe]),ge=z((c,a)=>{qn.current++,Se(c),Fn(a??null)},[]),Le=z(()=>{qn.current++,Se(null),Fn(null)},[]),Q=z(c=>ge(c,zo({kind:"cmd",cmd:c,reason:""})),[ge]),Jn=z((c,a)=>{!a?.silent&&c.note&&d({kind:"note",tone:c.tone,text:c.note}),c.picker&&(ct(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),ln(c.picker.title)),c.lead&&ge(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,zo(c.lead))},[d,ge]),Ut=z((c,a,i="info")=>{c&&d({kind:"note",tone:i,text:c}),a&&ge(a.kind==="cmd"?a.cmd:a.text,zo(a))},[d,ge]),[fn,xr]=F(null),[Vd,Gi]=F(!1),Wt=z(c=>{xr(c),Gi(!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]),Cr=ee(!1),Rr=z(async()=>{try{if(Cr.current||!nw(tw())||te(e)?.mode==="engineer")return;let c=await ew({pkg:xt,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;Cr.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${xt} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),Vn(!0),(await Bo().finally(()=>Vn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),Q("/exit"),_i(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${qo}`})}catch{}},[e,o,d,Q]),Zn=z(c=>{let a=Ne(e,s);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),un.current=c,Q("/login"),!1)},[e,s,d,Q]),[eo,Pr]=F(null),kt=z(c=>{let a=Mn(e,s,{claudeMissing:Di(t).state==="missing",allowAutoAudit:c,genreUnknown:mr.current});return a?Ln(a):{kind:"idle"}},[e,s,t]),hn=ee(!0),Ft=ee(!1),to=ee(0),mn=ee(0);Te(()=>{let c=setInterval(()=>{if(hn.current){to.current=0,mn.current=0;return}if(!N)try{if(!nn(bd(e)))return;if(Ee(e).status==="current"){hn.current=!0,to.current=0,mn.current=0;let i=kt(!1),h=i.kind==="recommend"?i.rec:null,u=Ft.current?`\u2713 Your builder finished the protocol update (v${ae}) \u2014 the dev\u2194docs hand-off is current again.`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs.";d({kind:"note",tone:"ok",text:`${u}${h?.lead?` ${On(h.lead)}`:""}`}),xr(null),h&&(h.lead||h.picker)?Jn(h,{silent:!0}):Ft.current||ge("write the docs for this repo"),Y(y=>y+1);return}if(Ft.current)return;to.current+=1;let a=to.current;if((a===4||a%15===0)&&mn.current<3){mn.current+=1;let i=mn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Ge(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,kt,Jn,ge]),Te(()=>{let c=Li??Wn(e);if(!N){or(0),tn(`${sr} ${c}`);return}or(3);let a=0;tn(`${rr[0]} ${c}`);let i=setInterval(()=>{a=(a+1)%rr.length,tn(`${rr[a]} ${c}`)},400);return()=>clearInterval(i)},[N,e,Li]),Te(()=>()=>or(0),[]),Te(()=>{let c=performance.now(),a=[],i=(w,$)=>{let x=performance.now();try{return $()}finally{let G=Math.round(performance.now()-x);G>=80&&a.push(`${w}: ${G}ms`)}};d({kind:"banner",info:i("banner",()=>uw(e,o,t,s))});let h=Di(t).state==="missing";if(h&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
380
- ${Pg}
381
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function pw(e,t,n,o){let r=ji(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",l=Ai(e),p=te(e),m=(p?.docsDir??Ed).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${m}/ + config`,g={version:t,engineVersion:Ad,claude:s,model:l.model,modelSource:uw[l.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:k};if(p===null)return g;try{let S=Pe(e,o);g.profile=S.name,g.apiUrl=S.connection.apiUrl,g.prod=S.production,g.project=S.project.projectName??S.project.projectId??"(chosen at login)";let v=Rt(S.name);if(v){let _={...rn(v.idToken)??{},...rn(v.accessToken)??{}},P=_.email??_.preferred_username??"signed in";at(v)?v.refreshToken&&(g.who=P,g.loggedOut=!1,g.sessionHint="session expired \u2014 refreshing\u2026"):(g.who=P,g.loggedOut=!1,g.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return g}function fw(e,t){try{let n=Pe(e,t),o=Rt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...rn(o.idToken)??{},...rn(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return at(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 Dd=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],sn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],hw="Ask me to write or update an article\u2026";function on({ch:e,dim:t}){let[n,o]=F(!0);return Se(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),E(j,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var mw=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function jd(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var gw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ww({startTime:e,chars:t}){let[n,o]=F(0);Se(()=>{let m=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(m)},[]);let r=sn[n%sn.length],s=Dd[Math.floor(n/16)%Dd.length],l=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return K(ne,{children:[E(j,{color:q,children:` ${r} ${s}\u2026 `}),E(j,{color:"gray",children:`(${Pn(l)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function yw({text:e}){let[t,n]=F(0);return Se(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),E(ne,{paddingX:1,children:E(j,{color:q,children:`${sn[t%sn.length]} ${e}`})})}var kw=12e4;function bw({p:e}){let[t,n]=F(0);Se(()=>{let T=setInterval(()=>n(M=>M+1),150);return()=>clearInterval(T)},[]);let o=sn[t%sn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),l=Math.round(e.chars/4),p=Date.now()-e.lastAt>=kw,m=e.verb??"Converting",k=e.unit??"article",g=e.rows.reduce((T,M)=>T+M.items,0),S=m.toLowerCase(),v=e.rows,_=0;if(v.length>ar){let T=v.findIndex(B=>B.status==="active"||B.status==="pending"),M=Math.max(0,Math.min(T-2,v.length-ar));_=v.slice(0,M).filter(B=>B.status==="done").length,v=v.slice(M,M+ar)}let P=Math.min(40,Math.max(...v.map(T=>vi(T.label).length),0)),N=T=>T==="failed"?"red":T==="active"?q:void 0;return K(ne,{flexDirection:"column",children:[K(ne,{children:[E(j,{color:q,children:` ${o} ${m} ${g} ${k}${g===1?"":"s"} `}),E(j,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${l} tokens \xB7 ${Pn(r)} \xB7 esc to stop`})]}),_>0&&E(j,{dimColor:!0,children:` \u2714 +${_} done`}),v.map(T=>K(j,{color:N(T.status),dimColor:T.status==="done"||T.status==="pending",children:[` ${ed[T.status]} ${vi(T.label).padEnd(P)}`,T.status==="active"&&T.itemsDone!==void 0?` (${T.itemsDone}/${T.items} ${k}${T.items===1?"":"s"})`:T.status!=="pending"?` (${T.items} ${k}${T.items===1?"":"s"})`:"",T.status==="active"?` \u2190 ${S}\u2026`:""]},T.label)),p&&E(j,{color:"yellow",children:` \u26A0 no activity for ${Pn(s)} \u2014 press esc to stop if it's wedged`})]})}var vw=10800*1e3;function Nd({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=$g(),[s,l]=F(n),[p,m]=F(null),[k,g]=F({text:"",pos:0}),S=k.text,v=z(c=>{g(a=>{let i=typeof c=="function"?c(a.text):c;return{text:i,pos:i.length}})},[]),_=z(c=>{g(a=>({text:a.text.slice(0,a.pos)+c+a.text.slice(a.pos),pos:a.pos+c.length}))},[]),P=z(()=>{g(c=>{if(c.pos===0)return c;let a=c.text.slice(0,c.pos),i=ad(a)??a.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[N,T]=F(!1),[M,B]=F(!1),[V,Y]=F(0),[ue,_e]=F(!1),[he,Te]=F(null),[Ke,Fn]=F(null),[lt,ct]=F([]),Hn=ee(!1),mr=ee(!1),[gr,_i]=F(!1),qn=ee(0),[Wd,Bn]=F(!1),[Fd,Vn]=F(!1),[wr,Li]=F(null),[Hd,Pt]=F(0),dt=ee(0),[an,St]=F(0),[Tt,Gn]=F(null),Oi=ee(new Map),qd=ee(0),Dt=ee([]),De=ee(null);De.current===null&&(De.current=fd({cwd:e,profileName:s,allowProdWrites:!1}));let Fe=ee({uuid:null,firstPrompt:null,titleFired:!1}),Yn=ee(new Map),jt=ee(!1),yr=ee([]),le=ee([]),At=ee([]),zn=ee(null),[Mi,ut]=F(null),kr=ee(null),[pt,ft]=F(null),[He,Et]=F(null),[qe,Nt]=F(null),[me,It]=F(null),[ve,ht]=F(null),[Xe,_t]=F(null),[Be,mt]=F(null),[Ui,ln]=F(null),[$e,gt]=F(null),[we,Lt]=F(null),[Wi,br]=F([]),wt=ee([]),cn=ee(!1),je=ee(null),[Kn,oe]=F(null),[Fi,Hi]=F(null),Xn=ee(!1),dn=ee(null),un=ee(null),[xe,yt]=F(null),[Qn,pn]=F(null),vr=!!(qe||me||ve||Xe||Be||$e||we||xe||Qn),[qi,Ot]=F(0),[Bi,Mt]=F(0),[Bd,Vi]=F(0),$r=xi(()=>{try{let c=Ai(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,Bd]),{stdout:Le}=Cg(),[,Vd]=F(0),Gi=ee(`${Le.columns??80}x${Le.rows??24}`),Qe=z(()=>Math.max(20,(Le.columns??80)-1),[Le]),d=z(c=>{Dt.current.push(c),console.log(Jr(c,Qe()))},[Qe]),ge=z((c,a)=>{qn.current++,Te(c),Fn(a??null)},[]),Oe=z(()=>{qn.current++,Te(null),Fn(null)},[]),Q=z(c=>ge(c,zo({kind:"cmd",cmd:c,reason:""})),[ge]),Jn=z((c,a)=>{!a?.silent&&c.note&&d({kind:"note",tone:c.tone,text:c.note}),c.picker&&(ct(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),ln(c.picker.title)),c.lead&&ge(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,zo(c.lead))},[d,ge]),Ut=z((c,a,i="info")=>{c&&d({kind:"note",tone:i,text:c}),a&&ge(a.kind==="cmd"?a.cmd:a.text,zo(a))},[d,ge]),[fn,xr]=F(null),[Gd,Yi]=F(!1),Wt=z(c=>{xr(c),Yi(!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]),Cr=ee(!1),Rr=z(async()=>{try{if(Cr.current||!ow(nw())||te(e)?.mode==="engineer")return;let c=await tw({pkg:xt,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;Cr.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${xt} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),Vn(!0),(await Bo().finally(()=>Vn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),Q("/exit"),Li(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${qo}`})}catch{}},[e,o,d,Q]),Zn=z(c=>{let a=Ne(e,s);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),un.current=c,Q("/login"),!1)},[e,s,d,Q]),[eo,Pr]=F(null),kt=z(c=>{let a=Mn(e,s,{claudeMissing:ji(t).state==="missing",allowAutoAudit:c,genreUnknown:mr.current});return a?On(a):{kind:"idle"}},[e,s,t]),hn=ee(!0),Ft=ee(!1),to=ee(0),mn=ee(0);Se(()=>{let c=setInterval(()=>{if(hn.current){to.current=0,mn.current=0;return}if(!N)try{if(!nn(vd(e)))return;if(Ee(e).status==="current"){hn.current=!0,to.current=0,mn.current=0;let i=kt(!1),h=i.kind==="recommend"?i.rec:null,u=Ft.current?`\u2713 Your builder finished the protocol update (v${ae}) \u2014 the dev\u2194docs hand-off is current again.`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs.";d({kind:"note",tone:"ok",text:`${u}${h?.lead?` ${Ln(h.lead)}`:""}`}),xr(null),h&&(h.lead||h.picker)?Jn(h,{silent:!0}):Ft.current||ge("write the docs for this repo"),Y(y=>y+1);return}if(Ft.current)return;to.current+=1;let a=to.current;if((a===4||a%15===0)&&mn.current<3){mn.current+=1;let i=mn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Ge(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,kt,Jn,ge]),Se(()=>{let c=Mi??Wn(e);if(!N){or(0),tn(`${sr} ${c}`);return}or(3);let a=0;tn(`${rr[0]} ${c}`);let i=setInterval(()=>{a=(a+1)%rr.length,tn(`${rr[a]} ${c}`)},400);return()=>clearInterval(i)},[N,e,Mi]),Se(()=>()=>or(0),[]),Se(()=>{let c=performance.now(),a=[],i=(w,$)=>{let x=performance.now();try{return $()}finally{let G=Math.round(performance.now()-x);G>=80&&a.push(`${w}: ${G}ms`)}};d({kind:"banner",info:i("banner",()=>pw(e,o,t,s))});let h=ji(t).state==="missing";if(h&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
382
+ ${Sg}
381
383
  Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!te(e)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
382
- ${Td}`}),Q(h?"/doctor":"/init");return}h&&Q("/doctor");try{let w=Pe(e,s),$=Rt(w.name);$&&at($)&&$.refreshToken?jg({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),Y(x=>x+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Q("/login")}):(!$||at($))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 sign in with /login.`}),Q("/login"))}catch{}try{let w=te(e),$=Pe(e,s),x=Rt($.name);w&&x&&!at(x)&&ui(e,w.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 w=i("resolve-genre",()=>Hg(e));w.persisted&&w.appType?d({kind:"note",tone:"ok",text:`\u2713 Detected a ${w.appType} app \u2014 enabled the ${w.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):w.source==="unknown"&&te(e)&&(mr.current=!0)}catch{}let u=Ee(e);try{if(i("reconcile-devhints",()=>$o(e)),u.status!=="current"&&!Ge(e)){let w=xo(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
383
- `)}),Wt(bt()),hn.current=!1,Ft.current=!1)}}catch{}try{let w=i("reconcile-feedback",()=>ow(e));w.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}try{let w=i("upgrade-actions",()=>rw(e));w.applied.length>0&&d({kind:"note",tone:"warn",text:Xo(w.applied).join(`
384
- `)})}catch{}let y=i("ready-decision",()=>kt(!0));y.kind==="autoAudit"?(d({kind:"note",tone:"info",text:y.note}),Sn().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&re(w.prompt,{display:w.display,quietUser:!0})})):y.kind==="recommend"&&Jn(y.rec);let b=Math.round(performance.now()-c);b>=800&&iw({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${b}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${a.length?a.join(`
384
+ ${Td}`}),Q(h?"/doctor":"/init");return}h&&Q("/doctor");try{let w=Pe(e,s),$=Rt(w.name);$&&at($)&&$.refreshToken?Ag({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),Y(x=>x+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Q("/login")}):(!$||at($))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 sign in with /login.`}),Q("/login"))}catch{}try{let w=te(e),$=Pe(e,s),x=Rt($.name);w&&x&&!at(x)&&pi(e,w.authoritativeSourceFiles)&&!fi(e,s)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),Q("/scope"))}catch{}try{let w=i("resolve-genre",()=>qg(e));w.persisted&&w.appType?d({kind:"note",tone:"ok",text:`\u2713 Detected a ${w.appType} app \u2014 enabled the ${w.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):w.source==="unknown"&&te(e)&&(mr.current=!0)}catch{}let u=Ee(e);try{if(i("reconcile-devhints",()=>$o(e)),u.status!=="current"&&!Ge(e)){let w=xo(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
385
+ `)}),Wt(bt()),hn.current=!1,Ft.current=!1)}}catch{}try{let w=i("reconcile-feedback",()=>rw(e));w.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}try{let w=i("upgrade-actions",()=>sw(e));w.applied.length>0&&d({kind:"note",tone:"warn",text:Xo(w.applied).join(`
386
+ `)})}catch{}let y=i("ready-decision",()=>kt(!0));y.kind==="autoAudit"?(d({kind:"note",tone:"info",text:y.note}),Tn().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&re(w.prompt,{display:w.display,quietUser:!0})})):y.kind==="recommend"&&Jn(y.rec);let b=Math.round(performance.now()-c);b>=800&&aw({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${b}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${a.length?a.join(`
385
387
  `):"no single phase \u226580ms"}
386
- cwd: ${e}`}),Rr()},[]),Te(()=>{let c=setInterval(()=>{Rr()},bw);return()=>clearInterval(c)},[Rr]),Te(()=>{if(N||ue||gr||Hn.current||he!==null||lt.length>0||T!==""||fn!==null||le.current.length>0||zn.current||vr)return;let c=kt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&Jn(c.rec,{silent:!0})},[N,ue,he,lt,T,fn,vr,V,kt,gr]),Te(()=>{let c=null,a=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let h=`${Oe.columns??80}x${Oe.rows??24}`;h!==Vi.current&&(Vi.current=h,Bd(u=>u+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+tl(Dt.current,Qe())+"\x1B[?2026l")},80))},400)};return Oe.on("resize",i),()=>{c&&clearTimeout(c),a&&clearTimeout(a),Oe.off("resize",i)}},[Oe,Qe]);let Me=Math.max(20,(Oe.columns??80)-1),Yi=$i(()=>pw(e,s),[e,s,V]),Tr=(()=>{if(Wd)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(wr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${wr?` v${wr}`:""}\u2026`,isSetup:!0};if(eo)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(fn)return Vd?{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(le.current.length>0)return le.current[0].mode==="conflict"?{text:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let c=te(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let a=xi(e,(c.docsDir??Ad).replace(/\/+$/,"")),i=(()=>{try{return nn(a)&&Cg(a).length>0}catch{return!1}})();try{let h=Pe(e,s),u=Rt(h.name);if(!(!!u&&!(at(u)&&!u.refreshToken)))return{text:`Sign in with /login (profile "${h.name}")\u2026`,isSetup:!0};if(!h.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!h.project.workspaceId&&!i)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return i?{text:fw,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),gn=Ga(T),zi=gn.length>0&&!N,Sr=p!==null?cd(p,8,Me):null,no=$e?$e.paths.filter(c=>!$e.query||c.toLowerCase().includes($e.query.toLowerCase())).slice(0,8):[],oo=xe?xe.sessions.filter(c=>{let a=xe.query.toLowerCase();return!a||c.name.toLowerCase().includes(a)||c.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],Ce=z((c,a)=>{De.current?.close(),De.current=pd({cwd:e,resume:c,profileName:a??s,allowProdWrites:jt.current}),c||(Fe.current={uuid:null,firstPrompt:null,titleFired:!1},ut(null)),Lt(0),Mt(0)},[e,s]),Ki=z((c,a,i)=>{if(hw.test(c))try{let h=Pe(e,s),u=typeof a.project_id=="string"&&a.project_id||h.project.projectId,y=er(a,i),b=[],w=tr(i);c.endsWith("publish_article")&&w&&b.push(`Live: ${w}`);let $=nr(i);$?b.push(`Preview: ${$}`):y&&u&&b.push(`Preview: ${Zo(h.connection.portalUrl,u,y,h.project.languageCode??"en")}`),b.length>0&&d({kind:"link",lines:b})}catch{}},[e,s,d]),re=z(async(c,a)=>{Bn(!0),Hn.current=!1,Le(),ct([]),ln(null),xr(null);let i=qn.current;a?.quietUser||d({kind:"user",text:a?.echoDisplay&&a.display?a.display:c});let h=Fe.current;h.firstPrompt||(h.firstPrompt=a?.display??c),dt.current=Date.now(),Pt(0),S(!0),Yn.current.clear();let u="",y=!1,b=!1,w="",$={num:0,closed:!1,cueSeen:!1},x=null,G=()=>{x||(x=setTimeout(()=>{x=null,m(w.length>0?w:null)},60))},H=()=>{x&&clearTimeout(x),x=null,m(null)},I=(C=!1)=>{let{head:A,keep:U}=dd(w,C);A.trim()&&d({kind:"assistant",text:yi(A.trimEnd(),$)}),w=U,H()};try{for await(let C of De.current.send(c))if(C.type==="session"){if(!h.uuid){h.uuid=C.sessionId;let A=new Date().toISOString(),U=kr.current,J=U??Og(h.firstPrompt??"session");Lg({uuid:C.sessionId,name:J,renamed:!!U,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:A,updatedAt:A}),ut(J),kr.current=null}}else if(C.type==="text"){w+=C.delta,u+=C.delta;let A=ud(w);if(A>0){let U=w.slice(0,A).trimEnd();U&&d({kind:"assistant",text:yi(U,$)}),w=w.slice(A)}G(),Pt(U=>U+C.delta.length)}else if(C.type==="tool"){y=!0;let A=Qo(C.name,C.input);A&&(I(),d({kind:"tool",title:A.title,sep:A.sep,arg:A.arg}),Yn.current.set(C.id,{name:C.name,input:C.input}))}else if(C.type==="article_diff"){let A=Ye(C.oldContent,C.newContent,Qe());A&&(I(),d({kind:"diff",added:A.added,removed:A.removed,lines:A.lines,hidden:A.hidden}))}else if(C.type==="tool_result"){C.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(C.output)&&(Xn.current=!0);let A=Yn.current.get(C.id);if(A){Yn.current.delete(C.id),I();let U=Jo(C.output,4,C.isError?void 0:A.name,A.input);d({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:C.isError}),C.isError||Ki(A.name,A.input,C.output)}}else if(C.type==="result"){I(!0),Lt(U=>U+C.outputTokens),Mt(U=>U+C.costUsd);let A=C.inputTokens+C.cacheReadTokens+C.cacheCreationTokens;if(d({kind:"done",seconds:Math.round((Date.now()-dt.current)/1e3),tokens:C.outputTokens,costUsd:C.costUsd,ok:C.ok,...A>0?{inTokens:A,cachedPct:Math.round(C.cacheReadTokens/A*100)}:{}}),!b&&!y&&!u.trim()&&!cn.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),C.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let U=vd(e);if(nn(U)){let J=dr(U,"utf8").trim();J&&(Pr(J),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(C.ok&&$.cueSeen)Ii(!0),ct([]);else{let U=C.ok?Xc(u,Jt.map(J=>J.name)):[];if(U.length>0)Q(U[0]);else if(C.ok&&u.trim()){let J=kt(!1);J.kind==="recommend"&&(J.rec.lead||J.rec.picker)||Fg(c,u,e).then(ye=>{ye&&qn.current===i&&ge(ye)}).catch(()=>{})}}if(h.uuid&&(Ci(h.uuid),!h.titleFired)){h.titleFired=!0;let U=h.uuid,J=h.firstPrompt;J&&fd(J,e).then(ye=>{ye&&(_g(U,ye),ut(ye))}).catch(()=>{})}}else C.type==="error"&&(I(!0),b=!0,C.kind==="auth"&&(Xn.current=!0),d({kind:"note",text:`agent error: ${C.message}`,tone:"error"}))}finally{S(!1),H(),Y(C=>C+1),Fe.current.uuid&&Gc(e,Fe.current.uuid,Dt.current),Xn.current?(Xn.current=!1,dn.current=a?.display??c,ge("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):dn.current=null,cn.current&&(cn.current=!1,wt.current.length>0&&(d({kind:"note",tone:"info",text:`(${wt.current.length} queued message(s) discarded)`}),wt.current=[],br([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Ki,Qe,ge,Q,Le,kt]),Ht=z(async c=>{let a=pr(e,"standard");dt.current=Date.now(),Pt(0),S(!0);let i=new AbortController;je.current=i;let h=async(u,y)=>{let b=Pi(u);oe({verb:"Publishing",total:b.length,done:0,active:[],rows:Un(b),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:y?`Resolving cross-links in ${u.length} article${u.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${u.length} article${u.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${Tn} agents at once) on ${a.model}\u2026 (esc to stop)`});let w=!1;for await(let $ of ur({cwd:e,partitions:b,promptFor:x=>Eo(x.paths),concurrency:Tn,profileName:s,allowProdWrites:jt.current,model:a.model,signal:i.signal}))if($.type==="partition_status")$.status==="running"?oe(x=>x&&{...x,active:[...x.active,$.label],rows:ze(x.rows,$.label,"active"),lastAt:Date.now()}):oe(x=>x&&{...x,active:x.active.filter(G=>G!==$.label),done:x.done+1,rows:ze(x.rows,$.label,$.status==="done"?"done":"failed"),lastAt:Date.now()});else if($.type==="partition_event")oe(x=>{if(!x)return x;let G={...x,lastAt:Date.now()};return $.event.type==="tool"?G.tools=x.tools+1:$.event.type==="text"&&(G.chars=x.chars+$.event.delta.length),G});else if($.type==="run_done"){w=$.aborted,Mt(I=>I+$.totalCostUsd),Lt(I=>I+$.results.reduce((C,A)=>C+A.outputTokens,0));let x=$.aborted?"Stopped. ":"",G=t.kind==="api"?"api":"subscription";d({kind:"note",tone:$.aborted?"warn":$.ok?"ok":"warn",text:x+ns($.results,b,G).join(`
387
- `)});let H=ts(e,s);if(H&&d({kind:"note",tone:"info",text:H}),!$.aborted){try{let I=await xd({cwd:e,profileName:s}),C=Cd(I);C?d({kind:"note",tone:"info",text:C}):I.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${I.skipped}`})}catch(I){d({kind:"note",tone:"warn",text:`Order sync failed: ${I.message}`})}try{let I=Pd(await Rd({cwd:e,profileName:s}));I&&d({kind:"note",tone:"info",text:I})}catch(I){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${I.message}`})}}}return w};try{if(!await h(c,!1)){let y=await os(e,s,c);y.length>0&&await h(y,!0)}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{je.current=null,oe(null),S(!1),Y(u=>u+1)}},[e,s,d,t]),Dr=z(async c=>{await re(Zr(c),{display:`/publish ${c}`,quietUser:!0});try{let a=await No(e,s,c.replace(/\\/g,"/"));a.length>0&&(ln(`Related articles not yet published (${a.length}):`),ct([`/publish --related ${c}`,...a.map(i=>`/publish ${i}`)]))}catch{}},[e,s,re]),jr=z(c=>{let a=Rt(c);if(!a||at(a)&&!a.refreshToken)return null;let i={...rn(a.idToken)??{},...rn(a.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),Ar=z((c,a)=>{if(a){let i=te(e);i&&(i.defaultProfile=c,hd(i,e))}l(c),Ce(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),jr(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),Q("/login")),Y(i=>i+1)},[e,d,Ce,jr,Q]),ro=z((c,a,i)=>{po(e,c,a,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Ce(),md(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:Xt(Kt(e)).join(`
388
- `)}),Wt(bt()),hn.current=Ee(e).status==="current",Ft.current=Ge(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,Ce,Wt]),so=z(async c=>{let a;try{a=await bn(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Q("/workspace");return}if(a.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=a.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),h=i.length>0?i:a.workspaces;if(h.length===1){let u=h[0],y=a.workspaces.length-h.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${y>0?" (skipped the API-documentation workspace)":""}.`}),ro(a.profile,a.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),Q("/workspace")},[e,d,ro,Q]),io=z((c,a)=>{fo(e,c,a.id,a.name),d({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),Ce(),so(c)},[e,d,Ce,so]),Xi=z(async c=>{let a;try{a=Pe(e,c)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:i}=await et(e,a.name),h=i.find(u=>u.id===a.project.projectId);h?.name&&sw(e,a.name,{projectName:h.name})}catch{}await so(a.name);return}try{let{projects:i}=await et(e,a.name);if(i.length===1){let h=i[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${h.name??h.id}".`}),io(a.name,{id:h.id,name:h.name});return}if(i.length>1){let h=i.map(u=>({id:u.id,name:u.name??u.id,sub:u.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),ht({cursor:0,current:-1,rows:h,profile:a.name,environment:a.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Q("/project")}},[e,d,so,io,Q]),qt=z(()=>{let c=le.current[0];if(!c)return;Le();let{plan:a,mode:i}=c;d({kind:"note",tone:"info",text:`\u25CF ${a.title} (${a.path})`});for(let u of a.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${u}`});a.overwritesLocalChanges&&i==="pull"&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let h=Ye(a.oldContent,a.newContent,Qe());d(h?{kind:"diff",added:h.added,removed:h.removed,lines:h.lines,hidden:h.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),i==="conflict"?(d({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),d({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):d({kind:"note",tone:"info",text:`Write ${a.path}? (y/n \u2014 anything else cancels)`})},[d,Qe,Le]),Er=z(()=>{if(le.current.length>0){qt();return}let c=At.current;At.current=[],c.length>0?(d({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),Ht(c)):Q("/pull")},[qt,d,Ht,Q]),Qi=z(c=>{if(le.current.length===0)return!1;let a=c.trim().toLowerCase(),i=le.current[0];if(i.mode==="conflict"){if(a==="l"||a==="local")le.current.shift(),At.current.push(i.plan.path),d({kind:"note",tone:"info",text:`Keeping local ${i.plan.path} \u2014 will publish over the portal.`});else if(a==="p"||a==="portal"){le.current.shift();try{gd({cwd:e,profileName:s},i.plan),d({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(h){d({kind:"note",tone:"error",text:`Take-portal failed: ${h.message}`})}}else if(a==="s"||a==="skip"||a==="n")le.current.shift(),d({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let h=le.current.length;return le.current=[],At.current=[],d({kind:"note",tone:"info",text:`Resolve cancelled (${h} conflict${h===1?"":"s"} left untouched).`}),!0}return Er(),!0}if(a==="y"||a==="yes"){let h=le.current.shift().plan;try{gd({cwd:e,profileName:s},h),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${h.path} (sync base advanced).`})}catch(u){d({kind:"note",tone:"error",text:`Pull failed: ${u.message}`})}}else if(a==="n"||a==="no"){let h=le.current.shift().plan;d({kind:"note",tone:"info",text:`Skipped ${h.path}.`})}else{let h=le.current.length;return le.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${h} article(s) left untouched).`}),!0}return Er(),!0},[e,s,Er,d]),Nr=z(async c=>{d({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let a=await Ri({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),h=a.entries.filter(y=>y.status==="conflict"&&y.path).map(y=>y.path);if(i){if(!h.includes(i)){d({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}h=[i]}if(h.length===0){d({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let u=[];for(let y of h)try{u.push({plan:await yd({cwd:e,profileName:s,relPath:y}),mode:"conflict"})}catch(b){d({kind:"note",tone:"error",text:`Could not load ${y} from Document360: ${b.message}`})}if(u.length===0)return;d({kind:"note",tone:"info",text:`Resolving ${u.length} conflict${u.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),le.current=u,At.current=[],qt()}catch(a){d({kind:"note",tone:"error",text:`Could not compute sync status: ${a.message}`})}},[e,s,d,qt]),Ji=z(c=>{let a=zn.current;if(!a)return!1;if(zn.current=null,Le(),c.trim()!==a.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:h}=Zs(e,a.targets);d({kind:"note",tone:h.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`});for(let u of h)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return a.hadDevhints&&(d({kind:"note",tone:"warn",text:Co().join(`
388
+ cwd: ${e}`}),Rr()},[]),Se(()=>{let c=setInterval(()=>{Rr()},vw);return()=>clearInterval(c)},[Rr]),Se(()=>{if(N||ue||gr||Hn.current||he!==null||lt.length>0||S!==""||fn!==null||le.current.length>0||zn.current||vr)return;let c=kt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&Jn(c.rec,{silent:!0})},[N,ue,he,lt,S,fn,vr,V,kt,gr]),Se(()=>{let c=null,a=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let h=`${Le.columns??80}x${Le.rows??24}`;h!==Gi.current&&(Gi.current=h,Vd(u=>u+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+nl(Dt.current,Qe())+"\x1B[?2026l")},80))},400)};return Le.on("resize",i),()=>{c&&clearTimeout(c),a&&clearTimeout(a),Le.off("resize",i)}},[Le,Qe]);let Me=Math.max(20,(Le.columns??80)-1),zi=xi(()=>fw(e,s),[e,s,V]),Sr=(()=>{if(Fd)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(wr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${wr?` v${wr}`:""}\u2026`,isSetup:!0};if(eo)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(fn)return Gd?{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(le.current.length>0)return le.current[0].mode==="conflict"?{text:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let c=te(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let a=Ci(e,(c.docsDir??Ed).replace(/\/+$/,"")),i=(()=>{try{return nn(a)&&Rg(a).length>0}catch{return!1}})();try{let h=Pe(e,s),u=Rt(h.name);if(!(!!u&&!(at(u)&&!u.refreshToken)))return{text:`Sign in with /login (profile "${h.name}")\u2026`,isSetup:!0};if(!h.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!h.project.workspaceId&&!i)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return i?{text:hw,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),gn=Ya(S),Ki=gn.length>0&&!N,Tr=p!==null?dd(p,8,Me):null,no=$e?$e.paths.filter(c=>!$e.query||c.toLowerCase().includes($e.query.toLowerCase())).slice(0,8):[],oo=xe?xe.sessions.filter(c=>{let a=xe.query.toLowerCase();return!a||c.name.toLowerCase().includes(a)||c.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],Ce=z((c,a)=>{De.current?.close(),De.current=fd({cwd:e,resume:c,profileName:a??s,allowProdWrites:jt.current}),c||(Fe.current={uuid:null,firstPrompt:null,titleFired:!1},ut(null)),Ot(0),Mt(0)},[e,s]),Xi=z((c,a,i)=>{if(mw.test(c))try{let h=Pe(e,s),u=typeof a.project_id=="string"&&a.project_id||h.project.projectId,y=er(a,i),b=[],w=tr(i);c.endsWith("publish_article")&&w&&b.push(`Live: ${w}`);let $=nr(i);$?b.push(`Preview: ${$}`):y&&u&&b.push(`Preview: ${Zo(h.connection.portalUrl,u,y,h.project.languageCode??"en")}`),b.length>0&&d({kind:"link",lines:b})}catch{}},[e,s,d]),re=z(async(c,a)=>{Bn(!0),Hn.current=!1,Oe(),ct([]),ln(null),xr(null);let i=qn.current;a?.quietUser||d({kind:"user",text:a?.echoDisplay&&a.display?a.display:c});let h=Fe.current;h.firstPrompt||(h.firstPrompt=a?.display??c),dt.current=Date.now(),Pt(0),T(!0),Yn.current.clear();let u="",y=!1,b=!1,w="",$={num:0,closed:!1,cueSeen:!1},x=null,G=()=>{x||(x=setTimeout(()=>{x=null,m(w.length>0?w:null)},60))},H=()=>{x&&clearTimeout(x),x=null,m(null)},I=(C=!1)=>{let{head:A,keep:U}=ud(w,C);A.trim()&&d({kind:"assistant",text:ki(A.trimEnd(),$)}),w=U,H()};try{for await(let C of De.current.send(c))if(C.type==="session"){if(!h.uuid){h.uuid=C.sessionId;let A=new Date().toISOString(),U=kr.current,J=U??Og(h.firstPrompt??"session");Mg({uuid:C.sessionId,name:J,renamed:!!U,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:A,updatedAt:A}),ut(J),kr.current=null}}else if(C.type==="text"){w+=C.delta,u+=C.delta;let A=pd(w);if(A>0){let U=w.slice(0,A).trimEnd();U&&d({kind:"assistant",text:ki(U,$)}),w=w.slice(A)}G(),Pt(U=>U+C.delta.length)}else if(C.type==="tool"){y=!0;let A=Qo(C.name,C.input);A&&(I(),d({kind:"tool",title:A.title,sep:A.sep,arg:A.arg}),Yn.current.set(C.id,{name:C.name,input:C.input}))}else if(C.type==="article_diff"){let A=Ye(C.oldContent,C.newContent,Qe());A&&(I(),d({kind:"diff",added:A.added,removed:A.removed,lines:A.lines,hidden:A.hidden}))}else if(C.type==="tool_result"){C.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(C.output)&&(Xn.current=!0);let A=Yn.current.get(C.id);if(A){Yn.current.delete(C.id),I();let U=Jo(C.output,4,C.isError?void 0:A.name,A.input);d({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:C.isError}),C.isError||Xi(A.name,A.input,C.output)}}else if(C.type==="result"){I(!0),Ot(U=>U+C.outputTokens),Mt(U=>U+C.costUsd);let A=C.inputTokens+C.cacheReadTokens+C.cacheCreationTokens;if(d({kind:"done",seconds:Math.round((Date.now()-dt.current)/1e3),tokens:C.outputTokens,costUsd:C.costUsd,ok:C.ok,...A>0?{inTokens:A,cachedPct:Math.round(C.cacheReadTokens/A*100)}:{}}),!b&&!y&&!u.trim()&&!cn.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),C.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let U=$d(e);if(nn(U)){let J=dr(U,"utf8").trim();J&&(Pr(J),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(C.ok&&$.cueSeen)_i(!0),ct([]);else{let U=C.ok?Qc(u,Jt.map(J=>J.name)):[];if(U.length>0)Q(U[0]);else if(C.ok&&u.trim()){let J=kt(!1);J.kind==="recommend"&&(J.rec.lead||J.rec.picker)||Hg(c,u,e).then(ye=>{ye&&qn.current===i&&ge(ye)}).catch(()=>{})}}if(h.uuid&&(Ri(h.uuid),!h.titleFired)){h.titleFired=!0;let U=h.uuid,J=h.firstPrompt;J&&hd(J,e).then(ye=>{ye&&(Lg(U,ye),ut(ye))}).catch(()=>{})}}else C.type==="error"&&(I(!0),b=!0,C.kind==="auth"&&(Xn.current=!0),d({kind:"note",text:`agent error: ${C.message}`,tone:"error"}))}finally{T(!1),H(),Y(C=>C+1),Fe.current.uuid&&Yc(e,Fe.current.uuid,Dt.current),Xn.current?(Xn.current=!1,dn.current=a?.display??c,ge("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):dn.current=null,cn.current&&(cn.current=!1,wt.current.length>0&&(d({kind:"note",tone:"info",text:`(${wt.current.length} queued message(s) discarded)`}),wt.current=[],br([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Xi,Qe,ge,Q,Oe,kt]),Ht=z(async c=>{let a=pr(e,"standard");dt.current=Date.now(),Pt(0),T(!0);let i=new AbortController;je.current=i;let h=async(u,y)=>{let b=Si(u);oe({verb:"Publishing",total:b.length,done:0,active:[],rows:Un(b),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:y?`Resolving cross-links in ${u.length} article${u.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${u.length} article${u.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${Sn} agents at once) on ${a.model}\u2026 (esc to stop)`});let w=!1;for await(let $ of ur({cwd:e,partitions:b,promptFor:x=>Eo(x.paths),concurrency:Sn,profileName:s,allowProdWrites:jt.current,model:a.model,signal:i.signal}))if($.type==="partition_status")$.status==="running"?oe(x=>x&&{...x,active:[...x.active,$.label],rows:ze(x.rows,$.label,"active"),lastAt:Date.now()}):oe(x=>x&&{...x,active:x.active.filter(G=>G!==$.label),done:x.done+1,rows:ze(x.rows,$.label,$.status==="done"?"done":"failed"),lastAt:Date.now()});else if($.type==="partition_event")oe(x=>{if(!x)return x;let G={...x,lastAt:Date.now()};return $.event.type==="tool"?G.tools=x.tools+1:$.event.type==="text"&&(G.chars=x.chars+$.event.delta.length),G});else if($.type==="run_done"){w=$.aborted,Mt(I=>I+$.totalCostUsd),Ot(I=>I+$.results.reduce((C,A)=>C+A.outputTokens,0));let x=$.aborted?"Stopped. ":"",G=t.kind==="api"?"api":"subscription";d({kind:"note",tone:$.aborted?"warn":$.ok?"ok":"warn",text:x+ns($.results,b,G).join(`
389
+ `)});let H=ts(e,s);if(H&&d({kind:"note",tone:"info",text:H}),!$.aborted){try{let I=await Cd({cwd:e,profileName:s}),C=Rd(I);C?d({kind:"note",tone:"info",text:C}):I.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${I.skipped}`})}catch(I){d({kind:"note",tone:"warn",text:`Order sync failed: ${I.message}`})}try{let I=Sd(await Pd({cwd:e,profileName:s}));I&&d({kind:"note",tone:"info",text:I})}catch(I){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${I.message}`})}}}return w};try{if(!await h(c,!1)){let y=await os(e,s,c);y.length>0&&await h(y,!0)}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{je.current=null,oe(null),T(!1),Y(u=>u+1)}},[e,s,d,t]),Dr=z(async c=>{await re(Zr(c),{display:`/publish ${c}`,quietUser:!0});try{let a=await No(e,s,c.replace(/\\/g,"/"));a.length>0&&(ln(`Related articles not yet published (${a.length}):`),ct([`/publish --related ${c}`,...a.map(i=>`/publish ${i}`)]))}catch{}},[e,s,re]),jr=z(c=>{let a=Rt(c);if(!a||at(a)&&!a.refreshToken)return null;let i={...rn(a.idToken)??{},...rn(a.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),Ar=z((c,a)=>{if(a){let i=te(e);i&&(i.defaultProfile=c,md(i,e))}l(c),Ce(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),jr(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),Q("/login")),Y(i=>i+1)},[e,d,Ce,jr,Q]),ro=z((c,a,i)=>{po(e,c,a,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Ce(),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:Xt(Kt(e)).join(`
390
+ `)}),Wt(bt()),hn.current=Ee(e).status==="current",Ft.current=Ge(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,Ce,Wt]),so=z(async c=>{let a;try{a=await bn(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Q("/workspace");return}if(a.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=a.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),h=i.length>0?i:a.workspaces;if(h.length===1){let u=h[0],y=a.workspaces.length-h.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${y>0?" (skipped the API-documentation workspace)":""}.`}),ro(a.profile,a.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),Q("/workspace")},[e,d,ro,Q]),io=z((c,a)=>{fo(e,c,a.id,a.name),d({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),Ce(),so(c)},[e,d,Ce,so]),Qi=z(async c=>{let a;try{a=Pe(e,c)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:i}=await et(e,a.name),h=i.find(u=>u.id===a.project.projectId);h?.name&&iw(e,a.name,{projectName:h.name})}catch{}await so(a.name);return}try{let{projects:i}=await et(e,a.name);if(i.length===1){let h=i[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${h.name??h.id}".`}),io(a.name,{id:h.id,name:h.name});return}if(i.length>1){let h=i.map(u=>({id:u.id,name:u.name??u.id,sub:u.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),ht({cursor:0,current:-1,rows:h,profile:a.name,environment:a.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Q("/project")}},[e,d,so,io,Q]),qt=z(()=>{let c=le.current[0];if(!c)return;Oe();let{plan:a,mode:i}=c;d({kind:"note",tone:"info",text:`\u25CF ${a.title} (${a.path})`});for(let u of a.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${u}`});a.overwritesLocalChanges&&i==="pull"&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let h=Ye(a.oldContent,a.newContent,Qe());d(h?{kind:"diff",added:h.added,removed:h.removed,lines:h.lines,hidden:h.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),i==="conflict"?(d({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),d({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):d({kind:"note",tone:"info",text:`Write ${a.path}? (y/n \u2014 anything else cancels)`})},[d,Qe,Oe]),Er=z(()=>{if(le.current.length>0){qt();return}let c=At.current;At.current=[],c.length>0?(d({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),Ht(c)):Q("/pull")},[qt,d,Ht,Q]),Ji=z(c=>{if(le.current.length===0)return!1;let a=c.trim().toLowerCase(),i=le.current[0];if(i.mode==="conflict"){if(a==="l"||a==="local")le.current.shift(),At.current.push(i.plan.path),d({kind:"note",tone:"info",text:`Keeping local ${i.plan.path} \u2014 will publish over the portal.`});else if(a==="p"||a==="portal"){le.current.shift();try{wd({cwd:e,profileName:s},i.plan),d({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(h){d({kind:"note",tone:"error",text:`Take-portal failed: ${h.message}`})}}else if(a==="s"||a==="skip"||a==="n")le.current.shift(),d({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let h=le.current.length;return le.current=[],At.current=[],d({kind:"note",tone:"info",text:`Resolve cancelled (${h} conflict${h===1?"":"s"} left untouched).`}),!0}return Er(),!0}if(a==="y"||a==="yes"){let h=le.current.shift().plan;try{wd({cwd:e,profileName:s},h),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${h.path} (sync base advanced).`})}catch(u){d({kind:"note",tone:"error",text:`Pull failed: ${u.message}`})}}else if(a==="n"||a==="no"){let h=le.current.shift().plan;d({kind:"note",tone:"info",text:`Skipped ${h.path}.`})}else{let h=le.current.length;return le.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${h} article(s) left untouched).`}),!0}return Er(),!0},[e,s,Er,d]),Nr=z(async c=>{d({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let a=await Pi({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),h=a.entries.filter(y=>y.status==="conflict"&&y.path).map(y=>y.path);if(i){if(!h.includes(i)){d({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}h=[i]}if(h.length===0){d({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let u=[];for(let y of h)try{u.push({plan:await kd({cwd:e,profileName:s,relPath:y}),mode:"conflict"})}catch(b){d({kind:"note",tone:"error",text:`Could not load ${y} from Document360: ${b.message}`})}if(u.length===0)return;d({kind:"note",tone:"info",text:`Resolving ${u.length} conflict${u.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),le.current=u,At.current=[],qt()}catch(a){d({kind:"note",tone:"error",text:`Could not compute sync status: ${a.message}`})}},[e,s,d,qt]),Zi=z(c=>{let a=zn.current;if(!a)return!1;if(zn.current=null,Oe(),c.trim()!==a.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:h}=Zs(e,a.targets);d({kind:"note",tone:h.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`});for(let u of h)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return a.hadDevhints&&(d({kind:"note",tone:"warn",text:Co().join(`
389
391
  `)}),Wt(Hr())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
390
- ${Td}`}),Q("/init"),Bn(!1),!0},[e,d,Wt,Le,Q]),wn=z(async c=>{let a=c.slice(1).trim().split(/\s+/),i=(a[0]??"").toLowerCase(),h=a.slice(1);if(Bn(!0),Lo(h)&&["write","check","review","reorder"].includes(i)){let u=Dn(e,s);if(u.length===0){d({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let y=b=>i==="write"?`/write ${Pl(h,b).join(" ")}`.trim():`/${i} ${[b,...h.filter(w=>w!=="--scope")].join(" ")}`.trim();if(u.length===1){wn(y(u[0].token));return}mt({cursor:0,rows:u,run:b=>{wn(y(b))}});return}if(st(i,h)){let u=Dn(e,s);if(u.length>1){let y=h.filter(x=>x.startsWith("--")).join(" "),b=x=>`/${i}${x?` ${i==="write"?`--scope ${x}`:x}`:""}${y?` ${y}`:""} ${x?"":"--all"}`.replace(/\s+/g," ").trim(),w=u.reduce((x,G)=>x+G.count,0),$={token:"",label:i==="review"?`Everything \u2014 all ${w} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${u.length} categories`:`Everything \u2014 rewrite all ${w} planned articles`,count:w};mt({cursor:0,rows:[$,...u],run:x=>{wn(b(x))}});return}}switch(i){case"help":pn({tab:0});return;case"exit":case"quit":De.current?.close(),r();return;case"clear":Ce(),Dt.current=[],Bn(!1),Le(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=Pe(e,s)}catch(y){d({kind:"note",tone:"error",text:y.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),B(!0);try{let y=await Tg(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},w=>d({kind:"note",tone:"info",text:w})),b=Sg(u.name,y);if(Dg(b),await Lr(b,u.name,w=>d({kind:"note",tone:"info",text:w})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${go(b)}`}),await Xi(s),un.current){let w=un.current;un.current=null;let $=Ne(e,s);$.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${w}.`}),Q(w)):(d({kind:"note",tone:"warn",text:`${$.reason} (then ${w}.)`}),Q("/login"),un.current=w)}else dn.current&&(ge(dn.current,"\u21E5 tab to re-send your last prompt\u2026"),dn.current=null)}catch(y){d({kind:"note",tone:"error",text:`Login failed: ${y.message}`})}finally{B(!1),Y(y=>y+1)}return}case"allow-prod":{let u=!1;try{u=Pe(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}jt.current=!0,Ce(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=_s(h.join(" ")),y=Fe.current.uuid;if(!y){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}kr.current=u,ut(u),tn(`${sr} ${u}`),d({kind:"note",tone:"ok",text:`Session will be named "${u}" once it starts.`});return}if(!u){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let b=Fe.current.firstPrompt??"";fd(b,e).then(w=>{w?(ge(`/rename ${w}`),d({kind:"note",tone:"info",text:`Suggestion: "${w}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Wg(y,u),ut(u),tn(`${sr} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=h[0],y=te(e);if(!u){let b=Object.entries(y?.profiles??{});if(b.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let w=b.map(([G,H])=>({name:G,env:H.connection?.environment??"custom",prod:H.production===!0,who:jr(G)})),$=s??y?.defaultProfile,x=Math.max(0,w.findIndex(G=>G.name===$));Et({cursor:x,current:x,rows:w});return}if(u==="add"){let b=Os(e,h[1],h[2]);if(b){d({kind:"note",tone:"error",text:b});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),Ar(h[1],!1);return}if(!y?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}Ar(u,!0);return}case"doctor":await An(h,{cwd:e,version:o});return;case"genre":{await Yo(h,{cwd:e});try{mr.current=!(te(e)?.appType??qg(e))}catch{}Y(u=>u+1);return}case"roadmap":{if(h[0]?.toLowerCase()==="done"){let u=ii(e,h.slice(1).join(" ").trim());d({kind:"note",tone:u.ok?"ok":"warn",text:u.line}),Y(y=>y+1);return}d({kind:"note",tone:"info",text:si(e).join(`
391
- `)});return}case"mcp":await To(h);return;case"init":{if(te(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let u=zg().map(y=>({name:y,apiUrl:Kg(y).apiUrl}));Nt({cursor:0,rows:u});return}case"resume":{let u=h.join(" ").trim(),y=Ug(e).filter($=>$.uuid!==Fe.current.uuid);if(!u){if(!y.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}yt({query:"",cursor:0,sessions:y});return}let b=Mg(e,u);if(!b){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}Ce(b.uuid),Fe.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},ut(b.name),Ci(b.uuid),Dt.current=[];let w=ki(e,b.uuid);for(let $ of w)d($);d({kind:"note",tone:"ok",text:w.length?`Resumed "${b.name}" \u2014 restored ${w.length} message(s); continue where you left off.`:`Resumed "${b.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=h.join(" ").trim(),y;try{y=await bn(e,s)}catch(w){d({kind:"note",tone:"error",text:`Could not list workspaces: ${w.message}`});return}if(!u){let w=y.workspaces.map(x=>({id:x.id,name:x.name??x.id,type:x.workspace_type}));if(w.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let $=Math.max(0,w.findIndex(x=>x.id===y.current));It({cursor:$,current:$,rows:w,profile:y.profile,projectId:y.projectId,projectName:y.projectName,environment:y.environment});return}let b=_r(y.workspaces,u);if(!b){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}ro(y.profile,y.projectId,b);return}case"project":{let u=h.join(" ").trim(),y;try{y=await et(e,s)}catch(w){d({kind:"note",tone:"error",text:`Could not list projects: ${w.message} (signed in? try /login)`});return}if(!u){let w=y.projects.map(x=>({id:x.id,name:x.name??x.id,sub:x.sub_domain}));if(w.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let $=w.findIndex(x=>x.id===y.current);ht({cursor:Math.max(0,$),current:$,rows:w,profile:y.profile,environment:y.environment});return}let b=Or(y.projects,u);if(!b){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${y.projects.map(w=>w.name??w.id).join(", ")}`});return}io(y.profile,b);return}case"logout":{let u;try{u=Pe(e,s).name}catch(b){d({kind:"note",tone:"error",text:b.message});return}let y=Ng(u);Ig(e,u),Ce(),Y(b=>b+1),d({kind:"note",tone:y?"ok":"info",text:y?`\u2713 Signed out of "${u}" and cleared its project/workspace selection.`:`Profile "${u}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Q("/login");return}case"publish":{if(!Zn(c.trim()))return;if(h[0]==="--related"&&h[1]){let w=await No(e,s,h[1].replace(/\\/g,"/"));if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Ht(w);return}let u=h.filter(w=>!w.startsWith("--"));if(u[0]){await Dr(u[0]);return}let y=h.includes("--all"),b=h.includes("--force");d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let w=await Ri({cwd:e,profileName:s}),{clean:$,conflicts:x}=Do(w.entries),G=y&&b&&x.length>0,H=Ao(w.entries);if(H>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${H} article${H===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),x.length>0&&!G&&d({kind:"note",tone:"warn",text:jo(x.length)}),$.length===0&&!G){if(x.length>0){Q("/resolve");return}d({kind:"note",tone:"ok",text:H>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let I=w.counts["unknown-base"]??0;I>0&&d({kind:"note",tone:"info",text:`(${I} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Fi("Reconciling structure on Document360 (order + related articles)\u2026");try{let C=await xd({cwd:e,profileName:s}),A=Pd(await Rd({cwd:e,profileName:s})),U=Cd(C);U?d({kind:"note",tone:"info",text:U}):C.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${C.skipped}`}),A&&d({kind:"note",tone:"info",text:A}),d({kind:"note",tone:"ok",text:U||A?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(U||A)&&Q("/structure")}catch(C){d({kind:"note",tone:"warn",text:`Structure sync failed: ${C.message}`})}finally{Fi(null)}return}if(y){let I=(G?[...$,...x]:$).map(C=>C.path);await Ht(I),x.length>0&&!G&&Q("/resolve");return}_t({cursor:0,rows:ll($,x)})}catch(w){d({kind:"note",tone:"error",text:`Could not compute sync status: ${w.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!Zn(c.trim()))return;await Nr(h.find(u=>!u.startsWith("--")));return}case"preview":{let u=h.join(" ").trim();if(!u){let b=[];try{b=Object.keys(md(e,Pe(e,s).name)?.articles??{})}catch{}if(b.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}gt({query:"",cursor:0,paths:b});return}let y=Rg(u)?u:xi(e,u);if(nn(y)){try{d({kind:"preview",name:Wn(y),text:Dd(dr(y,"utf8"))})}catch(b){d({kind:"note",tone:"error",text:`Could not read ${y}: ${b.message}`})}return}if(mw.test(u)){try{let b=Pe(e,s),w={profile:b.name,connection:b.connection},$=b.project.projectId??Ag(w),x=await Eg(w,$,u);d({kind:"preview",name:x.title??u,text:x.content??"*(article has no content)*"})}catch(b){d({kind:"note",tone:"error",text:`Could not fetch article: ${b.message}`})}return}d({kind:"note",tone:"error",text:`"${u}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let u=h[0]?.trim();if(!u){let $=Uo(ji(e));ft({cursor:$,current:$});return}let{lines:y,changed:b,effective:w}=jn(e,u);for(let $ of y)d({kind:"note",tone:$.startsWith("\u26A0")?"warn":$.startsWith("\u2713")?"ok":"info",text:$});b&&(Bi($=>$+1),De.current?.setModel(w));return}case"convert":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:y}=ps(h),b=Jg(e,s);if(b.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let w=fs(b,u);if(w.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${b.length} are tracked overall.)`});return}let $=Pi(w),x=3,G=`/convert${u?` --scope ${u}`:""} --run`,H=pr(e,"light");if(!y){let C=kd({files:hs(e,w),op:"convert",model:H.model}),A=u?`Scope: ${u} (${w.length} of ${b.length} tracked)
392
+ ${Td}`}),Q("/init"),Bn(!1),!0},[e,d,Wt,Oe,Q]),wn=z(async c=>{let a=c.slice(1).trim().split(/\s+/),i=(a[0]??"").toLowerCase(),h=a.slice(1);if(Bn(!0),Oo(h)&&["write","check","review","reorder"].includes(i)){let u=Dn(e,s);if(u.length===0){d({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let y=b=>i==="write"?`/write ${Sl(h,b).join(" ")}`.trim():`/${i} ${[b,...h.filter(w=>w!=="--scope")].join(" ")}`.trim();if(u.length===1){wn(y(u[0].token));return}mt({cursor:0,rows:u,run:b=>{wn(y(b))}});return}if(st(i,h)){let u=Dn(e,s);if(u.length>1){let y=h.filter(x=>x.startsWith("--")).join(" "),b=x=>`/${i}${x?` ${i==="write"?`--scope ${x}`:x}`:""}${y?` ${y}`:""} ${x?"":"--all"}`.replace(/\s+/g," ").trim(),w=u.reduce((x,G)=>x+G.count,0),$={token:"",label:i==="review"?`Everything \u2014 all ${w} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${u.length} categories`:`Everything \u2014 rewrite all ${w} planned articles`,count:w};mt({cursor:0,rows:[$,...u],run:x=>{wn(b(x))}});return}}switch(i){case"help":pn({tab:0});return;case"exit":case"quit":De.current?.close(),r();return;case"clear":Ce(),Dt.current=[],Bn(!1),Oe(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=Pe(e,s)}catch(y){d({kind:"note",tone:"error",text:y.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),B(!0);try{let y=await Tg(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},w=>d({kind:"note",tone:"info",text:w})),b=Dg(u.name,y);if(jg(b),await Or(b,u.name,w=>d({kind:"note",tone:"info",text:w})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${go(b)}`}),await Qi(s),un.current){let w=un.current;un.current=null;let $=Ne(e,s);$.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${w}.`}),Q(w)):(d({kind:"note",tone:"warn",text:`${$.reason} (then ${w}.)`}),Q("/login"),un.current=w)}else dn.current&&(ge(dn.current,"\u21E5 tab to re-send your last prompt\u2026"),dn.current=null)}catch(y){d({kind:"note",tone:"error",text:`Login failed: ${y.message}`})}finally{B(!1),Y(y=>y+1)}return}case"allow-prod":{let u=!1;try{u=Pe(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}jt.current=!0,Ce(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=_s(h.join(" ")),y=Fe.current.uuid;if(!y){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}kr.current=u,ut(u),tn(`${sr} ${u}`),d({kind:"note",tone:"ok",text:`Session will be named "${u}" once it starts.`});return}if(!u){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let b=Fe.current.firstPrompt??"";hd(b,e).then(w=>{w?(ge(`/rename ${w}`),d({kind:"note",tone:"info",text:`Suggestion: "${w}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Fg(y,u),ut(u),tn(`${sr} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=h[0],y=te(e);if(!u){let b=Object.entries(y?.profiles??{});if(b.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let w=b.map(([G,H])=>({name:G,env:H.connection?.environment??"custom",prod:H.production===!0,who:jr(G)})),$=s??y?.defaultProfile,x=Math.max(0,w.findIndex(G=>G.name===$));Et({cursor:x,current:x,rows:w});return}if(u==="add"){let b=Ls(e,h[1],h[2]);if(b){d({kind:"note",tone:"error",text:b});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),Ar(h[1],!1);return}if(!y?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}Ar(u,!0);return}case"doctor":await An(h,{cwd:e,version:o});return;case"genre":{await Yo(h,{cwd:e});try{mr.current=!(te(e)?.appType??Bg(e))}catch{}Y(u=>u+1);return}case"roadmap":{if(h[0]?.toLowerCase()==="done"){let u=ai(e,h.slice(1).join(" ").trim());d({kind:"note",tone:u.ok?"ok":"warn",text:u.line}),Y(y=>y+1);return}d({kind:"note",tone:"info",text:ii(e).join(`
393
+ `)});return}case"mcp":await So(h);return;case"init":{if(te(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let u=Kg().map(y=>({name:y,apiUrl:Xg(y).apiUrl}));Nt({cursor:0,rows:u});return}case"resume":{let u=h.join(" ").trim(),y=Wg(e).filter($=>$.uuid!==Fe.current.uuid);if(!u){if(!y.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}yt({query:"",cursor:0,sessions:y});return}let b=Ug(e,u);if(!b){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}Ce(b.uuid),Fe.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},ut(b.name),Ri(b.uuid),Dt.current=[];let w=bi(e,b.uuid);for(let $ of w)d($);d({kind:"note",tone:"ok",text:w.length?`Resumed "${b.name}" \u2014 restored ${w.length} message(s); continue where you left off.`:`Resumed "${b.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=h.join(" ").trim(),y;try{y=await bn(e,s)}catch(w){d({kind:"note",tone:"error",text:`Could not list workspaces: ${w.message}`});return}if(!u){let w=y.workspaces.map(x=>({id:x.id,name:x.name??x.id,type:x.workspace_type}));if(w.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let $=Math.max(0,w.findIndex(x=>x.id===y.current));It({cursor:$,current:$,rows:w,profile:y.profile,projectId:y.projectId,projectName:y.projectName,environment:y.environment});return}let b=_r(y.workspaces,u);if(!b){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}ro(y.profile,y.projectId,b);return}case"project":{let u=h.join(" ").trim(),y;try{y=await et(e,s)}catch(w){d({kind:"note",tone:"error",text:`Could not list projects: ${w.message} (signed in? try /login)`});return}if(!u){let w=y.projects.map(x=>({id:x.id,name:x.name??x.id,sub:x.sub_domain}));if(w.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let $=w.findIndex(x=>x.id===y.current);ht({cursor:Math.max(0,$),current:$,rows:w,profile:y.profile,environment:y.environment});return}let b=Lr(y.projects,u);if(!b){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${y.projects.map(w=>w.name??w.id).join(", ")}`});return}io(y.profile,b);return}case"logout":{let u;try{u=Pe(e,s).name}catch(b){d({kind:"note",tone:"error",text:b.message});return}let y=Ig(u);_g(e,u),Ce(),Y(b=>b+1),d({kind:"note",tone:y?"ok":"info",text:y?`\u2713 Signed out of "${u}" and cleared its project/workspace selection.`:`Profile "${u}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Q("/login");return}case"publish":{if(!Zn(c.trim()))return;if(h[0]==="--related"&&h[1]){let w=await No(e,s,h[1].replace(/\\/g,"/"));if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Ht(w);return}let u=h.filter(w=>!w.startsWith("--"));if(u[0]){await Dr(u[0]);return}let y=h.includes("--all"),b=h.includes("--force");d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let w=await Pi({cwd:e,profileName:s}),{clean:$,conflicts:x}=Do(w.entries),G=y&&b&&x.length>0,H=Ao(w.entries);if(H>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${H} article${H===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),x.length>0&&!G&&d({kind:"note",tone:"warn",text:jo(x.length)}),$.length===0&&!G){if(x.length>0){Q("/resolve");return}d({kind:"note",tone:"ok",text:H>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let I=w.counts["unknown-base"]??0;I>0&&d({kind:"note",tone:"info",text:`(${I} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Hi("Reconciling structure on Document360 (order + related articles)\u2026");try{let C=await Cd({cwd:e,profileName:s}),A=Sd(await Pd({cwd:e,profileName:s})),U=Rd(C);U?d({kind:"note",tone:"info",text:U}):C.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${C.skipped}`}),A&&d({kind:"note",tone:"info",text:A}),d({kind:"note",tone:"ok",text:U||A?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(U||A)&&Q("/structure")}catch(C){d({kind:"note",tone:"warn",text:`Structure sync failed: ${C.message}`})}finally{Hi(null)}return}if(y){let I=(G?[...$,...x]:$).map(C=>C.path);await Ht(I),x.length>0&&!G&&Q("/resolve");return}_t({cursor:0,rows:cl($,x)})}catch(w){d({kind:"note",tone:"error",text:`Could not compute sync status: ${w.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!Zn(c.trim()))return;await Nr(h.find(u=>!u.startsWith("--")));return}case"preview":{let u=h.join(" ").trim();if(!u){let b=[];try{b=Object.keys(gd(e,Pe(e,s).name)?.articles??{})}catch{}if(b.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}gt({query:"",cursor:0,paths:b});return}let y=Pg(u)?u:Ci(e,u);if(nn(y)){try{d({kind:"preview",name:Wn(y),text:jd(dr(y,"utf8"))})}catch(b){d({kind:"note",tone:"error",text:`Could not read ${y}: ${b.message}`})}return}if(gw.test(u)){try{let b=Pe(e,s),w={profile:b.name,connection:b.connection},$=b.project.projectId??Eg(w),x=await Ng(w,$,u);d({kind:"preview",name:x.title??u,text:x.content??"*(article has no content)*"})}catch(b){d({kind:"note",tone:"error",text:`Could not fetch article: ${b.message}`})}return}d({kind:"note",tone:"error",text:`"${u}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let u=h[0]?.trim();if(!u){let $=Uo(Ai(e));ft({cursor:$,current:$});return}let{lines:y,changed:b,effective:w}=jn(e,u);for(let $ of y)d({kind:"note",tone:$.startsWith("\u26A0")?"warn":$.startsWith("\u2713")?"ok":"info",text:$});b&&(Vi($=>$+1),De.current?.setModel(w));return}case"convert":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:y}=ps(h),b=Zg(e,s);if(b.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let w=fs(b,u);if(w.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${b.length} are tracked overall.)`});return}let $=Si(w),x=3,G=`/convert${u?` --scope ${u}`:""} --run`,H=pr(e,"light");if(!y){let C=bd({files:hs(e,w),op:"convert",model:H.model}),A=u?`Scope: ${u} (${w.length} of ${b.length} tracked)
392
394
  `:"",U=`
393
395
  Model: ${H.model}${H.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:A+gs($,C,x).join(`
394
- `)+U}),Q(G);return}dt.current=Date.now(),Pt(0),S(!0);let I=new AbortController;je.current=I,oe({verb:"Converting",total:$.length,done:0,active:[],rows:Un($),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${w.length} articles across ${$.length} partitions (\u2264${x} agents at once) on ${H.model}\u2026 (esc to stop)`});try{for await(let C of ur({cwd:e,partitions:$,promptFor:ms,concurrency:x,profileName:s,allowProdWrites:jt.current,model:H.model,signal:I.signal}))if(C.type==="partition_status")C.status==="running"?oe(A=>A&&{...A,active:[...A.active,C.label],rows:ze(A.rows,C.label,"active"),lastAt:Date.now()}):oe(A=>A&&{...A,active:A.active.filter(U=>U!==C.label),done:A.done+1,rows:ze(A.rows,C.label,C.status==="done"?"done":"failed"),lastAt:Date.now()});else if(C.type==="partition_event")oe(A=>{if(!A)return A;let U={...A,lastAt:Date.now()};return C.event.type==="tool"?U.tools=A.tools+1:C.event.type==="text"&&(U.chars=A.chars+C.event.delta.length),U});else if(C.type==="run_done"){Mt(J=>J+C.totalCostUsd),Lt(J=>J+C.results.reduce((ye,Vt)=>ye+Vt.outputTokens,0));let A=C.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";d({kind:"note",tone:C.aborted?"warn":C.ok?"ok":"warn",text:A+ws(C.results,$,U).join(`
395
- `)})}}catch(C){d({kind:"note",tone:"error",text:`Convert run failed: ${C.message}`})}finally{je.current=null,oe(null),S(!1),Y(C=>C+1)}return}case"write":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Zg(e);if(u.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:y,path:b,preview:w,concurrency:$,rewrite:x}=bs(h),{docsDir:G,targets:H,reason:I,rewriting:C}=Ts(e,u,{scope:y,path:b,rewrite:x});if(H.length===0){d({kind:"note",tone:"warn",text:I??"Nothing to write."});return}C&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${H.length} already-written article${H.length===1?"":"s"} (overwrites them; git has your baseline).`});let A=Pi(H),U=ks($),J=pr(e,"standard"),ye=!!b;if(w&&!ye){let X=kd({files:$s(e,u,H),op:"write",model:J.model}),se=y?`Scope: ${y} (${H.length} pending)
396
+ `)+U}),Q(G);return}dt.current=Date.now(),Pt(0),T(!0);let I=new AbortController;je.current=I,oe({verb:"Converting",total:$.length,done:0,active:[],rows:Un($),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${w.length} articles across ${$.length} partitions (\u2264${x} agents at once) on ${H.model}\u2026 (esc to stop)`});try{for await(let C of ur({cwd:e,partitions:$,promptFor:ms,concurrency:x,profileName:s,allowProdWrites:jt.current,model:H.model,signal:I.signal}))if(C.type==="partition_status")C.status==="running"?oe(A=>A&&{...A,active:[...A.active,C.label],rows:ze(A.rows,C.label,"active"),lastAt:Date.now()}):oe(A=>A&&{...A,active:A.active.filter(U=>U!==C.label),done:A.done+1,rows:ze(A.rows,C.label,C.status==="done"?"done":"failed"),lastAt:Date.now()});else if(C.type==="partition_event")oe(A=>{if(!A)return A;let U={...A,lastAt:Date.now()};return C.event.type==="tool"?U.tools=A.tools+1:C.event.type==="text"&&(U.chars=A.chars+C.event.delta.length),U});else if(C.type==="run_done"){Mt(J=>J+C.totalCostUsd),Ot(J=>J+C.results.reduce((ye,Vt)=>ye+Vt.outputTokens,0));let A=C.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";d({kind:"note",tone:C.aborted?"warn":C.ok?"ok":"warn",text:A+ws(C.results,$,U).join(`
397
+ `)})}}catch(C){d({kind:"note",tone:"error",text:`Convert run failed: ${C.message}`})}finally{je.current=null,oe(null),T(!1),Y(C=>C+1)}return}case"write":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=ew(e);if(u.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:y,path:b,preview:w,concurrency:$,rewrite:x}=bs(h),{docsDir:G,targets:H,reason:I,rewriting:C}=Ss(e,u,{scope:y,path:b,rewrite:x});if(H.length===0){d({kind:"note",tone:"warn",text:I??"Nothing to write."});return}C&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${H.length} already-written article${H.length===1?"":"s"} (overwrites them; git has your baseline).`});let A=Si(H),U=ks($),J=pr(e,"standard"),ye=!!b;if(w&&!ye){let X=bd({files:$s(e,u,H),op:"write",model:J.model}),se=y?`Scope: ${y} (${H.length} pending)
396
398
  `:"",pe=`
397
399
  Model: ${J.model}${J.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:se+Cs(A,X,U).join(`
398
- `)+pe}),Q(`/write${y?` --scope ${y}`:""}`);return}dt.current=Date.now(),Pt(0),S(!0);let Vt=new AbortController;je.current=Vt,oe({verb:"Writing",total:A.length,done:0,active:[],rows:Un(A),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${H.length} article${H.length===1?"":"s"} across ${A.length} partition${A.length===1?"":"s"} (\u2264${U} agents at once) on ${J.model}${J.forced?" (forced)":""}\u2026 (esc to stop)`});let co=new Set;try{for await(let X of ur({cwd:e,partitions:A,promptFor:se=>xs(se,G,{rewrite:C||ye}),concurrency:U,profileName:s,allowProdWrites:jt.current,model:J.model,signal:Vt.signal}))if(X.type==="partition_status")X.status==="running"?oe(se=>se&&{...se,active:[...se.active,X.label],rows:ze(se.rows,X.label,"active"),lastAt:Date.now()}):oe(se=>se&&{...se,active:se.active.filter(pe=>pe!==X.label),done:se.done+1,rows:ze(se.rows,X.label,X.status==="done"?"done":"failed"),lastAt:Date.now()});else if(X.type==="partition_event"){let se=null;if(X.event.type==="tool"){let pe=Jc(X.event.name,X.event.input,A[X.index]?.paths??[]);pe&&!co.has(pe)&&(co.add(pe),se=X.label)}oe(pe=>{if(!pe)return pe;let Ue={...pe,lastAt:Date.now()};return X.event.type==="tool"?Ue.tools=pe.tools+1:X.event.type==="text"&&(Ue.chars=pe.chars+X.event.delta.length),se&&(Ue.rows=Qc(Ue.rows,se)),Ue})}else if(X.type==="run_done"){Mt(Je=>Je+X.totalCostUsd),Lt(Je=>Je+X.results.reduce((Ve,zd)=>Ve+zd.outputTokens,0));let se=X.aborted?"Stopped. ":"",pe=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:X.aborted?"warn":X.ok?"ok":"warn",text:se+Rs(X.results,A,pe).join(`
399
- `)}),!X.aborted&&X.ok)try{let Je=(co.size>0?[...co]:H).map(Ve=>`${G}/${Ve}`);Ti(e,Je,{writtenCap:Si})}catch{}let Ue=X.aborted?null:Ps(e,G,H);if(Ue&&d({kind:"note",tone:"warn",text:Ue}),!X.aborted&&X.ok){let Je=y??b??"",Ve=Je?` ${Je}`:"";Ut(Ue?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${Ve} --fix, then /review${Ve} --fix for editorial quality, then /publish --all (add /screenshot --all first if you want images).`:`Written. I\u2019d run /review${Ve} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot --all first if you want images).`,{kind:"cmd",cmd:Ue?`/check${Ve} --fix`:`/review${Ve} --fix`,reason:""})}}}catch(X){d({kind:"note",tone:"error",text:`Write run failed: ${X.message}`})}finally{je.current=null,oe(null),S(!1),Y(X=>X+1)}return}case"draft":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:y}=Ss(e);if(u.length===0&&y===0){d({kind:"note",tone:"info",text:js});return}let b=h.join(" ").trim();if(!b&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
400
+ `)+pe}),Q(`/write${y?` --scope ${y}`:""}`);return}dt.current=Date.now(),Pt(0),T(!0);let Vt=new AbortController;je.current=Vt,oe({verb:"Writing",total:A.length,done:0,active:[],rows:Un(A),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${H.length} article${H.length===1?"":"s"} across ${A.length} partition${A.length===1?"":"s"} (\u2264${U} agents at once) on ${J.model}${J.forced?" (forced)":""}\u2026 (esc to stop)`});let co=new Set;try{for await(let X of ur({cwd:e,partitions:A,promptFor:se=>xs(se,G,{rewrite:C||ye}),concurrency:U,profileName:s,allowProdWrites:jt.current,model:J.model,signal:Vt.signal}))if(X.type==="partition_status")X.status==="running"?oe(se=>se&&{...se,active:[...se.active,X.label],rows:ze(se.rows,X.label,"active"),lastAt:Date.now()}):oe(se=>se&&{...se,active:se.active.filter(pe=>pe!==X.label),done:se.done+1,rows:ze(se.rows,X.label,X.status==="done"?"done":"failed"),lastAt:Date.now()});else if(X.type==="partition_event"){let se=null;if(X.event.type==="tool"){let pe=Zc(X.event.name,X.event.input,A[X.index]?.paths??[]);pe&&!co.has(pe)&&(co.add(pe),se=X.label)}oe(pe=>{if(!pe)return pe;let Ue={...pe,lastAt:Date.now()};return X.event.type==="tool"?Ue.tools=pe.tools+1:X.event.type==="text"&&(Ue.chars=pe.chars+X.event.delta.length),se&&(Ue.rows=Jc(Ue.rows,se)),Ue})}else if(X.type==="run_done"){Mt(Je=>Je+X.totalCostUsd),Ot(Je=>Je+X.results.reduce((Ve,Kd)=>Ve+Kd.outputTokens,0));let se=X.aborted?"Stopped. ":"",pe=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:X.aborted?"warn":X.ok?"ok":"warn",text:se+Rs(X.results,A,pe).join(`
401
+ `)}),!X.aborted&&X.ok)try{let Je=(co.size>0?[...co]:H).map(Ve=>`${G}/${Ve}`);Ti(e,Je,{writtenCap:Di})}catch{}let Ue=X.aborted?null:Ps(e,G,H);if(Ue&&d({kind:"note",tone:"warn",text:Ue}),!X.aborted&&X.ok){let Je=y??b??"",Ve=Je?` ${Je}`:"";Ut(Ue?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${Ve} --fix, then /review${Ve} --fix for editorial quality, then /publish --all (add /screenshot --all first if you want images).`:`Written. I\u2019d run /review${Ve} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot --all first if you want images).`,{kind:"cmd",cmd:Ue?`/check${Ve} --fix`:`/review${Ve} --fix`,reason:""})}}}catch(X){d({kind:"note",tone:"error",text:`Write run failed: ${X.message}`})}finally{je.current=null,oe(null),T(!1),Y(X=>X+1)}return}case"draft":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:y}=Ts(e);if(u.length===0&&y===0){d({kind:"note",tone:"info",text:js});return}let b=h.join(" ").trim();if(!b&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
400
402
  ${u.map(x=>` \u2022 ${x.name} (${x.docCount} doc${x.docCount===1?"":"s"})`).join(`
401
- `)}`}),ct(u.map(x=>`/draft ${x.name}`));return}let w="",$;if(b){let x=Ds(u,b);x?w=x:$=b}else w=u[0]?.name??"";await re(Mo(w,$),{display:b?`/draft ${b}`:"/draft",quietUser:!0});return}case"pull":{if(!Zn(c.trim()))return;let u=h.find(y=>y.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let w=Date.now(),$=await Ri({cwd:e,profileName:s});d({kind:"note",tone:"info",text:_o($,Date.now()-w).join(`
402
- `)});return}if(u==="--baseline"){let w=h.find(H=>!H.startsWith("--")),$=w?w.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:$?`Setting the sync baseline for ${$}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let x=await Vg({cwd:e,profileName:s,relPaths:$?[$]:void 0}),G=$?{rebaselined:[],skipped:[]}:await Gg({cwd:e,profileName:s});if(x.baselined.length===0&&x.skipped.length===0&&G.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}x.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${x.baselined.length} article${x.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),G.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${G.rebaselined.length} article${G.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),x.skipped.length>0&&d({kind:"note",tone:"warn",text:`${x.skipped.length} skipped:
403
+ `)}`}),ct(u.map(x=>`/draft ${x.name}`));return}let w="",$;if(b){let x=Ds(u,b);x?w=x:$=b}else w=u[0]?.name??"";await re(Mo(w,$),{display:b?`/draft ${b}`:"/draft",quietUser:!0});return}case"pull":{if(!Zn(c.trim()))return;let u=h.find(y=>y.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let w=Date.now(),$=await Pi({cwd:e,profileName:s});d({kind:"note",tone:"info",text:_o($,Date.now()-w).join(`
404
+ `)});return}if(u==="--baseline"){let w=h.find(H=>!H.startsWith("--")),$=w?w.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:$?`Setting the sync baseline for ${$}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let x=await Gg({cwd:e,profileName:s,relPaths:$?[$]:void 0}),G=$?{rebaselined:[],skipped:[]}:await Yg({cwd:e,profileName:s});if(x.baselined.length===0&&x.skipped.length===0&&G.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}x.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${x.baselined.length} article${x.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),G.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${G.rebaselined.length} article${G.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),x.skipped.length>0&&d({kind:"note",tone:"warn",text:`${x.skipped.length} skipped:
403
405
  ${x.skipped.map(H=>` - ${H.path} (${H.reason})`).join(`
404
- `)}`}),Y(H=>H+1);return}if(u==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let w=await Bg({cwd:e,profileName:s}),$=w.onlyInLegacy.length===0&&w.onlyInManifest.length===0&&w.mappedMissingFromManifest.length===0,x=[`Legacy listing: ${w.legacyCount} \xB7 Manifest: ${w.manifestCount} \xB7 in both: ${w.inBoth}`];$?x.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(w.mappedMissingFromManifest.length&&x.push(`\u2717 ${w.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${w.mappedMissingFromManifest.slice(0,5).join(", ")}`),w.onlyInLegacy.length&&x.push(`\u26A0 ${w.onlyInLegacy.length} only in the legacy listing: ${w.onlyInLegacy.slice(0,5).join(", ")}`),w.onlyInManifest.length&&x.push(`\u26A0 ${w.onlyInManifest.length} only in the manifest: ${w.onlyInManifest.slice(0,5).join(", ")}`),x.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:$?"ok":"warn",text:x.join(`
405
- `)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=h[0];if(y){let w=await yd({cwd:e,profileName:s,relPath:y.replace(/\\/g,"/")});le.current=[{plan:w,mode:w.overwritesLocalChanges?"conflict":"pull"}],At.current=[],qt();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let b=await cs({cwd:e,profileName:s});for(let w of ds(b))d({kind:"note",tone:w.tone,text:w.text});Y(w=>w+1)}catch(y){d({kind:"note",tone:"error",text:`Pull failed: ${y.message}`})}return}case"scope":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Yg(e);if(u.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Ot({cursor:0,rows:u.map(y=>({...y,checked:y.recommended}))});return}case"audit":{if(h[0]==="--auto"){let y=te(e);if(!y){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=h[1]!=="off";hd({...y,autoAudit:b},e),d({kind:"note",tone:"ok",text:b?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let u=await Sn();u.kind==="forward-to-agent"&&u.prompt&&await re(u.prompt,{display:u.display,quietUser:!0});return}case"check":{let u=h.find(w=>!w.startsWith("--")),y=u?` ${u}`:"",b=wd({cwd:e,scope:u});if(h.includes("--fix")){if(b.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 ${b.length} doc issue${b.length===1?"":"s"}\u2026`});let w=$d(e,u);await re(ti(b),{display:`/check${y} --fix`,quietUser:!0});try{Ti(e,w,{reviewedCap:Si})}catch{}let $=wd({cwd:e,scope:u});d({kind:"note",tone:$.length===0?"ok":"warn",text:$.length===0?"\u2713 Doc-checker: all issues resolved.":Go($).join(`
406
+ `)}`}),Y(H=>H+1);return}if(u==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let w=await Vg({cwd:e,profileName:s}),$=w.onlyInLegacy.length===0&&w.onlyInManifest.length===0&&w.mappedMissingFromManifest.length===0,x=[`Legacy listing: ${w.legacyCount} \xB7 Manifest: ${w.manifestCount} \xB7 in both: ${w.inBoth}`];$?x.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(w.mappedMissingFromManifest.length&&x.push(`\u2717 ${w.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${w.mappedMissingFromManifest.slice(0,5).join(", ")}`),w.onlyInLegacy.length&&x.push(`\u26A0 ${w.onlyInLegacy.length} only in the legacy listing: ${w.onlyInLegacy.slice(0,5).join(", ")}`),w.onlyInManifest.length&&x.push(`\u26A0 ${w.onlyInManifest.length} only in the manifest: ${w.onlyInManifest.slice(0,5).join(", ")}`),x.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:$?"ok":"warn",text:x.join(`
407
+ `)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=h[0];if(y){let w=await kd({cwd:e,profileName:s,relPath:y.replace(/\\/g,"/")});le.current=[{plan:w,mode:w.overwritesLocalChanges?"conflict":"pull"}],At.current=[],qt();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let b=await cs({cwd:e,profileName:s});for(let w of ds(b))d({kind:"note",tone:w.tone,text:w.text});Y(w=>w+1)}catch(y){d({kind:"note",tone:"error",text:`Pull failed: ${y.message}`})}return}case"scope":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=zg(e);if(u.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Lt({cursor:0,rows:u.map(y=>({...y,checked:y.recommended}))});return}case"audit":{if(h[0]==="--auto"){let y=te(e);if(!y){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=h[1]!=="off";md({...y,autoAudit:b},e),d({kind:"note",tone:"ok",text:b?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let u=await Tn();u.kind==="forward-to-agent"&&u.prompt&&await re(u.prompt,{display:u.display,quietUser:!0});return}case"check":{let u=h.find(w=>!w.startsWith("--")),y=u?` ${u}`:"",b=yd({cwd:e,scope:u});if(h.includes("--fix")){if(b.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 ${b.length} doc issue${b.length===1?"":"s"}\u2026`});let w=xd(e,u);await re(ti(b),{display:`/check${y} --fix`,quietUser:!0});try{Ti(e,w,{reviewedCap:Di})}catch{}let $=yd({cwd:e,scope:u});d({kind:"note",tone:$.length===0?"ok":"warn",text:$.length===0?"\u2713 Doc-checker: all issues resolved.":Go($).join(`
406
408
  `)}),Ut($.length===0?`Deterministic issues fixed. Next: /review${y} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${y} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${y} --fix`,reason:""});return}d({kind:"note",tone:b.length===0?"ok":"warn",text:Go(b).join(`
407
409
  `)}),b.length>0&&Ut(`Found ${b.length} doc issue${b.length===1?"":"s"} above. /check${y} --fix has the agent fix them in place (or /review${y} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${y} --fix`,reason:""});return}case"structure":{let u=_n(e,s);if(u.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):","",...u].join(`
408
- `)});return}case"reorder":{let u=oi(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await re(u.prompt,{display:u.display,quietUser:!0}),Ut("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let u=ni(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=h.includes("--fix"),b=h.find($=>!$.startsWith("--")),w=y?$d(e,b):[];if(await re(u.prompt,{display:u.display,quietUser:!0}),y)try{Ti(e,w,{reviewedCap:Si})}catch{}if(y)Ut("\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let $=h.filter(x=>x!=="--fix").join(" ");Ut(`The review listed issues above. /review${$?` ${$}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${$?` ${$}`:""} --fix`,reason:""})}return}case"capture-setup":{let u=await En();u.kind==="forward-to-agent"&&u.prompt&&await re(u.prompt,{display:u.display,quietUser:!0});let y=Hs(e);y&&d({kind:"note",tone:"info",text:y.join(`
410
+ `)});return}case"reorder":{let u=oi(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await re(u.prompt,{display:u.display,quietUser:!0}),Ut("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let u=ni(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=h.includes("--fix"),b=h.find($=>!$.startsWith("--")),w=y?xd(e,b):[];if(await re(u.prompt,{display:u.display,quietUser:!0}),y)try{Ti(e,w,{reviewedCap:Di})}catch{}if(y)Ut("\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let $=h.filter(x=>x!=="--fix").join(" ");Ut(`The review listed issues above. /review${$?` ${$}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${$?` ${$}`:""} --fix`,reason:""})}return}case"capture-setup":{let u=await En();u.kind==="forward-to-agent"&&u.prompt&&await re(u.prompt,{display:u.display,quietUser:!0});let y=Hs(e);y&&d({kind:"note",tone:"info",text:y.join(`
409
411
  `)});return}case"devhints":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Xt(Kt(e)).join(`
410
- `)}),Wt(bt()),hn.current=Ee(e).status==="current",Ft.current=Ge(e);return}case"discover":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await re(rs(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(qs(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 re(Bs(),{display:"/inbox",quietUser:!0});return}case"feedback":{let u=vd(e),y="";try{y=nn(u)?dr(u,"utf8"):""}catch{y=""}if(!/^## /m.test(y)){d({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let b=await wi(y.trim());d({kind:"note",tone:b?"ok":"warn",text:b?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${u} and copy it manually.`}),b&&Pr(null);return}case"document":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:y}=Es(h);if(!y&&As(e)===0){d({kind:"note",tone:"info",text:Is});return}let b=`/document${y?` ${y}`:""}${u?" --publish":""}`;await re(Ns(y,u),{display:b,quietUser:!0});return}case"catch-up":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Zn(c.trim()))return;let{publish:u}=Gs(h);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let y=await zs({cwd:e,profileName:s});for(let w of Ks(y))d({kind:"note",tone:w.startsWith("\u2713")?"ok":w.startsWith("\u2139")?"info":"warn",text:w});let b=In(Nn(e));d({kind:"note",tone:"info",text:b?`Catching up on ${b}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await re(Ys({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{Cr.current=!0,d({kind:"note",tone:"info",text:`Updating ${xt}\u2026 (don\u2019t close this window)`}),Vn(!0),(await Bo().finally(()=>Vn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),Q("/exit"),_i("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${qo}`});return}case"screenshot":{let u=Us(h);if(u.mode==="list"){if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Fs(Ws(e,u.scope),u.scope).join(`
411
- `)});return}if(u.mode==="single"){let I=await Fo(h);I.kind==="forward-to-agent"&&I.prompt&&await re(I.prompt,{display:I.display,quietUser:!0});return}if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=u.mode==="scope"?u.scope:void 0,b=Qg(e,{scope:y}).map(I=>I.id);if(b.length===0){d({kind:"note",tone:"info",text:y?`No screenshot placeholders under ${y}.`:"No screenshot placeholders found in the docs."});return}let w=6,$=Xg(b,3),x=pr(e,"standard");dt.current=Date.now(),Pt(0),S(!0);let G=new AbortController;je.current=G,oe({verb:"Authoring",unit:"spec",total:$.length,done:0,active:[],rows:Un($),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${b.length} screenshot spec${b.length===1?"":"s"} across ${$.length} partition${$.length===1?"":"s"} (\u2264${w} agents at once) on ${x.model}${x.forced?" (forced)":""}\u2026 (esc to stop)`});let H=!1;try{for await(let I of ur({cwd:e,partitions:$,promptFor:rc,concurrency:w,profileName:s,allowProdWrites:jt.current,model:x.model,signal:G.signal}))if(I.type==="partition_status")I.status==="running"?oe(C=>C&&{...C,active:[...C.active,I.label],rows:ze(C.rows,I.label,"active"),lastAt:Date.now()}):oe(C=>C&&{...C,active:C.active.filter(A=>A!==I.label),done:C.done+1,rows:ze(C.rows,I.label,I.status==="done"?"done":"failed"),lastAt:Date.now()});else if(I.type==="partition_event")oe(C=>{if(!C)return C;let A={...C,lastAt:Date.now()};return I.event.type==="tool"?A.tools=C.tools+1:I.event.type==="text"&&(A.chars=C.chars+I.event.delta.length),A});else if(I.type==="run_done"){Mt(J=>J+I.totalCostUsd),Lt(J=>J+I.results.reduce((ye,Vt)=>ye+Vt.outputTokens,0));let C=I.results.filter(J=>J.ok).length,A=I.aborted?"Stopped. ":"";H=!I.aborted&&u.setup;let U=I.aborted?"":H?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:I.aborted?"warn":I.ok?"ok":"warn",text:`${A}Authored specs \u2014 ${C}/${I.results.length} batches ok.${U}`})}}catch(I){d({kind:"note",tone:"error",text:`Spec authoring failed: ${I.message}`})}finally{je.current=null,oe(null),S(!1),Y(I=>I+1)}if(H){let I=await En();I.kind==="forward-to-agent"&&I.prompt&&await re(I.prompt,{display:I.display,quietUser:!0});let C=Hs(e);C&&d({kind:"note",tone:"info",text:C.join(`
412
- `)})}return}case"reset":{let u=Js(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}zn.current={repoName:Wn(e),targets:u,hadDevhints:nn(bd(e))},d({kind:"note",tone:"warn",text:ei(e,u).join(`
413
- `)}),ge(Wn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,qt,Nr,d,Ce,re,Ht,Dr,Xi]),ao=z(c=>{let a=(c??T).trim();if(v(""),Gn(null),Tt(0),a.startsWith("/")&&(Hn.current=!1,Le(),ln(null),ct(h=>td(h,a))),!a||(Ii(!1),Ji(a))||Qi(a))return;yr.current.push(a);let i=sd(a,Oi.current);if(a.startsWith("/"))d({kind:"user",text:a}),_e(!0),wn(i).finally(()=>_e(!1));else if(aw(i)){d({kind:"user",text:a});let h=lw(i);if(!h)re(i,{display:a,quietUser:!0});else{try{cw(e,{title:h,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}re(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${h}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${h}" and the article path(s) you wrote.`,{display:a,quietUser:!0})}}else re(i,{display:a})},[T,Ji,Qi,wn,re]),Zi=z(c=>{if(c.length>1){if(c.includes("\x1B"))return;let a=nd(c);if(od(a)){let i=rd(++Hd.current,a);Oi.current.set(i,a),_(i)}else _(a);return}_(c)},[_]),Bt=Math.max(10,Me-6),ea=$i(()=>lr(k.text,Bt),[k.text,Bt]),Ir=z(c=>g(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+c))})),[]),lo=z(c=>g(a=>({...a,pos:ad(lr(a.text,Bt),a.pos,c)})),[Bt]),yn=z(c=>g(a=>({...a,pos:ld(lr(a.text,Bt),a.pos,c)})),[Bt]),Gd=["\x1B[H","\x1B[1~","\x1BOH"],Yd=["\x1B[F","\x1B[4~","\x1BOF"],ta=z((c,a)=>a.leftArrow?(Ir(-1),!0):a.rightArrow?(Ir(1),!0):c&&Gd.includes(c)?(yn("start"),!0):c&&Yd.includes(c)?(yn("end"),!0):a.ctrl&&c==="a"?(yn("start"),!0):a.ctrl&&c==="e"?(yn("end"),!0):!1,[Ir,yn]);return $g((c,a)=>{if(a.ctrl&&c==="c"){De.current?.close(),r();return}if(!M){if(N){if(a.escape){if(je.current){if(!je.current.signal.aborted){let i=(Kn?.verb??"work").toLowerCase(),h=Kn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${h}s)\u2026`}),je.current.abort()}return}cn.current||(cn.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),De.current?.interrupt());return}if(a.return){let i=T.trim();if(!i)return;wt.current.push(i),br([...wt.current]),v("");return}if(ta(c,a))return;if(a.upArrow){lo(-1);return}if(a.downArrow){lo(1);return}if(a.backspace||a.delete){P();return}c&&!a.ctrl&&!a.meta&&Zi(c);return}if(pt){if(a.upArrow){ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ft(i=>i&&{...i,cursor:Math.min(We.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=We.length){ft(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=We[pt.cursor];ft(null);let{lines:h,changed:u,effective:y}=jn(e,i.value??"default");for(let b of h)d({kind:"note",tone:b.startsWith("\u26A0")?"warn":b.startsWith("\u2713")?"ok":"info",text:b});u&&(Bi(b=>b+1),De.current?.setModel(y));return}if(c==="s"){let i=We[pt.cursor];ft(null),De.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){ft(null);return}return}if(He){if(a.upArrow){Et(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Et(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=He.rows.length){Et(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return||c==="s"){let i=He.rows[He.cursor];Et(null),Ar(i.name,a.return===!0);return}if(a.escape){Et(null);return}return}if(Qn){if(a.escape){pn(null);return}if(a.leftArrow||a.tab&&a.shift){pn(i=>i&&{tab:(i.tab-1+Ae.length)%Ae.length});return}if(a.rightArrow||a.tab){pn(i=>i&&{tab:(i.tab+1)%Ae.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ae.length){pn({tab:Number(c)-1});return}return}if(qe){if(a.upArrow){Nt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Nt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=qe.rows.length){Nt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=qe.rows[qe.cursor].name;if(Nt(null),!qr(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let u=!1;try{let y=Rt(i);u=!!y&&!(at(y)&&!y.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${i} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${i}) and pick your project.`}),Q("/login"),Y(y=>y+1);return}if(a.escape){Nt(null);return}return}if(me){if(a.upArrow){It(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){It(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=me.rows.length){It(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=me.rows[me.cursor],{profile:h,projectId:u}=me;It(null),ro(h,u,i);return}if(a.escape){It(null);return}return}if(ve){if(a.upArrow){ht(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ht(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ve.rows.length){ht(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=ve.rows[ve.cursor],{profile:h}=ve;ht(null),io(h,i);return}if(a.escape){ht(null);return}return}if(we){if(a.upArrow){Ot(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ot(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){Ot(i=>i&&{...i,rows:i.rows.map((h,u)=>u===i.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let i=we.rows.filter(h=>h.checked).map(h=>h.path);if(Ot(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}ss(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of i)d({kind:"note",tone:"info",text:` ${h}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){Ot(null);return}return}if(Be){if(a.upArrow){mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){mt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Be.rows.length){mt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Be.rows[Be.cursor],h=Be.run;mt(null),h(i.token);return}if(a.escape){mt(null);return}return}if(Xe){if(a.upArrow){_t(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){_t(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Xe.rows.length){_t(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Xe.rows[Xe.cursor];_t(null),i.conflict?Nr(i.paths[0]):i.kind==="article"?Dr(i.paths[0]):Ht(i.paths);return}if(a.escape){_t(null);return}return}if($e){if(a.escape){gt(null);return}if(a.upArrow){gt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){gt(i=>i&&{...i,cursor:Math.min(Math.max(0,no.length-1),i.cursor+1)});return}if(a.return){let i=no[$e.cursor];if(i){gt(null);try{d({kind:"preview",name:Wn(i),text:Dd(dr(xi(e,i),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${i}: ${h.message}`})}}return}if(a.backspace||a.delete){gt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){gt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(xe){if(a.escape){yt(null);return}if(a.upArrow){yt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){yt(i=>i&&{...i,cursor:Math.min(Math.max(0,oo.length-1),i.cursor+1)});return}if(a.return){let i=oo[xe.cursor];if(i){yt(null),Ce(i.uuid),Fe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},ut(i.name),Ci(i.uuid),Dt.current=[];let h=ki(e,i.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${i.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){yt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){yt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(a.tab&&!T&&he){v(he),Le();return}if(!T&&lt.length>0&&!gr&&c&&/^[1-9]$/.test(c)){let i=lt[Number(c)-1];if(i){v(Ct(i));return}}if(!T&&(eo||fn)&&c==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let i=eo!=null;wi(eo??fn).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?i?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":i?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&i&&Pr(null),u&&!i&&Gi(!0)});return}if(!ta(c,a)){if(zi){if(a.upArrow){Tt(i=>Math.max(0,i-1));return}if(a.downArrow){Tt(i=>Math.min(gn.length-1,i+1));return}if(a.tab){v("/"+(gn[an]?.name??"")+" "),Tt(0);return}if(a.return){let i=gn[an];if(i){let h=T.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Ya(i.usage)&&!h){v("/"+i.name+" "),Tt(0);return}ao("/"+i.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(T!==""&&St===null){lo(-1);return}let i=yr.current;if(!i.length)return;let h=St===null?i.length-1:Math.max(0,St-1);Gn(h),v(i[h]??"");return}if(a.downArrow){if(T!==""&&St===null){lo(1);return}let i=yr.current;if(St===null)return;let h=St+1;h>=i.length?(Gn(null),v("")):(Gn(h),v(i[h]??""));return}}if(a.return){ao();return}if(a.backspace||a.delete){P();return}if(a.escape){v(""),Tt(0),Le(),ct([]),ln(null),Hn.current=!0;return}c&&!a.ctrl&&!a.meta&&Zi(c)}}}),Te(()=>{if(N||M)return;let c=wt.current.shift();c!==void 0&&(br([...wt.current]),ao(c))},[N,M,ao]),K(ne,{flexDirection:"column",width:Me,children:[Sr!==null&&K(ne,{marginTop:1,flexDirection:"column",children:[Sr.truncated&&E(j,{dimColor:!0,children:"\u2026"}),E(j,{children:Sr.text})]}),N&&(Kn?E(kw,{p:Kn}):E(gw,{startTime:dt.current,chars:Fd})),!N&&Wi?E(ww,{text:Wi}):null,E(ne,{borderStyle:"round",borderColor:Yi.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:T?ea.map((c,a)=>{let i=k.text.slice(c.start,c.end),h=a===cr(ea,k.pos),u=Math.min(k.pos,c.end)-c.start;return K(j,{children:[E(j,{color:q,children:a===0?"> ":" "}),h?K(fr,{children:[i.slice(0,u),E(on,{ch:i[u]??" "}),i.slice(u+1)]}):i||" "]},`${a}-${c.start}`)}):K(j,{children:[E(j,{color:q,children:"> "}),vr?E(on,{ch:" "}):he&&!N&&Ke?K(fr,{children:[E(on,{ch:Ke[0],dim:!0}),E(j,{color:"gray",children:Ke.slice(1)})]}):he&&!N?K(fr,{children:[E(on,{ch:he[0],dim:!0}),E(j,{color:"gray",children:he.slice(1)}),E(j,{dimColor:!0,children:" (tab)"})]}):(Tr.isSetup||!Ud)&&!N?K(fr,{children:[E(on,{ch:Tr.text[0],dim:!0}),E(j,{color:"gray",children:Tr.text.slice(1)})]}):E(on,{ch:" "})]})}),Ui.length>0&&E(ne,{flexDirection:"column",paddingX:1,children:Ui.map((c,a)=>E(j,{color:"gray",children:`\u29D7 queued: ${c}`},`${a}-${c.slice(0,24)}`))}),Qn?E(Kc,{tab:Qn.tab,width:Me,version:o,engineVersion:jd}):pt?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Select model"}),E(j,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),We.map((c,a)=>K(j,{color:a===pt.cursor?q:void 0,children:[a===pt.cursor?"\u276F ":" ",`${a+1}. ${c.label}${a===pt.current?" \u2714":""}`.padEnd(16),E(j,{color:"gray",children:c.desc})]},c.label)),E(j,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):He?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Switch connection profile"}),He.rows.map((c,a)=>K(j,{color:a===He.cursor?q:void 0,children:[a===He.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===He.current?" \u2714":""}`.padEnd(20),E(j,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?E(j,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),E(j,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):qe?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Pick your Document360 environment"}),qe.rows.map((c,a)=>K(j,{color:a===qe.cursor?q:void 0,children:[a===qe.cursor?"\u276F ":" ",`${a+1}. ${c.name}`.padEnd(16),E(j,{color:"gray",children:c.apiUrl})]},c.name)),E(j,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):me?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Switch workspace"}),E(j,{dimColor:!0,children:`environment ${me.environment} \xB7 project ${me.projectName??`${me.projectId.slice(0,8)}\u2026`}`}),me.rows.map((c,a)=>K(j,{color:a===me.cursor?q:void 0,children:[a===me.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===me.current?" \u2714":""}`.padEnd(30),E(j,{color:"gray",children:c.type??""})]},c.id)),E(j,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ve?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Choose project"}),E(j,{dimColor:!0,children:`environment ${ve.environment}`}),ve.rows.map((c,a)=>K(j,{color:a===ve.cursor?q:void 0,children:[a===ve.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===ve.current?" \u2714":""}`.padEnd(30),E(j,{color:"gray",children:c.sub??""})]},c.id)),E(j,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):we?(()=>{let a=Math.min(Math.max(0,we.cursor-Math.floor(7)),Math.max(0,we.rows.length-14)),i=we.rows.slice(a,a+14),h=we.rows.filter(u=>u.checked).length;return K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Which folders back the user docs? (${h} selected of ${we.rows.length})`}),a>0?E(j,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((u,y)=>{let b=a+y;return K(j,{color:b===we.cursor?q:void 0,children:[b===we.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Me-34)),E(j,{color:"gray",children:Io(u)})]},u.path)}),a+14<we.rows.length?E(j,{dimColor:!0,children:` \u2193 ${we.rows.length-a-14} more`}):null,E(j,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Be?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Which category? (pick one to scope to)"}),Be.rows.map((c,a)=>{let i=a===Be.cursor,h=`${a+1}.`.padEnd(3);return K(j,{color:i?q:void 0,children:[i?"\u276F ":" ",`${h} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Me-24))),E(j,{color:"gray",children:` ${c.token}`})]},c.token)}),E(j,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Xe?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Xe.rows.map((c,a)=>{let i=a===Xe.cursor,h=c.indent?" ":" ",u=`${a+1}.`.padEnd(3);return K(j,{color:i?q:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${h}${u} ${c.label}`.padEnd(Math.min(56,Me-24)),c.note?E(j,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),E(j,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):$e?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Preview article${$e.query?` \u2014 filter: ${$e.query}`:" (type to filter)"}`}),no.length===0?E(j,{color:"gray",children:"no articles match"}):no.map((c,a)=>K(j,{color:a===$e.cursor?q:void 0,children:[a===$e.cursor?"\u276F ":" ",c]},c)),E(j,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):xe?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Resume session${xe.query?` \u2014 filter: ${xe.query}`:" (type to filter)"}`}),oo.length===0?E(j,{color:"gray",children:"no sessions match"}):oo.map((c,a)=>K(j,{color:a===xe.cursor?q:void 0,children:[a===xe.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),E(j,{color:a===xe.cursor?q:"gray",children:c.firstPrompt.slice(0,Math.max(10,Me-40))})]},c.uuid)),E(j,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):zi?K(ne,{flexDirection:"column",children:[gn.map((c,a)=>K(j,{color:a===an?q:void 0,children:[a===an?"\u276F ":" ",c.usage.padEnd(22)," ",E(j,{color:a===an?q:"gray",children:c.name==="model"&&$r?`${c.desc} (currently ${$r})`:c.desc})]},c.name)),E(j,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!T&&lt.length>0?K(ne,{flexDirection:"column",paddingX:1,children:[Mi?E(j,{color:q,children:Mi}):null,lt.map((c,a)=>{let i=Ct(c),h=i.slice(0,Math.max(20,Me-5)),u=Me-h.length-7,y=u>=12?(ed(c)??Va(i)).slice(0,u):"";return K(j,{children:[E(j,{color:q,children:a+1})," ",h,y?E(j,{dimColor:!0,children:` \u2014 ${y}`}):null]},i)}),E(j,{dimColor:!0,children:`press 1-${lt.length} to fill \xB7 esc cancel`})]}):E(ne,{paddingX:1,children:K(j,{color:"gray",children:[Yi.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${$r??"model n/a"}${t.kind==="api"?qi>0?` \xB7 ${be(qi)}`:"":Hi>0?` \xB7 ${rt(Hi)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as xw}from"react/jsx-runtime";async function Nd(e=process.cwd(),t="auto",n,o="0.0.0"){let r=$w(t);r.kind==="none"&&(console.error(""),console.error(R("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=vw(xw(Ed,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
414
- `),process.exit(0)}W();import{writeCrashLog as Id,isBenignTransportError as Cw}from"document360-engine";var _d=!1;function Ai(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Od(e){if(_d)return;_d=!0;let t=(n,o)=>{if(Cw(o)){Id({kind:n,level:"transport",message:Ai(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=Id({kind:n,level:"fatal",message:Ai(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
415
- `+R(`\u2717 d360-writer crashed: ${Ai(o)}`)+`
412
+ `)}),Wt(bt()),hn.current=Ee(e).status==="current",Ft.current=Ge(e);return}case"discover":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await re(rs(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(qs(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 re(Bs(),{display:"/inbox",quietUser:!0});return}case"feedback":{let u=$d(e),y="";try{y=nn(u)?dr(u,"utf8"):""}catch{y=""}if(!/^## /m.test(y)){d({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let b=await yi(y.trim());d({kind:"note",tone:b?"ok":"warn",text:b?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${u} and copy it manually.`}),b&&Pr(null);return}case"document":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:y}=Es(h);if(!y&&As(e)===0){d({kind:"note",tone:"info",text:Is});return}let b=`/document${y?` ${y}`:""}${u?" --publish":""}`;await re(Ns(y,u),{display:b,quietUser:!0});return}case"catch-up":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Zn(c.trim()))return;let{publish:u}=Gs(h);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let y=await zs({cwd:e,profileName:s});for(let w of Ks(y))d({kind:"note",tone:w.startsWith("\u2713")?"ok":w.startsWith("\u2139")?"info":"warn",text:w});let b=In(Nn(e));d({kind:"note",tone:"info",text:b?`Catching up on ${b}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await re(Ys({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{Cr.current=!0,d({kind:"note",tone:"info",text:`Updating ${xt}\u2026 (don\u2019t close this window)`}),Vn(!0),(await Bo().finally(()=>Vn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),Q("/exit"),Li("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${qo}`});return}case"screenshot":{let u=Us(h);if(u.mode==="list"){if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Fs(Ws(e,u.scope),u.scope).join(`
413
+ `)});return}if(u.mode==="single"){let I=await Fo(h);I.kind==="forward-to-agent"&&I.prompt&&await re(I.prompt,{display:I.display,quietUser:!0});return}if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=u.mode==="scope"?u.scope:void 0,b=Jg(e,{scope:y}).map(I=>I.id);if(b.length===0){d({kind:"note",tone:"info",text:y?`No screenshot placeholders under ${y}.`:"No screenshot placeholders found in the docs."});return}let w=6,$=Qg(b,3),x=pr(e,"standard");dt.current=Date.now(),Pt(0),T(!0);let G=new AbortController;je.current=G,oe({verb:"Authoring",unit:"spec",total:$.length,done:0,active:[],rows:Un($),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${b.length} screenshot spec${b.length===1?"":"s"} across ${$.length} partition${$.length===1?"":"s"} (\u2264${w} agents at once) on ${x.model}${x.forced?" (forced)":""}\u2026 (esc to stop)`});let H=!1;try{for await(let I of ur({cwd:e,partitions:$,promptFor:sc,concurrency:w,profileName:s,allowProdWrites:jt.current,model:x.model,signal:G.signal}))if(I.type==="partition_status")I.status==="running"?oe(C=>C&&{...C,active:[...C.active,I.label],rows:ze(C.rows,I.label,"active"),lastAt:Date.now()}):oe(C=>C&&{...C,active:C.active.filter(A=>A!==I.label),done:C.done+1,rows:ze(C.rows,I.label,I.status==="done"?"done":"failed"),lastAt:Date.now()});else if(I.type==="partition_event")oe(C=>{if(!C)return C;let A={...C,lastAt:Date.now()};return I.event.type==="tool"?A.tools=C.tools+1:I.event.type==="text"&&(A.chars=C.chars+I.event.delta.length),A});else if(I.type==="run_done"){Mt(J=>J+I.totalCostUsd),Ot(J=>J+I.results.reduce((ye,Vt)=>ye+Vt.outputTokens,0));let C=I.results.filter(J=>J.ok).length,A=I.aborted?"Stopped. ":"";H=!I.aborted&&u.setup;let U=I.aborted?"":H?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:I.aborted?"warn":I.ok?"ok":"warn",text:`${A}Authored specs \u2014 ${C}/${I.results.length} batches ok.${U}`})}}catch(I){d({kind:"note",tone:"error",text:`Spec authoring failed: ${I.message}`})}finally{je.current=null,oe(null),T(!1),Y(I=>I+1)}if(H){let I=await En();I.kind==="forward-to-agent"&&I.prompt&&await re(I.prompt,{display:I.display,quietUser:!0});let C=Hs(e);C&&d({kind:"note",tone:"info",text:C.join(`
414
+ `)})}return}case"reset":{let u=Js(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}zn.current={repoName:Wn(e),targets:u,hadDevhints:nn(vd(e))},d({kind:"note",tone:"warn",text:ei(e,u).join(`
415
+ `)}),ge(Wn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,qt,Nr,d,Ce,re,Ht,Dr,Qi]),ao=z(c=>{let a=(c??S).trim();if(v(""),Gn(null),St(0),a.startsWith("/")&&(Hn.current=!1,Oe(),ln(null),ct(h=>nd(h,a))),!a||(_i(!1),Zi(a))||Ji(a))return;yr.current.push(a);let i=id(a,Oi.current);if(a.startsWith("/"))d({kind:"user",text:a}),_e(!0),wn(i).finally(()=>_e(!1));else if(lw(i)){d({kind:"user",text:a});let h=cw(i);if(!h)re(i,{display:a,quietUser:!0});else{try{dw(e,{title:h,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}re(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${h}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${h}" and the article path(s) you wrote.`,{display:a,quietUser:!0})}}else{let h=Rc(e,i);re(h??i,{display:a})}},[S,Zi,Ji,wn,re]),ea=z(c=>{if(c.length>1){if(c.includes("\x1B"))return;let a=od(c);if(rd(a)){let i=sd(++qd.current,a);Oi.current.set(i,a),_(i)}else _(a);return}_(c)},[_]),Bt=Math.max(10,Me-6),ta=xi(()=>lr(k.text,Bt),[k.text,Bt]),Ir=z(c=>g(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+c))})),[]),lo=z(c=>g(a=>({...a,pos:ld(lr(a.text,Bt),a.pos,c)})),[Bt]),yn=z(c=>g(a=>({...a,pos:cd(lr(a.text,Bt),a.pos,c)})),[Bt]),Yd=["\x1B[H","\x1B[1~","\x1BOH"],zd=["\x1B[F","\x1B[4~","\x1BOF"],na=z((c,a)=>a.leftArrow?(Ir(-1),!0):a.rightArrow?(Ir(1),!0):c&&Yd.includes(c)?(yn("start"),!0):c&&zd.includes(c)?(yn("end"),!0):a.ctrl&&c==="a"?(yn("start"),!0):a.ctrl&&c==="e"?(yn("end"),!0):!1,[Ir,yn]);return xg((c,a)=>{if(a.ctrl&&c==="c"){De.current?.close(),r();return}if(!M){if(N){if(a.escape){if(je.current){if(!je.current.signal.aborted){let i=(Kn?.verb??"work").toLowerCase(),h=Kn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${h}s)\u2026`}),je.current.abort()}return}cn.current||(cn.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),De.current?.interrupt());return}if(a.return){let i=S.trim();if(!i)return;wt.current.push(i),br([...wt.current]),v("");return}if(na(c,a))return;if(a.upArrow){lo(-1);return}if(a.downArrow){lo(1);return}if(a.backspace||a.delete){P();return}c&&!a.ctrl&&!a.meta&&ea(c);return}if(pt){if(a.upArrow){ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ft(i=>i&&{...i,cursor:Math.min(We.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=We.length){ft(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=We[pt.cursor];ft(null);let{lines:h,changed:u,effective:y}=jn(e,i.value??"default");for(let b of h)d({kind:"note",tone:b.startsWith("\u26A0")?"warn":b.startsWith("\u2713")?"ok":"info",text:b});u&&(Vi(b=>b+1),De.current?.setModel(y));return}if(c==="s"){let i=We[pt.cursor];ft(null),De.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){ft(null);return}return}if(He){if(a.upArrow){Et(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Et(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=He.rows.length){Et(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return||c==="s"){let i=He.rows[He.cursor];Et(null),Ar(i.name,a.return===!0);return}if(a.escape){Et(null);return}return}if(Qn){if(a.escape){pn(null);return}if(a.leftArrow||a.tab&&a.shift){pn(i=>i&&{tab:(i.tab-1+Ae.length)%Ae.length});return}if(a.rightArrow||a.tab){pn(i=>i&&{tab:(i.tab+1)%Ae.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ae.length){pn({tab:Number(c)-1});return}return}if(qe){if(a.upArrow){Nt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Nt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=qe.rows.length){Nt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=qe.rows[qe.cursor].name;if(Nt(null),!qr(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let u=!1;try{let y=Rt(i);u=!!y&&!(at(y)&&!y.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${i} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${i}) and pick your project.`}),Q("/login"),Y(y=>y+1);return}if(a.escape){Nt(null);return}return}if(me){if(a.upArrow){It(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){It(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=me.rows.length){It(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=me.rows[me.cursor],{profile:h,projectId:u}=me;It(null),ro(h,u,i);return}if(a.escape){It(null);return}return}if(ve){if(a.upArrow){ht(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ht(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ve.rows.length){ht(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=ve.rows[ve.cursor],{profile:h}=ve;ht(null),io(h,i);return}if(a.escape){ht(null);return}return}if(we){if(a.upArrow){Lt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Lt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){Lt(i=>i&&{...i,rows:i.rows.map((h,u)=>u===i.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let i=we.rows.filter(h=>h.checked).map(h=>h.path);if(Lt(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}ss(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of i)d({kind:"note",tone:"info",text:` ${h}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){Lt(null);return}return}if(Be){if(a.upArrow){mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){mt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Be.rows.length){mt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Be.rows[Be.cursor],h=Be.run;mt(null),h(i.token);return}if(a.escape){mt(null);return}return}if(Xe){if(a.upArrow){_t(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){_t(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Xe.rows.length){_t(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Xe.rows[Xe.cursor];_t(null),i.conflict?Nr(i.paths[0]):i.kind==="article"?Dr(i.paths[0]):Ht(i.paths);return}if(a.escape){_t(null);return}return}if($e){if(a.escape){gt(null);return}if(a.upArrow){gt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){gt(i=>i&&{...i,cursor:Math.min(Math.max(0,no.length-1),i.cursor+1)});return}if(a.return){let i=no[$e.cursor];if(i){gt(null);try{d({kind:"preview",name:Wn(i),text:jd(dr(Ci(e,i),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${i}: ${h.message}`})}}return}if(a.backspace||a.delete){gt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){gt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(xe){if(a.escape){yt(null);return}if(a.upArrow){yt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){yt(i=>i&&{...i,cursor:Math.min(Math.max(0,oo.length-1),i.cursor+1)});return}if(a.return){let i=oo[xe.cursor];if(i){yt(null),Ce(i.uuid),Fe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},ut(i.name),Ri(i.uuid),Dt.current=[];let h=bi(e,i.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${i.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){yt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){yt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(a.tab&&!S&&he){v(he),Oe();return}if(!S&&lt.length>0&&!gr&&c&&/^[1-9]$/.test(c)){let i=lt[Number(c)-1];if(i){v(Ct(i));return}}if(!S&&(eo||fn)&&c==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let i=eo!=null;yi(eo??fn).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?i?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":i?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&i&&Pr(null),u&&!i&&Yi(!0)});return}if(!na(c,a)){if(Ki){if(a.upArrow){St(i=>Math.max(0,i-1));return}if(a.downArrow){St(i=>Math.min(gn.length-1,i+1));return}if(a.tab){v("/"+(gn[an]?.name??"")+" "),St(0);return}if(a.return){let i=gn[an];if(i){let h=S.trim().slice(1).split(/\s+/).slice(1).join(" ");if(za(i.usage)&&!h){v("/"+i.name+" "),St(0);return}ao("/"+i.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(S!==""&&Tt===null){lo(-1);return}let i=yr.current;if(!i.length)return;let h=Tt===null?i.length-1:Math.max(0,Tt-1);Gn(h),v(i[h]??"");return}if(a.downArrow){if(S!==""&&Tt===null){lo(1);return}let i=yr.current;if(Tt===null)return;let h=Tt+1;h>=i.length?(Gn(null),v("")):(Gn(h),v(i[h]??""));return}}if(a.return){ao();return}if(a.backspace||a.delete){P();return}if(a.escape){v(""),St(0),Oe(),ct([]),ln(null),Hn.current=!0;return}c&&!a.ctrl&&!a.meta&&ea(c)}}}),Se(()=>{if(N||M)return;let c=wt.current.shift();c!==void 0&&(br([...wt.current]),ao(c))},[N,M,ao]),K(ne,{flexDirection:"column",width:Me,children:[Tr!==null&&K(ne,{marginTop:1,flexDirection:"column",children:[Tr.truncated&&E(j,{dimColor:!0,children:"\u2026"}),E(j,{children:Tr.text})]}),N&&(Kn?E(bw,{p:Kn}):E(ww,{startTime:dt.current,chars:Hd})),!N&&Fi?E(yw,{text:Fi}):null,E(ne,{borderStyle:"round",borderColor:zi.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:S?ta.map((c,a)=>{let i=k.text.slice(c.start,c.end),h=a===cr(ta,k.pos),u=Math.min(k.pos,c.end)-c.start;return K(j,{children:[E(j,{color:q,children:a===0?"> ":" "}),h?K(fr,{children:[i.slice(0,u),E(on,{ch:i[u]??" "}),i.slice(u+1)]}):i||" "]},`${a}-${c.start}`)}):K(j,{children:[E(j,{color:q,children:"> "}),vr?E(on,{ch:" "}):he&&!N&&Ke?K(fr,{children:[E(on,{ch:Ke[0],dim:!0}),E(j,{color:"gray",children:Ke.slice(1)})]}):he&&!N?K(fr,{children:[E(on,{ch:he[0],dim:!0}),E(j,{color:"gray",children:he.slice(1)}),E(j,{dimColor:!0,children:" (tab)"})]}):(Sr.isSetup||!Wd)&&!N?K(fr,{children:[E(on,{ch:Sr.text[0],dim:!0}),E(j,{color:"gray",children:Sr.text.slice(1)})]}):E(on,{ch:" "})]})}),Wi.length>0&&E(ne,{flexDirection:"column",paddingX:1,children:Wi.map((c,a)=>E(j,{color:"gray",children:`\u29D7 queued: ${c}`},`${a}-${c.slice(0,24)}`))}),Qn?E(Xc,{tab:Qn.tab,width:Me,version:o,engineVersion:Ad}):pt?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Select model"}),E(j,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),We.map((c,a)=>K(j,{color:a===pt.cursor?q:void 0,children:[a===pt.cursor?"\u276F ":" ",`${a+1}. ${c.label}${a===pt.current?" \u2714":""}`.padEnd(16),E(j,{color:"gray",children:c.desc})]},c.label)),E(j,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):He?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Switch connection profile"}),He.rows.map((c,a)=>K(j,{color:a===He.cursor?q:void 0,children:[a===He.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===He.current?" \u2714":""}`.padEnd(20),E(j,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?E(j,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),E(j,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):qe?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Pick your Document360 environment"}),qe.rows.map((c,a)=>K(j,{color:a===qe.cursor?q:void 0,children:[a===qe.cursor?"\u276F ":" ",`${a+1}. ${c.name}`.padEnd(16),E(j,{color:"gray",children:c.apiUrl})]},c.name)),E(j,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):me?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Switch workspace"}),E(j,{dimColor:!0,children:`environment ${me.environment} \xB7 project ${me.projectName??`${me.projectId.slice(0,8)}\u2026`}`}),me.rows.map((c,a)=>K(j,{color:a===me.cursor?q:void 0,children:[a===me.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===me.current?" \u2714":""}`.padEnd(30),E(j,{color:"gray",children:c.type??""})]},c.id)),E(j,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ve?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Choose project"}),E(j,{dimColor:!0,children:`environment ${ve.environment}`}),ve.rows.map((c,a)=>K(j,{color:a===ve.cursor?q:void 0,children:[a===ve.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===ve.current?" \u2714":""}`.padEnd(30),E(j,{color:"gray",children:c.sub??""})]},c.id)),E(j,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):we?(()=>{let a=Math.min(Math.max(0,we.cursor-Math.floor(7)),Math.max(0,we.rows.length-14)),i=we.rows.slice(a,a+14),h=we.rows.filter(u=>u.checked).length;return K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Which folders back the user docs? (${h} selected of ${we.rows.length})`}),a>0?E(j,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((u,y)=>{let b=a+y;return K(j,{color:b===we.cursor?q:void 0,children:[b===we.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Me-34)),E(j,{color:"gray",children:Io(u)})]},u.path)}),a+14<we.rows.length?E(j,{dimColor:!0,children:` \u2193 ${we.rows.length-a-14} more`}):null,E(j,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Be?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Which category? (pick one to scope to)"}),Be.rows.map((c,a)=>{let i=a===Be.cursor,h=`${a+1}.`.padEnd(3);return K(j,{color:i?q:void 0,children:[i?"\u276F ":" ",`${h} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Me-24))),E(j,{color:"gray",children:` ${c.token}`})]},c.token)}),E(j,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Xe?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Xe.rows.map((c,a)=>{let i=a===Xe.cursor,h=c.indent?" ":" ",u=`${a+1}.`.padEnd(3);return K(j,{color:i?q:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${h}${u} ${c.label}`.padEnd(Math.min(56,Me-24)),c.note?E(j,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),E(j,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):$e?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Preview article${$e.query?` \u2014 filter: ${$e.query}`:" (type to filter)"}`}),no.length===0?E(j,{color:"gray",children:"no articles match"}):no.map((c,a)=>K(j,{color:a===$e.cursor?q:void 0,children:[a===$e.cursor?"\u276F ":" ",c]},c)),E(j,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):xe?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Resume session${xe.query?` \u2014 filter: ${xe.query}`:" (type to filter)"}`}),oo.length===0?E(j,{color:"gray",children:"no sessions match"}):oo.map((c,a)=>K(j,{color:a===xe.cursor?q:void 0,children:[a===xe.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),E(j,{color:a===xe.cursor?q:"gray",children:c.firstPrompt.slice(0,Math.max(10,Me-40))})]},c.uuid)),E(j,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Ki?K(ne,{flexDirection:"column",children:[gn.map((c,a)=>K(j,{color:a===an?q:void 0,children:[a===an?"\u276F ":" ",c.usage.padEnd(22)," ",E(j,{color:a===an?q:"gray",children:c.name==="model"&&$r?`${c.desc} (currently ${$r})`:c.desc})]},c.name)),E(j,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!S&&lt.length>0?K(ne,{flexDirection:"column",paddingX:1,children:[Ui?E(j,{color:q,children:Ui}):null,lt.map((c,a)=>{let i=Ct(c),h=i.slice(0,Math.max(20,Me-5)),u=Me-h.length-7,y=u>=12?(td(c)??Ga(i)).slice(0,u):"";return K(j,{children:[E(j,{color:q,children:a+1})," ",h,y?E(j,{dimColor:!0,children:` \u2014 ${y}`}):null]},i)}),E(j,{dimColor:!0,children:`press 1-${lt.length} to fill \xB7 esc cancel`})]}):E(ne,{paddingX:1,children:K(j,{color:"gray",children:[zi.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${$r??"model n/a"}${t.kind==="api"?Bi>0?` \xB7 ${be(Bi)}`:"":qi>0?` \xB7 ${rt(qi)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Cw}from"react/jsx-runtime";async function Id(e=process.cwd(),t="auto",n,o="0.0.0"){let r=xw(t);r.kind==="none"&&(console.error(""),console.error(R("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${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}=$w(Cw(Nd,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
416
+ `),process.exit(0)}W();import{writeCrashLog as _d,isBenignTransportError as Rw}from"document360-engine";var Ld=!1;function Ei(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Od(e){if(Ld)return;Ld=!0;let t=(n,o)=>{if(Rw(o)){_d({kind:n,level:"transport",message:Ei(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=_d({kind:n,level:"fatal",message:Ei(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
417
+ `+R(`\u2717 d360-writer crashed: ${Ei(o)}`)+`
416
418
  `),r&&process.stderr.write(f(` Crash details: ${r}`)+`
417
419
  `+f(" Run: d360-writer logs")+`
418
- `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Sw=Pw(import.meta.url),hr=Sw("../package.json");Od("d360-writer");var Ie=new Rw;function Ei(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Ie.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=>{Ei(e),await wo({profile:e.profile,manual:e.manual})});Ie.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ei(e),await fa({profile:e.profile})});Ie.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ei(e),await pa({profile:e.profile})});var Ni=Ie.command("profile").description("Manage connection profiles for the current repo");Ni.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>yo(process.cwd()));Ni.command("use <name>").description("Set the default profile for this repo").action(e=>ko(process.cwd(),e));Ni.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>bo(process.cwd(),e));var Ld=Ie.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Ld.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Gt(process.cwd(),e.profile));Ld.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await sa(process.cwd(),e,t.profile)});var Md=Ie.command("project").description("Choose the Document360 project for this repo (active profile's identity)");Md.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>ho(process.cwd(),e.profile));Md.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await aa(process.cwd(),e,t.profile)});Ie.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Po(),Ha));await e()});Ie.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>wa());Ie.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(()=>(Wo(),Xl)),n=await t(process.cwd(),hr.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Ie.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(hr.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(Tw.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 ya(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 Fc(e.cwd,e.auth,e.profile,hr.version):await Nd(e.cwd,e.auth,e.profile,hr.version)});Ie.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
420
+ `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Dw=Sw(import.meta.url),hr=Dw("../package.json");Od("d360-writer");var Ie=new Pw;function Ni(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Ie.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=>{Ni(e),await wo({profile:e.profile,manual:e.manual})});Ie.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ni(e),await ha({profile:e.profile})});Ie.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ni(e),await fa({profile:e.profile})});var Ii=Ie.command("profile").description("Manage connection profiles for the current repo");Ii.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>yo(process.cwd()));Ii.command("use <name>").description("Set the default profile for this repo").action(e=>ko(process.cwd(),e));Ii.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>bo(process.cwd(),e));var Md=Ie.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Md.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Gt(process.cwd(),e.profile));Md.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await ia(process.cwd(),e,t.profile)});var Ud=Ie.command("project").description("Choose the Document360 project for this repo (active profile's identity)");Ud.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>ho(process.cwd(),e.profile));Ud.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await la(process.cwd(),e,t.profile)});Ie.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Po(),qa));await e()});Ie.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>ya());Ie.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(()=>(Wo(),Ql)),n=await t(process.cwd(),hr.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Ie.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(hr.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(Tw.includes(e.auth)||(console.error(`\u2717 Invalid --auth mode: ${e.auth}`),console.error("Run: d360-writer --auth auto | api | subscription"),process.exit(2)),e.prompt){await ka(e.cwd,e.prompt,e.auth,e.resume,e.profile,e.yes);return}e.resume&&(console.error("\u2717 --resume requires --prompt. In the interactive REPL, use /resume instead."),process.exit(2)),e.classic||!process.stdin.isTTY?await Hc(e.cwd,e.auth,e.profile,hr.version):await Id(e.cwd,e.auth,e.profile,hr.version)});Ie.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});