document360-writer 0.5.128 → 0.5.129

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 +91 -91
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var bu=Object.defineProperty;var mo=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var ma=(e,t)=>{for(var n in t)bu(e,n,{get:t[n],enumerable:!0})};import tt from"picocolors";var q,$u,xu,vu,ga,xn,m,C,O,j,_,ie,ke,W=mo(()=>{"use strict";q="#7f56d9",[$u,xu,vu]=[127,86,217],ga=e=>tt.isColorSupported?`\x1B[38;2;${$u};${xu};${vu}m${e}\x1B[39m`:e,xn=e=>tt.bold(ga(e)),m=e=>tt.dim(e),C=e=>tt.red(e),O=e=>tt.yellow(e),j=e=>tt.green(e),_=ga,ie=e=>tt.gray(e),ke=e=>tt.bold(e)});import{existsSync as Xt,writeFileSync as ot,readFileSync as lp,readdirSync as cp}from"node:fs";import{join as Ia}from"node:path";import{devHintsGuidePath as Ro,hintsDir as _a,hooksDir as Oa,architectureDir as Fa,messagesDir as Gr,creatorNotesPath as La,devhintsStatePath as Ha,directivesPath as Ma,DIRECTIVES_HEADER as dp,roadmapPath as Ua,ROADMAP_HEADER as up,ensureDir as Rn,writeMessage as pp,listOpenForDev as hp}from"document360-engine";function qa(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var xu=Object.defineProperty;var mo=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var ma=(e,t)=>{for(var n in t)xu(e,n,{get:t[n],enumerable:!0})};import tt from"picocolors";var q,vu,Cu,Ru,ga,xn,m,C,O,E,_,ie,be,W=mo(()=>{"use strict";q="#7f56d9",[vu,Cu,Ru]=[127,86,217],ga=e=>tt.isColorSupported?`\x1B[38;2;${vu};${Cu};${Ru}m${e}\x1B[39m`:e,xn=e=>tt.bold(ga(e)),m=e=>tt.dim(e),C=e=>tt.red(e),O=e=>tt.yellow(e),E=e=>tt.green(e),_=ga,ie=e=>tt.gray(e),be=e=>tt.bold(e)});import{existsSync as Xt,writeFileSync as ot,readFileSync as dp,readdirSync as up}from"node:fs";import{join as Ia}from"node:path";import{devHintsGuidePath as Ro,hintsDir as _a,hooksDir as Oa,architectureDir as Fa,messagesDir as Gr,creatorNotesPath as La,devhintsStatePath as Ha,directivesPath as Ma,DIRECTIVES_HEADER as pp,roadmapPath as Ua,ROADMAP_HEADER as hp,ensureDir as Rn,writeMessage as fp,listOpenForDev as mp}from"document360-engine";function qa(){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 mp(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
221
+ `}function wp(){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
@@ -233,11 +233,11 @@ Anything only a human knows that would help document this product. For example:
233
233
 
234
234
  (Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
235
235
  `}function Jt(e){Rn(_a(e)),Rn(Fa(e)),Rn(Gr(e));for(let n of[_a(e),Gr(e)]){let o=Ia(n,".gitkeep");Xt(o)||ot(o,`# Keeps this document360-writer inbox tracked in git even when empty.
236
- `)}Xt(La(e))||ot(La(e),mp()),Xt(Ma(e))||ot(Ma(e),dp),Xt(Ua(e))||ot(Ua(e),up),ot(Ro(e),qa()),Rn(Oa(e)),ot(Ia(Oa(e),"open-questions.mjs"),fp);let t=Ie(e);return Va(e,new Date().toISOString()),t}async function Ba(e,t){for(let n of Zt(Jt(t.cwd)))console.log(n);return{kind:"continue"}}function vt(){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 Yr(e){try{let t=lp(Ha(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Va(e,t){let o={...Yr(e)??{},emittedVersion:ae,emittedAt:t};ot(Ha(e),`${JSON.stringify(o,null,2)}
238
- `)}function ze(e){try{return cp(Fa(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ie(e){let n=Yr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ae?"stale":"current",completedVersion:n}}function So(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ae};try{if(!Xt(Ro(e)))return n;let o=Yr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;ae>r&&(Rn(Gr(e)),ot(Ro(e),qa()),Va(e,t),n.guideRefreshed=!0),ae>s&&(hp(e).some(p=>p.kind==="request"&&p.subject.startsWith(Wa))||(pp(e,{id:`onb${ae}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Wa}${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:","",vt()].join(`
236
+ `)}Xt(La(e))||ot(La(e),wp()),Xt(Ma(e))||ot(Ma(e),pp),Xt(Ua(e))||ot(Ua(e),hp),ot(Ro(e),qa()),Rn(Oa(e)),ot(Ia(Oa(e),"open-questions.mjs"),gp);let t=Ie(e);return Va(e,new Date().toISOString()),t}async function Ba(e,t){for(let n of Zt(Jt(t.cwd)))console.log(n);return{kind:"continue"}}function vt(){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 Yr(e){try{let t=dp(Ha(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Va(e,t){let o={...Yr(e)??{},emittedVersion:ae,emittedAt:t};ot(Ha(e),`${JSON.stringify(o,null,2)}
238
+ `)}function ze(e){try{return up(Fa(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ie(e){let n=Yr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ae?"stale":"current",completedVersion:n}}function So(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ae};try{if(!Xt(Ro(e)))return n;let o=Yr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;ae>r&&(Rn(Gr(e)),ot(Ro(e),qa()),Va(e,t),n.guideRefreshed=!0),ae>s&&(mp(e).some(p=>p.kind==="request"&&p.subject.startsWith(Wa))||(fp(e,{id:`onb${ae}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Wa}${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:","",vt()].join(`
239
239
  `)}),n.notifiedBuilder=!0))}catch{}return n}function Po(e){if(!Xt(Ro(e)))return[];let t=Ie(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${ae}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Qt,vt(),Qt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function zr(){return['document360-writer (its "docs agent") has been removed from this repository. Please undo its dev\u2192docs',"hand-off setup and restore this repo to how it was before \u2014 in order:","","1. In this repo's agent-memory file (CLAUDE.md, or AGENTS.md \u2014 whichever it edited), REMOVE the",' "Documentation hand-off" section that was added (the rule about dropping hint files in'," `.d360-writer/hints/`, keeping `.d360-writer/architecture/` current, checking"," `.d360-writer/messages/`, and relaying `@d360-writer` directives to `.d360-writer/directives.md`)."," Leave everything else in that file untouched.","2. The `.d360-writer/` folder is already deleted on disk. If it was committed, remove it from version"," control too \u2014 `git rm -r --cached .d360-writer` (if it still resolves) \u2014 and commit the deletions.","3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
240
- `)}function To(){return['\u{1F9F9} One leftover: your builder still has the "Documentation hand-off" rule in its CLAUDE.md / AGENTS.md'," (reset only clears d360-writer's own .d360-writer/ folder \u2014 never your repo's files)."," To restore it, paste this prompt into your repo's coding agent (Claude Code / Codex / Cursor):",Qt,zr(),Qt]}function Zt(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):",Qt,vt(),Qt,"","That one run writes the architecture brief, adds the ongoing rule to your agent memory (CLAUDE.md / AGENTS.md)","and commits it so teammates inherit it, answers any open questions the writer left, and asks you for tribal","knowledge \u2014 no manual file edits. It also sets up the two-way channel: the writer can ask you questions","(`/inbox` on its side), and you can ask it to document a session on demand (Part 4 of the guide).","","When it finishes, come back to THIS terminal and run:"," write the docs for this repo"]}var Qt,ae,fp,Wa,rt=mo(()=>{"use strict";Qt="-".repeat(64),ae=10,fp=`#!/usr/bin/env node
240
+ `)}function To(){return['\u{1F9F9} One leftover: your builder still has the "Documentation hand-off" rule in its CLAUDE.md / AGENTS.md'," (reset only clears d360-writer's own .d360-writer/ folder \u2014 never your repo's files)."," To restore it, paste this prompt into your repo's coding agent (Claude Code / Codex / Cursor):",Qt,zr(),Qt]}function Zt(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):",Qt,vt(),Qt,"","That one run writes the architecture brief, adds the ongoing rule to your agent memory (CLAUDE.md / AGENTS.md)","and commits it so teammates inherit it, answers any open questions the writer left, and asks you for tribal","knowledge \u2014 no manual file edits. It also sets up the two-way channel: the writer can ask you questions","(`/inbox` on its side), and you can ask it to document a session on demand (Part 4 of the guide).","","When it finishes, come back to THIS terminal and run:"," write the docs for this repo"]}var Qt,ae,gp,Wa,rt=mo(()=>{"use strict";Qt="-".repeat(64),ae=10,gp=`#!/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,28 +275,28 @@ try {
275
275
  } catch {
276
276
  /* a session-start nudge must never break the session */
277
277
  }
278
- `;Wa="Re-run dev\u2194docs onboarding (protocol v"});var tl={};ma(tl,{initCommand:()=>Xr,scaffoldInit:()=>Kr});import{input as Sn,confirm as gp}from"@inquirer/prompts";import{basename as Ga,join as Do}from"node:path";import{existsSync as en,readFileSync as wp,readdirSync as yp,writeFileSync as kp}from"node:fs";import{writeProjectConfig as Ya,readProjectConfig as bp,projectConfigPath as za,writerDir as $p,DEFAULT_DOCS_DIR as Ka,DEFAULT_CAPTURE_DIR as Xa,DEFAULT_OUTPUT_DIR as Qa}from"document360-engine";function Kr(e,t="berlin"){let n=za(e);if(en(n))return{created:!1,path:n,profileName:""};let o={projectId:Za(e)??Ga(e),docsDir:Ka,captureDir:Xa,outputDir:Qa,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:el(e)};return Ya(o,e),Ja(e),{created:!0,path:n,profileName:t}}function Ja(e){let t=Do($p(e),".gitignore");en(t)||kp(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
279
- `),"utf8")}async function Xr(){let e=process.cwd(),t=za(e);if(en(t)&&!await gp({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(m("init cancelled.")),{kind:"continue"};let n=Za(e)??Ga(e),o=await Sn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Sn({message:"Capture directory (where document360-capture .spec.ts files live):",default:Xa}),s=await Sn({message:"Screenshot output directory:",default:Qa}),a=await Sn({message:"Default connection profile name:",default:"berlin"}),p=await Sn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:Ka,captureDir:r,outputDir:s,profiles:{[a]:{connection:{environment:p},production:!1}},defaultProfile:a,authoritativeSourceFiles:el(e)},k=bp(e);k?.terminologyGlossary&&(g.terminologyGlossary=k.terminologyGlossary),Ya(g,e),Ja(e);let y=Jt(e);console.log(""),console.log(j(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${a}`)} ${m("(sign in; project & workspace auto-selected)")}`),console.log("");for(let S of Zt(y))console.log(S);return console.log(""),console.log(`${m("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Za(e){let t=Do(e,"package.json");if(!en(t))return null;try{return JSON.parse(wp(t,"utf8")).name??null}catch{return null}}function el(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])en(Do(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Do(e,n);en(o)&&!xp(o)&&t.push(n)}return t}function xp(e){try{return yp(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Ao=mo(()=>{"use strict";W();rt()});var cc={};ma(cc,{doctorCommand:()=>In,renderDoctorChecks:()=>lc,runDoctorChecks:()=>ac});import{existsSync as ff}from"node:fs";import{d360GetAll as mf,getAccessToken as gf,isExpired as Vs,loadProfileMap as wf,loadTokens as yf,packageSkillsDir as sc,ENGINE_VERSION as kf,projectConfigPath as bf,readProjectConfig as $f,DEFAULT_DOCS_DIR as xf,fetchManifestSummary as vf,resolveActiveProfile as Cf,classifyClaudeAuth as Rf,CLAUDE_CODE_SETUP_HINT as ic,resolveModelSetting as Sf,probeModel as Pf,detectAppType as Tf,playbookSkillName as Df,D360AuthError as Af}from"document360-engine";async function ac(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=Rf();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. ${ic}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ic});let s=Sf(e);if(n.push({level:"ok",label:`Model: ${s.model} (${s.source==="auto"?"auto \u2014 right-sized for docs; /model to change":s.source})`}),r.state==="ready"){let R=await Pf(e,s.model??void 0);R.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(R.latencyMs/1e3).toFixed(1)}s`}):R.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${R.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let a=$f(e);if(!a)return n.push({level:"fail",label:`No ${bf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let p=(a.docsDir??xf).replace(/\/+$/,"");n.push(a.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let g=a.authoritativeSourceFiles??[];n.push(g.length>0?{level:"ok",label:`Sources: docs grounded in ${g.length} path(s) (${g.slice(0,3).join(", ")}${g.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let k=a.appType??Tf(e);if(k){let R=a.appType?"from config":"auto-detected",E=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${R})${E?` \u2192 ${Df(k)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let y;try{y=Cf(e),n.push({level:"ok",label:`Profile: ${y.name} (${y.connection.name})${y.production?" \u26A0 PRODUCTION":""}`})}catch(R){return n.push({level:"fail",label:`Profile config: ${R.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let S=yf(y.name);S?Vs(S)&&!S.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Vs(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 ${y.name})`}),n.push(y.project.workspaceId?{level:"ok",label:`Workspace: ${y.project.workspaceName??y.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let v=wf(e,y.name);v?v.projectId&&y.project.projectId&&v.projectId!==y.project.projectId?n.push({level:"fail",label:`Category map projectId (${v.projectId}) \u2260 profile projectId (${y.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(v.articles).length} articles, ${Object.keys(v.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${y.name}" (created on first /publish)`}),n.push(ff(sc())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${sc()}`,fix:"Reinstall document360-writer (broken install)"});let I=Ie(e);if(I.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ae})`}):I.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${I.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&&(!Vs(S)||S.refreshToken)){let R={profile:y.name,connection:y.connection};try{await gf(R);let T=await mf(R,"/v3/projects");n.push({level:"ok",label:`API reachable (${y.connection.apiUrl}) \u2014 ${T.length} project(s) visible`})}catch(T){n.push({level:"fail",label:`API call failed: ${T.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let E=v?.projectId??y.project.projectId;if(E&&y.project.workspaceId)try{let T=await vf(R,E,y.project.workspaceId);if(T){let L=(T.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${y.connection.name} (${T.languages?.length??0} language${(T.languages?.length??0)===1?"":"s"}) \xB7 hash ${L||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${y.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(T){T instanceof Af||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(T.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${y.project.projectName??E})`,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 lc(e){let t=[""];for(let r of e){let s=r.level==="ok"?j("\u2713"):r.level==="warn"?O("\u26A0"):C("\u2717");t.push(` ${s} ${r.label}${r.detail?m(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${m("fix:")} ${_(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?j(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):C(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function In(e,t){console.log(m("Running checks\u2026"));for(let n of lc(await ac(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Bo=mo(()=>{"use strict";rt();W()});import{Command as Zw}from"commander";import{createRequire as ey}from"node:module";import{AUTH_MODES as ty}from"document360-engine";import{input as Lu}from"@inquirer/prompts";import{loginPkce as Mu,refreshTokens as Uu,toStoredTokens as xa,clearTokens as Wu,decodeJwtClaims as $a,isExpired as Fu,loadTokens as Hu,saveTokens as va,resolveActiveProfile as ko,setProfileProject as qu,readProjectConfig as Bu}from"document360-engine";W();import{select as Cu}from"@inquirer/prompts";import{resolveActiveProfile as Ru,setProfileProject as Su,resolveProjectId as Pu,listWorkspaces as Tu}from"document360-engine";async function vn(e,t){let n=Ru(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Pu(o);return{workspaces:await Tu(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var wa=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Fr(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function go(e,t,n,o,r){Su(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ya(e,t,n){let o;try{o=await vn(e,n)}catch(s){return console.log(C(`Could not list workspaces: ${s.message}`)),1}let r=Fr(o.workspaces,t);return r?(go(e,o.profile,o.projectId,r.id,r.name),console.log(j(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(C(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Kt(e,t){let n;try{n=await vn(e,t)}catch(k){console.log(C(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:a}=n;if(o.length===0){console.log(m("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===a?_("\u25CF"):" "} ${wa(k)} ${m(k.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let p=await Cu({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${wa(k)}${k.id===a?" (current)":""}`,value:k.id}))}),g=o.find(k=>k.id===p);go(e,s,r,p,g?.name),console.log(j(`\u2713 Workspace set to "${g?.name??p}" for profile "${s}".`))}W();import{select as Du}from"@inquirer/prompts";import{resolveActiveProfile as Au,setProfileProject as ju,listProjects as Eu}from"document360-engine";async function nt(e,t){let n=Au(e,t),o={profile:n.name,connection:n.connection};return{projects:await Eu(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ka=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Hr(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function wo(e,t,n,o){ju(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function ba(e,t,n){let o;try{o=await nt(e,n)}catch(s){return console.log(C(`Could not list projects: ${s.message}`)),1}let r=Hr(o.projects,t);return r?(wo(e,o.profile,r.id,r.name),console.log(j(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(C(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function yo(e,t){let n;try{n=await nt(e,t)}catch(g){console.log(C(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(m("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===s?_("\u25CF"):" "} ${ka(g)} ${m(g.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let a=await Du({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${ka(g)}${g.id===s?" (current)":""}`,value:g.id}))}),p=o.find(g=>g.id===a);wo(e,r,a,p?.name),console.log(j(`\u2713 Project set to "${p?.name??a}" for profile "${r}". Next: pick a workspace.`))}W();import Nu from"picocolors";function Iu(e=process.env){return e.FORCE_HYPERLINK==="0"||!Nu.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 _u(e,t=e,n){return Iu(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Ou=/https?:\/\/[^\s\x1b]+/g;function Cn(e,t){return e.replace(Ou,n=>_u(n,n,t))}function Ca(e){return{...$a(e.idToken)??{},...$a(e.accessToken)??{}}}function bo(e){let t=Ca(e),n=t.email??t.preferred_username??t.sub??"unknown",o=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${n}${o}`}async function $o(e){let t=ko(process.cwd(),e.profile),n=t.connection;console.log(m(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Mu(n,{manual:e.manual,promptForRedirect:s=>Lu({message:s})},s=>console.log(Cn(s))),r=xa(t.name,o);if(va(r),await qr(r,t.name,s=>console.log(m(s))),console.log(""),console.log(j(`\u2713 Logged in to "${t.name}" as ${bo(r)}`)),console.log(m(` access token expires: ${r.expiresAt}`)),console.log(m(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Bu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Kt(process.cwd(),t.name))}catch{}}async function qr(e,t,n){let r=Ca(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(ko(process.cwd(),t).project.projectId)return;let a;try{let{projects:p}=await nt(process.cwd(),t);a=p.find(g=>g.id===r)?.name}catch{}qu(process.cwd(),t,{projectId:r,projectName:a}),n(` Project "${a??r}" written to profile "${t}".`)}catch{}}async function Ra(e){let t=ko(process.cwd(),e.profile),n=t.connection,o=Hu(t.name);if(!o){console.log(C(`Not logged in to Document360 (profile "${t.name}").`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${_(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${bo(o)}`),Fu(o))if(o.refreshToken)try{let r=xa(t.name,await Uu(n,o.refreshToken));va(r),console.log(j(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(O(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(O("Session expired (no refresh token).")),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(m(` expires: ${o.expiresAt}`))}async function Sa(e){let t=ko(process.cwd(),e.profile);Wu(t.name)?console.log(j(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(m(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as Pa,writeProjectConfig as Vu,resolveActiveProfile as Gu,loadTokens as Yu,isExpired as zu}from"document360-engine";function xo(e){let t=Pa(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(C("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?_("\u25CF "):" ",s=o.production?O(" \u26A0 PRODUCTION"):"",a=o.connection.environment??"(inline)",p=Yu(n),g=p?zu(p)&&!p.refreshToken?O("expired"):m("logged in"):m("not logged in");console.log(`${r}${_(n)} \u2192 ${a}${s} [${g}]`)}console.log(""),console.log(m("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function vo(e,t){let n=Pa(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(C(`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(j(`\u2713 Default profile is now "${t}"${o}`))}function Co(e,t){try{let n=Gu(e,t);console.log(""),console.log(`Profile ${_(n.name)}${n.production?O(" \u26A0 PRODUCTION"):""}`),console.log(m(` api: ${n.connection.apiUrl}`)),console.log(m(` identity: ${n.connection.authorizationUrl}`)),console.log(m(` clientId: ${n.connection.clientId}`)),console.log(m(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(m(` project: ${n.project.projectId??"(set at login)"}`)),console.log(m(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(C(n.message)),process.exitCode=1}}W();import{existsSync as Ku,readdirSync as Xu,statSync as Ta}from"node:fs";import{join as Da}from"node:path";import{apiLogDir as Qu}from"document360-engine";function Aa(){let e=Qu();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Ku(e)){console.log(m(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Xu(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(m(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Ta(Da(e,r)).size/1024).toFixed(1);console.log(` ${r} ${m(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${m("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Ta(Da(e,r)).size/1024).toFixed(1);console.log(` ${C(r)} ${m(`${s} KB`)}`)}}console.log(""),console.log(m("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(m("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as Ju,resolveAuth as Zu,findByName as ep,slugify as tp,touchSession as np,upsertSession as op,resolveActiveProfile as rp}from"document360-engine";async function ja(e,t,n,o,r,s){let a=Zu(n);a.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2)),a.kind==="subscription"&&console.error(m("Using your Claude subscription (no API key set)."));let p=null;try{p=rp(e,r)}catch(v){console.error(C(`Document360 profile error: ${v.message}`)),process.exit(2)}p.production&&(console.error(O(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(C("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(m(" --yes given \u2014 proceeding against production.")));let g;if(o){let v=ep(e,o);v||(console.error(C(`No saved session matches "${o}" in this repo.`)),console.error(m("List sessions inside the REPL with /resume.")),process.exit(2)),g=v.uuid,console.error(m(`Resuming "${v.name}"`))}let k=Ju({cwd:e,resume:g,profileName:r,allowProdWrites:s===!0}),y=g??null,S=1;for await(let v of k.send(t))switch(v.type){case"session":if(!y){y=v.sessionId;let I=new Date().toISOString();op({uuid:y,name:tp(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:I,updatedAt:I})}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(m(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(C("agent finished with an error result"));break;case"error":console.error(""),console.error(C(`agent error: ${v.message}`)),process.exit(1)}y&&np(y),process.stdout.write(`
280
- `),process.exit(S)}import{createInterface as ag}from"node:readline/promises";import{createSession as Si,resolveAuth as lg,getSession as cg,setTitle as dg,slugify as ug,touchSession as dd,upsertSession as pg,generateTitle as hg,resolveActiveProfile as ud,resolveModelSetting as fg,readProjectConfig as mg,resolveAndPersistAppType as gg,decodeJwtClaims as cd,isExpired as wg,loadTokens as yg,isDirectiveMention as kg,stripDirectiveMention as bg,appendDirective as $g,reconcileUpgradeActions as xg,stampArticles as vg,listArticleFiles as Cg,CONTENT_CAP_VERSION as Rg}from"document360-engine";import{ENGINE_VERSION as ip}from"document360-engine";var Ne=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --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 /capture \u2014 the writer drives a real browser that signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot",s:"Pick a shot to author or capture (bare); /screenshot --list prints full capture status."},{t:"cmd",name:"/capture",s:"Take the screenshots for authored specs (bare = pick; id/path/--all)."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"One-time setup in the app repo: npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth (real login, once per machine)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress + the next step (`done` marks the next step finished)."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"Author-picker (bare); author specs with <id>, a path, or --all; --list for status."},{t:"cmd",name:"/capture",s:"Take the screenshots (bare = pick ready specs; id/path/--all)."},{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 sp(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 Ea(e){let n=[e?`document360-writer \u2014 help \xB7 v${e.version} \xB7 engine v${e.engineVersion}`:"document360-writer \u2014 help",""];for(let o of Ne){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(sp(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function Br(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:ip}:void 0;for(let o of Ea(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 ap}from"document360-engine";async function Na(e,t){let n=t.currentUuid(),o=n?ap(n):void 0;return console.log(o?m(`
278
+ `;Wa="Re-run dev\u2194docs onboarding (protocol v"});var tl={};ma(tl,{initCommand:()=>Xr,scaffoldInit:()=>Kr});import{input as Sn,confirm as yp}from"@inquirer/prompts";import{basename as Ga,join as Do}from"node:path";import{existsSync as en,readFileSync as kp,readdirSync as bp,writeFileSync as $p}from"node:fs";import{writeProjectConfig as Ya,readProjectConfig as xp,projectConfigPath as za,writerDir as vp,DEFAULT_DOCS_DIR as Ka,DEFAULT_CAPTURE_DIR as Xa,DEFAULT_OUTPUT_DIR as Qa}from"document360-engine";function Kr(e,t="berlin"){let n=za(e);if(en(n))return{created:!1,path:n,profileName:""};let o={projectId:Za(e)??Ga(e),docsDir:Ka,captureDir:Xa,outputDir:Qa,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:el(e)};return Ya(o,e),Ja(e),{created:!0,path:n,profileName:t}}function Ja(e){let t=Do(vp(e),".gitignore");en(t)||$p(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
279
+ `),"utf8")}async function Xr(){let e=process.cwd(),t=za(e);if(en(t)&&!await yp({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(m("init cancelled.")),{kind:"continue"};let n=Za(e)??Ga(e),o=await Sn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Sn({message:"Capture directory (where document360-capture .spec.ts files live):",default:Xa}),s=await Sn({message:"Screenshot output directory:",default:Qa}),a=await Sn({message:"Default connection profile name:",default:"berlin"}),p=await Sn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:Ka,captureDir:r,outputDir:s,profiles:{[a]:{connection:{environment:p},production:!1}},defaultProfile:a,authoritativeSourceFiles:el(e)},k=xp(e);k?.terminologyGlossary&&(g.terminologyGlossary=k.terminologyGlossary),Ya(g,e),Ja(e);let y=Jt(e);console.log(""),console.log(E(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${a}`)} ${m("(sign in; project & workspace auto-selected)")}`),console.log("");for(let S of Zt(y))console.log(S);return console.log(""),console.log(`${m("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Za(e){let t=Do(e,"package.json");if(!en(t))return null;try{return JSON.parse(kp(t,"utf8")).name??null}catch{return null}}function el(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])en(Do(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Do(e,n);en(o)&&!Cp(o)&&t.push(n)}return t}function Cp(e){try{return bp(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Ao=mo(()=>{"use strict";W();rt()});var cc={};ma(cc,{doctorCommand:()=>In,renderDoctorChecks:()=>lc,runDoctorChecks:()=>ac});import{existsSync as gf}from"node:fs";import{d360GetAll as wf,getAccessToken as yf,isExpired as Vs,loadProfileMap as kf,loadTokens as bf,packageSkillsDir as sc,ENGINE_VERSION as $f,projectConfigPath as xf,readProjectConfig as vf,DEFAULT_DOCS_DIR as Cf,fetchManifestSummary as Rf,resolveActiveProfile as Sf,classifyClaudeAuth as Pf,CLAUDE_CODE_SETUP_HINT as ic,resolveModelSetting as Tf,probeModel as Df,detectAppType as Af,playbookSkillName as jf,D360AuthError as Ef}from"document360-engine";async function ac(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${$f}`});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=Pf();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. ${ic}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ic});let s=Tf(e);if(n.push({level:"ok",label:`Model: ${s.model} (${s.source==="auto"?"auto \u2014 right-sized for docs; /model to change":s.source})`}),r.state==="ready"){let R=await Df(e,s.model??void 0);R.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(R.latencyMs/1e3).toFixed(1)}s`}):R.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${R.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let a=vf(e);if(!a)return n.push({level:"fail",label:`No ${xf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let p=(a.docsDir??Cf).replace(/\/+$/,"");n.push(a.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let g=a.authoritativeSourceFiles??[];n.push(g.length>0?{level:"ok",label:`Sources: docs grounded in ${g.length} path(s) (${g.slice(0,3).join(", ")}${g.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let k=a.appType??Af(e);if(k){let R=a.appType?"from config":"auto-detected",N=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${R})${N?` \u2192 ${jf(k)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let y;try{y=Sf(e),n.push({level:"ok",label:`Profile: ${y.name} (${y.connection.name})${y.production?" \u26A0 PRODUCTION":""}`})}catch(R){return n.push({level:"fail",label:`Profile config: ${R.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let S=bf(y.name);S?Vs(S)&&!S.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Vs(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 ${y.name})`}),n.push(y.project.workspaceId?{level:"ok",label:`Workspace: ${y.project.workspaceName??y.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let v=kf(e,y.name);v?v.projectId&&y.project.projectId&&v.projectId!==y.project.projectId?n.push({level:"fail",label:`Category map projectId (${v.projectId}) \u2260 profile projectId (${y.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(v.articles).length} articles, ${Object.keys(v.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${y.name}" (created on first /publish)`}),n.push(gf(sc())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${sc()}`,fix:"Reinstall document360-writer (broken install)"});let I=Ie(e);if(I.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ae})`}):I.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${I.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&&(!Vs(S)||S.refreshToken)){let R={profile:y.name,connection:y.connection};try{await yf(R);let T=await wf(R,"/v3/projects");n.push({level:"ok",label:`API reachable (${y.connection.apiUrl}) \u2014 ${T.length} project(s) visible`})}catch(T){n.push({level:"fail",label:`API call failed: ${T.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=v?.projectId??y.project.projectId;if(N&&y.project.workspaceId)try{let T=await Rf(R,N,y.project.workspaceId);if(T){let L=(T.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${y.connection.name} (${T.languages?.length??0} language${(T.languages?.length??0)===1?"":"s"}) \xB7 hash ${L||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${y.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(T){T instanceof Ef||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(T.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${y.project.projectName??N})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${T.message.slice(0,80)})`})}}return n}function lc(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?O("\u26A0"):C("\u2717");t.push(` ${s} ${r.label}${r.detail?m(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${m("fix:")} ${_(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?E(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):C(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function In(e,t){console.log(m("Running checks\u2026"));for(let n of lc(await ac(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Bo=mo(()=>{"use strict";rt();W()});import{Command as ny}from"commander";import{createRequire as oy}from"node:module";import{AUTH_MODES as ry}from"document360-engine";import{input as Uu}from"@inquirer/prompts";import{loginPkce as Wu,refreshTokens as Fu,toStoredTokens as xa,clearTokens as Hu,decodeJwtClaims as $a,isExpired as qu,loadTokens as Bu,saveTokens as va,resolveActiveProfile as ko,setProfileProject as Vu,readProjectConfig as Gu}from"document360-engine";W();import{select as Su}from"@inquirer/prompts";import{resolveActiveProfile as Pu,setProfileProject as Tu,resolveProjectId as Du,listWorkspaces as Au}from"document360-engine";async function vn(e,t){let n=Pu(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Du(o);return{workspaces:await Au(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var wa=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Fr(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function go(e,t,n,o,r){Tu(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ya(e,t,n){let o;try{o=await vn(e,n)}catch(s){return console.log(C(`Could not list workspaces: ${s.message}`)),1}let r=Fr(o.workspaces,t);return r?(go(e,o.profile,o.projectId,r.id,r.name),console.log(E(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(C(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Kt(e,t){let n;try{n=await vn(e,t)}catch(k){console.log(C(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:a}=n;if(o.length===0){console.log(m("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===a?_("\u25CF"):" "} ${wa(k)} ${m(k.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let p=await Su({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${wa(k)}${k.id===a?" (current)":""}`,value:k.id}))}),g=o.find(k=>k.id===p);go(e,s,r,p,g?.name),console.log(E(`\u2713 Workspace set to "${g?.name??p}" for profile "${s}".`))}W();import{select as ju}from"@inquirer/prompts";import{resolveActiveProfile as Eu,setProfileProject as Nu,listProjects as Iu}from"document360-engine";async function nt(e,t){let n=Eu(e,t),o={profile:n.name,connection:n.connection};return{projects:await Iu(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ka=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Hr(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function wo(e,t,n,o){Nu(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function ba(e,t,n){let o;try{o=await nt(e,n)}catch(s){return console.log(C(`Could not list projects: ${s.message}`)),1}let r=Hr(o.projects,t);return r?(wo(e,o.profile,r.id,r.name),console.log(E(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(C(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function yo(e,t){let n;try{n=await nt(e,t)}catch(g){console.log(C(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(m("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===s?_("\u25CF"):" "} ${ka(g)} ${m(g.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let a=await ju({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${ka(g)}${g.id===s?" (current)":""}`,value:g.id}))}),p=o.find(g=>g.id===a);wo(e,r,a,p?.name),console.log(E(`\u2713 Project set to "${p?.name??a}" for profile "${r}". Next: pick a workspace.`))}W();import _u from"picocolors";function Ou(e=process.env){return e.FORCE_HYPERLINK==="0"||!_u.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 Lu(e,t=e,n){return Ou(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Mu=/https?:\/\/[^\s\x1b]+/g;function Cn(e,t){return e.replace(Mu,n=>Lu(n,n,t))}function Ca(e){return{...$a(e.idToken)??{},...$a(e.accessToken)??{}}}function bo(e){let t=Ca(e),n=t.email??t.preferred_username??t.sub??"unknown",o=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${n}${o}`}async function $o(e){let t=ko(process.cwd(),e.profile),n=t.connection;console.log(m(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Wu(n,{manual:e.manual,promptForRedirect:s=>Uu({message:s})},s=>console.log(Cn(s))),r=xa(t.name,o);if(va(r),await qr(r,t.name,s=>console.log(m(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${bo(r)}`)),console.log(m(` access token expires: ${r.expiresAt}`)),console.log(m(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Gu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Kt(process.cwd(),t.name))}catch{}}async function qr(e,t,n){let r=Ca(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(ko(process.cwd(),t).project.projectId)return;let a;try{let{projects:p}=await nt(process.cwd(),t);a=p.find(g=>g.id===r)?.name}catch{}Vu(process.cwd(),t,{projectId:r,projectName:a}),n(` Project "${a??r}" written to profile "${t}".`)}catch{}}async function Ra(e){let t=ko(process.cwd(),e.profile),n=t.connection,o=Bu(t.name);if(!o){console.log(C(`Not logged in to Document360 (profile "${t.name}").`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${_(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${bo(o)}`),qu(o))if(o.refreshToken)try{let r=xa(t.name,await Fu(n,o.refreshToken));va(r),console.log(E(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(O(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(O("Session expired (no refresh token).")),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(m(` expires: ${o.expiresAt}`))}async function Sa(e){let t=ko(process.cwd(),e.profile);Hu(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(m(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as Pa,writeProjectConfig as Yu,resolveActiveProfile as zu,loadTokens as Ku,isExpired as Xu}from"document360-engine";function xo(e){let t=Pa(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(C("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?_("\u25CF "):" ",s=o.production?O(" \u26A0 PRODUCTION"):"",a=o.connection.environment??"(inline)",p=Ku(n),g=p?Xu(p)&&!p.refreshToken?O("expired"):m("logged in"):m("not logged in");console.log(`${r}${_(n)} \u2192 ${a}${s} [${g}]`)}console.log(""),console.log(m("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function vo(e,t){let n=Pa(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(C(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Yu(n,e);let o=n.profiles[t].production?O(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function Co(e,t){try{let n=zu(e,t);console.log(""),console.log(`Profile ${_(n.name)}${n.production?O(" \u26A0 PRODUCTION"):""}`),console.log(m(` api: ${n.connection.apiUrl}`)),console.log(m(` identity: ${n.connection.authorizationUrl}`)),console.log(m(` clientId: ${n.connection.clientId}`)),console.log(m(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(m(` project: ${n.project.projectId??"(set at login)"}`)),console.log(m(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(C(n.message)),process.exitCode=1}}W();import{existsSync as Qu,readdirSync as Ju,statSync as Ta}from"node:fs";import{join as Da}from"node:path";import{apiLogDir as Zu}from"document360-engine";function Aa(){let e=Zu();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Qu(e)){console.log(m(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Ju(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(m(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Ta(Da(e,r)).size/1024).toFixed(1);console.log(` ${r} ${m(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${m("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Ta(Da(e,r)).size/1024).toFixed(1);console.log(` ${C(r)} ${m(`${s} KB`)}`)}}console.log(""),console.log(m("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(m("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as ep,resolveAuth as tp,findByName as np,slugify as op,touchSession as rp,upsertSession as sp,resolveActiveProfile as ip}from"document360-engine";async function ja(e,t,n,o,r,s){let a=tp(n);a.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2)),a.kind==="subscription"&&console.error(m("Using your Claude subscription (no API key set)."));let p=null;try{p=ip(e,r)}catch(v){console.error(C(`Document360 profile error: ${v.message}`)),process.exit(2)}p.production&&(console.error(O(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(C("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(m(" --yes given \u2014 proceeding against production.")));let g;if(o){let v=np(e,o);v||(console.error(C(`No saved session matches "${o}" in this repo.`)),console.error(m("List sessions inside the REPL with /resume.")),process.exit(2)),g=v.uuid,console.error(m(`Resuming "${v.name}"`))}let k=ep({cwd:e,resume:g,profileName:r,allowProdWrites:s===!0}),y=g??null,S=1;for await(let v of k.send(t))switch(v.type){case"session":if(!y){y=v.sessionId;let I=new Date().toISOString();sp({uuid:y,name:op(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:I,updatedAt:I})}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(m(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(C("agent finished with an error result"));break;case"error":console.error(""),console.error(C(`agent error: ${v.message}`)),process.exit(1)}y&&rp(y),process.stdout.write(`
280
+ `),process.exit(S)}import{createInterface as dg}from"node:readline/promises";import{createSession as Si,resolveAuth as ug,getSession as pg,setTitle as hg,slugify as fg,touchSession as pd,upsertSession as mg,generateTitle as gg,resolveActiveProfile as hd,resolveModelSetting as wg,readProjectConfig as yg,resolveAndPersistAppType as kg,decodeJwtClaims as ud,isExpired as bg,loadTokens as $g,isDirectiveMention as xg,stripDirectiveMention as vg,appendDirective as Cg,reconcileUpgradeActions as Rg,stampArticles as Sg,listArticleFiles as Pg,CONTENT_CAP_VERSION as Tg}from"document360-engine";import{ENGINE_VERSION as lp}from"document360-engine";var Ne=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --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 /capture \u2014 the writer drives a real browser that signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot",s:"Pick a shot to author or capture (bare); /screenshot --list prints full capture status."},{t:"cmd",name:"/capture",s:"Take the screenshots for authored specs (bare = pick; id/path/--all)."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"One-time setup in the app repo: npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth (real login, once per machine)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress + the next step (`done` marks the next step finished)."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"Author-picker (bare); author specs with <id>, a path, or --all; --list for status."},{t:"cmd",name:"/capture",s:"Take the screenshots (bare = pick ready specs; id/path/--all)."},{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 ap(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 Ea(e){let n=[e?`document360-writer \u2014 help \xB7 v${e.version} \xB7 engine v${e.engineVersion}`:"document360-writer \u2014 help",""];for(let o of Ne){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(ap(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function Br(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:lp}:void 0;for(let o of Ea(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 cp}from"document360-engine";async function Na(e,t){let n=t.currentUuid(),o=n?cp(n):void 0;return console.log(o?m(`
281
281
  (conversation reset \u2014 "${o.name}" is still available via /resume)
282
282
  `):m(`
283
283
  (conversation reset \u2014 agent will start fresh on the next prompt)
284
- `)),{kind:"clear"}}async function Vr(){return{kind:"exit"}}Ao();W();import{readMcpConfig as Qr,writeMcpConfig as nl}from"document360-engine";async function jo(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(vp(),{kind:"continue"}):t==="add"?(Cp(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Rp(e.slice(1)),{kind:"continue"}):(console.log(C(`Unknown /mcp subcommand: ${t}`)),console.log(m("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function vp(){let e=Qr(),t=Object.keys(e.servers);if(t.length===0){console.log(m(`
284
+ `)),{kind:"clear"}}async function Vr(){return{kind:"exit"}}Ao();W();import{readMcpConfig as Qr,writeMcpConfig as nl}from"document360-engine";async function jo(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Rp(),{kind:"continue"}):t==="add"?(Sp(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Pp(e.slice(1)),{kind:"continue"}):(console.log(C(`Unknown /mcp subcommand: ${t}`)),console.log(m("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Rp(){let e=Qr(),t=Object.keys(e.servers);if(t.length===0){console.log(m(`
285
285
  No MCP servers registered. Add one with /mcp add <name> <type> <ref>
286
- `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${_(n)} ${m("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?m(` [headers: ${r.join(", ")}]`):"";console.log(` ${_(n)} ${m(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Cp(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(C("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(C(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Qr(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let a={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let g=o[++p],k=g?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(C(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}a[k[1].trim()]=k[2].trim()}else{console.log(C(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(a).length>0?a:void 0}}r.servers[t]=s,nl(r),console.log(""),console.log(j(`\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(m(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Rp(e){let t=e[0];if(!t){console.log(C("Usage: /mcp remove <name>"));return}let n=Qr();if(!n.servers[t]){console.log(C(`No server named "${t}".`));return}delete n.servers[t],nl(n),console.log(j(`\u2713 Removed "${t}".`)),console.log(m(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as Fp}from"node:fs";import{join as Hp}from"node:path";import{select as qp}from"@inquirer/prompts";import{computeSyncStatus as Eo,planPartitions as Bp,relatedArticlePaths as Vp,resolveModelForOperation as Gp,runPartitioned as Yp,loadProfileMap as zp,resolveActiveProfile as Kp,resolveCrossLinks as Xp,applyStructureOrder as wl,orderSyncLine as yl,applyRelatedArticles as kl,relatedSyncLine as bl}from"document360-engine";import J from"picocolors";import hl from"wrap-ansi";import os from"string-width";W();import st from"picocolors";import Jr from"wrap-ansi";import Zr from"string-width";var tn=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [id|path|--all]",desc:"bare: pick a shot to author or capture; id/path/--all: author capture specs (bulk also refreshes the capture checklist; --no-setup skips); --list: status",group:"docs"},{name:"capture",usage:"/capture [id|path|--all]",desc:"bare: pick ready specs to shoot; id/path/--all: take the screenshots (drives d360-capture \u2014 no separate terminal)",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"}],ol={"/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":"author screenshot capture specs","/capture":"take the screenshots for authored specs","/doctor":"run a health check"};function rl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(ol[n])return ol[n];let o=tn.find(r=>r.name===t);return o?o.desc:""}function sl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return tn.filter(n=>n.name.startsWith(t))}function il(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Sp=new RegExp(`^\\s*/(?:${tn.map(e=>e.name).join("|")})(?:\\s|$)`),al=e=>Sp.test(e),ll=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),cl=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),dl=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Pp(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(ll(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&cl(t[o+1])){let p=dl(r);o+=2;let g=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)g.push(dl(t[o++]));n.push({kind:"table",header:p,rows:g});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let g=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(g),text:g.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}if(al(r)){n.push({kind:"para",text:r.trim()}),o++;continue}let a=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!al(t[o])&&!ll(t[o])&&!(t[o].includes("|")&&o+1<t.length&&cl(t[o+1]));)a.push(t[o++]);n.push({kind:"para",text:a.join(" ")})}return n}function es(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?st.bold(t.slice(2,-2)):t.startsWith("`")?_(t.slice(1,-1)):st.italic(t.slice(1,-1)))}var Tp=(e,t)=>e+" ".repeat(Math.max(0,t-Zr(e)));function Dp(e,t,n){let o=e.length,r=e.map((R,E)=>Math.max(Zr(R),...t.map(T=>Zr(T[E]??"")))),s=Math.max(24,n),a=3*o+1,p=[...r],g=()=>p.reduce((R,E)=>R+E,0)+a,k=0;for(;g()>s&&k++<1e4;){let R=-1,E=6;for(let T=0;T<o;T++)p[T]>E&&(E=p[T],R=T);if(R===-1)break;p[R]-=1}let y=(R,E,T)=>st.gray(R+p.map(L=>"\u2500".repeat(L+2)).join(E)+T),S=st.gray("\u2502"),v=(R,E)=>{let T=p.map((Y,z)=>{let pe=R[z]??"",Xe=E?st.bold(pe):es(pe);return Jr(Xe,Y,{hard:!0}).split(`
288
- `)}),L=Math.max(...T.map(Y=>Y.length)),G=[];for(let Y=0;Y<L;Y++)G.push(p.map((z,pe)=>`${S} ${Tp(T[pe][Y]??"",z)} `).join("")+S);return G.join(`
289
- `)},I=[y("\u250C","\u252C","\u2510"),v(e,!0)];return I.push(t.length===0?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524")),t.forEach((R,E)=>{I.push(v(R,!1)),I.push(E===t.length-1?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524"))}),I.join(`
290
- `)}function Ap(e,t){switch(e.kind){case"heading":return st.bold(e.text);case"hr":return st.gray("\u2500".repeat(t));case"para":return Jr(es(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",s=" ".repeat(2+r.length+1),[a="",...p]=Jr(es(o.text),Math.max(10,t-s.length)).split(`
286
+ `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${_(n)} ${m("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?m(` [headers: ${r.join(", ")}]`):"";console.log(` ${_(n)} ${m(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Sp(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(C("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(C(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Qr(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let a={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let g=o[++p],k=g?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(C(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}a[k[1].trim()]=k[2].trim()}else{console.log(C(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(a).length>0?a:void 0}}r.servers[t]=s,nl(r),console.log(""),console.log(E(`\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(m(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Pp(e){let t=e[0];if(!t){console.log(C("Usage: /mcp remove <name>"));return}let n=Qr();if(!n.servers[t]){console.log(C(`No server named "${t}".`));return}delete n.servers[t],nl(n),console.log(E(`\u2713 Removed "${t}".`)),console.log(m(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as qp}from"node:fs";import{join as Bp}from"node:path";import{select as Vp}from"@inquirer/prompts";import{computeSyncStatus as Eo,planPartitions as Gp,relatedArticlePaths as Yp,resolveModelForOperation as zp,runPartitioned as Kp,loadProfileMap as Xp,resolveActiveProfile as Qp,resolveCrossLinks as Jp,applyStructureOrder as wl,orderSyncLine as yl,applyRelatedArticles as kl,relatedSyncLine as bl}from"document360-engine";import J from"picocolors";import hl from"wrap-ansi";import os from"string-width";W();import st from"picocolors";import Jr from"wrap-ansi";import Zr from"string-width";var tn=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [id|path|--all]",desc:"bare: pick a shot to author or capture; id/path/--all: author capture specs (bulk also refreshes the capture checklist; --no-setup skips); --list: status",group:"docs"},{name:"capture",usage:"/capture [id|path|--all]",desc:"bare: pick ready specs to shoot; id/path/--all: take the screenshots (drives d360-capture \u2014 no separate terminal)",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"}],ol={"/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":"author screenshot capture specs","/capture":"take the screenshots for authored specs","/doctor":"run a health check"};function rl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(ol[n])return ol[n];let o=tn.find(r=>r.name===t);return o?o.desc:""}function sl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return tn.filter(n=>n.name.startsWith(t))}function il(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Tp=new RegExp(`^\\s*/(?:${tn.map(e=>e.name).join("|")})(?:\\s|$)`),al=e=>Tp.test(e),ll=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),cl=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),dl=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Dp(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(ll(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&cl(t[o+1])){let p=dl(r);o+=2;let g=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)g.push(dl(t[o++]));n.push({kind:"table",header:p,rows:g});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let g=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(g),text:g.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}if(al(r)){n.push({kind:"para",text:r.trim()}),o++;continue}let a=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!al(t[o])&&!ll(t[o])&&!(t[o].includes("|")&&o+1<t.length&&cl(t[o+1]));)a.push(t[o++]);n.push({kind:"para",text:a.join(" ")})}return n}function es(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?st.bold(t.slice(2,-2)):t.startsWith("`")?_(t.slice(1,-1)):st.italic(t.slice(1,-1)))}var Ap=(e,t)=>e+" ".repeat(Math.max(0,t-Zr(e)));function jp(e,t,n){let o=e.length,r=e.map((R,N)=>Math.max(Zr(R),...t.map(T=>Zr(T[N]??"")))),s=Math.max(24,n),a=3*o+1,p=[...r],g=()=>p.reduce((R,N)=>R+N,0)+a,k=0;for(;g()>s&&k++<1e4;){let R=-1,N=6;for(let T=0;T<o;T++)p[T]>N&&(N=p[T],R=T);if(R===-1)break;p[R]-=1}let y=(R,N,T)=>st.gray(R+p.map(L=>"\u2500".repeat(L+2)).join(N)+T),S=st.gray("\u2502"),v=(R,N)=>{let T=p.map((Y,z)=>{let pe=R[z]??"",Xe=N?st.bold(pe):es(pe);return Jr(Xe,Y,{hard:!0}).split(`
288
+ `)}),L=Math.max(...T.map(Y=>Y.length)),G=[];for(let Y=0;Y<L;Y++)G.push(p.map((z,pe)=>`${S} ${Ap(T[pe][Y]??"",z)} `).join("")+S);return G.join(`
289
+ `)},I=[y("\u250C","\u252C","\u2510"),v(e,!0)];return I.push(t.length===0?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524")),t.forEach((R,N)=>{I.push(v(R,!1)),I.push(N===t.length-1?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524"))}),I.join(`
290
+ `)}function Ep(e,t){switch(e.kind){case"heading":return st.bold(e.text);case"hr":return st.gray("\u2500".repeat(t));case"para":return Jr(es(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",s=" ".repeat(2+r.length+1),[a="",...p]=Jr(es(o.text),Math.max(10,t-s.length)).split(`
291
291
  `);return` ${r} ${a}`+p.map(g=>`
292
292
  ${s}${g}`).join("")}).join(`
293
293
  `)}case"code":return e.lines.map(n=>st.gray(" "+n)).join(`
294
- `);case"table":return Dp(e.header,e.rows,t)}}function ts(e,t){let n=Math.max(20,t);return Pp(e).map(o=>Ap(o,n)).join(`
294
+ `);case"table":return jp(e.header,e.rows,t)}}function ts(e,t){let n=Math.max(20,t);return Dp(e).map(o=>Ep(o,n)).join(`
295
295
 
296
- `)}W();import jp from"picocolors";var Ep=[127,86,217],Np=[22,38,43],ul={T:Ep,E:Np},Pn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],ns=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Ip=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function pl(){if(!jp.isColorSupported)return[];let e=Pn[0].length,t=[];for(let n=0;n<Pn.length;n+=2){let o="";for(let r=0;r<e;r++){let s=ul[Pn[n][r]],a=n+1<Pn.length?ul[Pn[n+1][r]]:void 0;s&&a?o+=`${ns(s)}${Ip(a)}\u2580\x1B[49m\x1B[39m`:s?o+=`${ns(s)}\u2580\x1B[39m`:a?o+=`${ns(a)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Tn(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 Dn(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 it(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var nn=(e,t)=>` ${e.padEnd(13)}${t}`;function _p(e,t){let n=[xn("\u270E document360-writer")+J.gray(` v${e.version} \xB7 engine v${e.engineVersion}`),J.gray(" Reads your code, writes your docs."),"",nn("Claude:",`${e.claude}${J.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),nn("Document360:",e.configured?e.loggedOut?J.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?J.gray(` (${e.sessionHint})`):""}`:J.yellow("not set up \u2014 run /init")),nn("Profile:",e.configured?`${e.profile}${J.gray(` (${e.apiUrl})`)}${e.prod?J.bold(J.yellow(" \u26A0 PRODUCTION")):""}`:J.gray("\u2014 (run /init)")),nn("Project:",e.project),nn("Mode:",J.gray(e.mode)),nn("cwd:",J.gray(e.cwd))],o=pl();if(o.length===0)return n.join(`
296
+ `)}W();import Np from"picocolors";var Ip=[127,86,217],_p=[22,38,43],ul={T:Ip,E:_p},Pn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],ns=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Op=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function pl(){if(!Np.isColorSupported)return[];let e=Pn[0].length,t=[];for(let n=0;n<Pn.length;n+=2){let o="";for(let r=0;r<e;r++){let s=ul[Pn[n][r]],a=n+1<Pn.length?ul[Pn[n+1][r]]:void 0;s&&a?o+=`${ns(s)}${Op(a)}\u2580\x1B[49m\x1B[39m`:s?o+=`${ns(s)}\u2580\x1B[39m`:a?o+=`${ns(a)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Tn(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 Dn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function $e(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function it(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var nn=(e,t)=>` ${e.padEnd(13)}${t}`;function Lp(e,t){let n=[xn("\u270E document360-writer")+J.gray(` v${e.version} \xB7 engine v${e.engineVersion}`),J.gray(" Reads your code, writes your docs."),"",nn("Claude:",`${e.claude}${J.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),nn("Document360:",e.configured?e.loggedOut?J.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?J.gray(` (${e.sessionHint})`):""}`:J.yellow("not set up \u2014 run /init")),nn("Profile:",e.configured?`${e.profile}${J.gray(` (${e.apiUrl})`)}${e.prod?J.bold(J.yellow(" \u26A0 PRODUCTION")):""}`:J.gray("\u2014 (run /init)")),nn("Project:",e.project),nn("Mode:",J.gray(e.mode)),nn("cwd:",J.gray(e.cwd))],o=pl();if(o.length===0)return n.join(`
297
297
  `);let r=2,s=3,a=os(o[0]);if(!(t>=r+a+s+Math.max(...n.map(y=>os(y)))))return[...o.map(y=>" "+y),...n].join(`
298
298
  `);let g=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let y=0;y<Math.max(o.length+g,n.length);y++){let S=o[y-g]??" ".repeat(a);k.push((" ".repeat(r)+S+" ".repeat(s)+(n[y]??"")).trimEnd())}return k.join(`
299
- `)}var Op={error:J.red,warn:J.yellow,ok:J.green,info:J.gray};function rs(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1$2 ")}function ss(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return _p(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),a=50,p=e.text.split(`
299
+ `)}var Mp={error:J.red,warn:J.yellow,ok:J.green,info:J.gray};function rs(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1$2 ")}function ss(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Lp(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),a=50,p=e.text.split(`
300
300
  `).flatMap(k=>hl(k,s,{hard:!0}).split(`
301
301
  `)),g=Math.max(0,p.length-a);return g>0&&(p=[...p.slice(0,a),J.dim(`\u2026 +${g} more lines`)]),`
302
302
  `+p.map((k,y)=>o+(y===0?_(" \u276F "):" ")+k+" ".repeat(Math.max(0,s-os(k))+1)+r).join(`
@@ -309,22 +309,22 @@ ${s}${g}`).join("")}).join(`
309
309
  `+xn(`\u25A3 Preview \u2014 ${e.name}`)+`
310
310
 
311
311
  `+ts(e.text,n);case"note":return`
312
- `+Op[e.tone](Cn(rs(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${Tn(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
313
- `+(e.ok?J.magenta("\u2736 "):J.red("\u2736 "))+J.gray(`Cooked for ${Dn(e.seconds)} \xB7 ${Tn(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${be(e.costUsd)}`:""))}}}function fl(e,t){return e.map(n=>ss(n,t)).join(`
314
- `)}import{resolveActiveProfile as Lp,loadTokens as Mp,isExpired as Up,decodeJwtClaims as ml}from"document360-engine";function Wp(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function _e(e,t){try{let n=Lp(e,t),o=Mp(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Up(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let a={...ml(o.idToken)??{},...ml(o.accessToken)??{}}.doc360_project_id;if(typeof a=="string"&&a&&a!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${Wp(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var An=3;function is(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 gl={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function as(e){return e.filter(t=>t.path!==null&&t.status in gl&&!t.link).map(t=>({path:t.path,label:gl[t.status]}))}function No(e){let t=as(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 Io(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 _o(e){return e.filter(t=>t.link).length}function ls(e,t){try{let n=zp(e,Kp(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Xp(Fp(Hp(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages not published yet \u2014 they show as plain text for now and turn into live links once those pages are published.`}catch{return null}}function Qp(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 $l(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let s=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),a=o.get(s);a?a.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((a,p)=>a.path.localeCompare(p.path));n.push({kind:"category",label:`${Qp(r)} (${s.length})`,paths:s.map(a=>a.path),indent:!1});for(let a of s){let p=a.path.replace(/\\/g,"/").split("/").pop()??a.path;n.push({kind:"article",label:p,paths:[a.path],indent:!0,note:a.label})}}for(let r of[...t].sort((s,a)=>s.path.localeCompare(a.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function Oo(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 cs(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),s=e.filter(v=>!v.ok),a=e.reduce((v,I)=>v+o(I),0),p=r.reduce((v,I)=>v+o(I),0),g=n==="api"?`${be(e.reduce((v,I)=>v+I.costUsd,0))} total`:it(e.reduce((v,I)=>v+I.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,y=v=>`${v} article${v===1?"":"s"}`,S=[];if(s.length===0)S.push(`Published ${y(a)} (${k}) successfully \xB7 ${g}.`),S.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{S.push(`Published ${p}/${y(a)} (${k}) \xB7 ${g}.`),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 Ct(e,t){let{model:n}=Gp(e.cwd,"standard"),o=async(r,s)=>{let a=Bp(r);console.log(m(s?`Resolving cross-links in ${r.length} article${r.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${r.length} article${r.length===1?"":"s"} across ${a.length} partition${a.length===1?"":"s"} (\u2264${An} agents at once) on ${n}\u2026`)),s||console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let p=!1;for await(let g of Yp({cwd:e.cwd,partitions:a,promptFor:k=>Oo(k.paths),concurrency:An,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(g.type==="partition_status")g.status==="running"?console.log(m(` \u25B8 ${g.label} \u2014 publishing\u2026`)):g.status==="done"?console.log(j(` \u2713 ${g.label}`)):console.log(C(` \u2717 ${g.label}`));else if(g.type==="run_done"){p=g.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let S of cs(g.results,a,k))console.log(g.ok?j(S):O(S));let y=ls(e.cwd,e.profileName);y&&console.log(m(y));try{let S=yl(await wl({cwd:e.cwd,profileName:e.profileName}));S&&console.log(m(S))}catch{}try{let S=bl(await kl({cwd:e.cwd,profileName:e.profileName}));S&&console.log(m(S))}catch{}}return p};try{if(!await o(t,!1)){let s=await ds(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(C(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Lo(e,t,n){let o=Vp(e,n);if(o.length===0)return[];let r=new Set(as((await Eo({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function ds(e,t,n){try{let o=new Set(n),r=await Eo({cwd:e,profileName:t});return as(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function xl(e,t){let n=_e(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Lo(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(j("\u2713 All related articles are already published.")),{kind:"continue"}):await Ct(t,r)}if(o==="--all"){console.log(m("Checking what needs publishing\u2026"));try{let r=await Eo({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:a}=No(r.entries),p=_o(r.entries),g=e.includes("--force")&&a.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.`)),a.length>0&&!g&&console.log(O(Io(a.length)));let k=g?[...s,...a]:s;if(k.length===0){if(a.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(j(p>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let y=yl(await wl({cwd:t.cwd,profileName:t.profileName}));y&&console.log(m(y));let S=bl(await kl({cwd:t.cwd,profileName:t.profileName}));S&&console.log(m(S))}catch{}return{kind:"continue"}}return t?await Ct(t,k.map(y=>y.path)):{kind:"forward-to-agent",prompt:Oo(k.map(y=>y.path)),display:"/publish --all"}}catch(r){return console.log(C(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(m("Checking what needs publishing\u2026"));let r;try{let s=await Eo({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:p}=No(s.entries);r=a;let g=_o(s.entries);if(g>0&&console.log(O(`\u26A0 ${g} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),p.length>0&&console.log(O(Io(p.length))),r.length===0&&p.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(C(`Could not compute sync status: ${s.message}`)),console.log(m("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(j("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(m(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${m(`(${s.label})`)}`);return console.log(m("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>qp({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(o==="--all")return await Ct(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:is(o),display:`/publish ${o}`}}async function jn(){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 Jp}from"document360-engine";function us(){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 vl(e,t){let n=t?.cwd??process.cwd();return Jp(n)?{kind:"forward-to-agent",prompt:us(),display:"/discover"}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{checkbox as Zp}from"@inquirer/prompts";import{inventoryRepo as eh,readProjectConfig as Cl,writeProjectConfig as th}from"document360-engine";function ps(e,t){let n=Cl(e);n&&(n.authoritativeSourceFiles=t,th(n,e))}function Mo(e){let t=[`${e.fileCount}${e.fileCount>=5e3?"+":""} files`];return e.stacks.length&&t.push(e.stacks.join("+")),t.push(e.reason),t.join(" \xB7 ")}async function Rl(e,t){let n=t?.cwd??process.cwd();if(!Cl(n))return console.log(C("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=eh(n);if(o.length===0)return console.log(m('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(_("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${m(Mo(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Zp({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Mo(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(m("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};ps(n,r),console.log(j(`\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 uh}from"@inquirer/prompts";import{applyPull as ms,computeSyncStatus as Il,compareRemoteSources as ph,planPull as _l,planImport as hh,applyImport as fh,establishBaselines as mh,rebaselineServerMeta as gh,D360AuthError as wh}from"document360-engine";W();var Sl=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:C,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:O,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:_,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:C,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:C,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ie,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:m,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:m,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:ie,mark:"\xB7"}];function nh(e){return e.path?e.path:`${e.title??"(untitled)"} ${ie(`[${e.articleId}]`)}`}function oh(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 Uo(e,t){let n=[],o=e.entries.filter(y=>y.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 y of o)n.push(` ${O("~")} ${O(y.path??"")} ${ie(`\u2192 "${y.link.title}"`)}`)}for(let y of Sl){let S=e.entries.filter(v=>v.status===y.status&&!(y.status==="untracked-local"&&v.link));if(S.length!==0){n.push(""),n.push(ke(y.header));for(let v of S)n.push(` ${y.paint(y.mark)} ${y.paint(nh(v))}${v.detail?ie(` (${v.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let a={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},p=o.length,g=s===r?j("\u2713 everything up to date"):[r>0?j(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...Sl.map(y=>{let S=(e.counts[y.status]??0)-(y.status==="untracked-local"?p:0);return S>0?`${S} ${a[y.status]}`:null})].filter(Boolean).join(ie(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${oh(t)}`:"";return n.push(g+ie(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as rh}from"diff";import Pl from"picocolors";var Tl=80,sh="\x1B[48;2;74;28;28m",ih="\x1B[48;2;24;66;24m",Dl="\x1B[49m",hs=e=>String(e).padStart(5);function Al(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function jl(e,t,n){if(n===void 0||n<t-4)return e.slice(0,t);let o=Math.max(0,n-12);return`\u2026${e.slice(o).slice(0,Math.max(8,t-1))}`}function Ke(e,t,n){let o=v=>{let I=v.replace(/\r\n/g,`
312
+ `+Mp[e.tone](Cn(rs(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${Tn(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
313
+ `+(e.ok?J.magenta("\u2736 "):J.red("\u2736 "))+J.gray(`Cooked for ${Dn(e.seconds)} \xB7 ${Tn(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${$e(e.costUsd)}`:""))}}}function fl(e,t){return e.map(n=>ss(n,t)).join(`
314
+ `)}import{resolveActiveProfile as Up,loadTokens as Wp,isExpired as Fp,decodeJwtClaims as ml}from"document360-engine";function Hp(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function _e(e,t){try{let n=Up(e,t),o=Wp(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Fp(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let a={...ml(o.idToken)??{},...ml(o.accessToken)??{}}.doc360_project_id;if(typeof a=="string"&&a&&a!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${Hp(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var An=3;function is(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 gl={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function as(e){return e.filter(t=>t.path!==null&&t.status in gl&&!t.link).map(t=>({path:t.path,label:gl[t.status]}))}function No(e){let t=as(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 Io(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 _o(e){return e.filter(t=>t.link).length}function ls(e,t){try{let n=Xp(e,Qp(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Jp(qp(Bp(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 Zp(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 $l(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let s=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),a=o.get(s);a?a.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((a,p)=>a.path.localeCompare(p.path));n.push({kind:"category",label:`${Zp(r)} (${s.length})`,paths:s.map(a=>a.path),indent:!1});for(let a of s){let p=a.path.replace(/\\/g,"/").split("/").pop()??a.path;n.push({kind:"article",label:p,paths:[a.path],indent:!0,note:a.label})}}for(let r of[...t].sort((s,a)=>s.path.localeCompare(a.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function Oo(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 cs(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),s=e.filter(v=>!v.ok),a=e.reduce((v,I)=>v+o(I),0),p=r.reduce((v,I)=>v+o(I),0),g=n==="api"?`${$e(e.reduce((v,I)=>v+I.costUsd,0))} total`:it(e.reduce((v,I)=>v+I.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,y=v=>`${v} article${v===1?"":"s"}`,S=[];if(s.length===0)S.push(`Published ${y(a)} (${k}) successfully \xB7 ${g}.`),S.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{S.push(`Published ${p}/${y(a)} (${k}) \xB7 ${g}.`),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 Ct(e,t){let{model:n}=zp(e.cwd,"standard"),o=async(r,s)=>{let a=Gp(r);console.log(m(s?`Resolving cross-links in ${r.length} article${r.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${r.length} article${r.length===1?"":"s"} across ${a.length} partition${a.length===1?"":"s"} (\u2264${An} agents at once) on ${n}\u2026`)),s||console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let p=!1;for await(let g of Kp({cwd:e.cwd,partitions:a,promptFor:k=>Oo(k.paths),concurrency:An,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(g.type==="partition_status")g.status==="running"?console.log(m(` \u25B8 ${g.label} \u2014 publishing\u2026`)):g.status==="done"?console.log(E(` \u2713 ${g.label}`)):console.log(C(` \u2717 ${g.label}`));else if(g.type==="run_done"){p=g.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let S of cs(g.results,a,k))console.log(g.ok?E(S):O(S));let y=ls(e.cwd,e.profileName);y&&console.log(m(y));try{let S=yl(await wl({cwd:e.cwd,profileName:e.profileName}));S&&console.log(m(S))}catch{}try{let S=bl(await kl({cwd:e.cwd,profileName:e.profileName}));S&&console.log(m(S))}catch{}}return p};try{if(!await o(t,!1)){let s=await ds(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(C(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Lo(e,t,n){let o=Yp(e,n);if(o.length===0)return[];let r=new Set(as((await Eo({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function ds(e,t,n){try{let o=new Set(n),r=await Eo({cwd:e,profileName:t});return as(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function xl(e,t){let n=_e(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Lo(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(E("\u2713 All related articles are already published.")),{kind:"continue"}):await Ct(t,r)}if(o==="--all"){console.log(m("Checking what needs publishing\u2026"));try{let r=await Eo({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:a}=No(r.entries),p=_o(r.entries),g=e.includes("--force")&&a.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.`)),a.length>0&&!g&&console.log(O(Io(a.length)));let k=g?[...s,...a]:s;if(k.length===0){if(a.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(E(p>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let y=yl(await wl({cwd:t.cwd,profileName:t.profileName}));y&&console.log(m(y));let S=bl(await kl({cwd:t.cwd,profileName:t.profileName}));S&&console.log(m(S))}catch{}return{kind:"continue"}}return t?await Ct(t,k.map(y=>y.path)):{kind:"forward-to-agent",prompt:Oo(k.map(y=>y.path)),display:"/publish --all"}}catch(r){return console.log(C(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(m("Checking what needs publishing\u2026"));let r;try{let s=await Eo({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:p}=No(s.entries);r=a;let g=_o(s.entries);if(g>0&&console.log(O(`\u26A0 ${g} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),p.length>0&&console.log(O(Io(p.length))),r.length===0&&p.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(C(`Could not compute sync status: ${s.message}`)),console.log(m("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(E("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(m(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${m(`(${s.label})`)}`);return console.log(m("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>Vp({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(o==="--all")return await Ct(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:is(o),display:`/publish ${o}`}}async function jn(){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 eh}from"document360-engine";function us(){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 vl(e,t){let n=t?.cwd??process.cwd();return eh(n)?{kind:"forward-to-agent",prompt:us(),display:"/discover"}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{checkbox as th}from"@inquirer/prompts";import{inventoryRepo as nh,readProjectConfig as Cl,writeProjectConfig as oh}from"document360-engine";function ps(e,t){let n=Cl(e);n&&(n.authoritativeSourceFiles=t,oh(n,e))}function Mo(e){let t=[`${e.fileCount}${e.fileCount>=5e3?"+":""} files`];return e.stacks.length&&t.push(e.stacks.join("+")),t.push(e.reason),t.join(" \xB7 ")}async function Rl(e,t){let n=t?.cwd??process.cwd();if(!Cl(n))return console.log(C("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=nh(n);if(o.length===0)return console.log(m('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(_("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${m(Mo(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>th({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Mo(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(m("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};ps(n,r),console.log(E(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as hh}from"@inquirer/prompts";import{applyPull as ms,computeSyncStatus as Il,compareRemoteSources as fh,planPull as _l,planImport as mh,applyImport as gh,establishBaselines as wh,rebaselineServerMeta as yh,D360AuthError as kh}from"document360-engine";W();var Sl=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:C,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:O,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:_,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:C,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:C,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ie,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:m,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:m,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:ie,mark:"\xB7"}];function rh(e){return e.path?e.path:`${e.title??"(untitled)"} ${ie(`[${e.articleId}]`)}`}function sh(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 Uo(e,t){let n=[],o=e.entries.filter(y=>y.link);if(o.length>0){n.push(""),n.push(be("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let y of o)n.push(` ${O("~")} ${O(y.path??"")} ${ie(`\u2192 "${y.link.title}"`)}`)}for(let y of Sl){let S=e.entries.filter(v=>v.status===y.status&&!(y.status==="untracked-local"&&v.link));if(S.length!==0){n.push(""),n.push(be(y.header));for(let v of S)n.push(` ${y.paint(y.mark)} ${y.paint(rh(v))}${v.detail?ie(` (${v.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let a={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},p=o.length,g=s===r?E("\u2713 everything up to date"):[r>0?E(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...Sl.map(y=>{let S=(e.counts[y.status]??0)-(y.status==="untracked-local"?p:0);return S>0?`${S} ${a[y.status]}`:null})].filter(Boolean).join(ie(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${sh(t)}`:"";return n.push(g+ie(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as ih}from"diff";import Pl from"picocolors";var Tl=80,ah="\x1B[48;2;74;28;28m",lh="\x1B[48;2;24;66;24m",Dl="\x1B[49m",hs=e=>String(e).padStart(5);function Al(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function jl(e,t,n){if(n===void 0||n<t-4)return e.slice(0,t);let o=Math.max(0,n-12);return`\u2026${e.slice(o).slice(0,Math.max(8,t-1))}`}function Ke(e,t,n){let o=v=>{let I=v.replace(/\r\n/g,`
319
319
  `);return I.endsWith(`
320
320
  `)||I===""?I:I+`
321
- `},r=o(e),s=o(t);if(r===s)return null;let a=Math.max(20,n-10),p=rh("a","b",r,s,"","",{context:3}),g=0,k=0,y=[];p.hunks.forEach((v,I)=>{I>0&&y.push(Pl.gray(" \u2026"));let R=v.oldStart,E=v.newStart,T=[],L=[],G=()=>{for(let Y=0;Y<T.length;Y++){let z=Y<L.length?Al(T[Y],L[Y]):void 0;k++,y.push(`${sh}${hs(R++)} - ${jl(T[Y],a,z)}${Dl}`)}for(let Y=0;Y<L.length;Y++){let z=Y<T.length?Al(T[Y],L[Y]):void 0;g++,y.push(`${ih}${hs(E++)} + ${jl(L[Y],a,z)}${Dl}`)}T=[],L=[]};for(let Y of v.lines){let z=Y[0],pe=Y.slice(1);z==="-"?T.push(pe):z==="+"?L.push(pe):(G(),y.push(Pl.gray(hs(E))+" "+pe.slice(0,a)),R++,E++)}G()});let S=y.slice(0,Tl);return{added:g,removed:k,lines:S,hidden:Math.max(0,y.length-Tl)}}W();import{select as ah}from"@inquirer/prompts";import{applyPull as lh,computeSyncStatus as ch,planPull as dh}from"document360-engine";var El=e=>e===1?"":"s";async function fs(e,t){console.log(""),console.log(`${_("\u25CF")} ${ke(t.title)} ${ie(`(${t.path})`)}`);for(let r of t.notes)console.log(O(` \u26A0 ${r}`));let n=Ke(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${El(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(m(` \u2026 +${n.hidden} more diff lines`))}else console.log(m(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>ah({message:`Conflict \u2014 ${t.path}`,choices:[{name:"Keep local (publish \u2014 overwrites the portal edit)",value:"local"},{name:"Take portal (overwrites your local edits)",value:"portal"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip");return o==="portal"?(lh({cwd:e.cwd,profileName:e.profileName},t),console.log(j(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(m(" Skipped \u2014 still a conflict.")),"skipped")}async function Nl(e,t){let n=_e(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await ch({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(j(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(j("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let a=[];for(let p of s){let g=await dh({cwd:t.cwd,profileName:t.profileName,relPath:p});await fs(t,g)==="keep-local"&&a.push(p)}if(a.length>0)return console.log(m(`Publishing ${a.length} kept-local article${El(a.length)} over the portal\u2026`)),await Ct(t,a)}catch(r){console.log(C(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Ol(e,t){let n=_e(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await yh(t),{kind:"continue"};if(o==="--baseline")return await kh(t,e.filter(a=>a!=="--baseline")),{kind:"continue"};if(o==="--compare")return await bh(t),{kind:"continue"};if(o)return console.log(C(`Unknown option: ${o}`)),console.log(m("Usage: /pull pull portal edits + import new portal articles")),console.log(m(" /pull <path> pull one article (or resolve a conflict)")),console.log(m(" /pull --status drift report only (no writes)")),console.log(m(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await $h(t,r),{kind:"continue"};console.log(m("Pulling changes from Document360\u2026"));let s=await gs({cwd:t.cwd,profileName:t.profileName});for(let a of ws(s))console.log(a.tone==="ok"?j(a.text):a.tone==="warn"?O(a.text):m(a.text));console.log("")}catch(r){r instanceof wh?console.log(C(r.message)):console.log(C(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function gs(e){let t=await Il({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});ms({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 hh({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});fh({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 Wo=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Rt=e=>e===1?"":"s";function ws(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Rt(e.pulled.length)} into local: ${Wo(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Rt(e.imported.length)}: ${Wo(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Rt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Rt(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). (${Wo(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Rt(e.failed.length)} failed: ${Wo(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 yh(e){console.log(m("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Il({cwd:e.cwd,profileName:e.profileName});for(let o of Uo(n,Date.now()-t))console.log(o);console.log("")}async function kh(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(m(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await mh({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await gh({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(j("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(j(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(j(`\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(m(` - ${s.path} (${s.reason})`))}}async function bh(e){console.log(m("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await ph({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(j("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(C(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(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(m(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function $h(e,t){let n=t.replace(/\\/g,"/"),o=await _l({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await fs(e,o)==="keep-local"&&(console.log(m(`Publishing ${o.path} over the portal\u2026`)),await Ct(e,[o.path]));return}console.log(""),console.log(`${_("\u25CF")} ${ke(o.title)} ${ie(`(${o.path})`)}`);for(let a of o.notes)console.log(O(` \u26A0 ${a}`));let r=Ke(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(m(" Local file already matches the remote content \u2014 advancing the sync base only.")),ms({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ie(` \u23BF Added ${r.added} line${Rt(r.added)}, removed ${r.removed} line${Rt(r.removed)}`));for(let a of r.lines)console.log(a);if(r.hidden>0&&console.log(m(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>uh({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(m(" Skipped."));return}ms({cwd:e.cwd,profileName:e.profileName},o),console.log(j(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as xh}from"node:fs";import{resolve as vh}from"node:path";import{estimateBulkCost as Ch,planPartitions as Rh,readProjectConfig as Sh,resolveModelForOperation as Ph,runPartitioned as Th,trackedArticlePaths as Dh}from"document360-engine";var ys=3;function ks(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 bs(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function $s(e,t){return t.map(n=>{let o=0;try{o=xh(vh(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function xs(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite \u2014 be efficient:
321
+ `},r=o(e),s=o(t);if(r===s)return null;let a=Math.max(20,n-10),p=ih("a","b",r,s,"","",{context:3}),g=0,k=0,y=[];p.hunks.forEach((v,I)=>{I>0&&y.push(Pl.gray(" \u2026"));let R=v.oldStart,N=v.newStart,T=[],L=[],G=()=>{for(let Y=0;Y<T.length;Y++){let z=Y<L.length?Al(T[Y],L[Y]):void 0;k++,y.push(`${ah}${hs(R++)} - ${jl(T[Y],a,z)}${Dl}`)}for(let Y=0;Y<L.length;Y++){let z=Y<T.length?Al(T[Y],L[Y]):void 0;g++,y.push(`${lh}${hs(N++)} + ${jl(L[Y],a,z)}${Dl}`)}T=[],L=[]};for(let Y of v.lines){let z=Y[0],pe=Y.slice(1);z==="-"?T.push(pe):z==="+"?L.push(pe):(G(),y.push(Pl.gray(hs(N))+" "+pe.slice(0,a)),R++,N++)}G()});let S=y.slice(0,Tl);return{added:g,removed:k,lines:S,hidden:Math.max(0,y.length-Tl)}}W();import{select as ch}from"@inquirer/prompts";import{applyPull as dh,computeSyncStatus as uh,planPull as ph}from"document360-engine";var El=e=>e===1?"":"s";async function fs(e,t){console.log(""),console.log(`${_("\u25CF")} ${be(t.title)} ${ie(`(${t.path})`)}`);for(let r of t.notes)console.log(O(` \u26A0 ${r}`));let n=Ke(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${El(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(m(` \u2026 +${n.hidden} more diff lines`))}else console.log(m(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>ch({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"?(dh({cwd:e.cwd,profileName:e.profileName},t),console.log(E(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(m(" Skipped \u2014 still a conflict.")),"skipped")}async function Nl(e,t){let n=_e(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await uh({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(E(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(E("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let a=[];for(let p of s){let g=await ph({cwd:t.cwd,profileName:t.profileName,relPath:p});await fs(t,g)==="keep-local"&&a.push(p)}if(a.length>0)return console.log(m(`Publishing ${a.length} kept-local article${El(a.length)} over the portal\u2026`)),await Ct(t,a)}catch(r){console.log(C(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Ol(e,t){let n=_e(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await bh(t),{kind:"continue"};if(o==="--baseline")return await $h(t,e.filter(a=>a!=="--baseline")),{kind:"continue"};if(o==="--compare")return await xh(t),{kind:"continue"};if(o)return console.log(C(`Unknown option: ${o}`)),console.log(m("Usage: /pull pull portal edits + import new portal articles")),console.log(m(" /pull <path> pull one article (or resolve a conflict)")),console.log(m(" /pull --status drift report only (no writes)")),console.log(m(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await vh(t,r),{kind:"continue"};console.log(m("Pulling changes from Document360\u2026"));let s=await gs({cwd:t.cwd,profileName:t.profileName});for(let a of ws(s))console.log(a.tone==="ok"?E(a.text):a.tone==="warn"?O(a.text):m(a.text));console.log("")}catch(r){r instanceof kh?console.log(C(r.message)):console.log(C(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function gs(e){let t=await Il({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});ms({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 mh({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});gh({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 Wo=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Rt=e=>e===1?"":"s";function ws(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Rt(e.pulled.length)} into local: ${Wo(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Rt(e.imported.length)}: ${Wo(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Rt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Rt(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). (${Wo(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Rt(e.failed.length)} failed: ${Wo(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 bh(e){console.log(m("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Il({cwd:e.cwd,profileName:e.profileName});for(let o of Uo(n,Date.now()-t))console.log(o);console.log("")}async function $h(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(m(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await wh({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await yh({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(E("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(E(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(E(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(O(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(m(` - ${s.path} (${s.reason})`))}}async function xh(e){console.log(m("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await fh({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${be(String(t.legacyCount))} \xB7 Manifest: ${be(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(E("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(C(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(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(m(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function vh(e,t){let n=t.replace(/\\/g,"/"),o=await _l({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await fs(e,o)==="keep-local"&&(console.log(m(`Publishing ${o.path} over the portal\u2026`)),await Ct(e,[o.path]));return}console.log(""),console.log(`${_("\u25CF")} ${be(o.title)} ${ie(`(${o.path})`)}`);for(let a of o.notes)console.log(O(` \u26A0 ${a}`));let r=Ke(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(m(" Local file already matches the remote content \u2014 advancing the sync base only.")),ms({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ie(` \u23BF Added ${r.added} line${Rt(r.added)}, removed ${r.removed} line${Rt(r.removed)}`));for(let a of r.lines)console.log(a);if(r.hidden>0&&console.log(m(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>hh({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(m(" Skipped."));return}ms({cwd:e.cwd,profileName:e.profileName},o),console.log(E(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as Ch}from"node:fs";import{resolve as Rh}from"node:path";import{estimateBulkCost as Sh,planPartitions as Ph,readProjectConfig as Th,resolveModelForOperation as Dh,runPartitioned as Ah,trackedArticlePaths as jh}from"document360-engine";var ys=3;function ks(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 bs(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function $s(e,t){return t.map(n=>{let o=0;try{o=Ch(Rh(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function xs(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 vs(e,t,n){let o=e.reduce((p,g)=>p+g.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(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 Cs(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),a=e.reduce((R,E)=>R+o(E),0),p=r.reduce((R,E)=>R+o(E),0),g=e.reduce((R,E)=>R+E.costUsd,0),k=e.reduce((R,E)=>R+E.outputTokens,0),y=n==="api"?`${be(g)} total`:it(k),S=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=R=>`${R} article${R===1?"":"s"}`,I=[];if(s.length===0)I.push(`Converted ${v(a)} (${S}) successfully \xB7 ${y}.`);else{I.push(`Converted ${p}/${v(a)} (${S}) \xB7 ${y}.`),I.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let R of s)I.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return I}async function Ll(e,t){if(!Sh(t.cwd))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=ks(e),r=Dh(t.cwd,t.profileName);if(r.length===0)return console.log(C("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=bs(r,n);if(s.length===0)return console.log(C(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let a=Rh(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:g,forced:k}=Ph(t.cwd,"light");if(!o){let y=Ch({files:$s(t.cwd,s),op:"convert",model:g});n&&console.log(m(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let S of vs(a,y,ys))console.log(S);return console.log(m(`Model: ${g}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(m(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Converting ${s.length} articles across ${a.length} partitions (\u2264${ys} agents at once) on ${g}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let y of Th({cwd:t.cwd,partitions:a,promptFor:xs,concurrency:ys,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:g}))if(y.type==="partition_status")y.status==="running"?console.log(m(` \u25B8 ${y.label} \u2014 converting\u2026`)):y.status==="done"?console.log(j(` \u2713 ${y.label}`)):console.log(C(` \u2717 ${y.label}`));else if(y.type==="run_done"){console.log("");let S=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let v of Cs(y.results,a,S))console.log(y.ok?j(v):O(v))}}catch(y){console.log(C(`Convert run failed: ${y.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as Wl}from"node:fs";import{resolve as Fl}from"node:path";import{estimateBulkCost as Mh,lintDocs as Uh,planPartitions as Wh,readDocsPlan as Fh,readProjectConfig as Hl,DEFAULT_DOCS_DIR as Hh,resolveModelForOperation as qh,runPartitioned as Bh,stampArticles as Vh,CONTENT_CAP_VERSION as Gh}from"document360-engine";import{readProjectConfig as Ah,loadProfileMap as jh,resolveActiveProfile as Eh,desiredCategoryOrder as Nh,desiredArticleOrder as Ih,DEFAULT_DOCS_DIR as _h}from"document360-engine";var Rs=e=>e.replace(/\\/g,"/"),Oh=e=>Rs(e).split("/").pop()??e;function Lh(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function En(e,t){try{let n=Ah(e);if(!n)return[];let o=Eh(e,t),r=jh(e,o.name);if(!r)return[];let s=Rs(n.docsDir??_h).replace(/\/+$/,""),a=new Map;for(let g of Ih(r))a.set(g.categoryPath,(a.get(g.categoryPath)??0)+1);let p=[];for(let g of Nh(r)){let k=Rs(g.path),y=k.startsWith(`${s}/`)?k.slice(s.length+1):k===s?"":k;y&&p.push({token:y,label:Lh(Oh(k)),count:a.get(g.path)??0})}return p}catch{return[]}}function Ml(e,t){let n=En(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 at(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function on(e,t,n,o){let r=En(e,o);if(r.length<=1)return[];let s=n.filter(k=>k.startsWith("--")).join(" "),a=s?` ${s}`:"",p=`/${t}${a} --all`.replace(/\s+/g," "),g=k=>t==="write"?`/write --scope ${k}${a}`:`/${t} ${k}${a}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((k,y)=>k+y.count,0)} articles). Pick a target:`,` ${p} (everything)`,...r.map(k=>` ${g(k.token)} (${k.label} \xB7 ${k.count} article${k.count===1?"":"s"})`)]}function Fo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Ul(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 Yh=3,zh=8;function Ss(e){return e===void 0||!Number.isFinite(e)?Yh:Math.max(1,Math.min(Math.floor(e),zh))}function Ps(e){let t,n,o=!1,r=!1,s,a=g=>{let k=Number(g);return g!==void 0&&Number.isFinite(k)?k:void 0};for(let g=0;g<e.length;g++){let k=e[g];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[++g]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?s=a(e[++g]):k?.startsWith("--concurrency=")?s=a(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=g=>g?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function Kh(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Xh(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Ts(e,t,n){return n.filter(o=>{try{return Wl(Fl(e,t,o)).size===0}catch{return!0}})}function Ds(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let a of o.get(r)?.sources??[])try{s+=Wl(Fl(e,a)).size}catch{}return{path:r,bytes:s}})}function As(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 vs(e,t,n){let o=e.reduce((p,g)=>p+g.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${$e(r)}\u2013${$e(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Cs(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),a=e.reduce((R,N)=>R+o(N),0),p=r.reduce((R,N)=>R+o(N),0),g=e.reduce((R,N)=>R+N.costUsd,0),k=e.reduce((R,N)=>R+N.outputTokens,0),y=n==="api"?`${$e(g)} total`:it(k),S=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=R=>`${R} article${R===1?"":"s"}`,I=[];if(s.length===0)I.push(`Converted ${v(a)} (${S}) successfully \xB7 ${y}.`);else{I.push(`Converted ${p}/${v(a)} (${S}) \xB7 ${y}.`),I.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let R of s)I.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return I}async function Ll(e,t){if(!Th(t.cwd))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=ks(e),r=jh(t.cwd,t.profileName);if(r.length===0)return console.log(C("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=bs(r,n);if(s.length===0)return console.log(C(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let a=Ph(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:g,forced:k}=Dh(t.cwd,"light");if(!o){let y=Sh({files:$s(t.cwd,s),op:"convert",model:g});n&&console.log(m(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let S of vs(a,y,ys))console.log(S);return console.log(m(`Model: ${g}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(m(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Converting ${s.length} articles across ${a.length} partitions (\u2264${ys} agents at once) on ${g}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let y of Ah({cwd:t.cwd,partitions:a,promptFor:xs,concurrency:ys,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:g}))if(y.type==="partition_status")y.status==="running"?console.log(m(` \u25B8 ${y.label} \u2014 converting\u2026`)):y.status==="done"?console.log(E(` \u2713 ${y.label}`)):console.log(C(` \u2717 ${y.label}`));else if(y.type==="run_done"){console.log("");let S=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let v of Cs(y.results,a,S))console.log(y.ok?E(v):O(v))}}catch(y){console.log(C(`Convert run failed: ${y.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as Wl}from"node:fs";import{resolve as Fl}from"node:path";import{estimateBulkCost as Wh,lintDocs as Fh,planPartitions as Hh,readDocsPlan as qh,readProjectConfig as Hl,DEFAULT_DOCS_DIR as Bh,resolveModelForOperation as Vh,runPartitioned as Gh,stampArticles as Yh,CONTENT_CAP_VERSION as zh}from"document360-engine";import{readProjectConfig as Eh,loadProfileMap as Nh,resolveActiveProfile as Ih,desiredCategoryOrder as _h,desiredArticleOrder as Oh,DEFAULT_DOCS_DIR as Lh}from"document360-engine";var Rs=e=>e.replace(/\\/g,"/"),Mh=e=>Rs(e).split("/").pop()??e;function Uh(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function En(e,t){try{let n=Eh(e);if(!n)return[];let o=Ih(e,t),r=Nh(e,o.name);if(!r)return[];let s=Rs(n.docsDir??Lh).replace(/\/+$/,""),a=new Map;for(let g of Oh(r))a.set(g.categoryPath,(a.get(g.categoryPath)??0)+1);let p=[];for(let g of _h(r)){let k=Rs(g.path),y=k.startsWith(`${s}/`)?k.slice(s.length+1):k===s?"":k;y&&p.push({token:y,label:Uh(Mh(k)),count:a.get(g.path)??0})}return p}catch{return[]}}function Ml(e,t){let n=En(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 at(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function on(e,t,n,o){let r=En(e,o);if(r.length<=1)return[];let s=n.filter(k=>k.startsWith("--")).join(" "),a=s?` ${s}`:"",p=`/${t}${a} --all`.replace(/\s+/g," "),g=k=>t==="write"?`/write --scope ${k}${a}`:`/${t} ${k}${a}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((k,y)=>k+y.count,0)} articles). Pick a target:`,` ${p} (everything)`,...r.map(k=>` ${g(k.token)} (${k.label} \xB7 ${k.count} article${k.count===1?"":"s"})`)]}function Fo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Ul(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 Kh=3,Xh=8;function Ss(e){return e===void 0||!Number.isFinite(e)?Kh:Math.max(1,Math.min(Math.floor(e),Xh))}function Ps(e){let t,n,o=!1,r=!1,s,a=g=>{let k=Number(g);return g!==void 0&&Number.isFinite(k)?k:void 0};for(let g=0;g<e.length;g++){let k=e[g];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[++g]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?s=a(e[++g]):k?.startsWith("--concurrency=")?s=a(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=g=>g?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function Qh(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Jh(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Ts(e,t,n){return n.filter(o=>{try{return Wl(Fl(e,t,o)).size===0}catch{return!0}})}function Ds(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let a of o.get(r)?.sources??[])try{s+=Wl(Fl(e,a)).size}catch{}return{path:r,bytes:s}})}function As(e,t,n={}){let o=n.rewrite?`- Some or all of these articles ALREADY EXIST on disk \u2014 this is a re-author (rewrite/upgrade), NOT a first draft. For any that exist, do NOT preserve or lightly-edit the current file: RE-AUTHOR it from scratch against the plan + sources + the active doc-type playbook standard. The existing file is what you're replacing \u2014 its structure is NOT the target; match only the project's voice/terminology.
328
328
  `:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
329
329
  - It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose, its \`type\` (concept | task | reference | faq | tutorial | troubleshooting | best-practices | use-case; missing \u21D2 task), and the source files it draws from (AGENT-PLAN.md has the same table).
330
330
  - Use the skeleton for that \`type\` (see write-article): a \`concept\`/overview page opens with what the product IS + its mental model and takes NO Prerequisites/Steps; only a \`task\` or \`tutorial\` page gets numbered steps (a tutorial ends every stage with a visible checkpoint); a \`troubleshooting\` page is symptom \u2192 cause \u2192 fix. Titles follow the type grammar (task: "How to <verb> <object>"; concept: "Understanding <X>"; troubleshooting: the symptom the user sees).
@@ -334,90 +334,90 @@ ${s}${g}`).join("")}).join(`
334
334
  - Each article is independent. Do NOT write, edit, or publish any article not in this list, and do NOT publish to Document360 \u2014 these are local drafts.
335
335
  Articles:
336
336
  `+e.paths.map(r=>`- ${r}`).join(`
337
- `)}function js(e,t,n){let o=e.reduce((a,p)=>a+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(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.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 Es(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),a=e.reduce((R,E)=>R+o(E),0),p=r.reduce((R,E)=>R+o(E),0),g=e.reduce((R,E)=>R+E.costUsd,0),k=e.reduce((R,E)=>R+E.outputTokens,0),y=n==="api"?`${be(g)} total`:it(k),S=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=R=>`${R} article${R===1?"":"s"}`,I=[];if(s.length===0)I.push(`Wrote ${v(a)} (${S}) successfully \xB7 ${y}.`),I.push("Next \u2014 push them to Document360:"),I.push("/publish --all"),I.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{I.push(`Wrote ${p}/${v(a)} (${S}) \xB7 ${y}.`),I.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let R of s)I.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return I}function Ns(e,t,n){try{let o=Uh({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 Is(e,t,n){let o=(Hl(e)?.docsDir??Hh).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Kh(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=Xh(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let a=Ts(e,o,s);if(a.length===0){let p=n.scope?` under "${n.scope}"`:"",g=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${g} --rewrite to regenerate them all.`}}return{docsDir:o,targets:a,planCount:r.length}}async function ql(e,t){if(!Hl(t.cwd))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Fo(e)){for(let L of Ml(t.cwd,t.profileName))console.log(m(L));return{kind:"continue"}}if(at("write",e)){let L=on(t.cwd,"write",e,t.profileName);if(L.length>0){for(let G of L)console.log(m(G));return{kind:"continue"}}}let n=Fh(t.cwd);if(n.length===0)return console.log(C("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:a,rewrite:p}=Ps(e),{docsDir:g,targets:k,reason:y,rewriting:S}=Is(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(y?O(y):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=Wh(k),I=Ss(a),{model:R,forced:E}=qh(t.cwd,"standard"),T=!!r;if(s&&!T){let L=Mh({files:Ds(t.cwd,n,k),op:"write",model:R});o&&console.log(m(`Scope: ${o} (${k.length} pending).`));for(let G of js(v,L,I))console.log(G);return console.log(m(`Model: ${R}${E?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(m(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Writing ${k.length} article${k.length===1?"":"s"} across ${v.length} partition${v.length===1?"":"s"} (\u2264${I} agents at once) on ${R}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let L of Bh({cwd:t.cwd,partitions:v,promptFor:G=>As(G,g,{rewrite:S||T}),concurrency:I,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:R}))if(L.type==="partition_status")L.status==="running"?console.log(m(` \u25B8 ${L.label} \u2014 writing\u2026`)):L.status==="done"?console.log(j(` \u2713 ${L.label}`)):console.log(C(` \u2717 ${L.label}`));else if(L.type==="run_done"){console.log("");let G=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let z of Es(L.results,v,G))console.log(L.ok?j(z):O(z));if(L.ok)try{Vh(t.cwd,k.map(z=>`${g}/${z}`),{writtenCap:Gh})}catch{}let Y=Ns(t.cwd,g,k);Y&&console.log(O(Y))}}catch(L){console.log(C(`Write run failed: ${L.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as Qh,readdirSync as Bl,statSync as Vl}from"node:fs";import{join as Gl}from"node:path";import{inputDir as Jh,readProjectConfig as Zh}from"document360-engine";var Yl=/\.(md|markdown|pdf|txt)$/i;function _s(e){let t=Jh(e);if(!Qh(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Bl(t)){let s=Gl(t,r),a=!1;try{a=Vl(s).isDirectory()}catch{continue}if(a){if(r.startsWith("."))continue;let p=ef(s);p>0&&n.push({name:r,docCount:p})}else Yl.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 Bl(e))try{Vl(Gl(e,n)).isFile()&&Yl.test(n)&&t++}catch{}return t}function Os(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 Ho(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 Ls="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function zl(e,t){let n=t?.cwd??process.cwd();if(!Zh(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=_s(n);if(o.length===0&&r===0)return console.log(m(Ls)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(m("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let g of o)console.log(` ${g.name} ${m(`(${g.docCount} doc${g.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Ho(p),display:p?`/draft ${p}`:"/draft"}}let a=Os(o,s);return{kind:"forward-to-agent",prompt:Ho(a??"",a?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as tf,readProjectConfig as nf}from"document360-engine";function Ms(e){try{return tf(e).filter(t=>t.kind==="request").length}catch{return 0}}function Us(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Ws(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 Fs="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 Kl(e,t){let n=t?.cwd??process.cwd();if(!nf(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Us(e);if(!r&&Ms(n)===0)return console.log(m(Fs)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Ws(r,o),display:s}}W();import{search as of}from"@inquirer/prompts";import{findByName as rf,getSession as sf,listSessions as af,relativeTime as Ql}from"document360-engine";async function Jl(e,t){let n=af(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(m("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=rf(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(C(`No session matches "${o}".`)),Xl(n),{kind:"continue"})}if(!process.stdin.isTTY)return Xl(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>of({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let a=(s??"").toLowerCase();return n.filter(p=>!a||p.name.toLowerCase().includes(a)||p.firstPrompt.toLowerCase().includes(a)).map(p=>({name:`${p.name} ${Ql(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=sf(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Xl(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${m(Ql(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as lf}from"document360-engine";function Hs(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 Zl(e,t){let n=Hs(e.join(" "));if(!n)return console.log(C("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(lf(o,n)?console.log(j(`\u2713 Session renamed to "${n}"`)):console.log(C("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(j(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as ec,readProjectConfig as cf,writeProjectConfig as df}from"document360-engine";W();function qs(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=cf(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 ec().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},df(o,e),null):`Unknown environment "${r}". Known: ${ec().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function tc(e,t){let n=e[0];if(!n)return xo(t.cwd),{kind:"continue"};if(n==="add"){let o=qs(t.cwd,e[1],e[2]);return o?(console.log(C(o)),{kind:"continue"}):(console.log(j(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/login")}`),{kind:"continue"})}return vo(t.cwd,n),Co(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as uf}from"@inquirer/prompts";import{readProjectConfig as pf,readUserConfig as nc,resolveModelSetting as Bs,writeUserConfig as oc}from"document360-engine";var Fe=[{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 qo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Fe.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function hf(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 Nn(e,t){let n=()=>Bs(e).model;if(t==="default"){let s=nc();return s.defaultModel?(delete s.defaultModel,oc(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Bs(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}}oc({...nc(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=pf(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 rc(e,t){let n=e[0]?.trim();if(!n){let a=Bs(t.cwd);if(!process.stdin.isTTY)return console.log(`${ke("Model:")} ${_(a.model)}${a.source==="auto"?m(" (auto)"):""}`),console.log(m(` source: ${hf(a)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=qo(a),g;try{g=await t.withPausedInput(()=>uf({message:`Select model (current: ${a.model}${a.source==="auto"?" \xB7 auto":""})`,default:Fe[p].value,choices:Fe.map((v,I)=>({name:`${v.label}${I===p?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:k,changed:y,effective:S}=Nn(t.cwd,g??"default");for(let v of k)console.log(v.startsWith("\u26A0")?O(v):v.startsWith("\u2713")?j(v):m(v));return y&&await t.setModel(S),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Nn(t.cwd,n);for(let a of o)console.log(a.startsWith("\u26A0")?O(a):a.startsWith("\u2713")?j(a):m(a));return r&&await t.setModel(s),{kind:"continue"}}Bo();async function dc(e,t){return await t.withPausedInput(()=>Kt(t.cwd)),{kind:"clear"}}async function uc(e,t){return await t.withPausedInput(()=>yo(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as jf}from"document360-engine";async function pc(e,t){let n=!1;try{n=jf(t.cwd).production}catch{}return n?(console.log(O("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(m("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var hc=async(e,t)=>{try{await t.withPausedInput(()=>$o({}))}catch(n){console.log(C(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as Ef,clearTokens as Nf,clearProfileProject as If}from"document360-engine";async function fc(e,t){let n;try{n=Ef(t.cwd,t.profileName).name}catch(r){return console.log(C(r.message)),{kind:"continue"}}let o=Nf(n);return If(t.cwd,n),console.log(o?j(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):m(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(m("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as Gs}from"node:fs";import{isAbsolute as gc,join as wc,resolve as yc}from"node:path";import{readProjectConfig as kc,screenshotPlaceholderIds as _f,DEFAULT_CAPTURE_DIR as bc,DEFAULT_OUTPUT_DIR as Of}from"document360-engine";var mc=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ys(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?mc(n[1]):void 0};let o=n[0];return o?o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:mc(o),setup:t}:{mode:"single",id:o}:{mode:"list",picker:!0}}function St(e,t){let n=kc(e),o=n?.captureDir??bc,r=n?.outputDir??Of,s=(a,p)=>gc(a)?wc(a,p):yc(e,a,p);return _f(e,{scope:t}).map(({id:a,file:p})=>{let g=Gs(s(r,`${a}.png`))?"captured":Gs(s(o,`${a}.spec.ts`))?"spec":"placeholder";return{id:a,file:p,state:g}})}function $c(e,t){let n=kc(e)?.captureDir??bc;return Gs(gc(n)?wc(n,`${t}.spec.ts`):yc(e,n,`${t}.spec.ts`))}var Lf={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Mf={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Vo(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(s=>s.file))].sort(),o=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of n){r.push(s);for(let a of e.filter(p=>p.file===s))r.push(` ${Lf[a.state]} ${a.id.padEnd(34)} ${Mf[a.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function xc(e){let t=e.filter(s=>s.state==="placeholder"),n=e.filter(s=>s.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(s=>s.id),indent:!1});let r=new Map;for(let s of t){let a=r.get(s.file);a?a.push(s):r.set(s.file,[s])}for(let s of[...r.keys()].sort()){let a=r.get(s);if(a.length===1){o.push({kind:"shot",action:"author",label:a[0].id,ids:[a[0].id],indent:!1,note:` ${s}`});continue}o.push({kind:"article",action:"author",label:`${s} (${a.length})`,ids:a.map(p=>p.id),indent:!1});for(let p of a)o.push({kind:"shot",action:"author",label:p.id,ids:[p.id],indent:!0})}n.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${n.length} ready specs`,ids:n.map(s=>s.id),indent:!1});for(let s of n)o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],indent:n.length>1,note:" \u25D0 ready \u2014 enter captures"});return o}function vc(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 js(e,t,n){let o=e.reduce((a,p)=>a+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(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.paths.length===1?"":"s"}`),"",`Estimated cost: ${$e(r)}\u2013${$e(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Es(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),a=e.reduce((R,N)=>R+o(N),0),p=r.reduce((R,N)=>R+o(N),0),g=e.reduce((R,N)=>R+N.costUsd,0),k=e.reduce((R,N)=>R+N.outputTokens,0),y=n==="api"?`${$e(g)} total`:it(k),S=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=R=>`${R} article${R===1?"":"s"}`,I=[];if(s.length===0)I.push(`Wrote ${v(a)} (${S}) successfully \xB7 ${y}.`),I.push("Next \u2014 push them to Document360:"),I.push("/publish --all"),I.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{I.push(`Wrote ${p}/${v(a)} (${S}) \xB7 ${y}.`),I.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let R of s)I.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return I}function Ns(e,t,n){try{let o=Fh({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 Is(e,t,n){let o=(Hl(e)?.docsDir??Bh).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Qh(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=Jh(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let a=Ts(e,o,s);if(a.length===0){let p=n.scope?` under "${n.scope}"`:"",g=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${g} --rewrite to regenerate them all.`}}return{docsDir:o,targets:a,planCount:r.length}}async function ql(e,t){if(!Hl(t.cwd))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Fo(e)){for(let L of Ml(t.cwd,t.profileName))console.log(m(L));return{kind:"continue"}}if(at("write",e)){let L=on(t.cwd,"write",e,t.profileName);if(L.length>0){for(let G of L)console.log(m(G));return{kind:"continue"}}}let n=qh(t.cwd);if(n.length===0)return console.log(C("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:a,rewrite:p}=Ps(e),{docsDir:g,targets:k,reason:y,rewriting:S}=Is(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(y?O(y):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=Hh(k),I=Ss(a),{model:R,forced:N}=Vh(t.cwd,"standard"),T=!!r;if(s&&!T){let L=Wh({files:Ds(t.cwd,n,k),op:"write",model:R});o&&console.log(m(`Scope: ${o} (${k.length} pending).`));for(let G of js(v,L,I))console.log(G);return console.log(m(`Model: ${R}${N?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(m(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Writing ${k.length} article${k.length===1?"":"s"} across ${v.length} partition${v.length===1?"":"s"} (\u2264${I} agents at once) on ${R}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let L of Gh({cwd:t.cwd,partitions:v,promptFor:G=>As(G,g,{rewrite:S||T}),concurrency:I,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:R}))if(L.type==="partition_status")L.status==="running"?console.log(m(` \u25B8 ${L.label} \u2014 writing\u2026`)):L.status==="done"?console.log(E(` \u2713 ${L.label}`)):console.log(C(` \u2717 ${L.label}`));else if(L.type==="run_done"){console.log("");let G=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let z of Es(L.results,v,G))console.log(L.ok?E(z):O(z));if(L.ok)try{Yh(t.cwd,k.map(z=>`${g}/${z}`),{writtenCap:zh})}catch{}let Y=Ns(t.cwd,g,k);Y&&console.log(O(Y))}}catch(L){console.log(C(`Write run failed: ${L.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as Zh,readdirSync as Bl,statSync as Vl}from"node:fs";import{join as Gl}from"node:path";import{inputDir as ef,readProjectConfig as tf}from"document360-engine";var Yl=/\.(md|markdown|pdf|txt)$/i;function _s(e){let t=ef(e);if(!Zh(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Bl(t)){let s=Gl(t,r),a=!1;try{a=Vl(s).isDirectory()}catch{continue}if(a){if(r.startsWith("."))continue;let p=nf(s);p>0&&n.push({name:r,docCount:p})}else Yl.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function nf(e){let t=0;for(let n of Bl(e))try{Vl(Gl(e,n)).isFile()&&Yl.test(n)&&t++}catch{}return t}function Os(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 Ho(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 Ls="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function zl(e,t){let n=t?.cwd??process.cwd();if(!tf(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=_s(n);if(o.length===0&&r===0)return console.log(m(Ls)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(m("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let g of o)console.log(` ${g.name} ${m(`(${g.docCount} doc${g.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Ho(p),display:p?`/draft ${p}`:"/draft"}}let a=Os(o,s);return{kind:"forward-to-agent",prompt:Ho(a??"",a?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as of,readProjectConfig as rf}from"document360-engine";function Ms(e){try{return of(e).filter(t=>t.kind==="request").length}catch{return 0}}function Us(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Ws(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 Fs="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 Kl(e,t){let n=t?.cwd??process.cwd();if(!rf(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Us(e);if(!r&&Ms(n)===0)return console.log(m(Fs)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Ws(r,o),display:s}}W();import{search as sf}from"@inquirer/prompts";import{findByName as af,getSession as lf,listSessions as cf,relativeTime as Ql}from"document360-engine";async function Jl(e,t){let n=cf(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(m("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=af(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(C(`No session matches "${o}".`)),Xl(n),{kind:"continue"})}if(!process.stdin.isTTY)return Xl(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>sf({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let a=(s??"").toLowerCase();return n.filter(p=>!a||p.name.toLowerCase().includes(a)||p.firstPrompt.toLowerCase().includes(a)).map(p=>({name:`${p.name} ${Ql(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=lf(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Xl(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${m(Ql(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as df}from"document360-engine";function Hs(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 Zl(e,t){let n=Hs(e.join(" "));if(!n)return console.log(C("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(df(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log(C("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(E(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as ec,readProjectConfig as uf,writeProjectConfig as pf}from"document360-engine";W();function qs(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 ec().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},pf(o,e),null):`Unknown environment "${r}". Known: ${ec().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function tc(e,t){let n=e[0];if(!n)return xo(t.cwd),{kind:"continue"};if(n==="add"){let o=qs(t.cwd,e[1],e[2]);return o?(console.log(C(o)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/login")}`),{kind:"continue"})}return vo(t.cwd,n),Co(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as hf}from"@inquirer/prompts";import{readProjectConfig as ff,readUserConfig as nc,resolveModelSetting as Bs,writeUserConfig as oc}from"document360-engine";var Fe=[{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 qo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Fe.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function mf(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 Nn(e,t){let n=()=>Bs(e).model;if(t==="default"){let s=nc();return s.defaultModel?(delete s.defaultModel,oc(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Bs(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}}oc({...nc(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=ff(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 rc(e,t){let n=e[0]?.trim();if(!n){let a=Bs(t.cwd);if(!process.stdin.isTTY)return console.log(`${be("Model:")} ${_(a.model)}${a.source==="auto"?m(" (auto)"):""}`),console.log(m(` source: ${mf(a)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=qo(a),g;try{g=await t.withPausedInput(()=>hf({message:`Select model (current: ${a.model}${a.source==="auto"?" \xB7 auto":""})`,default:Fe[p].value,choices:Fe.map((v,I)=>({name:`${v.label}${I===p?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:k,changed:y,effective:S}=Nn(t.cwd,g??"default");for(let v of k)console.log(v.startsWith("\u26A0")?O(v):v.startsWith("\u2713")?E(v):m(v));return y&&await t.setModel(S),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Nn(t.cwd,n);for(let a of o)console.log(a.startsWith("\u26A0")?O(a):a.startsWith("\u2713")?E(a):m(a));return r&&await t.setModel(s),{kind:"continue"}}Bo();async function dc(e,t){return await t.withPausedInput(()=>Kt(t.cwd)),{kind:"clear"}}async function uc(e,t){return await t.withPausedInput(()=>yo(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as Nf}from"document360-engine";async function pc(e,t){let n=!1;try{n=Nf(t.cwd).production}catch{}return n?(console.log(O("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(m("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var hc=async(e,t)=>{try{await t.withPausedInput(()=>$o({}))}catch(n){console.log(C(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as If,clearTokens as _f,clearProfileProject as Of}from"document360-engine";async function fc(e,t){let n;try{n=If(t.cwd,t.profileName).name}catch(r){return console.log(C(r.message)),{kind:"continue"}}let o=_f(n);return Of(t.cwd,n),console.log(o?E(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):m(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(m("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as Gs}from"node:fs";import{isAbsolute as gc,join as wc,resolve as yc}from"node:path";import{readProjectConfig as kc,screenshotPlaceholderIds as Lf,DEFAULT_CAPTURE_DIR as bc,DEFAULT_OUTPUT_DIR as Mf}from"document360-engine";var mc=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ys(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?mc(n[1]):void 0};let o=n[0];return o?o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:mc(o),setup:t}:{mode:"single",id:o}:{mode:"list",picker:!0}}function St(e,t){let n=kc(e),o=n?.captureDir??bc,r=n?.outputDir??Mf,s=(a,p)=>gc(a)?wc(a,p):yc(e,a,p);return Lf(e,{scope:t}).map(({id:a,file:p})=>{let g=Gs(s(r,`${a}.png`))?"captured":Gs(s(o,`${a}.spec.ts`))?"spec":"placeholder";return{id:a,file:p,state:g}})}function $c(e,t){let n=kc(e)?.captureDir??bc;return Gs(gc(n)?wc(n,`${t}.spec.ts`):yc(e,n,`${t}.spec.ts`))}var Uf={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Wf={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Vo(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(s=>s.file))].sort(),o=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of n){r.push(s);for(let a of e.filter(p=>p.file===s))r.push(` ${Uf[a.state]} ${a.id.padEnd(34)} ${Wf[a.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function xc(e){let t=e.filter(s=>s.state==="placeholder"),n=e.filter(s=>s.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(s=>s.id),indent:!1});let r=new Map;for(let s of t){let a=r.get(s.file);a?a.push(s):r.set(s.file,[s])}for(let s of[...r.keys()].sort()){let a=r.get(s);if(a.length===1){o.push({kind:"shot",action:"author",label:a[0].id,ids:[a[0].id],indent:!1,note:` ${s}`});continue}o.push({kind:"article",action:"author",label:`${s} (${a.length})`,ids:a.map(p=>p.id),indent:!1});for(let p of a)o.push({kind:"shot",action:"author",label:p.id,ids:[p.id],indent:!0})}n.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${n.length} ready specs`,ids:n.map(s=>s.id),indent:!1});for(let s of n)o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],indent:n.length>1,note:" \u25D0 ready \u2014 enter captures"});return o}function vc(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 Go(e,t){let n=Ys(e);if(n.mode==="list"){let a=t?.cwd??process.cwd(),p=St(a,n.scope);for(let k of Vo(p,n.scope))console.log(k);let g=p.filter(k=>k.state==="placeholder").length;return g>0&&(console.log(""),console.log(`Author specs: /screenshot <id> (one shot) \xB7 /screenshot <path> (a folder) \xB7 /screenshot --all (all ${g} unauthored)`)),{kind:"continue"}}if(n.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${n.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${n.id}.spec.ts. Report per the skill's writer-facing format \u2014 spec path, data to`,"stage, dev requests only if any, and the capture command; no grounding narration."].join(`
342
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{spawn as Uf}from"node:child_process";import{existsSync as Cc,statSync as Wf}from"node:fs";import{isAbsolute as Ff,join as Rc,resolve as Hf}from"node:path";import{readProjectConfig as qf,DEFAULT_OUTPUT_DIR as Bf}from"document360-engine";var Vf=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function zs(e){let t=e.find(n=>!n.startsWith("--"));return e.includes("--all")?{mode:"all"}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:Vf(t)}:{mode:"single",id:t}:{mode:"picker"}}function Ks(e,t){let n=St(e,t);return{ready:n.filter(o=>o.state==="spec").map(o=>o.id),captured:n.filter(o=>o.state==="captured").map(o=>o.id)}}function Sc(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"),o=[];t.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${t.length} ready specs`,ids:t.map(s=>s.id),indent:!1});let r=new Map;for(let s of t){let a=r.get(s.file);a?a.push(s):r.set(s.file,[s])}for(let s of[...r.keys()].sort()){let a=r.get(s);if(a.length===1){o.push({kind:"shot",action:"capture",label:a[0].id,ids:[a[0].id],indent:!1,note:` ${s}`});continue}o.push({kind:"article",action:"capture",label:`${s} (${a.length})`,ids:a.map(p=>p.id),indent:!1});for(let p of a)o.push({kind:"shot",action:"capture",label:p.id,ids:[p.id],indent:!0})}for(let s of[...n].sort((a,p)=>a.id.localeCompare(p.id)))o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],indent:!1,note:" \u25CF captured \u2014 re-capture"});return o}function Gf(e,t){let n=qf(e)?.outputDir??Bf;return Ff(n)?Rc(n,`${t}.png`):Hf(e,n,`${t}.png`)}function Xs(e,t,n,o){let r=Gf(e,t);return Cc(r)&&Wf(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function Pc(e,t=4){return e.split(/\r?\n/).map(o=>o.trimEnd()).filter(o=>o.trim().length>0).slice(-t).join(`
344
- `)}function Qs(e){return new Promise((t,n)=>{let o=Uf("d360-capture",["capture",e.id],{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";e.stdio==="pipe"&&(o.stdout?.on("data",a=>{r+=a.toString()}),o.stderr?.on("data",a=>{r+=a.toString()}));let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",a=>{e.signal?.removeEventListener("abort",s),n(a)}),o.on("close",a=>{e.signal?.removeEventListener("abort",s),t({exitCode:a??1,output:r})})})}function Yo(e){return Cc(Rc(e,".d360-writer","capture.json"))}function Tc(e,t){let n=new Map(St(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function Dc(e,t){let n=t?.cwd??process.cwd(),o=zs(e);if(!Yo(n))return console.log("Screenshot capture is not set up in this repo yet. Run: d360-capture init"),{kind:"continue"};let{ready:r,captured:s}=Ks(n,o.mode==="scope"?o.scope:void 0),a=o.mode==="single"?[o.id]:o.mode==="picker"?r:[...r,...s];if(a.length===0)return console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};let p=Date.now(),g=[];for(let y of a){console.log(`\u25B6 ${y}`);try{let{exitCode:S}=await Qs({cwd:n,id:y,stdio:"inherit"});g.push({id:y,outcome:Xs(n,y,S,p)})}catch(S){if(S.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};g.push({id:y,outcome:"failed",detail:S.message})}}let k=y=>g.filter(S=>S.outcome===y).length;return console.log(`\u2713 ${k("captured")} captured \xB7 \u2298 ${k("skipped")} skipped \xB7 \u2717 ${k("failed")} failed`),{kind:"continue"}}import{existsSync as Yf,readFileSync as zf}from"node:fs";import{isAbsolute as Kf,join as Xf,resolve as Qf}from"node:path";import{readProjectConfig as Jf,DEFAULT_CAPTURE_DIR as Zf}from"document360-engine";async function _n(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-SETUP.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
345
- `),display:"/capture-setup"}}var Ac="-".repeat(64);function Js(e){let t=Zf;try{let y=Jf(e);y?.captureDir&&(t=y.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Kf(t)?Xf(t,"CAPTURE-TESTID-REQUESTS.json"):Qf(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Yf(n))return null;let o;try{let y=JSON.parse(zf(n,"utf8").replace(/^/,""));o=Array.isArray(y?.requests)?y.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(y=>y.file).filter(Boolean)).size,s=o.length,a=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,g=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${a} 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.","",Ac,`Read ${g} and ${k}. They list ${a} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",Ac]}rt();W();import{listOpenForDocs as em,readProjectConfig as tm}from"document360-engine";function Zs(e){try{return em(e).length}catch{return 0}}function ei(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape.",' \u2022 answer to a [discovery]-tagged question (subject starts "[discovery] ") \u2192 this is product-discovery,'," not an article edit: fold the fact into `.d360-writer/product-brief.md` (updating the cited grounding,"," clearing the matching OPEN marker), then RE-RUN the discover-product readiness assessment \u2014 set the"," brief's frontmatter status to `confident` and offer propose-structure if every rubric dimension now"," passes, else ask the next focused batch via d360_ask_builder. Do not touch articles for these.",' \u2022 answer to a [depth]-tagged question (subject starts "[depth] ") \u2192 this is per-feature depth-mining,'," not the brief and not an article edit: fold it into the DOCS PLAN per propose-structure's"," depth-reconcile \u2014 adjust that feature's article palette in plan.json/AGENT-PLAN.md (add rows citing"," the answer's .d360-writer/messages/ file in `sources`, never renumber existing rows), decrement"," open_depth_questions in AGENT-PLAN.md's frontmatter, and flip status to `pinned` at zero."," \u2022 answer (a reply to any other question you asked; `re` = your question id) \u2192 fold the fact into the"," affected article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only \u2014 do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
346
- `)}async function jc(e,t){let n=t?.cwd??process.cwd();return tm(n)?Zs(n)===0?(console.log(m("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:ei(),display:"/inbox"}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as nm,listOpenForDocs as om,listOpenDirectives as rm,readProjectConfig as sm,computeSyncStatus as im,planPull as am,applyPull as lm,planImport as cm,applyImport as dm}from"document360-engine";function On(e){let t=0,n=0,o=0,r=0;try{t=nm(e).length}catch{}try{let s=om(e);n=s.filter(a=>a.kind==="request").length,o=s.filter(a=>a.kind==="answer").length}catch{}try{r=rm(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function Ln(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 ni(e){return{publish:e.includes("--publish")}}function oi({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page" \u2014 .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and \u2014 if it already exists \u2014 RE-ASSERTS and VERIFIES that the category is hidden). If the result has `hiddenConfirmed: false` or a `warning`, SURFACE that warning to the user PROMINENTLY at the end of your summary (\u26A0 the internal feedback control zone may be public on their KB \u2014 they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY \u2014 triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","4. Decide the right doc actions across ALL of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief \u2014 EXCEPT an answer to a [discovery]-tagged question (subject starts \"[discovery] \"), which is product discovery: fold it into `.d360-writer/product-brief.md`, then re-run the discover-product readiness assessment (flip the brief to `confident` if every rubric dimension now passes and offer propose-structure, else leave a follow-up [discovery] question), and EXCEPT an answer to a [depth]-tagged question (subject starts \"[depth] \"), which is per-feature depth-mining: fold it into the DOCS PLAN per propose-structure's depth-reconcile (adjust that feature's article palette in plan.json/AGENT-PLAN.md, cite the answer's messages/ file in new rows' `sources`, never renumber existing rows, decrement AGENT-PLAN.md's open_depth_questions and flip status to `pinned` at zero) \u2014 address each feedback item (improve the doc it points at \u2014 as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts \u2014 following the active doc-type playbook).","5. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the loop:"," \u2022 stamp consumed hints, and mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done) \u2014 including a step whose work you can verify an EARLIER session already completed but left unstamped \u2014 and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed \u2014 never delete existing steps;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article \u2014 `**d360-writer response:** \u2713 actioned in <article> \u2014 <date>` (or `declined \u2014 <reason>`) \u2014 NEVER overwriting the person's own text \u2014 then call d360_feedback_done(article_id, resulting_articles);"," \u2022 EXCEPT the Creator-notes item (is_creator_notes:true): do NOT reply in it \u2014 instead fold its content into `.d360-writer/architecture/CREATOR-NOTES.md` as an appended, dated `## From portal Creator notes (<date>)` section (preserve every existing note + human edit), then call d360_feedback_done for it.","8. Push the drafts to Document360.","9. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs \u2014 only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)"];return t.push(e?"10. Then publish the new/updated articles live (publish-to-d360 skill), respecting the production write-guard.":"Leave everything as DRAFTS for review \u2014 do not publish live (run /publish when you want them live)."),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (plus the d360_ask_builder question you left for it)."),t.join(`
347
- `)}var um={status:im,plan:am,apply:lm,planImport:cm,applyImport:dm};async function ri(e,t=um){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 ti=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,zo=e=>e===1?"":"s";function si(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${zo(e.pulled.length)} into local: ${ti(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${zo(e.imported.length)} into local drafts: ${ti(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${zo(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${ti(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${zo(e.failed.length)} failed \u2014 left for /pull.`),t}async function Ec(e,t){let n=t?.cwd??process.cwd();if(!sm(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=_e(n,t?.profileName);if(!o.ok)return console.log(C(o.reason)),{kind:"continue"};let{publish:r}=ni(e);console.log(m("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await ri({cwd:n,profileName:t?.profileName});for(let p of si(s))console.log(p.startsWith("\u2713")?j(p):p.startsWith("\u2139")?m(p):O(p));let a=Ln(On(n));return console.log(m(a?`Catching up on ${a}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:oi({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as pm}from"node:child_process";var Pt="document360-writer",Ko=`npm i -g ${Pt}@latest`;async function Xo(){let e=process.platform==="win32";return new Promise(t=>{try{let n=pm(`npm i -g ${Pt}@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 Nc(){return console.log(m(`Updating ${Pt}\u2026`)),(await Xo()).ok?console.log(j("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(C(`Update failed \u2014 run manually: ${Ko}`)),{kind:"continue"}}W();rt();import{existsSync as ii,rmSync as hm}from"node:fs";import{basename as Ic,resolve as ai}from"node:path";import{execFileSync as fm}from"node:child_process";import{input as mm}from"@inquirer/prompts";import{readProjectConfig as gm,devHintsGuidePath as wm}from"document360-engine";var ym=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],km=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Qo=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),_c=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Oc(e){let t=Qo(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:_c(t)?!0:km.has(t)}function li(e){let t=null;try{t=gm(e)}catch{t=null}let n=new Set(ym);for(let o of[Qo(t?.docsDir),Qo(t?.captureDir),Qo(t?.outputDir)])o&&_c(o)&&n.add(o);return[...n].filter(o=>Oc(o)&&ii(ai(e,o)))}function ci(e,t){let n=[],o=[];for(let r of t){if(!Oc(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{hm(ai(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Lc(e,t){try{return fm("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
348
- `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function bm(e){return Lc(e,".d360-writer/hints")}function $m(e){return Lc(e,".d360-writer/messages")}function di(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=bm(e),o=$m(e),r=ii(ai(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: ${Ic(e)}`]}async function Mc(e,t){let n=li(t.cwd);for(let g of di(t.cwd,n))console.log(n.length===0?m(g):g);if(n.length===0)return{kind:"continue"};let o=Ic(t.cwd);if((await t.withPausedInput(()=>mm({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(O("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=ii(wm(t.cwd)),{removed:a,failed:p}=ci(t.cwd,n);console.log(j(`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`));for(let g of p)console.log(C(` \u2717 ${g.path}: ${g.error}`));if(s){for(let g of To())console.log(g);console.log(m("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(m("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}W();import{lintDocs as xm}from"document360-engine";function Jo(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 ui(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{spawn as Ff}from"node:child_process";import{existsSync as Cc,statSync as Hf}from"node:fs";import{isAbsolute as qf,join as Rc,resolve as Bf}from"node:path";import{readProjectConfig as Vf,DEFAULT_OUTPUT_DIR as Gf}from"document360-engine";var Yf=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function zs(e){let t=e.find(n=>!n.startsWith("--"));return e.includes("--all")?{mode:"all"}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:Yf(t)}:{mode:"single",id:t}:{mode:"picker"}}function Ks(e,t){let n=St(e,t);return{ready:n.filter(o=>o.state==="spec").map(o=>o.id),captured:n.filter(o=>o.state==="captured").map(o=>o.id)}}function Sc(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"),o=[];t.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${t.length} ready specs`,ids:t.map(s=>s.id),indent:!1});let r=new Map;for(let s of t){let a=r.get(s.file);a?a.push(s):r.set(s.file,[s])}for(let s of[...r.keys()].sort()){let a=r.get(s);if(a.length===1){o.push({kind:"shot",action:"capture",label:a[0].id,ids:[a[0].id],indent:!1,note:` ${s}`});continue}o.push({kind:"article",action:"capture",label:`${s} (${a.length})`,ids:a.map(p=>p.id),indent:!1});for(let p of a)o.push({kind:"shot",action:"capture",label:p.id,ids:[p.id],indent:!0})}for(let s of[...n].sort((a,p)=>a.id.localeCompare(p.id)))o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],indent:!1,note:" \u25CF captured \u2014 re-capture"});return o}function zf(e,t){let n=Vf(e)?.outputDir??Gf;return qf(n)?Rc(n,`${t}.png`):Bf(e,n,`${t}.png`)}function Xs(e,t,n,o){let r=zf(e,t);return Cc(r)&&Hf(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function Pc(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}function Tc(e,t=4){let n=/captured\s+·|^▶ Annotating|^✓ \d+ captured|^\s*[⊘✗]\s+\S+\s*$|^▶ Running \d+ spec/;return e.split(/\r?\n/).map(r=>r.trimEnd()).filter(r=>r.trim().length>0&&!n.test(r.trim())).slice(-t).join(`
344
+ `)}var Kf=/^[A-Za-z0-9._-]+$/;function Qs(e){return new Promise((t,n)=>{if(!Kf.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=Ff(`d360-capture capture ${e.id}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";e.stdio==="pipe"&&(o.stdout?.on("data",a=>{r+=a.toString()}),o.stderr?.on("data",a=>{r+=a.toString()}));let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",a=>{e.signal?.removeEventListener("abort",s),n(a)}),o.on("close",a=>{e.signal?.removeEventListener("abort",s),t({exitCode:a??1,output:r})})})}function Dc(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function Yo(e){return Cc(Rc(e,".d360-writer","capture.json"))}function Ac(e,t){let n=new Map(St(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function jc(e,t){let n=t?.cwd??process.cwd(),o=zs(e);if(!Yo(n))return console.log("Screenshot capture is not set up in this repo yet. Run: d360-capture init"),{kind:"continue"};let{ready:r,captured:s}=Ks(n,o.mode==="scope"?o.scope:void 0),a=o.mode==="single"?[o.id]:o.mode==="picker"?r:[...r,...s];if(a.length===0)return console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};let p=Date.now(),g=[];for(let y of a){console.log(`\u25B6 ${y}`);try{let{exitCode:S}=await Qs({cwd:n,id:y,stdio:"inherit"});g.push({id:y,outcome:Xs(n,y,S,p)})}catch(S){if(S.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};g.push({id:y,outcome:"failed",detail:S.message})}}let k=y=>g.filter(S=>S.outcome===y).length;return console.log(`\u2713 ${k("captured")} captured \xB7 \u2298 ${k("skipped")} skipped \xB7 \u2717 ${k("failed")} failed`),{kind:"continue"}}import{existsSync as Xf,readFileSync as Qf}from"node:fs";import{isAbsolute as Jf,join as Zf,resolve as em}from"node:path";import{readProjectConfig as tm,DEFAULT_CAPTURE_DIR as nm}from"document360-engine";async function _n(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-SETUP.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
345
+ `),display:"/capture-setup"}}var Ec="-".repeat(64);function Js(e){let t=nm;try{let y=tm(e);y?.captureDir&&(t=y.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Jf(t)?Zf(t,"CAPTURE-TESTID-REQUESTS.json"):em(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Xf(n))return null;let o;try{let y=JSON.parse(Qf(n,"utf8").replace(/^/,""));o=Array.isArray(y?.requests)?y.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(y=>y.file).filter(Boolean)).size,s=o.length,a=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,g=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${a} 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.","",Ec,`Read ${g} and ${k}. They list ${a} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",Ec]}rt();W();import{listOpenForDocs as om,readProjectConfig as rm}from"document360-engine";function Zs(e){try{return om(e).length}catch{return 0}}function ei(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape.",' \u2022 answer to a [discovery]-tagged question (subject starts "[discovery] ") \u2192 this is product-discovery,'," not an article edit: fold the fact into `.d360-writer/product-brief.md` (updating the cited grounding,"," clearing the matching OPEN marker), then RE-RUN the discover-product readiness assessment \u2014 set the"," brief's frontmatter status to `confident` and offer propose-structure if every rubric dimension now"," passes, else ask the next focused batch via d360_ask_builder. Do not touch articles for these.",' \u2022 answer to a [depth]-tagged question (subject starts "[depth] ") \u2192 this is per-feature depth-mining,'," not the brief and not an article edit: fold it into the DOCS PLAN per propose-structure's"," depth-reconcile \u2014 adjust that feature's article palette in plan.json/AGENT-PLAN.md (add rows citing"," the answer's .d360-writer/messages/ file in `sources`, never renumber existing rows), decrement"," open_depth_questions in AGENT-PLAN.md's frontmatter, and flip status to `pinned` at zero."," \u2022 answer (a reply to any other question you asked; `re` = your question id) \u2192 fold the fact into the"," affected article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only \u2014 do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
346
+ `)}async function Nc(e,t){let n=t?.cwd??process.cwd();return rm(n)?Zs(n)===0?(console.log(m("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:ei(),display:"/inbox"}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as sm,listOpenForDocs as im,listOpenDirectives as am,readProjectConfig as lm,computeSyncStatus as cm,planPull as dm,applyPull as um,planImport as pm,applyImport as hm}from"document360-engine";function On(e){let t=0,n=0,o=0,r=0;try{t=sm(e).length}catch{}try{let s=im(e);n=s.filter(a=>a.kind==="request").length,o=s.filter(a=>a.kind==="answer").length}catch{}try{r=am(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function Ln(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 ni(e){return{publish:e.includes("--publish")}}function oi({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page" \u2014 .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and \u2014 if it already exists \u2014 RE-ASSERTS and VERIFIES that the category is hidden). If the result has `hiddenConfirmed: false` or a `warning`, SURFACE that warning to the user PROMINENTLY at the end of your summary (\u26A0 the internal feedback control zone may be public on their KB \u2014 they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY \u2014 triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","4. Decide the right doc actions across ALL of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief \u2014 EXCEPT an answer to a [discovery]-tagged question (subject starts \"[discovery] \"), which is product discovery: fold it into `.d360-writer/product-brief.md`, then re-run the discover-product readiness assessment (flip the brief to `confident` if every rubric dimension now passes and offer propose-structure, else leave a follow-up [discovery] question), and EXCEPT an answer to a [depth]-tagged question (subject starts \"[depth] \"), which is per-feature depth-mining: fold it into the DOCS PLAN per propose-structure's depth-reconcile (adjust that feature's article palette in plan.json/AGENT-PLAN.md, cite the answer's messages/ file in new rows' `sources`, never renumber existing rows, decrement AGENT-PLAN.md's open_depth_questions and flip status to `pinned` at zero) \u2014 address each feedback item (improve the doc it points at \u2014 as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts \u2014 following the active doc-type playbook).","5. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the loop:"," \u2022 stamp consumed hints, and mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done) \u2014 including a step whose work you can verify an EARLIER session already completed but left unstamped \u2014 and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed \u2014 never delete existing steps;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article \u2014 `**d360-writer response:** \u2713 actioned in <article> \u2014 <date>` (or `declined \u2014 <reason>`) \u2014 NEVER overwriting the person's own text \u2014 then call d360_feedback_done(article_id, resulting_articles);"," \u2022 EXCEPT the Creator-notes item (is_creator_notes:true): do NOT reply in it \u2014 instead fold its content into `.d360-writer/architecture/CREATOR-NOTES.md` as an appended, dated `## From portal Creator notes (<date>)` section (preserve every existing note + human edit), then call d360_feedback_done for it.","8. Push the drafts to Document360.","9. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs \u2014 only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)"];return t.push(e?"10. Then publish the new/updated articles live (publish-to-d360 skill), respecting the production write-guard.":"Leave everything as DRAFTS for review \u2014 do not publish live (run /publish when you want them live)."),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (plus the d360_ask_builder question you left for it)."),t.join(`
347
+ `)}var fm={status:cm,plan:dm,apply:um,planImport:pm,applyImport:hm};async function ri(e,t=fm){let n={pulled:[],imported:[],conflicts:[],failed:[]},o;try{o=await t.status({cwd:e.cwd,profileName:e.profileName})}catch(r){return n.error=r.message,n}for(let r of o.entries)if(r.status==="conflict"&&r.path)n.conflicts.push(r.path);else if(r.status==="untracked-remote"&&r.articleId)try{let s=await t.planImport({cwd:e.cwd,profileName:e.profileName,articleId:r.articleId});t.applyImport({cwd:e.cwd,profileName:e.profileName},s),n.imported.push(s.path)}catch(s){n.failed.push({path:r.title??r.articleId,error:s.message})}else if(r.status==="remote-ahead"&&r.path)try{let s=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},s),n.pulled.push(r.path)}catch(s){n.failed.push({path:r.path,error:s.message})}return n}var ti=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,zo=e=>e===1?"":"s";function si(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${zo(e.pulled.length)} into local: ${ti(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${zo(e.imported.length)} into local drafts: ${ti(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${zo(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${ti(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${zo(e.failed.length)} failed \u2014 left for /pull.`),t}async function Ic(e,t){let n=t?.cwd??process.cwd();if(!lm(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=_e(n,t?.profileName);if(!o.ok)return console.log(C(o.reason)),{kind:"continue"};let{publish:r}=ni(e);console.log(m("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await ri({cwd:n,profileName:t?.profileName});for(let p of si(s))console.log(p.startsWith("\u2713")?E(p):p.startsWith("\u2139")?m(p):O(p));let a=Ln(On(n));return console.log(m(a?`Catching up on ${a}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:oi({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as mm}from"node:child_process";var Pt="document360-writer",Ko=`npm i -g ${Pt}@latest`;async function Xo(){let e=process.platform==="win32";return new Promise(t=>{try{let n=mm(`npm i -g ${Pt}@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 _c(){return console.log(m(`Updating ${Pt}\u2026`)),(await Xo()).ok?console.log(E("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(C(`Update failed \u2014 run manually: ${Ko}`)),{kind:"continue"}}W();rt();import{existsSync as ii,rmSync as gm}from"node:fs";import{basename as Oc,resolve as ai}from"node:path";import{execFileSync as wm}from"node:child_process";import{input as ym}from"@inquirer/prompts";import{readProjectConfig as km,devHintsGuidePath as bm}from"document360-engine";var $m=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],xm=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Qo=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Lc=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Mc(e){let t=Qo(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Lc(t)?!0:xm.has(t)}function li(e){let t=null;try{t=km(e)}catch{t=null}let n=new Set($m);for(let o of[Qo(t?.docsDir),Qo(t?.captureDir),Qo(t?.outputDir)])o&&Lc(o)&&n.add(o);return[...n].filter(o=>Mc(o)&&ii(ai(e,o)))}function ci(e,t){let n=[],o=[];for(let r of t){if(!Mc(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{gm(ai(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Uc(e,t){try{return wm("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
348
+ `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function vm(e){return Uc(e,".d360-writer/hints")}function Cm(e){return Uc(e,".d360-writer/messages")}function di(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=vm(e),o=Cm(e),r=ii(ai(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: ${Oc(e)}`]}async function Wc(e,t){let n=li(t.cwd);for(let g of di(t.cwd,n))console.log(n.length===0?m(g):g);if(n.length===0)return{kind:"continue"};let o=Oc(t.cwd);if((await t.withPausedInput(()=>ym({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(O("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=ii(bm(t.cwd)),{removed:a,failed:p}=ci(t.cwd,n);console.log(E(`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`));for(let g of p)console.log(C(` \u2717 ${g.path}: ${g.error}`));if(s){for(let g of To())console.log(g);console.log(m("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(m("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}W();import{lintDocs as Rm}from"document360-engine";function Jo(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 ui(e){let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}return["The documentation quality check found issues in already-written articles. FIX each one by EDITING the","article in place \u2014 do not rewrite whole articles, just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","How to fix, by issue type:","- internal-leak (an agent codename, an internal skill name, or a d360_* tool name): this is the"," documentation engine's own machinery and must NOT appear in user docs. Reword the sentence to describe"," the behavior in plain user terms, or delete the internal aside. Do NOT swap it for another internal term.","- unknown-command: the named /command or --flag does not exist in the product source. Find the correct"," command/flag in the source and use it; if there is no real equivalent, remove the claim.","- stale-fact: the version contradicts the product's package.json engines \u2014 correct it to the real value.","- ai-tell: a machine-sounding buzzword (e.g. delve, leverage, furthermore, robust). Rewrite the phrase in"," plain, direct developer language; preserve the meaning; do NOT swap one buzzword for another.","- stray-file: a junk *.publish.md file (a publish transform wrongly written to disk). DELETE the file \u2014",' do not edit it, do not publish it; the real article is its sibling without ".publish". Nothing else changes.',"","Rules: edit ONLY the listed articles; do not touch others; do not publish; introduce no new internal","nouns, invented commands, or wrong facts. When done, every listed issue should be gone.","","Issues:",[...t.entries()].map(([o,r])=>[o,...r.map(s=>` - L${s.line} [${s.kind}]: "${s.term}" \u2014 ${s.message}`)].join(`
349
349
  `)).join(`
350
350
  `)].join(`
351
- `)}async function Uc(e,t){let n=e.includes("--fix"),o=e.find(a=>!a.startsWith("--")),r=o?` ${o}`:"",s=xm({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(j("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(m(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:ui(s),display:`/check${r} --fix`});console.log(m("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let a of Jo(s))console.log(s.length===0?j(a):O(a));return s.length>0&&console.log(m("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}W();import{lintDocs as Tm,loadStyleGuide as Dm,buildReviewPrompt as Am,readProjectConfig as jm,DEFAULT_DOCS_DIR as Em}from"document360-engine";W();import{readProjectConfig as vm,loadProfileMap as Cm,resolveActiveProfile as Rm,desiredCategoryOrder as Sm,desiredArticleOrder as Pm}from"document360-engine";function Wc(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Fc=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Mn(e,t){try{if(!vm(e))return[];let n=Rm(e,t),o=Cm(e,n.name);if(!o)return[];let r=new Map;for(let a of Pm(o)){let p=r.get(a.categoryPath);p?p.push(a):r.set(a.categoryPath,[a])}let s=[];for(let a of Sm(o)){s.push(Wc(Fc(a.path)));for(let p of(r.get(a.path)??[]).sort((g,k)=>g.order-k.order))s.push(` ${Wc(Fc(p.path))}`)}return s}catch{return[]}}async function Hc(e,t){let n=Mn(t.cwd,t.profileName);if(n.length===0)return console.log(m("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(_("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function pi(e,t){let n=jm(e);if(!n)return null;let o=(n.docsDir??Em).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(y=>!y.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=Tm({cwd:e}),p=s?a.filter(y=>y.path===`${o}/${s}`||y.path.startsWith(`${o}/${s}/`)):a,g=s?"":Mn(e).join(`
352
- `);return{prompt:Am({docsRoot:o,scope:s,styleGuide:Dm(e),deterministicFindings:p,fix:r,structure:g||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function qc(e,t){if(at("review",e)){let o=on(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(m(r));return{kind:"continue"}}}let n=pi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as Nm}from"document360-engine";function hi(e,t){if(!Nm(e))return null;let n=t.find(r=>!r.startsWith("--"));return{prompt:[`Reorder the articles within ${n?`the "${n}" category`:"each category"} to the best reading order.`,"Follow the manage-structure skill: decide the ideal order with senior-editor judgment per the doc-genre","playbook (overview / mental-model first; reference and troubleshooting/FAQ last), then APPLY it with the","d360_reorder_articles tool \u2014 one category at a time, all paths in the same category folder.",n?"":"If the CATEGORY order itself reads wrong too, fix that first with the d360_reorder_categories tool (folder paths under one parent, in the desired order).","Do not rename files or folders or edit the map by hand; the tools handle it. Report the new order, and","remind me it reaches Document360 on the next /publish."].filter(Boolean).join(`
353
- `),display:`/reorder${n?` ${n}`:""}`}}async function Bc(e,t){if(at("reorder",e)){let o=on(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(m(r));return{kind:"continue"}}}let n=hi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as Im,writeProjectConfig as Vc,isAppType as _m,playbookSkillName as Om,detectAppType as Gc}from"document360-engine";var Yc=["web","cli","service","library"],Lm=new Set(["web","cli"]);function fi(e){return Lm.has(e)?`${Om(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Zo(e,t){let n=t.cwd,o=Im(n);if(!o)return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??Gc(n);if(s){let a=o.appType?"set in config":"auto-detected";console.log(`${_("Genre:")} ${s} (${a}) \u2014 ${fi(s)}`)}else console.log(O("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(m(`Set it: /genre <${Yc.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(m("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...a}=o;Vc(a,n);let p=Gc(n);return console.log(j(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${fi(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return _m(r)?(Vc({...o,appType:r},n),console.log(j(`\u2713 Genre set to ${r} \u2014 ${fi(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(C(`Unknown genre "${r}". Choose one of: ${Yc.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}W();import{listRoadmap as mi,roadmapProgress as zc,stampRoadmapDone as Mm}from"document360-engine";function gi(e){let t=mi(e);if(t.length===0)return["No docs roadmap yet \u2014 the docs agent seeds .d360-writer/roadmap.md when it pins a structure,","and adds steps as the app changes. You can also write steps by hand (## [open] <step>), or ask:",'"propose the docs roadmap for this repo".'];let n=zc(e),o=[`Docs roadmap \u2014 ${n.done} of ${n.total} step${n.total===1?"":"s"} done:`,""];for(let r of t)o.push(` ${r.status==="done"?"\u2713":"\u25CB"} ${r.title}${r.run?` \xB7 ${r.run}`:""}`);return o.push(""),o.push(n.next?`Next: ${n.next.title}${n.next.run?` \u2014 ${n.next.run}`:""}`:"Campaign complete \u2014 the docs agent adds new steps as the app changes."),o.push("(Edit .d360-writer/roadmap.md freely \xB7 /roadmap done marks the next step you finished yourself \u2014 add words from a title to pick another.)"),o}function wi(e,t){let n=mi(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)),a=o?s?[s]:n.filter(k=>r(k.title).includes(r(o))):[n[0]];if(a.length>1)return{ok:!1,line:`"${o}" matches ${a.length} open steps \u2014 add a distinguishing word:
351
+ `)}async function Fc(e,t){let n=e.includes("--fix"),o=e.find(a=>!a.startsWith("--")),r=o?` ${o}`:"",s=Rm({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(E("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(m(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:ui(s),display:`/check${r} --fix`});console.log(m("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let a of Jo(s))console.log(s.length===0?E(a):O(a));return s.length>0&&console.log(m("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}W();import{lintDocs as jm,loadStyleGuide as Em,buildReviewPrompt as Nm,readProjectConfig as Im,DEFAULT_DOCS_DIR as _m}from"document360-engine";W();import{readProjectConfig as Sm,loadProfileMap as Pm,resolveActiveProfile as Tm,desiredCategoryOrder as Dm,desiredArticleOrder as Am}from"document360-engine";function Hc(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var qc=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Mn(e,t){try{if(!Sm(e))return[];let n=Tm(e,t),o=Pm(e,n.name);if(!o)return[];let r=new Map;for(let a of Am(o)){let p=r.get(a.categoryPath);p?p.push(a):r.set(a.categoryPath,[a])}let s=[];for(let a of Dm(o)){s.push(Hc(qc(a.path)));for(let p of(r.get(a.path)??[]).sort((g,k)=>g.order-k.order))s.push(` ${Hc(qc(p.path))}`)}return s}catch{return[]}}async function Bc(e,t){let n=Mn(t.cwd,t.profileName);if(n.length===0)return console.log(m("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(_("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function pi(e,t){let n=Im(e);if(!n)return null;let o=(n.docsDir??_m).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(y=>!y.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=jm({cwd:e}),p=s?a.filter(y=>y.path===`${o}/${s}`||y.path.startsWith(`${o}/${s}/`)):a,g=s?"":Mn(e).join(`
352
+ `);return{prompt:Nm({docsRoot:o,scope:s,styleGuide:Em(e),deterministicFindings:p,fix:r,structure:g||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function Vc(e,t){if(at("review",e)){let o=on(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(m(r));return{kind:"continue"}}}let n=pi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as Om}from"document360-engine";function hi(e,t){if(!Om(e))return null;let n=t.find(r=>!r.startsWith("--"));return{prompt:[`Reorder the articles within ${n?`the "${n}" category`:"each category"} to the best reading order.`,"Follow the manage-structure skill: decide the ideal order with senior-editor judgment per the doc-genre","playbook (overview / mental-model first; reference and troubleshooting/FAQ last), then APPLY it with the","d360_reorder_articles tool \u2014 one category at a time, all paths in the same category folder.",n?"":"If the CATEGORY order itself reads wrong too, fix that first with the d360_reorder_categories tool (folder paths under one parent, in the desired order).","Do not rename files or folders or edit the map by hand; the tools handle it. Report the new order, and","remind me it reaches Document360 on the next /publish."].filter(Boolean).join(`
353
+ `),display:`/reorder${n?` ${n}`:""}`}}async function Gc(e,t){if(at("reorder",e)){let o=on(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(m(r));return{kind:"continue"}}}let n=hi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as Lm,writeProjectConfig as Yc,isAppType as Mm,playbookSkillName as Um,detectAppType as zc}from"document360-engine";var Kc=["web","cli","service","library"],Wm=new Set(["web","cli"]);function fi(e){return Wm.has(e)?`${Um(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Zo(e,t){let n=t.cwd,o=Lm(n);if(!o)return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??zc(n);if(s){let a=o.appType?"set in config":"auto-detected";console.log(`${_("Genre:")} ${s} (${a}) \u2014 ${fi(s)}`)}else console.log(O("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(m(`Set it: /genre <${Kc.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(m("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...a}=o;Yc(a,n);let p=zc(n);return console.log(E(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${fi(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return Mm(r)?(Yc({...o,appType:r},n),console.log(E(`\u2713 Genre set to ${r} \u2014 ${fi(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(C(`Unknown genre "${r}". Choose one of: ${Kc.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}W();import{listRoadmap as mi,roadmapProgress as Xc,stampRoadmapDone as Fm}from"document360-engine";function gi(e){let t=mi(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=Xc(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 wi(e,t){let n=mi(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)),a=o?s?[s]:n.filter(k=>r(k.title).includes(r(o))):[n[0]];if(a.length>1)return{ok:!1,line:`"${o}" matches ${a.length} open steps \u2014 add a distinguishing word:
354
354
  ${a.map(k=>` \u25CB ${k.title}`).join(`
355
355
  `)}`};if(a.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
356
356
  ${n.map(k=>` \u25CB ${k.title}`).join(`
357
- `)}`};let p=a[0].title;Mm(e,p,{doneAt:new Date().toISOString()});let g=zc(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${p}${g?` \u2014 next up: ${g.title}${g.run?` (${g.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function Kc(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=mi(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
+ `)}`};let p=a[0].title;Fm(e,p,{doneAt:new Date().toISOString()});let g=Xc(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${p}${g?` \u2014 next up: ${g.title}${g.run?` (${g.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function Qc(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=mi(e).find(r=>r.status==="open"&&r.title.trim().toLowerCase()===n);return o?[`Execute this open docs-roadmap step: "${o.title}".`,o.run?`Its run command: ${o.run}`:"",o.body?`Step detail:
358
358
  ${o.body}`:"","",`Close the loop IN THE SAME TURN the step's goal state is reached: call d360_roadmap_done with exactly the title "${o.title}", then tell the user it is marked done. This INCLUDES discovering the goal already holds \u2014 "no action needed" completes the STEP, not just the turn, so stamp it done then too. Leave it open ONLY if the work is genuinely incomplete (blocked, or background results not yet applied) \u2014 then say exactly what remains before it can be closed.`].filter(Boolean).join(`
359
- `):null}async function Xc(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=wi(n,e.slice(1).join(" ").trim());return console.log(r.ok?j(r.line):O(r.line)),{kind:"continue"}}let o=gi(n);console.log(_(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?m(r):r);return{kind:"continue"}}var Qc={help:Br,"?":Br,clear:Na,exit:Vr,quit:Vr,init:Xr,mcp:jo,publish:xl,audit:jn,discover:vl,scope:Rl,pull:Ol,resolve:Nl,convert:Ll,write:ql,draft:zl,document:Kl,resume:Jl,rename:Zl,profile:tc,model:rc,doctor:In,workspace:dc,project:uc,"allow-prod":pc,login:hc,logout:fc,screenshot:Go,capture:Dc,"capture-setup":_n,devhints:Ba,inbox:jc,"catch-up":Ec,update:Nc,reset:Mc,check:Uc,review:qc,reorder:Bc,structure:Hc,genre:Zo,roadmap:Xc};function Jc(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}rt();var Um="Or just tell me what to write or update.",Wm='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function de(e){return e===1?"":"s"}function er(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Un(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var Fm={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 Hm(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:Fm,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.discovery&&e.discovery.status!=="confident"){let n=e.discovery.openQuestions;t.push(e.discovery.status==="pending"?{key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/publish steps)."}:n>0?{key:"discovery",bullet:`product discovery is waiting on ${n} answer${de(n)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}:{key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.directives>0||e.pendingText){let n=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",o=[];e.directives>0&&o.push(`${e.directives} owner directive${de(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
360
- \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${de(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${de(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${de(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${de(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${de(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${de(n)} changed both here and on Document360 (conflicts) \u2014 /publish skips these`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each conflict \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${n} conflict${de(n)} (keep yours / take the portal's / skip).`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${de(n.total)} done \u2014 next: ${o.title}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${de(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${de(n)}.`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${de(n)} under .d360-writer/ \u2014 a commit request is standing in your builder's mailbox (the sync bookkeeping in there protects against duplicate publishes)`,lead:null,picker:null,follow:null})}return t}function Zc(e){return e.find(t=>t.lead||t.picker)??null}function yi(e,t){let n=t.filter(a=>a.bullet).map(a=>` \u2022 ${a.bullet}`),o=Zc(t),r=[];o?.lead?r.push(Un(o.lead)):o?.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let a of t.filter(p=>p!==o).slice(0,2))a.follow&&r.push(a.follow);let s=[[e,...n].join(`
361
- `)];return r.length&&s.push(r.join(" ")),s.push(Um),s.join(`
362
-
363
- `)}function Wn(e){if(!e.ready)return{kind:"idle"};let t=Hm(e);if(!e.hasDocs){let s=Zc(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:yi("\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:Wm,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null}}}if(t.length===0){let s=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${de(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${de(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${s}`,tone:"info",lead:null,picker:null}}}let n=t.filter(s=>s.lead||s.picker),o=n[0]??null;return o?(o.key==="audit"||o.key==="roadmap"&&n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${de(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:yi("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:yi("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as ki,readdirSync as $i}from"node:fs";import{spawnSync as qm}from"node:child_process";import{join as tr}from"node:path";import{readProjectConfig as td,resolveActiveProfile as nd,loadTokens as Bm,isExpired as Vm,loadProfileMap as od,localAheadPaths as Gm,loadKnownConflicts as Ym,readDocsPlan as zm,devHintsGuidePath as Km,DEFAULT_DOCS_DIR as bi,roadmapProgress as Xm,listRoadmap as Qm,readProductBriefState as Jm,reconcileCommitRequest as Zm}from"document360-engine";rt();function ed(e){try{return $i(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function xi(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>ed(tr(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&ed(tr(e,o)))}function vi(e,t){try{let n=td(e);if(!n)return!1;let o=nd(e,t),r=od(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=tr(e,(n.docsDir??bi).replace(/\/+$/,""));return!!(ki(s)&&$i(s).length>0||ki(Km(e)))}catch{return!1}}function Fn(e,t,n){try{let o=td(e);if(!o)return null;let r=nd(e,t),s=Bm(r.name),a=!!s&&(!Vm(s)||!!s.refreshToken),p=vi(e,t)||!xi(e,o.authoritativeSourceFiles),g=od(e,r.name),k=g?Object.keys(g.articles).length:0,y=tr(e,(o.docsDir??bi).replace(/\/+$/,"")),S=!1;try{S=ki(y)&&$i(y).length>0}catch{}let v=0;if(g?.lastAnalyzedCommit)try{let $e=qm("git",["rev-list","--count",`${g.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});$e.status===0&&(v=parseInt(($e.stdout||"").trim(),10)||0)}catch{}let I=0;try{let $e=zm(e);if($e.length>0){let dt=(o.docsDir??bi).replace(/\/+$/,"");I=Ts(e,dt,$e.map(He=>He.path)).length}}catch{}let R=On(e),E=Ln({...R,directives:0}),T=Gm(e,t),L=new Set(Ym(e,r.name)),G=T.filter($e=>L.has($e)).length,Y=T.length-G,z=Ie(e),pe=Xm(e),Xe=Zm(e,new Date().toISOString()),fe=Jm(e),At=fe?{status:fe.status,openQuestions:fe.openQuestions}:null;return!At&&S&&Qm(e).some(dt=>dt.status==="open"&&(dt.run??"").trim()==="/discover")&&(At={status:"pending",openQuestions:0}),{ready:a&&p&&!n.claudeMissing,hasDocs:S,tracked:k,pendingText:E,directives:R.directives,behind:v,pendingWrites:I,localAhead:Y,conflicts:G,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:z.status,devhintsCompletedVersion:z.completedVersion,devhintsToVersion:ae,builderStarted:ze(e),genreUnknown:n.genreUnknown,roadmap:pe,discovery:At,uncommittedDocs:Xe.dirty.length}}catch{return null}}function rd(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 nr(e){if(e.length===0)return[];let t=(s,a)=>`${s}${"\u2500".repeat(78)}${a}`,n=(s="")=>`\u2502 ${s.padEnd(76)} \u2502`,o=[`\u2B06 d360-writer upgraded \u2014 ${e.length===1?"one improvement affects":`${e.length} improvements affect`} the docs you've already written:`,"",t("\u250C","\u2510")];e.forEach((s,a)=>{a>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let p of rd(`${a+1}. ${s.feature}`,76))o.push(n(p));o.push(n());for(let p of rd(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 eg={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"},id=160,Ri=200,ad=40;function Pe(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function sd(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}: ${Pe(typeof r=="string"?r:JSON.stringify(r),ad)}`);return t.length>4&&n.push("\u2026"),Pe(n.join(", "),id)}var lt=e=>typeof e=="string"&&e?e:null,Ci=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function tg(e){let t=lt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function ng(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=lt(t.title);if(!o)return null;let r=tg(t.local_path);return n("Create article",`"${Pe(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=lt(t.title),r=Ci(t.article_id);return n("Update article",o?`"${Pe(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Ci(t.article_id)?`id ${Ci(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",lt(t.name)?`"${Pe(lt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=lt(t.file_path);return n("Upload image",o?Pe(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function or(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),a=s.join("__");if(r==="document360"){let k=ng(a,t);if(k)return k}let p=a.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:sd(t)}}let n=eg[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:Pe(o,id)}:{title:e,sep:"",arg:sd(t)}}function og(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 rg(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(og).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Pe(r,Ri))]}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}: ${Pe(String(r),ad)}`);return n.length>0?[Pe(n.join(" \xB7 "),Ri)]:null}return null}function sg(e){let t=lt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function ig(e,t,n){switch(e){case"d360_create_article":{let o=sg(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=lt(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 ${Pe(o[0],120)}`:""}`]}default:return null}}function rr(e,t=4,n,o){let r=e.replace(/\r\n/g,`
364
- `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let a=ig(n.slice(18),o,r);if(a)return{lines:a,hidden:0}}let s=rg(r)??r.split(`
365
- `);return{lines:s.slice(0,t).map(a=>Pe(a,Ri)),hidden:Math.max(0,s.length-t)}}function sr(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function ir(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 ld(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 ar(e){return ld(e,"url")}function lr(e){return ld(e,"preview_url")}var Sg=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Pg(e,t,n,o){if(Sg.test(e))try{let r=ud(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,a=ir(t,n),p=ar(n);e.endsWith("publish_article")&&p&&console.log(_(` \u2B95 Live: ${p}`));let g=lr(n);g?console.log(_(` \u2B95 Preview: ${g}`)):a&&s&&console.log(_(` \u2B95 Preview: ${sr(r.connection.portalUrl,s,a,r.project.languageCode??"en")}`))}catch{}}async function pd(e=process.cwd(),t="auto",n,o){let r=lg(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${_("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${_('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Tg(e,n),r.kind==="subscription"&&(r.stored?console.log(m(" Using your Claude subscription (no API key set).")):console.log(m(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,a=Si({cwd:e,profileName:n,allowProdWrites:s}),p={uuid:null,firstPrompt:null,titleFired:!1},g=ag({input:process.stdin,output:process.stdout}),k=[],y=null,S=!1;g.on("line",R=>{if(y){let E=y;y=null,E(R)}else k.push(R)}),g.on("close",()=>{if(S=!0,y){let R=y;y=null,R(null)}});function v(){return k.length>0?Promise.resolve(k.shift()):S?Promise.resolve(null):(process.stdout.write(_("> ")),new Promise(R=>{y=R}))}let I={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{a.close(),a=Si({cwd:e,profileName:n,allowProdWrites:s}),p={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>p.uuid,setPendingName:R=>{p.pendingName=R},setModel:async R=>a.setModel(R),withPausedInput:async R=>{g.pause();try{return await R()}finally{g.resume()}}};try{for(;;){let R=await v();if(R===null)break;let E=R.trim();if(E){if(E.startsWith("/")){let T=Jc(E);if(!T)continue;let L=Qc[T.name];if(!L){console.log(C(`Unknown command: /${T.name}`)),console.log(m("Type /help for the list."));continue}let G=await L(T.args,I);if(G.kind==="exit")break;if(G.kind==="clear"){I.restartAgent();continue}if(G.kind==="allow-prod"){s=!0,I.restartAgent(),console.log(j("\u2713 Production writes authorized for this session.")),console.log("");continue}if(G.kind==="resume"){a.close(),a=Si({cwd:e,resume:G.uuid,profileName:n,allowProdWrites:s});let Y=cg(G.uuid);p={uuid:G.uuid,firstPrompt:Y?.firstPrompt??null,titleFired:!0},dd(G.uuid),console.log(j(`\u2713 Resumed "${G.name}"`)),console.log("");continue}if(G.kind==="forward-to-agent"){p.firstPrompt||(p.firstPrompt=G.display??G.prompt);let Y=(G.display??"").trim().split(/\s+/),z=(Y[0]==="/check"||Y[0]==="/review")&&Y.includes("--fix"),pe=Y.slice(1).find(fe=>!fe.startsWith("--")),Xe=z?Cg(e,pe):[];if(await Pi(a,G.prompt,r,p,e),z)try{vg(e,Xe,{reviewedCap:Rg})}catch{}}else Dg(e,n);continue}if(kg(E)){let T=bg(E);if(T){try{$g(e,{title:T,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}p.firstPrompt||(p.firstPrompt=E),await Pi(a,`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=E),await Pi(a,E,r,p,e)}}}finally{a.close(),g.close()}}function Tg(e,t){console.log(""),console.log(xn("document360-writer")),console.log(m(` cwd: ${e}`));let n=fg(e);if(console.log(m(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Ag(e,t)),!mg(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(So(e),!ze(e))for(let r of Po(e))console.log(O(` ${r}`))}catch{}try{let r=gg(e);r.persisted&&r.appType?console.log(m(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=xg(e);for(let s of nr(r.applied))console.log(O(` ${s}`))}catch{}try{let r=Fn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Wn(r):null;if(s?.kind==="recommend"&&s.rec.note){let a=s.rec.tone==="warn"?O:m;for(let p of rs(s.rec.note).split(`
366
- `))console.log(a(` ${p}`));s.rec.picker&&console.log(_(` Pick one: ${s.rec.picker.options.map(p=>p.cmd).join(" \xB7 ")}`))}}catch{}}console.log(m(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Dg(e,t){try{let n=Fn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Wn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(m(` Next: ${Un(o.rec.lead)}`))}catch{}}function Ag(e,t){try{let n=ud(e,t),o=n.production?O(" \u26A0 PRODUCTION"):"",r=yg(n.name);if(!r)return m(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...cd(r.idToken)??{},...cd(r.accessToken)??{}},a=s.email??s.preferred_username??"signed in";return wg(r)&&!r.refreshToken?O(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):m(` Document360: ${a} \xB7 profile "${n.name}"${o}`)}catch(n){return m(` Document360: ${n.message.split(".")[0]}`)}}function jg(){console.error(""),console.error(`Sign in with your Claude subscription: run ${_("claude")} once, then retry.`),console.error(` (No Claude Code? ${_("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${_("https://console.anthropic.com/settings/keys")}`)}function Eg(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;pg({uuid:t,name:r??ug(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Ng(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||hg(o,t).then(r=>{r&&dg(n,r)}).catch(()=>{})}async function Pi(e,t,n,o,r){let s=new Map;for await(let a of e.send(t))Ig(a,o,r,n,s)}function Ig(e,t,n,o,r){switch(e.type){case"session":t.uuid||Eg(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=or(e.name,e.input);s&&(process.stdout.write(`
367
-
368
- `),console.log(`${j("\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=Ke(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let a=p=>p===1?"":"s";console.log(ie(` \u23BF Added ${s.added} line${a(s.added)}, removed ${s.removed} line${a(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(m(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let a=rr(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?C:ie;a.lines.forEach((g,k)=>console.log(p((k===0?" \u23BF ":" ")+g))),a.hidden>0&&console.log(m(` \u2026 +${a.hidden} lines`)),e.isError||Pg(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
369
- `);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(m(` (${Tn(s)}\u2192${Tn(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(dd(t.uuid),t.titleFired||Ng(t,n));break}case"error":console.error(""),console.error(C(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&jg();break}}import{render as Kw}from"ink";import{resolveAuth as Xw}from"document360-engine";import{useCallback as B,useEffect as De,useMemo as Ni,useRef as Z,useState as F}from"react";import{Box as re,Text as D,useApp as Kg,useInput as Xg,useStdout as Qg}from"ink";import{existsSync as sn,readFileSync as gr,readdirSync as Jg}from"node:fs";import{basename as qn,isAbsolute as Zg,join as Ii}from"node:path";import{createSession as Ld,classifyClaudeAuth as Wi,CLAUDE_CODE_SETUP_HINT as ew,loginPkce as tw,toStoredTokens as nw,saveTokens as ow,getAccessToken as rw,resolveActiveProfile as Te,resolveProjectId as sw,getArticle as iw,decodeJwtClaims as ln,isExpired as ct,loadTokens as Dt,clearTokens as aw,clearProfileProject as lw,setTitle as cw,slugify as dw,touchSession as _i,upsertSession as uw,generateTitle as Md,findByName as pw,listSessions as hw,renameSession as fw,suggestNextAction as mw,readProjectConfig as oe,writeProjectConfig as Ud,resolveAndPersistAppType as gw,detectAppType as ww,resolveModelSetting as Fi,loadProfileMap as Wd,applyPull as Fd,computeSyncStatus as Oi,lintDocs as Hd,compareRemoteSources as yw,planPull as qd,establishBaselines as kw,rebaselineServerMeta as bw,inventoryRepo as $w,knownEnvironments as xw,resolveEnvironment as vw,planPartitions as Li,partitionEvenly as Cw,screenshotPlaceholderIds as Rw,trackedArticlePaths as Sw,runPartitioned as wr,estimateBulkCost as Bd,resolveModelForOperation as yr,readDocsPlan as Pw,checkForUpdate as Tw,detectInstallKind as Dw,isSelfUpdatable as Aw,devHintsGuidePath as Vd,toolFeedbackPath as Gd,reconcileToolFeedback as jw,reconcileUpgradeActions as Ew,stampArticles as Mi,listArticleFiles as Yd,CONTENT_CAP_VERSION as Ui,ENGINE_VERSION as tu,DEFAULT_DOCS_DIR as nu,setProfileProject as Nw,writeCrashLog as Iw,applyStructureOrder as zd,orderSyncLine as Kd,applyRelatedArticles as Xd,relatedSyncLine as Qd}from"document360-engine";rt();import{spawn as hd}from"node:child_process";function _g(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Og(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?hd([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):hd(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",a=>o(a===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function Ti(e){for(let[t,n]of _g())if(await Og(t,n,e))return!0;return!1}var Lg=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Di(e,t){if(t.closed)return e;let n=e.split(`
370
- `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){Lg.test(s)&&(t.cueSeen=!0);continue}let a=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);a?(n[r]=`${a[1]}${++t.num}. ${a[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
371
- `)}import{existsSync as Mg,mkdirSync as Ug,readFileSync as Wg,writeFileSync as Fg}from"node:fs";import{join as fd}from"node:path";import{writerDir as Hg}from"document360-engine";function md(e){return fd(Hg(e),".sessions")}function gd(e,t){return fd(md(e),`${t}.json`)}function wd(e,t,n){try{Ug(md(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Fg(gd(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Ai(e,t){try{let n=gd(e,t);if(!Mg(n))return[];let o=JSON.parse(Wg(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var qg=e=>`\x1B]0;${e}\x07`,Bg=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function yd(e){process.stdout.isTTY&&process.stdout.write(e)}function rn(e){yd(qg(e))}function cr(e){yd(Bg(e))}var dr=["\xB7 "," \xB7"],ur="\u{1F7E3}";Bo();Ao();W();import{Box as kd,Text as ce}from"ink";import{jsx as ue,jsxs as pr}from"react/jsx-runtime";function Vg({row:e}){switch(e.t){case"head":return ue(ce,{color:q,bold:!0,children:e.s});case"text":return ue(ce,{children:e.s});case"dim":return ue(ce,{dimColor:!0,children:e.s});case"sub":return ue(ce,{bold:!0,dimColor:!0,children:e.s});case"good":return ue(ce,{color:"green",children:e.s});case"step":return pr(ce,{children:[ue(ce,{color:q,children:`${e.n}. `}),e.s]});case"cmd":return pr(ce,{children:[" ",ue(ce,{color:q,children:e.name.padEnd(20)}),ue(ce,{dimColor:!0,children:e.s})]});case"gap":return ue(ce,{children:" "})}}function bd({tab:e,width:t,version:n,engineVersion:o}){let r=Ne[e]??Ne[0],s=6+Ne.reduce((p,g)=>p+g.label.length+4,0),a="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return pr(kd,{flexDirection:"column",paddingX:1,children:[pr(ce,{children:[ue(ce,{color:q,bold:!0,children:"Help "}),Ne.map((p,g)=>g===e?ue(ce,{color:"white",backgroundColor:q,bold:!0,children:` ${p.label} `},p.key):ue(ce,{dimColor:!0,children:` ${p.label} `},p.key))]}),ue(ce,{color:q,children:a}),ue(kd,{flexDirection:"column",marginTop:1,children:r.rows.map((p,g)=>ue(Vg,{row:p},g))}),ue(ce,{dimColor:!0,children:`
372
- \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var Gg=/^(?:\d+[.)]|[-*•])\s+/;function $d(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
373
- `)){let a=s.trim().replace(Gg,""),p=a.match(/^`([^`]+)`$/);p&&(a=p[1].trim());let g=a.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!g||!o.has(g[1].toLowerCase()))continue;let k=`/${g[1].toLowerCase()}${g[2]?` ${g[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}W();function Hn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Oe(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function xd(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Yg=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function vd(e,t,n){if(!Yg.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(s=>{let a=s.replace(/\\/g,"/");return r===a||r.endsWith(`/${a}`)})??null}function ji(e){return e.replace(/^[\w.-]+\//,"")}var hr=16,Cd={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Tt(e){return typeof e=="string"?e:e.cmd}function Rd(e){return typeof e=="string"?void 0:e.desc}function Ei(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Sd(e,t){let n=Ei(t);return e.some(r=>Tt(r).trim()===t.trim()||!!n&&Ei(Tt(r))===n)?e.filter(r=>Tt(r).trim()!==t.trim()&&!(n&&Ei(Tt(r))===n)):[]}import{isDirectiveMention as _w,stripDirectiveMention as Ow,appendDirective as Lw}from"document360-engine";var zg=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Pd(e){return e.replace(/\r\n?/g,`
374
- `)}function Td(e){return e.includes(`
375
- `)||e.length>200}function Dd(e,t){let n=t.split(`
376
- `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Ad(e,t){return e.replace(zg,n=>t.get(n)??n)}function jd(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function fr(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
377
- `)){if(s.length===0)o.push({start:r,end:r});else for(let a=0;a<s.length;a+=n)o.push({start:r+a,end:r+Math.min(a+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function mr(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Ed(e,t,n){let o=mr(e,t),r=o+n;if(r<0||r>=e.length)return t;let s=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+s,e[r].end)}function Nd(e,t,n){let o=e[mr(e,t)];return n==="start"?o.start:o.end}function Id(e,t,n){let o=Math.max(1,n),r=e.split(`
359
+ `):null}async function Jc(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=wi(n,e.slice(1).join(" ").trim());return console.log(r.ok?E(r.line):O(r.line)),{kind:"continue"}}let o=gi(n);console.log(_(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?m(r):r);return{kind:"continue"}}var Zc={help:Br,"?":Br,clear:Na,exit:Vr,quit:Vr,init:Xr,mcp:jo,publish:xl,audit:jn,discover:vl,scope:Rl,pull:Ol,resolve:Nl,convert:Ll,write:ql,draft:zl,document:Kl,resume:Jl,rename:Zl,profile:tc,model:rc,doctor:In,workspace:dc,project:uc,"allow-prod":pc,login:hc,logout:fc,screenshot:Go,capture:jc,"capture-setup":_n,devhints:Ba,inbox:Nc,"catch-up":Ic,update:_c,reset:Wc,check:Fc,review:Vc,reorder:Gc,structure:Bc,genre:Zo,roadmap:Jc};function ed(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}rt();var Hm="Or just tell me what to write or update.",qm='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function de(e){return e===1?"":"s"}function er(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Un(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var Bm={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",options:[{cmd:"/genre web",desc:"web app / SaaS UI"},{cmd:"/genre cli",desc:"command-line tool"},{cmd:"/genre service",desc:"API / backend service"},{cmd:"/genre library",desc:"SDK / library"}]};function Vm(e){let t=[];if(e.devhints!=="current"&&e.builderStarted){let n=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",o=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";t.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${n}${o} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${n}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&t.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:Bm,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.discovery&&e.discovery.status!=="confident"){let n=e.discovery.openQuestions;t.push(e.discovery.status==="pending"?{key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/publish steps)."}:n>0?{key:"discovery",bullet:`product discovery is waiting on ${n} answer${de(n)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}:{key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.directives>0||e.pendingText){let n=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",o=[];e.directives>0&&o.push(`${e.directives} owner directive${de(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
360
+ \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${de(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${de(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${de(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${de(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${de(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${de(n)} changed both here and on Document360 (conflicts) \u2014 /publish skips these`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each conflict \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${n} conflict${de(n)} (keep yours / take the portal's / skip).`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${de(n.total)} done \u2014 next: ${o.title}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${de(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${de(n)}.`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${de(n)} under .d360-writer/ \u2014 a commit request is standing in your builder's mailbox (the sync bookkeeping in there protects against duplicate publishes)`,lead:null,picker:null,follow:null})}return t}function td(e){return e.find(t=>t.lead||t.picker)??null}function yi(e,t){let n=t.filter(a=>a.bullet).map(a=>` \u2022 ${a.bullet}`),o=td(t),r=[];o?.lead?r.push(Un(o.lead)):o?.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let a of t.filter(p=>p!==o).slice(0,2))a.follow&&r.push(a.follow);let s=[[e,...n].join(`
361
+ `)];return r.length&&s.push(r.join(" ")),s.push(Hm),s.join(`
362
+
363
+ `)}function Wn(e){if(!e.ready)return{kind:"idle"};let t=Vm(e);if(!e.hasDocs){let s=td(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:yi("\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:qm,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null}}}if(t.length===0){let s=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${de(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${de(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${s}`,tone:"info",lead:null,picker:null}}}let n=t.filter(s=>s.lead||s.picker),o=n[0]??null;return o?(o.key==="audit"||o.key==="roadmap"&&n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${de(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:yi("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:yi("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as ki,readdirSync as $i}from"node:fs";import{spawnSync as Gm}from"node:child_process";import{join as tr}from"node:path";import{readProjectConfig as od,resolveActiveProfile as rd,loadTokens as Ym,isExpired as zm,loadProfileMap as sd,localAheadPaths as Km,loadKnownConflicts as Xm,readDocsPlan as Qm,devHintsGuidePath as Jm,DEFAULT_DOCS_DIR as bi,roadmapProgress as Zm,listRoadmap as eg,readProductBriefState as tg,reconcileCommitRequest as ng}from"document360-engine";rt();function nd(e){try{return $i(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function xi(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>nd(tr(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&nd(tr(e,o)))}function vi(e,t){try{let n=od(e);if(!n)return!1;let o=rd(e,t),r=sd(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=tr(e,(n.docsDir??bi).replace(/\/+$/,""));return!!(ki(s)&&$i(s).length>0||ki(Jm(e)))}catch{return!1}}function Fn(e,t,n){try{let o=od(e);if(!o)return null;let r=rd(e,t),s=Ym(r.name),a=!!s&&(!zm(s)||!!s.refreshToken),p=vi(e,t)||!xi(e,o.authoritativeSourceFiles),g=sd(e,r.name),k=g?Object.keys(g.articles).length:0,y=tr(e,(o.docsDir??bi).replace(/\/+$/,"")),S=!1;try{S=ki(y)&&$i(y).length>0}catch{}let v=0;if(g?.lastAnalyzedCommit)try{let xe=Gm("git",["rev-list","--count",`${g.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});xe.status===0&&(v=parseInt((xe.stdout||"").trim(),10)||0)}catch{}let I=0;try{let xe=Qm(e);if(xe.length>0){let dt=(o.docsDir??bi).replace(/\/+$/,"");I=Ts(e,dt,xe.map(He=>He.path)).length}}catch{}let R=On(e),N=Ln({...R,directives:0}),T=Km(e,t),L=new Set(Xm(e,r.name)),G=T.filter(xe=>L.has(xe)).length,Y=T.length-G,z=Ie(e),pe=Zm(e),Xe=ng(e,new Date().toISOString()),fe=tg(e),At=fe?{status:fe.status,openQuestions:fe.openQuestions}:null;return!At&&S&&eg(e).some(dt=>dt.status==="open"&&(dt.run??"").trim()==="/discover")&&(At={status:"pending",openQuestions:0}),{ready:a&&p&&!n.claudeMissing,hasDocs:S,tracked:k,pendingText:N,directives:R.directives,behind:v,pendingWrites:I,localAhead:Y,conflicts:G,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:z.status,devhintsCompletedVersion:z.completedVersion,devhintsToVersion:ae,builderStarted:ze(e),genreUnknown:n.genreUnknown,roadmap:pe,discovery:At,uncommittedDocs:Xe.dirty.length}}catch{return null}}function id(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 nr(e){if(e.length===0)return[];let t=(s,a)=>`${s}${"\u2500".repeat(78)}${a}`,n=(s="")=>`\u2502 ${s.padEnd(76)} \u2502`,o=[`\u2B06 d360-writer upgraded \u2014 ${e.length===1?"one improvement affects":`${e.length} improvements affect`} the docs you've already written:`,"",t("\u250C","\u2510")];e.forEach((s,a)=>{a>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let p of id(`${a+1}. ${s.feature}`,76))o.push(n(p));o.push(n());for(let p of id(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 og={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"},ld=160,Ri=200,cd=40;function Pe(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function ad(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}: ${Pe(typeof r=="string"?r:JSON.stringify(r),cd)}`);return t.length>4&&n.push("\u2026"),Pe(n.join(", "),ld)}var lt=e=>typeof e=="string"&&e?e:null,Ci=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function rg(e){let t=lt(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 sg(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=lt(t.title);if(!o)return null;let r=rg(t.local_path);return n("Create article",`"${Pe(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=lt(t.title),r=Ci(t.article_id);return n("Update article",o?`"${Pe(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Ci(t.article_id)?`id ${Ci(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",lt(t.name)?`"${Pe(lt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=lt(t.file_path);return n("Upload image",o?Pe(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function or(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),a=s.join("__");if(r==="document360"){let k=sg(a,t);if(k)return k}let p=a.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:ad(t)}}let n=og[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:Pe(o,ld)}:{title:e,sep:"",arg:ad(t)}}function ig(e){if(e===null||typeof e!="object")return typeof e=="string"?e:null;let t=e;for(let n of["name","title","slug","id"])if(typeof t[n]=="string"&&t[n])return t[n];return null}function ag(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(ig).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Pe(r,Ri))]}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}: ${Pe(String(r),cd)}`);return n.length>0?[Pe(n.join(" \xB7 "),Ri)]:null}return null}function lg(e){let t=lt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function cg(e,t,n){switch(e){case"d360_create_article":{let o=lg(t?.local_path);return[`\u2713 draft created${o?` \xB7 ${o}`:""}`]}case"d360_update_article":return["\u2713 draft updated"];case"d360_fork_article":return["\u2713 forked to a new draft"];case"d360_publish_article":return["\u2713 PUBLISHED LIVE \u2014 visible to readers"];case"d360_unpublish_article":return["\u2713 reverted to draft (removed from readers)"];case"d360_create_category":{let o=lt(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 ${Pe(o[0],120)}`:""}`]}default:return null}}function rr(e,t=4,n,o){let r=e.replace(/\r\n/g,`
364
+ `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let a=cg(n.slice(18),o,r);if(a)return{lines:a,hidden:0}}let s=ag(r)??r.split(`
365
+ `);return{lines:s.slice(0,t).map(a=>Pe(a,Ri)),hidden:Math.max(0,s.length-t)}}function sr(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function ir(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 dd(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 ar(e){return dd(e,"url")}function lr(e){return dd(e,"preview_url")}var Dg=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Ag(e,t,n,o){if(Dg.test(e))try{let r=hd(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,a=ir(t,n),p=ar(n);e.endsWith("publish_article")&&p&&console.log(_(` \u2B95 Live: ${p}`));let g=lr(n);g?console.log(_(` \u2B95 Preview: ${g}`)):a&&s&&console.log(_(` \u2B95 Preview: ${sr(r.connection.portalUrl,s,a,r.project.languageCode??"en")}`))}catch{}}async function fd(e=process.cwd(),t="auto",n,o){let r=ug(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${_("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${_('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),jg(e,n),r.kind==="subscription"&&(r.stored?console.log(m(" Using your Claude subscription (no API key set).")):console.log(m(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,a=Si({cwd:e,profileName:n,allowProdWrites:s}),p={uuid:null,firstPrompt:null,titleFired:!1},g=dg({input:process.stdin,output:process.stdout}),k=[],y=null,S=!1;g.on("line",R=>{if(y){let N=y;y=null,N(R)}else k.push(R)}),g.on("close",()=>{if(S=!0,y){let R=y;y=null,R(null)}});function v(){return k.length>0?Promise.resolve(k.shift()):S?Promise.resolve(null):(process.stdout.write(_("> ")),new Promise(R=>{y=R}))}let I={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{a.close(),a=Si({cwd:e,profileName:n,allowProdWrites:s}),p={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>p.uuid,setPendingName:R=>{p.pendingName=R},setModel:async R=>a.setModel(R),withPausedInput:async R=>{g.pause();try{return await R()}finally{g.resume()}}};try{for(;;){let R=await v();if(R===null)break;let N=R.trim();if(N){if(N.startsWith("/")){let T=ed(N);if(!T)continue;let L=Zc[T.name];if(!L){console.log(C(`Unknown command: /${T.name}`)),console.log(m("Type /help for the list."));continue}let G=await L(T.args,I);if(G.kind==="exit")break;if(G.kind==="clear"){I.restartAgent();continue}if(G.kind==="allow-prod"){s=!0,I.restartAgent(),console.log(E("\u2713 Production writes authorized for this session.")),console.log("");continue}if(G.kind==="resume"){a.close(),a=Si({cwd:e,resume:G.uuid,profileName:n,allowProdWrites:s});let Y=pg(G.uuid);p={uuid:G.uuid,firstPrompt:Y?.firstPrompt??null,titleFired:!0},pd(G.uuid),console.log(E(`\u2713 Resumed "${G.name}"`)),console.log("");continue}if(G.kind==="forward-to-agent"){p.firstPrompt||(p.firstPrompt=G.display??G.prompt);let Y=(G.display??"").trim().split(/\s+/),z=(Y[0]==="/check"||Y[0]==="/review")&&Y.includes("--fix"),pe=Y.slice(1).find(fe=>!fe.startsWith("--")),Xe=z?Pg(e,pe):[];if(await Pi(a,G.prompt,r,p,e),z)try{Sg(e,Xe,{reviewedCap:Tg})}catch{}}else Eg(e,n);continue}if(xg(N)){let T=vg(N);if(T){try{Cg(e,{title:T,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}p.firstPrompt||(p.firstPrompt=N),await Pi(a,`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 Pi(a,N,r,p,e)}}}finally{a.close(),g.close()}}function jg(e,t){console.log(""),console.log(xn("document360-writer")),console.log(m(` cwd: ${e}`));let n=wg(e);if(console.log(m(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Ng(e,t)),!yg(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(So(e),!ze(e))for(let r of Po(e))console.log(O(` ${r}`))}catch{}try{let r=kg(e);r.persisted&&r.appType?console.log(m(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=Rg(e);for(let s of nr(r.applied))console.log(O(` ${s}`))}catch{}try{let r=Fn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Wn(r):null;if(s?.kind==="recommend"&&s.rec.note){let a=s.rec.tone==="warn"?O:m;for(let p of rs(s.rec.note).split(`
366
+ `))console.log(a(` ${p}`));s.rec.picker&&console.log(_(` Pick one: ${s.rec.picker.options.map(p=>p.cmd).join(" \xB7 ")}`))}}catch{}}console.log(m(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Eg(e,t){try{let n=Fn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Wn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(m(` Next: ${Un(o.rec.lead)}`))}catch{}}function Ng(e,t){try{let n=hd(e,t),o=n.production?O(" \u26A0 PRODUCTION"):"",r=$g(n.name);if(!r)return m(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...ud(r.idToken)??{},...ud(r.accessToken)??{}},a=s.email??s.preferred_username??"signed in";return bg(r)&&!r.refreshToken?O(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):m(` Document360: ${a} \xB7 profile "${n.name}"${o}`)}catch(n){return m(` Document360: ${n.message.split(".")[0]}`)}}function Ig(){console.error(""),console.error(`Sign in with your Claude subscription: run ${_("claude")} once, then retry.`),console.error(` (No Claude Code? ${_("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${_("https://console.anthropic.com/settings/keys")}`)}function _g(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;mg({uuid:t,name:r??fg(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Og(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||gg(o,t).then(r=>{r&&hg(n,r)}).catch(()=>{})}async function Pi(e,t,n,o,r){let s=new Map;for await(let a of e.send(t))Lg(a,o,r,n,s)}function Lg(e,t,n,o,r){switch(e.type){case"session":t.uuid||_g(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=or(e.name,e.input);s&&(process.stdout.write(`
367
+
368
+ `),console.log(`${E("\u25CF")} ${be(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=Ke(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let a=p=>p===1?"":"s";console.log(ie(` \u23BF Added ${s.added} line${a(s.added)}, removed ${s.removed} line${a(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(m(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let a=rr(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?C:ie;a.lines.forEach((g,k)=>console.log(p((k===0?" \u23BF ":" ")+g))),a.hidden>0&&console.log(m(` \u2026 +${a.hidden} lines`)),e.isError||Ag(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
369
+ `);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(m(` (${Tn(s)}\u2192${Tn(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(pd(t.uuid),t.titleFired||Og(t,n));break}case"error":console.error(""),console.error(C(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Ig();break}}import{render as Jw}from"ink";import{resolveAuth as Zw}from"document360-engine";import{useCallback as B,useEffect as De,useMemo as Ni,useRef as Z,useState as F}from"react";import{Box as re,Text as D,useApp as Jg,useInput as Zg,useStdout as ew}from"ink";import{existsSync as sn,readFileSync as gr,readdirSync as tw}from"node:fs";import{basename as qn,isAbsolute as nw,join as Ii}from"node:path";import{createSession as Ud,classifyClaudeAuth as Wi,CLAUDE_CODE_SETUP_HINT as ow,loginPkce as rw,toStoredTokens as sw,saveTokens as iw,getAccessToken as aw,resolveActiveProfile as Te,resolveProjectId as lw,getArticle as cw,decodeJwtClaims as ln,isExpired as ct,loadTokens as Dt,clearTokens as dw,clearProfileProject as uw,setTitle as pw,slugify as hw,touchSession as _i,upsertSession as fw,generateTitle as Wd,findByName as mw,listSessions as gw,renameSession as ww,suggestNextAction as yw,readProjectConfig as oe,writeProjectConfig as Fd,resolveAndPersistAppType as kw,detectAppType as bw,resolveModelSetting as Fi,loadProfileMap as Hd,applyPull as qd,computeSyncStatus as Oi,lintDocs as Bd,compareRemoteSources as $w,planPull as Vd,establishBaselines as xw,rebaselineServerMeta as vw,inventoryRepo as Cw,knownEnvironments as Rw,resolveEnvironment as Sw,planPartitions as Li,partitionEvenly as Pw,screenshotPlaceholderIds as Tw,trackedArticlePaths as Dw,runPartitioned as wr,estimateBulkCost as Gd,resolveModelForOperation as yr,readDocsPlan as Aw,checkForUpdate as jw,detectInstallKind as Ew,isSelfUpdatable as Nw,devHintsGuidePath as Yd,toolFeedbackPath as zd,reconcileToolFeedback as Iw,reconcileUpgradeActions as _w,stampArticles as Mi,listArticleFiles as Kd,CONTENT_CAP_VERSION as Ui,ENGINE_VERSION as ou,DEFAULT_DOCS_DIR as ru,setProfileProject as Ow,writeCrashLog as Lw,applyStructureOrder as Xd,orderSyncLine as Qd,applyRelatedArticles as Jd,relatedSyncLine as Zd}from"document360-engine";rt();import{spawn as md}from"node:child_process";function Mg(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Ug(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?md([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):md(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",a=>o(a===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function Ti(e){for(let[t,n]of Mg())if(await Ug(t,n,e))return!0;return!1}var Wg=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Di(e,t){if(t.closed)return e;let n=e.split(`
370
+ `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){Wg.test(s)&&(t.cueSeen=!0);continue}let a=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);a?(n[r]=`${a[1]}${++t.num}. ${a[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
371
+ `)}import{existsSync as Fg,mkdirSync as Hg,readFileSync as qg,writeFileSync as Bg}from"node:fs";import{join as gd}from"node:path";import{writerDir as Vg}from"document360-engine";function wd(e){return gd(Vg(e),".sessions")}function yd(e,t){return gd(wd(e),`${t}.json`)}function kd(e,t,n){try{Hg(wd(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Bg(yd(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Ai(e,t){try{let n=yd(e,t);if(!Fg(n))return[];let o=JSON.parse(qg(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Gg=e=>`\x1B]0;${e}\x07`,Yg=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function bd(e){process.stdout.isTTY&&process.stdout.write(e)}function rn(e){bd(Gg(e))}function cr(e){bd(Yg(e))}var dr=["\xB7 "," \xB7"],ur="\u{1F7E3}";Bo();Ao();W();import{Box as $d,Text as ce}from"ink";import{jsx as ue,jsxs as pr}from"react/jsx-runtime";function zg({row:e}){switch(e.t){case"head":return ue(ce,{color:q,bold:!0,children:e.s});case"text":return ue(ce,{children:e.s});case"dim":return ue(ce,{dimColor:!0,children:e.s});case"sub":return ue(ce,{bold:!0,dimColor:!0,children:e.s});case"good":return ue(ce,{color:"green",children:e.s});case"step":return pr(ce,{children:[ue(ce,{color:q,children:`${e.n}. `}),e.s]});case"cmd":return pr(ce,{children:[" ",ue(ce,{color:q,children:e.name.padEnd(20)}),ue(ce,{dimColor:!0,children:e.s})]});case"gap":return ue(ce,{children:" "})}}function xd({tab:e,width:t,version:n,engineVersion:o}){let r=Ne[e]??Ne[0],s=6+Ne.reduce((p,g)=>p+g.label.length+4,0),a="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return pr($d,{flexDirection:"column",paddingX:1,children:[pr(ce,{children:[ue(ce,{color:q,bold:!0,children:"Help "}),Ne.map((p,g)=>g===e?ue(ce,{color:"white",backgroundColor:q,bold:!0,children:` ${p.label} `},p.key):ue(ce,{dimColor:!0,children:` ${p.label} `},p.key))]}),ue(ce,{color:q,children:a}),ue($d,{flexDirection:"column",marginTop:1,children:r.rows.map((p,g)=>ue(zg,{row:p},g))}),ue(ce,{dimColor:!0,children:`
372
+ \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var Kg=/^(?:\d+[.)]|[-*•])\s+/;function vd(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
373
+ `)){let a=s.trim().replace(Kg,""),p=a.match(/^`([^`]+)`$/);p&&(a=p[1].trim());let g=a.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!g||!o.has(g[1].toLowerCase()))continue;let k=`/${g[1].toLowerCase()}${g[2]?` ${g[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}W();function Hn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Oe(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Cd(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Xg=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Rd(e,t,n){if(!Xg.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(s=>{let a=s.replace(/\\/g,"/");return r===a||r.endsWith(`/${a}`)})??null}function ji(e){return e.replace(/^[\w.-]+\//,"")}var hr=16,Sd={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Tt(e){return typeof e=="string"?e:e.cmd}function Pd(e){return typeof e=="string"?void 0:e.desc}function Ei(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Td(e,t){let n=Ei(t);return e.some(r=>Tt(r).trim()===t.trim()||!!n&&Ei(Tt(r))===n)?e.filter(r=>Tt(r).trim()!==t.trim()&&!(n&&Ei(Tt(r))===n)):[]}import{isDirectiveMention as Mw,stripDirectiveMention as Uw,appendDirective as Ww}from"document360-engine";var Qg=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Dd(e){return e.replace(/\r\n?/g,`
374
+ `)}function Ad(e){return e.includes(`
375
+ `)||e.length>200}function jd(e,t){let n=t.split(`
376
+ `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Ed(e,t){return e.replace(Qg,n=>t.get(n)??n)}function Nd(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function fr(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
377
+ `)){if(s.length===0)o.push({start:r,end:r});else for(let a=0;a<s.length;a+=n)o.push({start:r+a,end:r+Math.min(a+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function mr(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Id(e,t,n){let o=mr(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 _d(e,t,n){let o=e[mr(e,t)];return n==="start"?o.start:o.end}function Od(e,t,n){let o=Math.max(1,n),r=e.split(`
378
378
  `),s=0;for(let a=r.length-1;a>=0;a--){let p=r[a];if(s+=Math.max(1,Math.ceil(p.length/o)),s>=t){let g=s-t;return{text:[g>0?p.slice(g*o):p,...r.slice(a+1)].join(`
379
- `),truncated:a>0||g>0}}}return{text:e,truncated:!1}}function _d(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 Od(e){let t=!1,n=0,o=0;for(let r of e.split(`
380
- `)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as Bn,jsx as A,jsxs as V}from"react/jsx-runtime";var Mw={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},Jd=` 1. /init \u2014 pick your Document360 environment & scaffold config
379
+ `),truncated:a>0||g>0}}}return{text:e,truncated:!1}}function Ld(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 Md(e){let t=!1,n=0,o=0;for(let r of e.split(`
380
+ `)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as Bn,jsx as A,jsxs as V}from"react/jsx-runtime";var Fw={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},eu=` 1. /init \u2014 pick your Document360 environment & scaffold config
381
381
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
382
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Uw(e,t,n,o){let r=Wi(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",a=Fi(e),p=oe(e),g=(p?.docsDir??nu).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${g}/ + config`,y={version:t,engineVersion:tu,claude:s,model:a.model,modelSource:Mw[a.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 y;try{let S=Te(e,o);y.profile=S.name,y.apiUrl=S.connection.apiUrl,y.prod=S.production,y.project=S.project.projectName??S.project.projectId??"(chosen at login)";let v=Dt(S.name);if(v){let I={...ln(v.idToken)??{},...ln(v.accessToken)??{}},R=I.email??I.preferred_username??"signed in";ct(v)?v.refreshToken&&(y.who=R,y.loggedOut=!1,y.sessionHint="session expired \u2014 refreshing\u2026"):(y.who=R,y.loggedOut=!1,y.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return y}function Ww(e,t){try{let n=Te(e,t),o=Dt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...ln(o.idToken)??{},...ln(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return ct(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 Zd=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],cn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Fw="Ask me to write or update an article\u2026";function an({ch:e,dim:t}){let[n,o]=F(!0);return De(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),A(D,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Hw=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function eu(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var qw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Bw({startTime:e,chars:t}){let[n,o]=F(0);De(()=>{let g=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(g)},[]);let r=cn[n%cn.length],s=Zd[Math.floor(n/16)%Zd.length],a=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return V(re,{children:[A(D,{color:q,children:` ${r} ${s}\u2026 `}),A(D,{color:"gray",children:`(${Dn(a)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function Vw({text:e}){let[t,n]=F(0);return De(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),A(re,{paddingX:1,children:A(D,{color:q,children:`${cn[t%cn.length]} ${e}`})})}var Gw=12e4;function Yw({p:e}){let[t,n]=F(0);De(()=>{let T=setInterval(()=>n(L=>L+1),150);return()=>clearInterval(T)},[]);let o=cn[t%cn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),a=Math.round(e.chars/4),p=Date.now()-e.lastAt>=Gw,g=e.verb??"Converting",k=e.unit??"article",y=e.rows.reduce((T,L)=>T+L.items,0),S=g.toLowerCase(),v=e.rows,I=0;if(v.length>hr){let T=v.findIndex(G=>G.status==="active"||G.status==="pending"),L=Math.max(0,Math.min(T-2,v.length-hr));I=v.slice(0,L).filter(G=>G.status==="done").length,v=v.slice(L,L+hr)}let R=Math.min(40,Math.max(...v.map(T=>ji(T.label).length),0)),E=T=>T==="failed"?"red":T==="active"?q:void 0;return V(re,{flexDirection:"column",children:[V(re,{children:[A(D,{color:q,children:` ${o} ${g} ${y} ${k}${y===1?"":"s"} `}),A(D,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${a} tokens \xB7 ${Dn(r)} \xB7 esc to stop`})]}),I>0&&A(D,{dimColor:!0,children:` \u2714 +${I} done`}),v.map(T=>V(D,{color:E(T.status),dimColor:T.status==="done"||T.status==="pending",children:[` ${Cd[T.status]} ${ji(T.label).padEnd(R)}`,T.status==="active"&&T.itemsDone!==void 0?` (${T.itemsDone}/${T.items} ${k}${T.items===1?"":"s"})`:T.status!=="pending"?` (${T.items} ${k}${T.items===1?"":"s"})`:"",T.status==="active"?` \u2190 ${S}\u2026`:""]},T.label)),p&&A(D,{color:"yellow",children:` \u26A0 no activity for ${Dn(s)} \u2014 press esc to stop if it's wedged`})]})}var zw=10800*1e3;function ou({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Kg(),[s,a]=F(n),[p,g]=F(null),[k,y]=F({text:"",pos:0}),S=k.text,v=B(c=>{y(l=>{let i=typeof c=="function"?c(l.text):c;return{text:i,pos:i.length}})},[]),I=B(c=>{y(l=>({text:l.text.slice(0,l.pos)+c+l.text.slice(l.pos),pos:l.pos+c.length}))},[]),R=B(()=>{y(c=>{if(c.pos===0)return c;let l=c.text.slice(0,c.pos),i=jd(l)??l.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[E,T]=F(!1),[L,G]=F(!1),[Y,z]=F(0),[pe,Xe]=F(!1),[fe,At]=F(null),[$e,dt]=F(null),[He,ut]=F([]),Vn=Z(!1),br=Z(!1),[$r,Vi]=F(!1),Gn=Z(0),[du,Yn]=F(!1),[uu,zn]=F(!1),[xr,Gi]=F(null),[pu,jt]=F(0),pt=Z(0),[dn,Et]=F(0),[Nt,Kn]=F(null),Yi=Z(new Map),hu=Z(0),It=Z([]),Ae=Z(null);Ae.current===null&&(Ae.current=Ld({cwd:e,profileName:s,allowProdWrites:!1}));let qe=Z({uuid:null,firstPrompt:null,titleFired:!1}),Xn=Z(new Map),_t=Z(!1),vr=Z([]),le=Z([]),Ot=Z([]),Qn=Z(null),[zi,ht]=F(null),Cr=Z(null),[ft,mt]=F(null),[Be,Lt]=F(null),[Ve,Mt]=F(null),[me,Ut]=F(null),[xe,gt]=F(null),[Qe,Wt]=F(null),[Je,wt]=F(null),[Ge,yt]=F(null),[Ki,un]=F(null),[ve,kt]=F(null),[we,Ft]=F(null),[Xi,Rr]=F([]),bt=Z([]),pn=Z(!1),ye=Z(null),[Jn,te]=F(null),[Qi,Ji]=F(null),Zn=Z(!1),hn=Z(null),fn=Z(null),[Ce,$t]=F(null),[eo,mn]=F(null),Sr=!!(Ve||me||xe||Qe||Je||Ge||ve||we||Ce||eo),[Zi,Ht]=F(0),[ea,qt]=F(0),[fu,ta]=F(0),Pr=Ni(()=>{try{let c=Fi(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,fu]),{stdout:Me}=Qg(),[,mu]=F(0),na=Z(`${Me.columns??80}x${Me.rows??24}`),Ze=B(()=>Math.max(20,(Me.columns??80)-1),[Me]),u=B(c=>{It.current.push(c),console.log(ss(c,Ze()))},[Ze]),ge=B((c,l)=>{Gn.current++,At(c),dt(l??null)},[]),Ue=B(()=>{Gn.current++,At(null),dt(null)},[]),X=B(c=>ge(c,er({kind:"cmd",cmd:c,reason:""})),[ge]),to=B((c,l)=>{!l?.silent&&c.note&&u({kind:"note",tone:c.tone,text:c.note}),c.picker&&(ut(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),un(c.picker.title)),c.lead&&ge(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,er(c.lead))},[u,ge]),Re=B((c,l,i="info")=>{c&&u({kind:"note",tone:i,text:c}),l&&ge(l.kind==="cmd"?l.cmd:l.text,er(l))},[u,ge]),[gn,Tr]=F(null),[gu,oa]=F(!1),Bt=B(c=>{Tr(c),oa(!1),u({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),Dr=Z(!1),Ar=B(async()=>{try{if(Dr.current||!Aw(Dw())||oe(e)?.mode==="engineer")return;let c=await Tw({pkg:Pt,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;Dr.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${Pt} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),zn(!0),(await Xo().finally(()=>zn(!1))).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),X("/exit"),Gi(c.latest)):u({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${Ko}`})}catch{}},[e,o,u,X]),no=B(c=>{let l=_e(e,s);return l.ok?!0:(u({kind:"note",tone:"warn",text:l.reason}),fn.current=c,X("/login"),!1)},[e,s,u,X]),[oo,jr]=F(null),xt=B(c=>{let l=Fn(e,s,{claudeMissing:Wi(t).state==="missing",allowAutoAudit:c,genreUnknown:br.current});return l?Wn(l):{kind:"idle"}},[e,s,t]),wn=Z(!0),Vt=Z(!1),ro=Z(0),yn=Z(0);De(()=>{let c=setInterval(()=>{if(wn.current){ro.current=0,yn.current=0;return}if(!E)try{if(!sn(Vd(e)))return;if(Ie(e).status==="current"){wn.current=!0,ro.current=0,yn.current=0;let i=xt(!1),f=i.kind==="recommend"?i.rec:null,d=Vt.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.";u({kind:"note",tone:"ok",text:`${d}${f?.lead?` ${Un(f.lead)}`:""}`}),Tr(null),f&&(f.lead||f.picker)?to(f,{silent:!0}):Vt.current||ge("write the docs for this repo"),z(w=>w+1);return}if(Vt.current)return;ro.current+=1;let l=ro.current;if((l===4||l%15===0)&&yn.current<3){yn.current+=1;let i=yn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";u({kind:"note",tone:"info",text:ze(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${i}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${i}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,E,u,xt,to,ge]),De(()=>{let c=zi??qn(e);if(!E){cr(0),rn(`${ur} ${c}`);return}cr(3);let l=0;rn(`${dr[0]} ${c}`);let i=setInterval(()=>{l=(l+1)%dr.length,rn(`${dr[l]} ${c}`)},400);return()=>clearInterval(i)},[E,e,zi]),De(()=>()=>cr(0),[]),De(()=>{let c=performance.now(),l=[],i=(h,x)=>{let b=performance.now();try{return x()}finally{let U=Math.round(performance.now()-b);U>=80&&l.push(`${h}: ${U}ms`)}};u({kind:"banner",info:i("banner",()=>Uw(e,o,t,s))});let f=Wi(t).state==="missing";if(f&&u({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
383
- ${ew}
382
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Hw(e,t,n,o){let r=Wi(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",a=Fi(e),p=oe(e),g=(p?.docsDir??ru).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${g}/ + config`,y={version:t,engineVersion:ou,claude:s,model:a.model,modelSource:Fw[a.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 y;try{let S=Te(e,o);y.profile=S.name,y.apiUrl=S.connection.apiUrl,y.prod=S.production,y.project=S.project.projectName??S.project.projectId??"(chosen at login)";let v=Dt(S.name);if(v){let I={...ln(v.idToken)??{},...ln(v.accessToken)??{}},R=I.email??I.preferred_username??"signed in";ct(v)?v.refreshToken&&(y.who=R,y.loggedOut=!1,y.sessionHint="session expired \u2014 refreshing\u2026"):(y.who=R,y.loggedOut=!1,y.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return y}function qw(e,t){try{let n=Te(e,t),o=Dt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...ln(o.idToken)??{},...ln(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return ct(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 tu=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],cn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Bw="Ask me to write or update an article\u2026";function an({ch:e,dim:t}){let[n,o]=F(!0);return De(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),A(D,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Vw=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function nu(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 Yw({startTime:e,chars:t}){let[n,o]=F(0);De(()=>{let g=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(g)},[]);let r=cn[n%cn.length],s=tu[Math.floor(n/16)%tu.length],a=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return V(re,{children:[A(D,{color:q,children:` ${r} ${s}\u2026 `}),A(D,{color:"gray",children:`(${Dn(a)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function zw({text:e}){let[t,n]=F(0);return De(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),A(re,{paddingX:1,children:A(D,{color:q,children:`${cn[t%cn.length]} ${e}`})})}var Kw=12e4;function Xw({p:e}){let[t,n]=F(0);De(()=>{let T=setInterval(()=>n(L=>L+1),150);return()=>clearInterval(T)},[]);let o=cn[t%cn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),a=Math.round(e.chars/4),p=Date.now()-e.lastAt>=Kw,g=e.verb??"Converting",k=e.unit??"article",y=e.rows.reduce((T,L)=>T+L.items,0),S=g.toLowerCase(),v=e.rows,I=0;if(v.length>hr){let T=v.findIndex(G=>G.status==="active"||G.status==="pending"),L=Math.max(0,Math.min(T-2,v.length-hr));I=v.slice(0,L).filter(G=>G.status==="done").length,v=v.slice(L,L+hr)}let R=Math.min(40,Math.max(...v.map(T=>ji(T.label).length),0)),N=T=>T==="failed"?"red":T==="active"?q:void 0;return V(re,{flexDirection:"column",children:[V(re,{children:[A(D,{color:q,children:` ${o} ${g} ${y} ${k}${y===1?"":"s"} `}),A(D,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${a} tokens \xB7 ${Dn(r)} \xB7 esc to stop`})]}),I>0&&A(D,{dimColor:!0,children:` \u2714 +${I} done`}),v.map(T=>V(D,{color:N(T.status),dimColor:T.status==="done"||T.status==="pending",children:[` ${Sd[T.status]} ${ji(T.label).padEnd(R)}`,T.status==="active"&&T.itemsDone!==void 0?` (${T.itemsDone}/${T.items} ${k}${T.items===1?"":"s"})`:T.status!=="pending"?` (${T.items} ${k}${T.items===1?"":"s"})`:"",T.status==="active"?` \u2190 ${S}\u2026`:""]},T.label)),p&&A(D,{color:"yellow",children:` \u26A0 no activity for ${Dn(s)} \u2014 press esc to stop if it's wedged`})]})}var Qw=10800*1e3;function su({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Jg(),[s,a]=F(n),[p,g]=F(null),[k,y]=F({text:"",pos:0}),S=k.text,v=B(c=>{y(l=>{let i=typeof c=="function"?c(l.text):c;return{text:i,pos:i.length}})},[]),I=B(c=>{y(l=>({text:l.text.slice(0,l.pos)+c+l.text.slice(l.pos),pos:l.pos+c.length}))},[]),R=B(()=>{y(c=>{if(c.pos===0)return c;let l=c.text.slice(0,c.pos),i=Nd(l)??l.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[N,T]=F(!1),[L,G]=F(!1),[Y,z]=F(0),[pe,Xe]=F(!1),[fe,At]=F(null),[xe,dt]=F(null),[He,ut]=F([]),Vn=Z(!1),br=Z(!1),[$r,Vi]=F(!1),Gn=Z(0),[pu,Yn]=F(!1),[hu,zn]=F(!1),[xr,Gi]=F(null),[fu,jt]=F(0),pt=Z(0),[dn,Et]=F(0),[Nt,Kn]=F(null),Yi=Z(new Map),mu=Z(0),It=Z([]),Ae=Z(null);Ae.current===null&&(Ae.current=Ud({cwd:e,profileName:s,allowProdWrites:!1}));let qe=Z({uuid:null,firstPrompt:null,titleFired:!1}),Xn=Z(new Map),_t=Z(!1),vr=Z([]),le=Z([]),Ot=Z([]),Qn=Z(null),[zi,ht]=F(null),Cr=Z(null),[ft,mt]=F(null),[Be,Lt]=F(null),[Ve,Mt]=F(null),[me,Ut]=F(null),[ve,gt]=F(null),[Qe,Wt]=F(null),[Je,wt]=F(null),[Ge,yt]=F(null),[Ki,un]=F(null),[Ce,kt]=F(null),[we,Ft]=F(null),[Xi,Rr]=F([]),bt=Z([]),pn=Z(!1),ye=Z(null),[Jn,te]=F(null),[Qi,Ji]=F(null),Zn=Z(!1),hn=Z(null),fn=Z(null),[Re,$t]=F(null),[eo,mn]=F(null),Sr=!!(Ve||me||ve||Qe||Je||Ge||Ce||we||Re||eo),[Zi,Ht]=F(0),[ea,qt]=F(0),[gu,ta]=F(0),Pr=Ni(()=>{try{let c=Fi(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,gu]),{stdout:Me}=ew(),[,wu]=F(0),na=Z(`${Me.columns??80}x${Me.rows??24}`),Ze=B(()=>Math.max(20,(Me.columns??80)-1),[Me]),u=B(c=>{It.current.push(c),console.log(ss(c,Ze()))},[Ze]),ge=B((c,l)=>{Gn.current++,At(c),dt(l??null)},[]),Ue=B(()=>{Gn.current++,At(null),dt(null)},[]),X=B(c=>ge(c,er({kind:"cmd",cmd:c,reason:""})),[ge]),to=B((c,l)=>{!l?.silent&&c.note&&u({kind:"note",tone:c.tone,text:c.note}),c.picker&&(ut(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),un(c.picker.title)),c.lead&&ge(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,er(c.lead))},[u,ge]),ke=B((c,l,i="info")=>{c&&u({kind:"note",tone:i,text:c}),l&&ge(l.kind==="cmd"?l.cmd:l.text,er(l))},[u,ge]),[gn,Tr]=F(null),[yu,oa]=F(!1),Bt=B(c=>{Tr(c),oa(!1),u({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),Dr=Z(!1),Ar=B(async()=>{try{if(Dr.current||!Nw(Ew())||oe(e)?.mode==="engineer")return;let c=await jw({pkg:Pt,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;Dr.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${Pt} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),zn(!0),(await Xo().finally(()=>zn(!1))).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),X("/exit"),Gi(c.latest)):u({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${Ko}`})}catch{}},[e,o,u,X]),no=B(c=>{let l=_e(e,s);return l.ok?!0:(u({kind:"note",tone:"warn",text:l.reason}),fn.current=c,X("/login"),!1)},[e,s,u,X]),[oo,jr]=F(null),xt=B(c=>{let l=Fn(e,s,{claudeMissing:Wi(t).state==="missing",allowAutoAudit:c,genreUnknown:br.current});return l?Wn(l):{kind:"idle"}},[e,s,t]),wn=Z(!0),Vt=Z(!1),ro=Z(0),yn=Z(0);De(()=>{let c=setInterval(()=>{if(wn.current){ro.current=0,yn.current=0;return}if(!N)try{if(!sn(Yd(e)))return;if(Ie(e).status==="current"){wn.current=!0,ro.current=0,yn.current=0;let i=xt(!1),f=i.kind==="recommend"?i.rec:null,d=Vt.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.";u({kind:"note",tone:"ok",text:`${d}${f?.lead?` ${Un(f.lead)}`:""}`}),Tr(null),f&&(f.lead||f.picker)?to(f,{silent:!0}):Vt.current||ge("write the docs for this repo"),z(w=>w+1);return}if(Vt.current)return;ro.current+=1;let l=ro.current;if((l===4||l%15===0)&&yn.current<3){yn.current+=1;let i=yn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";u({kind:"note",tone:"info",text:ze(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${i}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${i}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,N,u,xt,to,ge]),De(()=>{let c=zi??qn(e);if(!N){cr(0),rn(`${ur} ${c}`);return}cr(3);let l=0;rn(`${dr[0]} ${c}`);let i=setInterval(()=>{l=(l+1)%dr.length,rn(`${dr[l]} ${c}`)},400);return()=>clearInterval(i)},[N,e,zi]),De(()=>()=>cr(0),[]),De(()=>{let c=performance.now(),l=[],i=(h,x)=>{let b=performance.now();try{return x()}finally{let U=Math.round(performance.now()-b);U>=80&&l.push(`${h}: ${U}ms`)}};u({kind:"banner",info:i("banner",()=>Hw(e,o,t,s))});let f=Wi(t).state==="missing";if(f&&u({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
383
+ ${ow}
384
384
  Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!oe(e)){u({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
385
- ${Jd}`}),X(f?"/doctor":"/init");return}f&&X("/doctor");try{let h=Te(e,s),x=Dt(h.name);x&&ct(x)&&x.refreshToken?rw({profile:h.name,connection:h.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),z(b=>b+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),X("/login")}):(!x||ct(x))&&(u({kind:"note",tone:"warn",text:`Profile "${h.name}" is not signed in \u2014 sign in with /login.`}),X("/login"))}catch{}try{let h=oe(e),x=Te(e,s),b=Dt(x.name);h&&b&&!ct(b)&&xi(e,h.authoritativeSourceFiles)&&!vi(e,s)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),X("/scope"))}catch{}try{let h=i("resolve-genre",()=>gw(e));h.persisted&&h.appType?u({kind:"note",tone:"ok",text:`\u2713 Detected a ${h.appType} app \u2014 enabled the ${h.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):h.source==="unknown"&&oe(e)&&(br.current=!0)}catch{}let d=Ie(e);try{if(i("reconcile-devhints",()=>So(e)),d.status!=="current"&&!ze(e)){let h=Po(e);h.length&&(u({kind:"note",tone:"warn",text:h.join(`
386
- `)}),Bt(vt()),wn.current=!1,Vt.current=!1)}}catch{}try{let h=i("reconcile-feedback",()=>jw(e));h.archived>0&&u({kind:"note",tone:"ok",text:`\u2713 Tidied ${h.archived} resolved item${h.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${h.open>0?`; ${h.open} still open`:""}.`})}catch{}try{let h=i("upgrade-actions",()=>Ew(e));h.applied.length>0&&u({kind:"note",tone:"warn",text:nr(h.applied).join(`
387
- `)})}catch{}let w=i("ready-decision",()=>xt(!0));w.kind==="autoAudit"?(u({kind:"note",tone:"info",text:w.note}),jn().then(h=>{h.kind==="forward-to-agent"&&h.prompt&&ne(h.prompt,{display:h.display,quietUser:!0})})):w.kind==="recommend"&&to(w.rec);let $=Math.round(performance.now()-c);$>=800&&Iw({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${$}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${l.length?l.join(`
385
+ ${eu}`}),X(f?"/doctor":"/init");return}f&&X("/doctor");try{let h=Te(e,s),x=Dt(h.name);x&&ct(x)&&x.refreshToken?aw({profile:h.name,connection:h.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),z(b=>b+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),X("/login")}):(!x||ct(x))&&(u({kind:"note",tone:"warn",text:`Profile "${h.name}" is not signed in \u2014 sign in with /login.`}),X("/login"))}catch{}try{let h=oe(e),x=Te(e,s),b=Dt(x.name);h&&b&&!ct(b)&&xi(e,h.authoritativeSourceFiles)&&!vi(e,s)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),X("/scope"))}catch{}try{let h=i("resolve-genre",()=>kw(e));h.persisted&&h.appType?u({kind:"note",tone:"ok",text:`\u2713 Detected a ${h.appType} app \u2014 enabled the ${h.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):h.source==="unknown"&&oe(e)&&(br.current=!0)}catch{}let d=Ie(e);try{if(i("reconcile-devhints",()=>So(e)),d.status!=="current"&&!ze(e)){let h=Po(e);h.length&&(u({kind:"note",tone:"warn",text:h.join(`
386
+ `)}),Bt(vt()),wn.current=!1,Vt.current=!1)}}catch{}try{let h=i("reconcile-feedback",()=>Iw(e));h.archived>0&&u({kind:"note",tone:"ok",text:`\u2713 Tidied ${h.archived} resolved item${h.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${h.open>0?`; ${h.open} still open`:""}.`})}catch{}try{let h=i("upgrade-actions",()=>_w(e));h.applied.length>0&&u({kind:"note",tone:"warn",text:nr(h.applied).join(`
387
+ `)})}catch{}let w=i("ready-decision",()=>xt(!0));w.kind==="autoAudit"?(u({kind:"note",tone:"info",text:w.note}),jn().then(h=>{h.kind==="forward-to-agent"&&h.prompt&&ne(h.prompt,{display:h.display,quietUser:!0})})):w.kind==="recommend"&&to(w.rec);let $=Math.round(performance.now()-c);$>=800&&Lw({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${$}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${l.length?l.join(`
388
388
  `):"no single phase \u226580ms"}
389
- cwd: ${e}`}),Ar()},[]),De(()=>{let c=setInterval(()=>{Ar()},zw);return()=>clearInterval(c)},[Ar]),De(()=>{if(E||pe||$r||Vn.current||fe!==null||He.length>0||S!==""||gn!==null||le.current.length>0||Qn.current||Sr)return;let c=xt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&to(c.rec,{silent:!0})},[E,pe,fe,He,S,gn,Sr,Y,xt,$r]),De(()=>{let c=null,l=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let f=`${Me.columns??80}x${Me.rows??24}`;f!==na.current&&(na.current=f,mu(d=>d+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+fl(It.current,Ze())+"\x1B[?2026l")},80))},400)};return Me.on("resize",i),()=>{c&&clearTimeout(c),l&&clearTimeout(l),Me.off("resize",i)}},[Me,Ze]);let je=Math.max(20,(Me.columns??80)-1),ra=Ni(()=>Ww(e,s),[e,s,Y]),Er=(()=>{if(uu)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(xr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${xr?` v${xr}`:""}\u2026`,isSetup:!0};if(oo)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(gn)return gu?{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=oe(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let l=Ii(e,(c.docsDir??nu).replace(/\/+$/,"")),i=(()=>{try{return sn(l)&&Jg(l).length>0}catch{return!1}})();try{let f=Te(e,s),d=Dt(f.name);if(!(!!d&&!(ct(d)&&!d.refreshToken)))return{text:`Sign in with /login (profile "${f.name}")\u2026`,isSetup:!0};if(!f.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!f.project.workspaceId&&!i)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return i?{text:Fw,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),kn=sl(S),sa=kn.length>0&&!E,Nr=p!==null?Id(p,8,je):null,so=ve?ve.paths.filter(c=>!ve.query||c.toLowerCase().includes(ve.query.toLowerCase())).slice(0,8):[],io=Ce?Ce.sessions.filter(c=>{let l=Ce.query.toLowerCase();return!l||c.name.toLowerCase().includes(l)||c.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],Se=B((c,l)=>{Ae.current?.close(),Ae.current=Ld({cwd:e,resume:c,profileName:l??s,allowProdWrites:_t.current}),c||(qe.current={uuid:null,firstPrompt:null,titleFired:!1},ht(null)),Ht(0),qt(0)},[e,s]),ia=B((c,l,i)=>{if(Hw.test(c))try{let f=Te(e,s),d=typeof l.project_id=="string"&&l.project_id||f.project.projectId,w=ir(l,i),$=[],h=ar(i);c.endsWith("publish_article")&&h&&$.push(`Live: ${h}`);let x=lr(i);x?$.push(`Preview: ${x}`):w&&d&&$.push(`Preview: ${sr(f.connection.portalUrl,d,w,f.project.languageCode??"en")}`),$.length>0&&u({kind:"link",lines:$})}catch{}},[e,s,u]),ne=B(async(c,l)=>{Yn(!0),Vn.current=!1,Ue(),ut([]),un(null),Tr(null);let i=Gn.current;l?.quietUser||u({kind:"user",text:l?.echoDisplay&&l.display?l.display:c});let f=qe.current;f.firstPrompt||(f.firstPrompt=l?.display??c),pt.current=Date.now(),jt(0),T(!0),Xn.current.clear();let d="",w=!1,$=!1,h="",x={num:0,closed:!1,cueSeen:!1},b=null,U=()=>{b||(b=setTimeout(()=>{b=null,g(h.length>0?h:null)},60))},M=()=>{b&&clearTimeout(b),b=null,g(null)},K=(P=!1)=>{let{head:N,keep:H}=_d(h,P);N.trim()&&u({kind:"assistant",text:Di(N.trimEnd(),x)}),h=H,M()};try{for await(let P of Ae.current.send(c))if(P.type==="session"){if(!f.uuid){f.uuid=P.sessionId;let N=new Date().toISOString(),H=Cr.current,ee=H??dw(f.firstPrompt??"session");uw({uuid:P.sessionId,name:ee,renamed:!!H,titled:!1,cwd:e,firstPrompt:f.firstPrompt??"",createdAt:N,updatedAt:N}),ht(ee),Cr.current=null}}else if(P.type==="text"){h+=P.delta,d+=P.delta;let N=Od(h);if(N>0){let H=h.slice(0,N).trimEnd();H&&u({kind:"assistant",text:Di(H,x)}),h=h.slice(N)}U(),jt(H=>H+P.delta.length)}else if(P.type==="tool"){w=!0;let N=or(P.name,P.input);N&&(K(),u({kind:"tool",title:N.title,sep:N.sep,arg:N.arg}),Xn.current.set(P.id,{name:P.name,input:P.input}))}else if(P.type==="article_diff"){let N=Ke(P.oldContent,P.newContent,Ze());N&&(K(),u({kind:"diff",added:N.added,removed:N.removed,lines:N.lines,hidden:N.hidden}))}else if(P.type==="tool_result"){P.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(P.output)&&(Zn.current=!0);let N=Xn.current.get(P.id);if(N){Xn.current.delete(P.id),K();let H=rr(P.output,4,P.isError?void 0:N.name,N.input);u({kind:"tool-result",lines:H.lines,hidden:H.hidden,isError:P.isError}),P.isError||ia(N.name,N.input,P.output)}}else if(P.type==="result"){K(!0),Ht(H=>H+P.outputTokens),qt(H=>H+P.costUsd);let N=P.inputTokens+P.cacheReadTokens+P.cacheCreationTokens;if(u({kind:"done",seconds:Math.round((Date.now()-pt.current)/1e3),tokens:P.outputTokens,costUsd:P.costUsd,ok:P.ok,...N>0?{inTokens:N,cachedPct:Math.round(P.cacheReadTokens/N*100)}:{}}),!$&&!w&&!d.trim()&&!pn.current&&u({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),P.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(d))try{let H=Gd(e);if(sn(H)){let ee=gr(H,"utf8").trim();ee&&(jr(ee),u({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(P.ok&&x.cueSeen)Vi(!0),ut([]);else{let H=P.ok?$d(d,tn.map(ee=>ee.name)):[];if(H.length>0)X(H[0]);else if(P.ok&&d.trim()){let ee=xt(!1);ee.kind==="recommend"&&(ee.rec.lead||ee.rec.picker)||mw(c,d,e).then(Ee=>{Ee&&Gn.current===i&&ge(Ee)}).catch(()=>{})}}if(f.uuid&&(_i(f.uuid),!f.titleFired)){f.titleFired=!0;let H=f.uuid,ee=f.firstPrompt;ee&&Md(ee,e).then(Ee=>{Ee&&(cw(H,Ee),ht(Ee))}).catch(()=>{})}}else P.type==="error"&&(K(!0),$=!0,P.kind==="auth"&&(Zn.current=!0),u({kind:"note",text:`agent error: ${P.message}`,tone:"error"}))}finally{T(!1),M(),z(P=>P+1),qe.current.uuid&&wd(e,qe.current.uuid,It.current),Zn.current?(Zn.current=!1,hn.current=l?.display??c,ge("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):hn.current=null,pn.current&&(pn.current=!1,bt.current.length>0&&(u({kind:"note",tone:"info",text:`(${bt.current.length} queued message(s) discarded)`}),bt.current=[],Rr([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,ia,Ze,ge,X,Ue,xt]),Gt=B(async c=>{let l=yr(e,"standard");pt.current=Date.now(),jt(0),T(!0);let i=new AbortController;ye.current=i;let f=async(d,w)=>{let $=Li(d);te({verb:"Publishing",total:$.length,done:0,active:[],rows:Hn($),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:w?`Resolving cross-links in ${d.length} article${d.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${d.length} article${d.length===1?"":"s"} across ${$.length} partition${$.length===1?"":"s"} (\u2264${An} agents at once) on ${l.model}\u2026 (esc to stop)`});let h=!1;for await(let x of wr({cwd:e,partitions:$,promptFor:b=>Oo(b.paths),concurrency:An,profileName:s,allowProdWrites:_t.current,model:l.model,signal:i.signal}))if(x.type==="partition_status")x.status==="running"?te(b=>b&&{...b,active:[...b.active,x.label],rows:Oe(b.rows,x.label,"active"),lastAt:Date.now()}):te(b=>b&&{...b,active:b.active.filter(U=>U!==x.label),done:b.done+1,rows:Oe(b.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_event")te(b=>{if(!b)return b;let U={...b,lastAt:Date.now()};return x.event.type==="tool"?U.tools=b.tools+1:x.event.type==="text"&&(U.chars=b.chars+x.event.delta.length),U});else if(x.type==="run_done"){h=x.aborted,qt(K=>K+x.totalCostUsd),Ht(K=>K+x.results.reduce((P,N)=>P+N.outputTokens,0));let b=x.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";u({kind:"note",tone:x.aborted?"warn":x.ok?"ok":"warn",text:b+cs(x.results,$,U).join(`
390
- `)});let M=ls(e,s);if(M&&u({kind:"note",tone:"info",text:M}),!x.aborted){try{let K=await zd({cwd:e,profileName:s}),P=Kd(K);P?u({kind:"note",tone:"info",text:P}):K.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${K.skipped}`})}catch(K){u({kind:"note",tone:"warn",text:`Order sync failed: ${K.message}`})}try{let K=Qd(await Xd({cwd:e,profileName:s}));K&&u({kind:"note",tone:"info",text:K})}catch(K){u({kind:"note",tone:"warn",text:`Related-articles sync failed: ${K.message}`})}}}return h};try{if(!await f(c,!1)){let w=await ds(e,s,c);w.length>0&&await f(w,!0)}}catch(d){u({kind:"note",tone:"error",text:`Publish run failed: ${d.message}`})}finally{ye.current=null,te(null),T(!1),z(d=>d+1)}},[e,s,u,t]),Ir=B(async c=>{await ne(is(c),{display:`/publish ${c}`,quietUser:!0});try{let l=await Lo(e,s,c.replace(/\\/g,"/"));l.length>0&&(un(`Related articles not yet published (${l.length}):`),ut([`/publish --related ${c}`,...l.map(i=>`/publish ${i}`)]))}catch{}},[e,s,ne]),aa=B(async(c,l)=>{let f=Cw(c,3),d=yr(e,"standard");pt.current=Date.now(),jt(0),T(!0);let w=new AbortController;ye.current=w,te({verb:"Authoring",unit:"spec",total:f.length,done:0,active:[],rows:Hn(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${c.length} screenshot spec${c.length===1?"":"s"} across ${f.length} partition${f.length===1?"":"s"} (\u22646 agents at once) on ${d.model}${d.forced?" (forced)":""}\u2026 (esc to stop)`});let $=!1;try{for await(let h of wr({cwd:e,partitions:f,promptFor:vc,concurrency:6,profileName:s,allowProdWrites:_t.current,model:d.model,signal:w.signal}))if(h.type==="partition_status")h.status==="running"?te(x=>x&&{...x,active:[...x.active,h.label],rows:Oe(x.rows,h.label,"active"),lastAt:Date.now()}):te(x=>x&&{...x,active:x.active.filter(b=>b!==h.label),done:x.done+1,rows:Oe(x.rows,h.label,h.status==="done"?"done":"failed"),lastAt:Date.now()});else if(h.type==="partition_event")te(x=>{if(!x)return x;let b={...x,lastAt:Date.now()};return h.event.type==="tool"?b.tools=x.tools+1:h.event.type==="text"&&(b.chars=x.chars+h.event.delta.length),b});else if(h.type==="run_done"){qt(M=>M+h.totalCostUsd),Ht(M=>M+h.results.reduce((K,P)=>K+P.outputTokens,0));let x=h.results.filter(M=>M.ok).length,b=h.aborted?"Stopped. ":"";$=!h.aborted&&l.setup;let U=h.aborted?"":$?" Refreshing the capture-setup checklist\u2026":" Next: /capture --all (or /capture-setup first for the staging checklist).";u({kind:"note",tone:h.aborted?"warn":h.ok?"ok":"warn",text:`${b}Authored specs \u2014 ${x}/${h.results.length} batches ok.${U}`})}}catch(h){u({kind:"note",tone:"error",text:`Spec authoring failed: ${h.message}`})}finally{ye.current=null,te(null),T(!1),z(h=>h+1)}if($){let h=await _n();h.kind==="forward-to-agent"&&h.prompt&&await ne(h.prompt,{display:h.display,quietUser:!0});let x=Js(e);x&&u({kind:"note",tone:"info",text:x.join(`
391
- `)})}},[e,s,u,ne]),la=B(async c=>{let l=await Go([c]);l.kind==="forward-to-agent"&&l.prompt&&await ne(l.prompt,{display:l.display,quietUser:!0}),$c(e,c)&&Re(`Spec ready \u2014 /capture ${c} takes the screenshot; /screenshot picks the next shot.`,{kind:"cmd",cmd:`/capture ${c}`,reason:""})},[e,ne,Re]),_r=B(async c=>{if(!Yo(e)){u({kind:"note",tone:"warn",text:"Screenshot capture is not set up in this repo yet \u2014 run d360-capture init in this repo's terminal, then d360-capture auth (once per machine)."});return}T(!0);let l=new AbortController;ye.current=l;let i=c.map(b=>({label:b,items:1,status:"pending"}));te({verb:"Capturing",unit:"screenshot",total:c.length,done:0,active:[],rows:i,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Capturing ${c.length} screenshot${c.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`});let f=Date.now(),d=[];try{for(let b of c){if(l.signal.aborted)break;te(P=>P&&{...P,active:[b],rows:Oe(P.rows,b,"active"),lastAt:Date.now()});let{exitCode:U,output:M}=await Qs({cwd:e,id:b,signal:l.signal,stdio:"pipe"}),K=l.signal.aborted&&U!==0?"failed":Xs(e,b,U,f);d.push({id:b,outcome:K,detail:K==="captured"?void 0:Pc(M)}),te(P=>P&&{...P,active:[],done:P.done+1,rows:Oe(P.rows,b,K==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(b){b.code==="ENOENT"?u({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /capture again."}):u({kind:"note",tone:"error",text:`Capture run failed: ${b.message}`})}finally{ye.current=null,te(null),T(!1),z(b=>b+1)}if(d.length===0)return;let w=d.filter(b=>b.outcome==="captured"),$=d.filter(b=>b.outcome==="skipped"),h=d.filter(b=>b.outcome==="failed"),x=c.length-d.length;u({kind:"note",tone:h.length?"warn":"ok",text:`${w.length?`\u2713 ${w.length} captured`:"\u2713 0 captured"}`+($.length?` \xB7 \u2298 ${$.length} skipped`:"")+(h.length?` \xB7 \u2717 ${h.length} failed`:"")+(x?` \xB7 ${x} not run (stopped)`:"")});for(let b of[...$,...h])b.detail&&u({kind:"note",tone:b.outcome==="failed"?"error":"info",text:`${b.outcome==="failed"?"\u2717":"\u2298"} ${b.id}
392
- ${b.detail}`});if(w.length>0){let b=Tc(e,w.map(M=>M.id)),U=b.length===1?`/publish ${b[0]}`:"/publish";Re(`PNG${w.length===1?"":"s"} saved to the screenshots folder \u2014 publish to put ${w.length===1?"it":"them"} in the article${b.length===1?"":"s"}: ${U}`,{kind:"cmd",cmd:U,reason:""})}},[e,u,Re]),Or=B(c=>{let l=Dt(c);if(!l||ct(l)&&!l.refreshToken)return null;let i={...ln(l.idToken)??{},...ln(l.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),Lr=B((c,l)=>{if(l){let i=oe(e);i&&(i.defaultProfile=c,Ud(i,e))}a(c),Se(void 0,c),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${l?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Or(c)||(u({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),X("/login")),z(i=>i+1)},[e,u,Se,Or,X]),ao=B((c,l,i)=>{go(e,c,l,i.id,i.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Se(),Wd(e,c)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),u({kind:"note",tone:"info",text:Zt(Jt(e)).join(`
393
- `)}),Bt(vt()),wn.current=Ie(e).status==="current",Vt.current=ze(e),u({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,u,Se,Bt]),lo=B(async c=>{let l;try{l=await vn(e,c)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),X("/workspace");return}if(l.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=l.workspaces.filter(d=>(d.workspace_type??"").toLowerCase()!=="apidocumentation"),f=i.length>0?i:l.workspaces;if(f.length===1){let d=f[0],w=l.workspaces.length-f.length;u({kind:"note",tone:"ok",text:`Selected the "${d.name??d.id}" workspace${w>0?" (skipped the API-documentation workspace)":""}.`}),ao(l.profile,l.projectId,d);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${f.length} available).`}),X("/workspace")},[e,u,ao,X]),co=B((c,l)=>{wo(e,c,l.id,l.name),u({kind:"note",tone:"ok",text:`Project set to "${l.name??l.id}" (agent restarted).`}),Se(),lo(c)},[e,u,Se,lo]),ca=B(async c=>{let l;try{l=Te(e,c)}catch{return}if(!l.project.workspaceId){if(l.project.projectId){if(!l.project.projectName)try{let{projects:i}=await nt(e,l.name),f=i.find(d=>d.id===l.project.projectId);f?.name&&Nw(e,l.name,{projectName:f.name})}catch{}await lo(l.name);return}try{let{projects:i}=await nt(e,l.name);if(i.length===1){let f=i[0];u({kind:"note",tone:"ok",text:`Using your Document360 project "${f.name??f.id}".`}),co(l.name,{id:f.id,name:f.name});return}if(i.length>1){let f=i.map(d=>({id:d.id,name:d.name??d.id,sub:d.sub_domain}));u({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),gt({cursor:0,current:-1,rows:f,profile:l.name,environment:l.connection.name});return}}catch{}u({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),X("/project")}},[e,u,lo,co,X]),Yt=B(()=>{let c=le.current[0];if(!c)return;Ue();let{plan:l,mode:i}=c;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let d of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${d}`});l.overwritesLocalChanges&&i==="pull"&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let f=Ke(l.oldContent,l.newContent,Ze());u(f?{kind:"diff",added:f.added,removed:f.removed,lines:f.lines,hidden:f.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),i==="conflict"?(u({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),u({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,Ze,Ue]),Mr=B(()=>{if(le.current.length>0){Yt();return}let c=Ot.current;Ot.current=[],c.length>0?(u({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),Gt(c)):X("/pull")},[Yt,u,Gt,X]),da=B(c=>{if(le.current.length===0)return!1;let l=c.trim().toLowerCase(),i=le.current[0];if(i.mode==="conflict"){if(l==="l"||l==="local")le.current.shift(),Ot.current.push(i.plan.path),u({kind:"note",tone:"info",text:`Keeping local ${i.plan.path} \u2014 will publish over the portal.`});else if(l==="p"||l==="portal"){le.current.shift();try{Fd({cwd:e,profileName:s},i.plan),u({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(f){u({kind:"note",tone:"error",text:`Take-portal failed: ${f.message}`})}}else if(l==="s"||l==="skip"||l==="n")le.current.shift(),u({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let f=le.current.length;return le.current=[],Ot.current=[],u({kind:"note",tone:"info",text:`Resolve cancelled (${f} conflict${f===1?"":"s"} left untouched).`}),!0}return Mr(),!0}if(l==="y"||l==="yes"){let f=le.current.shift().plan;try{Fd({cwd:e,profileName:s},f),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${f.path} (sync base advanced).`})}catch(d){u({kind:"note",tone:"error",text:`Pull failed: ${d.message}`})}}else if(l==="n"||l==="no"){let f=le.current.shift().plan;u({kind:"note",tone:"info",text:`Skipped ${f.path}.`})}else{let f=le.current.length;return le.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${f} article(s) left untouched).`}),!0}return Mr(),!0},[e,s,Mr,u]),Ur=B(async c=>{u({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let l=await Oi({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),f=l.entries.filter(w=>w.status==="conflict"&&w.path).map(w=>w.path);if(i){if(!f.includes(i)){u({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}f=[i]}if(f.length===0){u({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let d=[];for(let w of f)try{d.push({plan:await qd({cwd:e,profileName:s,relPath:w}),mode:"conflict"})}catch($){u({kind:"note",tone:"error",text:`Could not load ${w} from Document360: ${$.message}`})}if(d.length===0)return;u({kind:"note",tone:"info",text:`Resolving ${d.length} conflict${d.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),le.current=d,Ot.current=[],Yt()}catch(l){u({kind:"note",tone:"error",text:`Could not compute sync status: ${l.message}`})}},[e,s,u,Yt]),ua=B(c=>{let l=Qn.current;if(!l)return!1;if(Qn.current=null,Ue(),c.trim()!==l.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:f}=ci(e,l.targets);u({kind:"note",tone:f.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`});for(let d of f)u({kind:"note",tone:"error",text:` \u2717 ${d.path}: ${d.error}`});return l.hadDevhints&&(u({kind:"note",tone:"warn",text:To().join(`
389
+ cwd: ${e}`}),Ar()},[]),De(()=>{let c=setInterval(()=>{Ar()},Qw);return()=>clearInterval(c)},[Ar]),De(()=>{if(N||pe||$r||Vn.current||fe!==null||He.length>0||S!==""||gn!==null||le.current.length>0||Qn.current||Sr)return;let c=xt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&to(c.rec,{silent:!0})},[N,pe,fe,He,S,gn,Sr,Y,xt,$r]),De(()=>{let c=null,l=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let f=`${Me.columns??80}x${Me.rows??24}`;f!==na.current&&(na.current=f,wu(d=>d+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+fl(It.current,Ze())+"\x1B[?2026l")},80))},400)};return Me.on("resize",i),()=>{c&&clearTimeout(c),l&&clearTimeout(l),Me.off("resize",i)}},[Me,Ze]);let je=Math.max(20,(Me.columns??80)-1),ra=Ni(()=>qw(e,s),[e,s,Y]),Er=(()=>{if(hu)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(xr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${xr?` v${xr}`:""}\u2026`,isSetup:!0};if(oo)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(gn)return yu?{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=oe(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let l=Ii(e,(c.docsDir??ru).replace(/\/+$/,"")),i=(()=>{try{return sn(l)&&tw(l).length>0}catch{return!1}})();try{let f=Te(e,s),d=Dt(f.name);if(!(!!d&&!(ct(d)&&!d.refreshToken)))return{text:`Sign in with /login (profile "${f.name}")\u2026`,isSetup:!0};if(!f.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!f.project.workspaceId&&!i)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return i?{text:Bw,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),kn=sl(S),sa=kn.length>0&&!N,Nr=p!==null?Od(p,8,je):null,so=Ce?Ce.paths.filter(c=>!Ce.query||c.toLowerCase().includes(Ce.query.toLowerCase())).slice(0,8):[],io=Re?Re.sessions.filter(c=>{let l=Re.query.toLowerCase();return!l||c.name.toLowerCase().includes(l)||c.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],Se=B((c,l)=>{Ae.current?.close(),Ae.current=Ud({cwd:e,resume:c,profileName:l??s,allowProdWrites:_t.current}),c||(qe.current={uuid:null,firstPrompt:null,titleFired:!1},ht(null)),Ht(0),qt(0)},[e,s]),ia=B((c,l,i)=>{if(Vw.test(c))try{let f=Te(e,s),d=typeof l.project_id=="string"&&l.project_id||f.project.projectId,w=ir(l,i),$=[],h=ar(i);c.endsWith("publish_article")&&h&&$.push(`Live: ${h}`);let x=lr(i);x?$.push(`Preview: ${x}`):w&&d&&$.push(`Preview: ${sr(f.connection.portalUrl,d,w,f.project.languageCode??"en")}`),$.length>0&&u({kind:"link",lines:$})}catch{}},[e,s,u]),ne=B(async(c,l)=>{Yn(!0),Vn.current=!1,Ue(),ut([]),un(null),Tr(null);let i=Gn.current;l?.quietUser||u({kind:"user",text:l?.echoDisplay&&l.display?l.display:c});let f=qe.current;f.firstPrompt||(f.firstPrompt=l?.display??c),pt.current=Date.now(),jt(0),T(!0),Xn.current.clear();let d="",w=!1,$=!1,h="",x={num:0,closed:!1,cueSeen:!1},b=null,U=()=>{b||(b=setTimeout(()=>{b=null,g(h.length>0?h:null)},60))},M=()=>{b&&clearTimeout(b),b=null,g(null)},K=(P=!1)=>{let{head:j,keep:H}=Ld(h,P);j.trim()&&u({kind:"assistant",text:Di(j.trimEnd(),x)}),h=H,M()};try{for await(let P of Ae.current.send(c))if(P.type==="session"){if(!f.uuid){f.uuid=P.sessionId;let j=new Date().toISOString(),H=Cr.current,ee=H??hw(f.firstPrompt??"session");fw({uuid:P.sessionId,name:ee,renamed:!!H,titled:!1,cwd:e,firstPrompt:f.firstPrompt??"",createdAt:j,updatedAt:j}),ht(ee),Cr.current=null}}else if(P.type==="text"){h+=P.delta,d+=P.delta;let j=Md(h);if(j>0){let H=h.slice(0,j).trimEnd();H&&u({kind:"assistant",text:Di(H,x)}),h=h.slice(j)}U(),jt(H=>H+P.delta.length)}else if(P.type==="tool"){w=!0;let j=or(P.name,P.input);j&&(K(),u({kind:"tool",title:j.title,sep:j.sep,arg:j.arg}),Xn.current.set(P.id,{name:P.name,input:P.input}))}else if(P.type==="article_diff"){let j=Ke(P.oldContent,P.newContent,Ze());j&&(K(),u({kind:"diff",added:j.added,removed:j.removed,lines:j.lines,hidden:j.hidden}))}else if(P.type==="tool_result"){P.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(P.output)&&(Zn.current=!0);let j=Xn.current.get(P.id);if(j){Xn.current.delete(P.id),K();let H=rr(P.output,4,P.isError?void 0:j.name,j.input);u({kind:"tool-result",lines:H.lines,hidden:H.hidden,isError:P.isError}),P.isError||ia(j.name,j.input,P.output)}}else if(P.type==="result"){K(!0),Ht(H=>H+P.outputTokens),qt(H=>H+P.costUsd);let j=P.inputTokens+P.cacheReadTokens+P.cacheCreationTokens;if(u({kind:"done",seconds:Math.round((Date.now()-pt.current)/1e3),tokens:P.outputTokens,costUsd:P.costUsd,ok:P.ok,...j>0?{inTokens:j,cachedPct:Math.round(P.cacheReadTokens/j*100)}:{}}),!$&&!w&&!d.trim()&&!pn.current&&u({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),P.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(d))try{let H=zd(e);if(sn(H)){let ee=gr(H,"utf8").trim();ee&&(jr(ee),u({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(P.ok&&x.cueSeen)Vi(!0),ut([]);else{let H=P.ok?vd(d,tn.map(ee=>ee.name)):[];if(H.length>0)X(H[0]);else if(P.ok&&d.trim()){let ee=xt(!1);ee.kind==="recommend"&&(ee.rec.lead||ee.rec.picker)||yw(c,d,e).then(Ee=>{Ee&&Gn.current===i&&ge(Ee)}).catch(()=>{})}}if(f.uuid&&(_i(f.uuid),!f.titleFired)){f.titleFired=!0;let H=f.uuid,ee=f.firstPrompt;ee&&Wd(ee,e).then(Ee=>{Ee&&(pw(H,Ee),ht(Ee))}).catch(()=>{})}}else P.type==="error"&&(K(!0),$=!0,P.kind==="auth"&&(Zn.current=!0),u({kind:"note",text:`agent error: ${P.message}`,tone:"error"}))}finally{T(!1),M(),z(P=>P+1),qe.current.uuid&&kd(e,qe.current.uuid,It.current),Zn.current?(Zn.current=!1,hn.current=l?.display??c,ge("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):hn.current=null,pn.current&&(pn.current=!1,bt.current.length>0&&(u({kind:"note",tone:"info",text:`(${bt.current.length} queued message(s) discarded)`}),bt.current=[],Rr([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,ia,Ze,ge,X,Ue,xt]),Gt=B(async c=>{let l=yr(e,"standard");pt.current=Date.now(),jt(0),T(!0);let i=new AbortController;ye.current=i;let f=async(d,w)=>{let $=Li(d);te({verb:"Publishing",total:$.length,done:0,active:[],rows:Hn($),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:w?`Resolving cross-links in ${d.length} article${d.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${d.length} article${d.length===1?"":"s"} across ${$.length} partition${$.length===1?"":"s"} (\u2264${An} agents at once) on ${l.model}\u2026 (esc to stop)`});let h=!1;for await(let x of wr({cwd:e,partitions:$,promptFor:b=>Oo(b.paths),concurrency:An,profileName:s,allowProdWrites:_t.current,model:l.model,signal:i.signal}))if(x.type==="partition_status")x.status==="running"?te(b=>b&&{...b,active:[...b.active,x.label],rows:Oe(b.rows,x.label,"active"),lastAt:Date.now()}):te(b=>b&&{...b,active:b.active.filter(U=>U!==x.label),done:b.done+1,rows:Oe(b.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_event")te(b=>{if(!b)return b;let U={...b,lastAt:Date.now()};return x.event.type==="tool"?U.tools=b.tools+1:x.event.type==="text"&&(U.chars=b.chars+x.event.delta.length),U});else if(x.type==="run_done"){h=x.aborted,qt(K=>K+x.totalCostUsd),Ht(K=>K+x.results.reduce((P,j)=>P+j.outputTokens,0));let b=x.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";u({kind:"note",tone:x.aborted?"warn":x.ok?"ok":"warn",text:b+cs(x.results,$,U).join(`
390
+ `)});let M=ls(e,s);if(M&&u({kind:"note",tone:"info",text:M}),!x.aborted){try{let K=await Xd({cwd:e,profileName:s}),P=Qd(K);P?u({kind:"note",tone:"info",text:P}):K.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${K.skipped}`})}catch(K){u({kind:"note",tone:"warn",text:`Order sync failed: ${K.message}`})}try{let K=Zd(await Jd({cwd:e,profileName:s}));K&&u({kind:"note",tone:"info",text:K})}catch(K){u({kind:"note",tone:"warn",text:`Related-articles sync failed: ${K.message}`})}}}return h};try{if(!await f(c,!1)){let w=await ds(e,s,c);w.length>0&&await f(w,!0)}}catch(d){u({kind:"note",tone:"error",text:`Publish run failed: ${d.message}`})}finally{ye.current=null,te(null),T(!1),z(d=>d+1)}},[e,s,u,t]),Ir=B(async c=>{await ne(is(c),{display:`/publish ${c}`,quietUser:!0});try{let l=await Lo(e,s,c.replace(/\\/g,"/"));l.length>0&&(un(`Related articles not yet published (${l.length}):`),ut([`/publish --related ${c}`,...l.map(i=>`/publish ${i}`)]))}catch{}},[e,s,ne]),aa=B(async(c,l)=>{let f=Pw(c,3),d=yr(e,"standard");pt.current=Date.now(),jt(0),T(!0);let w=new AbortController;ye.current=w,te({verb:"Authoring",unit:"spec",total:f.length,done:0,active:[],rows:Hn(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${c.length} screenshot spec${c.length===1?"":"s"} across ${f.length} partition${f.length===1?"":"s"} (\u22646 agents at once) on ${d.model}${d.forced?" (forced)":""}\u2026 (esc to stop)`});let $=!1;try{for await(let h of wr({cwd:e,partitions:f,promptFor:vc,concurrency:6,profileName:s,allowProdWrites:_t.current,model:d.model,signal:w.signal}))if(h.type==="partition_status")h.status==="running"?te(x=>x&&{...x,active:[...x.active,h.label],rows:Oe(x.rows,h.label,"active"),lastAt:Date.now()}):te(x=>x&&{...x,active:x.active.filter(b=>b!==h.label),done:x.done+1,rows:Oe(x.rows,h.label,h.status==="done"?"done":"failed"),lastAt:Date.now()});else if(h.type==="partition_event")te(x=>{if(!x)return x;let b={...x,lastAt:Date.now()};return h.event.type==="tool"?b.tools=x.tools+1:h.event.type==="text"&&(b.chars=x.chars+h.event.delta.length),b});else if(h.type==="run_done"){qt(M=>M+h.totalCostUsd),Ht(M=>M+h.results.reduce((K,P)=>K+P.outputTokens,0));let x=h.results.filter(M=>M.ok).length,b=h.aborted?"Stopped. ":"";$=!h.aborted&&l.setup;let U=h.aborted?"":$?" Refreshing the capture-setup checklist\u2026":" Next: /capture --all (or /capture-setup first for the staging checklist).";u({kind:"note",tone:h.aborted?"warn":h.ok?"ok":"warn",text:`${b}Authored specs \u2014 ${x}/${h.results.length} batches ok.${U}`})}}catch(h){u({kind:"note",tone:"error",text:`Spec authoring failed: ${h.message}`})}finally{ye.current=null,te(null),T(!1),z(h=>h+1)}if($){let h=await _n();h.kind==="forward-to-agent"&&h.prompt&&await ne(h.prompt,{display:h.display,quietUser:!0});let x=Js(e);x&&u({kind:"note",tone:"info",text:x.join(`
391
+ `)})}},[e,s,u,ne]),la=B(async c=>{let l=await Go([c]);l.kind==="forward-to-agent"&&l.prompt&&await ne(l.prompt,{display:l.display,quietUser:!0}),$c(e,c)&&ke(`Spec ready \u2014 /capture ${c} takes the screenshot; /screenshot picks the next shot.`,{kind:"cmd",cmd:`/capture ${c}`,reason:""})},[e,ne,ke]),_r=B(async c=>{if(!Yo(e)){u({kind:"note",tone:"warn",text:"Screenshot capture is not set up in this repo yet \u2014 run d360-capture init in this repo's terminal, then d360-capture auth (once per machine)."});return}T(!0);let l=new AbortController;ye.current=l;let i=c.map(b=>({label:b,items:1,status:"pending"}));te({verb:"Capturing",unit:"screenshot",total:c.length,done:0,active:[],rows:i,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Capturing ${c.length} screenshot${c.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`});let f=Date.now(),d=[];try{for(let b of c){if(l.signal.aborted)break;te(j=>j&&{...j,active:[b],rows:Oe(j.rows,b,"active"),lastAt:Date.now()});let{exitCode:U,output:M}=await Qs({cwd:e,id:b,signal:l.signal,stdio:"pipe"});if(Dc(U,M)){u({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /capture again."});return}let K=l.signal.aborted&&U!==0?"failed":Xs(e,b,U,f),P=K==="captured"?void 0:K==="skipped"?Pc(M)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Tc(M);d.push({id:b,outcome:K,detail:P}),te(j=>j&&{...j,active:[],done:j.done+1,rows:Oe(j.rows,b,K==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(b){u({kind:"note",tone:"error",text:`Capture run failed: ${b.message}`})}finally{ye.current=null,te(null),T(!1),z(b=>b+1)}if(d.length===0)return;let w=d.filter(b=>b.outcome==="captured"),$=d.filter(b=>b.outcome==="skipped"),h=d.filter(b=>b.outcome==="failed"),x=c.length-d.length;u({kind:"note",tone:h.length?"warn":w.length?"ok":"info",text:`\u2713 ${w.length} captured`+($.length?` \xB7 \u2298 ${$.length} skipped`:"")+(h.length?` \xB7 \u2717 ${h.length} failed`:"")+(x?` \xB7 ${x} not run (stopped)`:"")});for(let b of $)u({kind:"note",tone:"info",text:`\u2298 ${b.id} \u2014 ${b.detail}`});for(let b of h)b.detail&&u({kind:"note",tone:"error",text:`\u2717 ${b.id}
392
+ ${b.detail}`});if(w.length>0){let b=Ac(e,w.map(M=>M.id)),U=b.length===1?`/publish ${b[0]}`:"/publish";ke(`PNG${w.length===1?"":"s"} saved to the screenshots folder \u2014 publish to put ${w.length===1?"it":"them"} in the article${b.length===1?"":"s"}: ${U}`,{kind:"cmd",cmd:U,reason:""})}else if($.length>0){let b=c.length===1?`/capture ${c[0]}`:"/capture";ke(`Stage the data the skip reason names (in your app), then ${b} to try again.`,{kind:"cmd",cmd:b,reason:""})}},[e,u,ke]),Or=B(c=>{let l=Dt(c);if(!l||ct(l)&&!l.refreshToken)return null;let i={...ln(l.idToken)??{},...ln(l.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),Lr=B((c,l)=>{if(l){let i=oe(e);i&&(i.defaultProfile=c,Fd(i,e))}a(c),Se(void 0,c),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${l?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Or(c)||(u({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),X("/login")),z(i=>i+1)},[e,u,Se,Or,X]),ao=B((c,l,i)=>{go(e,c,l,i.id,i.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Se(),Hd(e,c)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),u({kind:"note",tone:"info",text:Zt(Jt(e)).join(`
393
+ `)}),Bt(vt()),wn.current=Ie(e).status==="current",Vt.current=ze(e),u({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,u,Se,Bt]),lo=B(async c=>{let l;try{l=await vn(e,c)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),X("/workspace");return}if(l.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=l.workspaces.filter(d=>(d.workspace_type??"").toLowerCase()!=="apidocumentation"),f=i.length>0?i:l.workspaces;if(f.length===1){let d=f[0],w=l.workspaces.length-f.length;u({kind:"note",tone:"ok",text:`Selected the "${d.name??d.id}" workspace${w>0?" (skipped the API-documentation workspace)":""}.`}),ao(l.profile,l.projectId,d);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${f.length} available).`}),X("/workspace")},[e,u,ao,X]),co=B((c,l)=>{wo(e,c,l.id,l.name),u({kind:"note",tone:"ok",text:`Project set to "${l.name??l.id}" (agent restarted).`}),Se(),lo(c)},[e,u,Se,lo]),ca=B(async c=>{let l;try{l=Te(e,c)}catch{return}if(!l.project.workspaceId){if(l.project.projectId){if(!l.project.projectName)try{let{projects:i}=await nt(e,l.name),f=i.find(d=>d.id===l.project.projectId);f?.name&&Ow(e,l.name,{projectName:f.name})}catch{}await lo(l.name);return}try{let{projects:i}=await nt(e,l.name);if(i.length===1){let f=i[0];u({kind:"note",tone:"ok",text:`Using your Document360 project "${f.name??f.id}".`}),co(l.name,{id:f.id,name:f.name});return}if(i.length>1){let f=i.map(d=>({id:d.id,name:d.name??d.id,sub:d.sub_domain}));u({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),gt({cursor:0,current:-1,rows:f,profile:l.name,environment:l.connection.name});return}}catch{}u({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),X("/project")}},[e,u,lo,co,X]),Yt=B(()=>{let c=le.current[0];if(!c)return;Ue();let{plan:l,mode:i}=c;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let d of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${d}`});l.overwritesLocalChanges&&i==="pull"&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let f=Ke(l.oldContent,l.newContent,Ze());u(f?{kind:"diff",added:f.added,removed:f.removed,lines:f.lines,hidden:f.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),i==="conflict"?(u({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),u({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,Ze,Ue]),Mr=B(()=>{if(le.current.length>0){Yt();return}let c=Ot.current;Ot.current=[],c.length>0?(u({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),Gt(c)):X("/pull")},[Yt,u,Gt,X]),da=B(c=>{if(le.current.length===0)return!1;let l=c.trim().toLowerCase(),i=le.current[0];if(i.mode==="conflict"){if(l==="l"||l==="local")le.current.shift(),Ot.current.push(i.plan.path),u({kind:"note",tone:"info",text:`Keeping local ${i.plan.path} \u2014 will publish over the portal.`});else if(l==="p"||l==="portal"){le.current.shift();try{qd({cwd:e,profileName:s},i.plan),u({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(f){u({kind:"note",tone:"error",text:`Take-portal failed: ${f.message}`})}}else if(l==="s"||l==="skip"||l==="n")le.current.shift(),u({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let f=le.current.length;return le.current=[],Ot.current=[],u({kind:"note",tone:"info",text:`Resolve cancelled (${f} conflict${f===1?"":"s"} left untouched).`}),!0}return Mr(),!0}if(l==="y"||l==="yes"){let f=le.current.shift().plan;try{qd({cwd:e,profileName:s},f),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${f.path} (sync base advanced).`})}catch(d){u({kind:"note",tone:"error",text:`Pull failed: ${d.message}`})}}else if(l==="n"||l==="no"){let f=le.current.shift().plan;u({kind:"note",tone:"info",text:`Skipped ${f.path}.`})}else{let f=le.current.length;return le.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${f} article(s) left untouched).`}),!0}return Mr(),!0},[e,s,Mr,u]),Ur=B(async c=>{u({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let l=await Oi({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),f=l.entries.filter(w=>w.status==="conflict"&&w.path).map(w=>w.path);if(i){if(!f.includes(i)){u({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}f=[i]}if(f.length===0){u({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let d=[];for(let w of f)try{d.push({plan:await Vd({cwd:e,profileName:s,relPath:w}),mode:"conflict"})}catch($){u({kind:"note",tone:"error",text:`Could not load ${w} from Document360: ${$.message}`})}if(d.length===0)return;u({kind:"note",tone:"info",text:`Resolving ${d.length} conflict${d.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),le.current=d,Ot.current=[],Yt()}catch(l){u({kind:"note",tone:"error",text:`Could not compute sync status: ${l.message}`})}},[e,s,u,Yt]),ua=B(c=>{let l=Qn.current;if(!l)return!1;if(Qn.current=null,Ue(),c.trim()!==l.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:f}=ci(e,l.targets);u({kind:"note",tone:f.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`});for(let d of f)u({kind:"note",tone:"error",text:` \u2717 ${d.path}: ${d.error}`});return l.hadDevhints&&(u({kind:"note",tone:"warn",text:To().join(`
394
394
  `)}),Bt(zr())),u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
395
- ${Jd}`}),X("/init"),Yn(!1),!0},[e,u,Bt,Ue,X]),bn=B(async c=>{let l=c.slice(1).trim().split(/\s+/),i=(l[0]??"").toLowerCase(),f=l.slice(1);if(Yn(!0),Fo(f)&&["write","check","review","reorder"].includes(i)){let d=En(e,s);if(d.length===0){u({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let w=$=>i==="write"?`/write ${Ul(f,$).join(" ")}`.trim():`/${i} ${[$,...f.filter(h=>h!=="--scope")].join(" ")}`.trim();if(d.length===1){bn(w(d[0].token));return}yt({cursor:0,rows:d,run:$=>{bn(w($))}});return}if(at(i,f)){let d=En(e,s);if(d.length>1){let w=f.filter(b=>b.startsWith("--")).join(" "),$=b=>`/${i}${b?` ${i==="write"?`--scope ${b}`:b}`:""}${w?` ${w}`:""} ${b?"":"--all"}`.replace(/\s+/g," ").trim(),h=d.reduce((b,U)=>b+U.count,0),x={token:"",label:i==="review"?`Everything \u2014 all ${h} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${d.length} categories`:`Everything \u2014 rewrite all ${h} planned articles`,count:h};yt({cursor:0,rows:[x,...d],run:b=>{bn($(b))}});return}}switch(i){case"help":mn({tab:0});return;case"exit":case"quit":Ae.current?.close(),r();return;case"clear":Se(),It.current=[],Yn(!1),Ue(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let d;try{d=Te(e,s)}catch(w){u({kind:"note",tone:"error",text:w.message});return}u({kind:"note",tone:"info",text:`Profile "${d.name}" \u2192 ${d.connection.name} (${d.connection.apiUrl})${d.production?" \u26A0 PRODUCTION":""}`}),G(!0);try{let w=await tw(d.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},h=>u({kind:"note",tone:"info",text:h})),$=nw(d.name,w);if(ow($),await qr($,d.name,h=>u({kind:"note",tone:"info",text:h})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${d.name}" as ${bo($)}`}),await ca(s),fn.current){let h=fn.current;fn.current=null;let x=_e(e,s);x.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${h}.`}),X(h)):(u({kind:"note",tone:"warn",text:`${x.reason} (then ${h}.)`}),X("/login"),fn.current=h)}else hn.current&&(ge(hn.current,"\u21E5 tab to re-send your last prompt\u2026"),hn.current=null)}catch(w){u({kind:"note",tone:"error",text:`Login failed: ${w.message}`})}finally{G(!1),z(w=>w+1)}return}case"allow-prod":{let d=!1;try{d=Te(e,s).production}catch{}if(!d){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}_t.current=!0,Se(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let d=Hs(f.join(" ")),w=qe.current.uuid;if(!w){if(!d){u({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Cr.current=d,ht(d),rn(`${ur} ${d}`),u({kind:"note",tone:"ok",text:`Session will be named "${d}" once it starts.`});return}if(!d){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let $=qe.current.firstPrompt??"";Md($,e).then(h=>{h?(ge(`/rename ${h}`),u({kind:"note",tone:"info",text:`Suggestion: "${h}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}fw(w,d),ht(d),rn(`${ur} ${d}`),u({kind:"note",tone:"ok",text:`Session renamed to "${d}".`});return}case"profile":{let d=f[0],w=oe(e);if(!d){let $=Object.entries(w?.profiles??{});if($.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let h=$.map(([U,M])=>({name:U,env:M.connection?.environment??"custom",prod:M.production===!0,who:Or(U)})),x=s??w?.defaultProfile,b=Math.max(0,h.findIndex(U=>U.name===x));Lt({cursor:b,current:b,rows:h});return}if(d==="add"){let $=qs(e,f[1],f[2]);if($){u({kind:"note",tone:"error",text:$});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${f[1]}" created (environment: ${f[2]??f[1]}).`}),Lr(f[1],!1);return}if(!w?.profiles?.[d]){u({kind:"note",tone:"error",text:`Unknown profile "${d}". Create it: /profile add ${d} <environment>`});return}Lr(d,!0);return}case"doctor":await In(f,{cwd:e,version:o});return;case"genre":{await Zo(f,{cwd:e});try{br.current=!(oe(e)?.appType??ww(e))}catch{}z(d=>d+1);return}case"roadmap":{if(f[0]?.toLowerCase()==="done"){let d=wi(e,f.slice(1).join(" ").trim());u({kind:"note",tone:d.ok?"ok":"warn",text:d.line}),z(w=>w+1);return}u({kind:"note",tone:"info",text:gi(e).join(`
396
- `)});return}case"mcp":await jo(f);return;case"init":{if(oe(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let d=xw().map(w=>({name:w,apiUrl:vw(w).apiUrl}));Mt({cursor:0,rows:d});return}case"resume":{let d=f.join(" ").trim(),w=hw(e).filter(x=>x.uuid!==qe.current.uuid);if(!d){if(!w.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}$t({query:"",cursor:0,sessions:w});return}let $=pw(e,d);if(!$){u({kind:"note",tone:"error",text:`No session matches "${d}".`});return}Se($.uuid),qe.current={uuid:$.uuid,firstPrompt:$.firstPrompt,titleFired:!0},ht($.name),_i($.uuid),It.current=[];let h=Ai(e,$.uuid);for(let x of h)u(x);u({kind:"note",tone:"ok",text:h.length?`Resumed "${$.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${$.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let d=f.join(" ").trim(),w;try{w=await vn(e,s)}catch(h){u({kind:"note",tone:"error",text:`Could not list workspaces: ${h.message}`});return}if(!d){let h=w.workspaces.map(b=>({id:b.id,name:b.name??b.id,type:b.workspace_type}));if(h.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let x=Math.max(0,h.findIndex(b=>b.id===w.current));Ut({cursor:x,current:x,rows:h,profile:w.profile,projectId:w.projectId,projectName:w.projectName,environment:w.environment});return}let $=Fr(w.workspaces,d);if(!$){u({kind:"note",tone:"error",text:`No workspace matches "${d}".`});return}ao(w.profile,w.projectId,$);return}case"project":{let d=f.join(" ").trim(),w;try{w=await nt(e,s)}catch(h){u({kind:"note",tone:"error",text:`Could not list projects: ${h.message} (signed in? try /login)`});return}if(!d){let h=w.projects.map(b=>({id:b.id,name:b.name??b.id,sub:b.sub_domain}));if(h.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let x=h.findIndex(b=>b.id===w.current);gt({cursor:Math.max(0,x),current:x,rows:h,profile:w.profile,environment:w.environment});return}let $=Hr(w.projects,d);if(!$){u({kind:"note",tone:"error",text:`No project matches "${d}". Available: ${w.projects.map(h=>h.name??h.id).join(", ")}`});return}co(w.profile,$);return}case"logout":{let d;try{d=Te(e,s).name}catch($){u({kind:"note",tone:"error",text:$.message});return}let w=aw(d);lw(e,d),Se(),z($=>$+1),u({kind:"note",tone:w?"ok":"info",text:w?`\u2713 Signed out of "${d}" and cleared its project/workspace selection.`:`Profile "${d}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),X("/login");return}case"publish":{if(!no(c.trim()))return;if(f[0]==="--related"&&f[1]){let h=await Lo(e,s,f[1].replace(/\\/g,"/"));if(h.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Gt(h);return}let d=f.filter(h=>!h.startsWith("--"));if(d[0]){await Ir(d[0]);return}let w=f.includes("--all"),$=f.includes("--force");u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let h=await Oi({cwd:e,profileName:s}),{clean:x,conflicts:b}=No(h.entries),U=w&&$&&b.length>0,M=_o(h.entries);if(M>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${M} article${M===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),b.length>0&&!U&&u({kind:"note",tone:"warn",text:Io(b.length)}),x.length===0&&!U){if(b.length>0){X("/resolve");return}u({kind:"note",tone:"ok",text:M>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let K=h.counts["unknown-base"]??0;K>0&&u({kind:"note",tone:"info",text:`(${K} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Ji("Reconciling structure on Document360 (order + related articles)\u2026");try{let P=await zd({cwd:e,profileName:s}),N=Qd(await Xd({cwd:e,profileName:s})),H=Kd(P);H?u({kind:"note",tone:"info",text:H}):P.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${P.skipped}`}),N&&u({kind:"note",tone:"info",text:N}),u({kind:"note",tone:"ok",text:H||N?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(H||N)&&X("/structure")}catch(P){u({kind:"note",tone:"warn",text:`Structure sync failed: ${P.message}`})}finally{Ji(null)}return}if(w){let K=(U?[...x,...b]:x).map(P=>P.path);await Gt(K),b.length>0&&!U&&X("/resolve");return}Wt({cursor:0,rows:$l(x,b)})}catch(h){u({kind:"note",tone:"error",text:`Could not compute sync status: ${h.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!no(c.trim()))return;await Ur(f.find(d=>!d.startsWith("--")));return}case"preview":{let d=f.join(" ").trim();if(!d){let $=[];try{$=Object.keys(Wd(e,Te(e,s).name)?.articles??{})}catch{}if($.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}kt({query:"",cursor:0,paths:$});return}let w=Zg(d)?d:Ii(e,d);if(sn(w)){try{u({kind:"preview",name:qn(w),text:eu(gr(w,"utf8"))})}catch($){u({kind:"note",tone:"error",text:`Could not read ${w}: ${$.message}`})}return}if(qw.test(d)){try{let $=Te(e,s),h={profile:$.name,connection:$.connection},x=$.project.projectId??sw(h),b=await iw(h,x,d);u({kind:"preview",name:b.title??d,text:b.content??"*(article has no content)*"})}catch($){u({kind:"note",tone:"error",text:`Could not fetch article: ${$.message}`})}return}u({kind:"note",tone:"error",text:`"${d}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let d=f[0]?.trim();if(!d){let x=qo(Fi(e));mt({cursor:x,current:x});return}let{lines:w,changed:$,effective:h}=Nn(e,d);for(let x of w)u({kind:"note",tone:x.startsWith("\u26A0")?"warn":x.startsWith("\u2713")?"ok":"info",text:x});$&&(ta(x=>x+1),Ae.current?.setModel(h));return}case"convert":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:d,run:w}=ks(f),$=Sw(e,s);if($.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let h=bs($,d);if(h.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${d}". (${$.length} are tracked overall.)`});return}let x=Li(h),b=3,U=`/convert${d?` --scope ${d}`:""} --run`,M=yr(e,"light");if(!w){let P=Bd({files:$s(e,h),op:"convert",model:M.model}),N=d?`Scope: ${d} (${h.length} of ${$.length} tracked)
395
+ ${eu}`}),X("/init"),Yn(!1),!0},[e,u,Bt,Ue,X]),bn=B(async c=>{let l=c.slice(1).trim().split(/\s+/),i=(l[0]??"").toLowerCase(),f=l.slice(1);if(Yn(!0),Fo(f)&&["write","check","review","reorder"].includes(i)){let d=En(e,s);if(d.length===0){u({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let w=$=>i==="write"?`/write ${Ul(f,$).join(" ")}`.trim():`/${i} ${[$,...f.filter(h=>h!=="--scope")].join(" ")}`.trim();if(d.length===1){bn(w(d[0].token));return}yt({cursor:0,rows:d,run:$=>{bn(w($))}});return}if(at(i,f)){let d=En(e,s);if(d.length>1){let w=f.filter(b=>b.startsWith("--")).join(" "),$=b=>`/${i}${b?` ${i==="write"?`--scope ${b}`:b}`:""}${w?` ${w}`:""} ${b?"":"--all"}`.replace(/\s+/g," ").trim(),h=d.reduce((b,U)=>b+U.count,0),x={token:"",label:i==="review"?`Everything \u2014 all ${h} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${d.length} categories`:`Everything \u2014 rewrite all ${h} planned articles`,count:h};yt({cursor:0,rows:[x,...d],run:b=>{bn($(b))}});return}}switch(i){case"help":mn({tab:0});return;case"exit":case"quit":Ae.current?.close(),r();return;case"clear":Se(),It.current=[],Yn(!1),Ue(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let d;try{d=Te(e,s)}catch(w){u({kind:"note",tone:"error",text:w.message});return}u({kind:"note",tone:"info",text:`Profile "${d.name}" \u2192 ${d.connection.name} (${d.connection.apiUrl})${d.production?" \u26A0 PRODUCTION":""}`}),G(!0);try{let w=await rw(d.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},h=>u({kind:"note",tone:"info",text:h})),$=sw(d.name,w);if(iw($),await qr($,d.name,h=>u({kind:"note",tone:"info",text:h})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${d.name}" as ${bo($)}`}),await ca(s),fn.current){let h=fn.current;fn.current=null;let x=_e(e,s);x.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${h}.`}),X(h)):(u({kind:"note",tone:"warn",text:`${x.reason} (then ${h}.)`}),X("/login"),fn.current=h)}else hn.current&&(ge(hn.current,"\u21E5 tab to re-send your last prompt\u2026"),hn.current=null)}catch(w){u({kind:"note",tone:"error",text:`Login failed: ${w.message}`})}finally{G(!1),z(w=>w+1)}return}case"allow-prod":{let d=!1;try{d=Te(e,s).production}catch{}if(!d){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}_t.current=!0,Se(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let d=Hs(f.join(" ")),w=qe.current.uuid;if(!w){if(!d){u({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Cr.current=d,ht(d),rn(`${ur} ${d}`),u({kind:"note",tone:"ok",text:`Session will be named "${d}" once it starts.`});return}if(!d){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let $=qe.current.firstPrompt??"";Wd($,e).then(h=>{h?(ge(`/rename ${h}`),u({kind:"note",tone:"info",text:`Suggestion: "${h}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}ww(w,d),ht(d),rn(`${ur} ${d}`),u({kind:"note",tone:"ok",text:`Session renamed to "${d}".`});return}case"profile":{let d=f[0],w=oe(e);if(!d){let $=Object.entries(w?.profiles??{});if($.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let h=$.map(([U,M])=>({name:U,env:M.connection?.environment??"custom",prod:M.production===!0,who:Or(U)})),x=s??w?.defaultProfile,b=Math.max(0,h.findIndex(U=>U.name===x));Lt({cursor:b,current:b,rows:h});return}if(d==="add"){let $=qs(e,f[1],f[2]);if($){u({kind:"note",tone:"error",text:$});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${f[1]}" created (environment: ${f[2]??f[1]}).`}),Lr(f[1],!1);return}if(!w?.profiles?.[d]){u({kind:"note",tone:"error",text:`Unknown profile "${d}". Create it: /profile add ${d} <environment>`});return}Lr(d,!0);return}case"doctor":await In(f,{cwd:e,version:o});return;case"genre":{await Zo(f,{cwd:e});try{br.current=!(oe(e)?.appType??bw(e))}catch{}z(d=>d+1);return}case"roadmap":{if(f[0]?.toLowerCase()==="done"){let d=wi(e,f.slice(1).join(" ").trim());u({kind:"note",tone:d.ok?"ok":"warn",text:d.line}),z(w=>w+1);return}u({kind:"note",tone:"info",text:gi(e).join(`
396
+ `)});return}case"mcp":await jo(f);return;case"init":{if(oe(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let d=Rw().map(w=>({name:w,apiUrl:Sw(w).apiUrl}));Mt({cursor:0,rows:d});return}case"resume":{let d=f.join(" ").trim(),w=gw(e).filter(x=>x.uuid!==qe.current.uuid);if(!d){if(!w.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}$t({query:"",cursor:0,sessions:w});return}let $=mw(e,d);if(!$){u({kind:"note",tone:"error",text:`No session matches "${d}".`});return}Se($.uuid),qe.current={uuid:$.uuid,firstPrompt:$.firstPrompt,titleFired:!0},ht($.name),_i($.uuid),It.current=[];let h=Ai(e,$.uuid);for(let x of h)u(x);u({kind:"note",tone:"ok",text:h.length?`Resumed "${$.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${$.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let d=f.join(" ").trim(),w;try{w=await vn(e,s)}catch(h){u({kind:"note",tone:"error",text:`Could not list workspaces: ${h.message}`});return}if(!d){let h=w.workspaces.map(b=>({id:b.id,name:b.name??b.id,type:b.workspace_type}));if(h.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let x=Math.max(0,h.findIndex(b=>b.id===w.current));Ut({cursor:x,current:x,rows:h,profile:w.profile,projectId:w.projectId,projectName:w.projectName,environment:w.environment});return}let $=Fr(w.workspaces,d);if(!$){u({kind:"note",tone:"error",text:`No workspace matches "${d}".`});return}ao(w.profile,w.projectId,$);return}case"project":{let d=f.join(" ").trim(),w;try{w=await nt(e,s)}catch(h){u({kind:"note",tone:"error",text:`Could not list projects: ${h.message} (signed in? try /login)`});return}if(!d){let h=w.projects.map(b=>({id:b.id,name:b.name??b.id,sub:b.sub_domain}));if(h.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let x=h.findIndex(b=>b.id===w.current);gt({cursor:Math.max(0,x),current:x,rows:h,profile:w.profile,environment:w.environment});return}let $=Hr(w.projects,d);if(!$){u({kind:"note",tone:"error",text:`No project matches "${d}". Available: ${w.projects.map(h=>h.name??h.id).join(", ")}`});return}co(w.profile,$);return}case"logout":{let d;try{d=Te(e,s).name}catch($){u({kind:"note",tone:"error",text:$.message});return}let w=dw(d);uw(e,d),Se(),z($=>$+1),u({kind:"note",tone:w?"ok":"info",text:w?`\u2713 Signed out of "${d}" and cleared its project/workspace selection.`:`Profile "${d}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),X("/login");return}case"publish":{if(!no(c.trim()))return;if(f[0]==="--related"&&f[1]){let h=await Lo(e,s,f[1].replace(/\\/g,"/"));if(h.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Gt(h);return}let d=f.filter(h=>!h.startsWith("--"));if(d[0]){await Ir(d[0]);return}let w=f.includes("--all"),$=f.includes("--force");u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let h=await Oi({cwd:e,profileName:s}),{clean:x,conflicts:b}=No(h.entries),U=w&&$&&b.length>0,M=_o(h.entries);if(M>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${M} article${M===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),b.length>0&&!U&&u({kind:"note",tone:"warn",text:Io(b.length)}),x.length===0&&!U){if(b.length>0){X("/resolve");return}u({kind:"note",tone:"ok",text:M>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let K=h.counts["unknown-base"]??0;K>0&&u({kind:"note",tone:"info",text:`(${K} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Ji("Reconciling structure on Document360 (order + related articles)\u2026");try{let P=await Xd({cwd:e,profileName:s}),j=Zd(await Jd({cwd:e,profileName:s})),H=Qd(P);H?u({kind:"note",tone:"info",text:H}):P.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${P.skipped}`}),j&&u({kind:"note",tone:"info",text:j}),u({kind:"note",tone:"ok",text:H||j?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(H||j)&&X("/structure")}catch(P){u({kind:"note",tone:"warn",text:`Structure sync failed: ${P.message}`})}finally{Ji(null)}return}if(w){let K=(U?[...x,...b]:x).map(P=>P.path);await Gt(K),b.length>0&&!U&&X("/resolve");return}Wt({cursor:0,rows:$l(x,b)})}catch(h){u({kind:"note",tone:"error",text:`Could not compute sync status: ${h.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!no(c.trim()))return;await Ur(f.find(d=>!d.startsWith("--")));return}case"preview":{let d=f.join(" ").trim();if(!d){let $=[];try{$=Object.keys(Hd(e,Te(e,s).name)?.articles??{})}catch{}if($.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}kt({query:"",cursor:0,paths:$});return}let w=nw(d)?d:Ii(e,d);if(sn(w)){try{u({kind:"preview",name:qn(w),text:nu(gr(w,"utf8"))})}catch($){u({kind:"note",tone:"error",text:`Could not read ${w}: ${$.message}`})}return}if(Gw.test(d)){try{let $=Te(e,s),h={profile:$.name,connection:$.connection},x=$.project.projectId??lw(h),b=await cw(h,x,d);u({kind:"preview",name:b.title??d,text:b.content??"*(article has no content)*"})}catch($){u({kind:"note",tone:"error",text:`Could not fetch article: ${$.message}`})}return}u({kind:"note",tone:"error",text:`"${d}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let d=f[0]?.trim();if(!d){let x=qo(Fi(e));mt({cursor:x,current:x});return}let{lines:w,changed:$,effective:h}=Nn(e,d);for(let x of w)u({kind:"note",tone:x.startsWith("\u26A0")?"warn":x.startsWith("\u2713")?"ok":"info",text:x});$&&(ta(x=>x+1),Ae.current?.setModel(h));return}case"convert":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:d,run:w}=ks(f),$=Dw(e,s);if($.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let h=bs($,d);if(h.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${d}". (${$.length} are tracked overall.)`});return}let x=Li(h),b=3,U=`/convert${d?` --scope ${d}`:""} --run`,M=yr(e,"light");if(!w){let P=Gd({files:$s(e,h),op:"convert",model:M.model}),j=d?`Scope: ${d} (${h.length} of ${$.length} tracked)
397
397
  `:"",H=`
398
- Model: ${M.model}${M.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:N+vs(x,P,b).join(`
399
- `)+H}),X(U);return}pt.current=Date.now(),jt(0),T(!0);let K=new AbortController;ye.current=K,te({verb:"Converting",total:x.length,done:0,active:[],rows:Hn(x),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${h.length} articles across ${x.length} partitions (\u2264${b} agents at once) on ${M.model}\u2026 (esc to stop)`});try{for await(let P of wr({cwd:e,partitions:x,promptFor:xs,concurrency:b,profileName:s,allowProdWrites:_t.current,model:M.model,signal:K.signal}))if(P.type==="partition_status")P.status==="running"?te(N=>N&&{...N,active:[...N.active,P.label],rows:Oe(N.rows,P.label,"active"),lastAt:Date.now()}):te(N=>N&&{...N,active:N.active.filter(H=>H!==P.label),done:N.done+1,rows:Oe(N.rows,P.label,P.status==="done"?"done":"failed"),lastAt:Date.now()});else if(P.type==="partition_event")te(N=>{if(!N)return N;let H={...N,lastAt:Date.now()};return P.event.type==="tool"?H.tools=N.tools+1:P.event.type==="text"&&(H.chars=N.chars+P.event.delta.length),H});else if(P.type==="run_done"){qt(ee=>ee+P.totalCostUsd),Ht(ee=>ee+P.results.reduce((Ee,ho)=>Ee+ho.outputTokens,0));let N=P.aborted?"Stopped. ":"",H=t.kind==="api"?"api":"subscription";u({kind:"note",tone:P.aborted?"warn":P.ok?"ok":"warn",text:N+Cs(P.results,x,H).join(`
400
- `)})}}catch(P){u({kind:"note",tone:"error",text:`Convert run failed: ${P.message}`})}finally{ye.current=null,te(null),T(!1),z(P=>P+1)}return}case"write":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=Pw(e);if(d.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:w,path:$,preview:h,concurrency:x,rewrite:b}=Ps(f),{docsDir:U,targets:M,reason:K,rewriting:P}=Is(e,d,{scope:w,path:$,rewrite:b});if(M.length===0){u({kind:"note",tone:"warn",text:K??"Nothing to write."});return}P&&u({kind:"note",tone:"warn",text:`--rewrite: regenerating ${M.length} already-written article${M.length===1?"":"s"} (overwrites them; git has your baseline).`});let N=Li(M),H=Ss(x),ee=yr(e,"standard"),Ee=!!$;if(h&&!Ee){let Q=Bd({files:Ds(e,d,M),op:"write",model:ee.model}),se=w?`Scope: ${w} (${M.length} pending)
398
+ Model: ${M.model}${M.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:j+vs(x,P,b).join(`
399
+ `)+H}),X(U);return}pt.current=Date.now(),jt(0),T(!0);let K=new AbortController;ye.current=K,te({verb:"Converting",total:x.length,done:0,active:[],rows:Hn(x),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${h.length} articles across ${x.length} partitions (\u2264${b} agents at once) on ${M.model}\u2026 (esc to stop)`});try{for await(let P of wr({cwd:e,partitions:x,promptFor:xs,concurrency:b,profileName:s,allowProdWrites:_t.current,model:M.model,signal:K.signal}))if(P.type==="partition_status")P.status==="running"?te(j=>j&&{...j,active:[...j.active,P.label],rows:Oe(j.rows,P.label,"active"),lastAt:Date.now()}):te(j=>j&&{...j,active:j.active.filter(H=>H!==P.label),done:j.done+1,rows:Oe(j.rows,P.label,P.status==="done"?"done":"failed"),lastAt:Date.now()});else if(P.type==="partition_event")te(j=>{if(!j)return j;let H={...j,lastAt:Date.now()};return P.event.type==="tool"?H.tools=j.tools+1:P.event.type==="text"&&(H.chars=j.chars+P.event.delta.length),H});else if(P.type==="run_done"){qt(ee=>ee+P.totalCostUsd),Ht(ee=>ee+P.results.reduce((Ee,ho)=>Ee+ho.outputTokens,0));let j=P.aborted?"Stopped. ":"",H=t.kind==="api"?"api":"subscription";u({kind:"note",tone:P.aborted?"warn":P.ok?"ok":"warn",text:j+Cs(P.results,x,H).join(`
400
+ `)})}}catch(P){u({kind:"note",tone:"error",text:`Convert run failed: ${P.message}`})}finally{ye.current=null,te(null),T(!1),z(P=>P+1)}return}case"write":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=Aw(e);if(d.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:w,path:$,preview:h,concurrency:x,rewrite:b}=Ps(f),{docsDir:U,targets:M,reason:K,rewriting:P}=Is(e,d,{scope:w,path:$,rewrite:b});if(M.length===0){u({kind:"note",tone:"warn",text:K??"Nothing to write."});return}P&&u({kind:"note",tone:"warn",text:`--rewrite: regenerating ${M.length} already-written article${M.length===1?"":"s"} (overwrites them; git has your baseline).`});let j=Li(M),H=Ss(x),ee=yr(e,"standard"),Ee=!!$;if(h&&!Ee){let Q=Gd({files:Ds(e,d,M),op:"write",model:ee.model}),se=w?`Scope: ${w} (${M.length} pending)
401
401
  `:"",he=`
402
- Model: ${ee.model}${ee.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:se+js(N,Q,H).join(`
403
- `)+he}),X(`/write${w?` --scope ${w}`:""}`);return}pt.current=Date.now(),jt(0),T(!0);let ho=new AbortController;ye.current=ho,te({verb:"Writing",total:N.length,done:0,active:[],rows:Hn(N),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${M.length} article${M.length===1?"":"s"} across ${N.length} partition${N.length===1?"":"s"} (\u2264${H} agents at once) on ${ee.model}${ee.forced?" (forced)":""}\u2026 (esc to stop)`});let fo=new Set;try{for await(let Q of wr({cwd:e,partitions:N,promptFor:se=>As(se,U,{rewrite:P||Ee}),concurrency:H,profileName:s,allowProdWrites:_t.current,model:ee.model,signal:ho.signal}))if(Q.type==="partition_status")Q.status==="running"?te(se=>se&&{...se,active:[...se.active,Q.label],rows:Oe(se.rows,Q.label,"active"),lastAt:Date.now()}):te(se=>se&&{...se,active:se.active.filter(he=>he!==Q.label),done:se.done+1,rows:Oe(se.rows,Q.label,Q.status==="done"?"done":"failed"),lastAt:Date.now()});else if(Q.type==="partition_event"){let se=null;if(Q.event.type==="tool"){let he=vd(Q.event.name,Q.event.input,N[Q.index]?.paths??[]);he&&!fo.has(he)&&(fo.add(he),se=Q.label)}te(he=>{if(!he)return he;let We={...he,lastAt:Date.now()};return Q.event.type==="tool"?We.tools=he.tools+1:Q.event.type==="text"&&(We.chars=he.chars+Q.event.delta.length),se&&(We.rows=xd(We.rows,se)),We})}else if(Q.type==="run_done"){qt(et=>et+Q.totalCostUsd),Ht(et=>et+Q.results.reduce((Ye,ku)=>Ye+ku.outputTokens,0));let se=Q.aborted?"Stopped. ":"",he=t.kind==="api"?"api":"subscription";if(u({kind:"note",tone:Q.aborted?"warn":Q.ok?"ok":"warn",text:se+Es(Q.results,N,he).join(`
404
- `)}),!Q.aborted&&Q.ok)try{let et=(fo.size>0?[...fo]:M).map(Ye=>`${U}/${Ye}`);Mi(e,et,{writtenCap:Ui})}catch{}let We=Q.aborted?null:Ns(e,U,M);if(We&&u({kind:"note",tone:"warn",text:We}),!Q.aborted&&Q.ok){let et=w??$??"",Ye=et?` ${et}`:"";Re(We?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${Ye} --fix, then /review${Ye} --fix for editorial quality, then /publish --all (add /screenshot --all first if you want images).`:`Written. I\u2019d run /review${Ye} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot --all first if you want images).`,{kind:"cmd",cmd:We?`/check${Ye} --fix`:`/review${Ye} --fix`,reason:""})}}}catch(Q){u({kind:"note",tone:"error",text:`Write run failed: ${Q.message}`})}finally{ye.current=null,te(null),T(!1),z(Q=>Q+1)}return}case"draft":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:d,looseDocs:w}=_s(e);if(d.length===0&&w===0){u({kind:"note",tone:"info",text:Ls});return}let $=f.join(" ").trim();if(!$&&d.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
402
+ Model: ${ee.model}${ee.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:se+js(j,Q,H).join(`
403
+ `)+he}),X(`/write${w?` --scope ${w}`:""}`);return}pt.current=Date.now(),jt(0),T(!0);let ho=new AbortController;ye.current=ho,te({verb:"Writing",total:j.length,done:0,active:[],rows:Hn(j),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${M.length} article${M.length===1?"":"s"} across ${j.length} partition${j.length===1?"":"s"} (\u2264${H} agents at once) on ${ee.model}${ee.forced?" (forced)":""}\u2026 (esc to stop)`});let fo=new Set;try{for await(let Q of wr({cwd:e,partitions:j,promptFor:se=>As(se,U,{rewrite:P||Ee}),concurrency:H,profileName:s,allowProdWrites:_t.current,model:ee.model,signal:ho.signal}))if(Q.type==="partition_status")Q.status==="running"?te(se=>se&&{...se,active:[...se.active,Q.label],rows:Oe(se.rows,Q.label,"active"),lastAt:Date.now()}):te(se=>se&&{...se,active:se.active.filter(he=>he!==Q.label),done:se.done+1,rows:Oe(se.rows,Q.label,Q.status==="done"?"done":"failed"),lastAt:Date.now()});else if(Q.type==="partition_event"){let se=null;if(Q.event.type==="tool"){let he=Rd(Q.event.name,Q.event.input,j[Q.index]?.paths??[]);he&&!fo.has(he)&&(fo.add(he),se=Q.label)}te(he=>{if(!he)return he;let We={...he,lastAt:Date.now()};return Q.event.type==="tool"?We.tools=he.tools+1:Q.event.type==="text"&&(We.chars=he.chars+Q.event.delta.length),se&&(We.rows=Cd(We.rows,se)),We})}else if(Q.type==="run_done"){qt(et=>et+Q.totalCostUsd),Ht(et=>et+Q.results.reduce((Ye,$u)=>Ye+$u.outputTokens,0));let se=Q.aborted?"Stopped. ":"",he=t.kind==="api"?"api":"subscription";if(u({kind:"note",tone:Q.aborted?"warn":Q.ok?"ok":"warn",text:se+Es(Q.results,j,he).join(`
404
+ `)}),!Q.aborted&&Q.ok)try{let et=(fo.size>0?[...fo]:M).map(Ye=>`${U}/${Ye}`);Mi(e,et,{writtenCap:Ui})}catch{}let We=Q.aborted?null:Ns(e,U,M);if(We&&u({kind:"note",tone:"warn",text:We}),!Q.aborted&&Q.ok){let et=w??$??"",Ye=et?` ${et}`:"";ke(We?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${Ye} --fix, then /review${Ye} --fix for editorial quality, then /publish --all (add /screenshot --all first if you want images).`:`Written. I\u2019d run /review${Ye} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot --all first if you want images).`,{kind:"cmd",cmd:We?`/check${Ye} --fix`:`/review${Ye} --fix`,reason:""})}}}catch(Q){u({kind:"note",tone:"error",text:`Write run failed: ${Q.message}`})}finally{ye.current=null,te(null),T(!1),z(Q=>Q+1)}return}case"draft":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:d,looseDocs:w}=_s(e);if(d.length===0&&w===0){u({kind:"note",tone:"info",text:Ls});return}let $=f.join(" ").trim();if(!$&&d.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
405
405
  ${d.map(b=>` \u2022 ${b.name} (${b.docCount} doc${b.docCount===1?"":"s"})`).join(`
406
406
  `)}`}),ut(d.map(b=>`/draft ${b.name}`));return}let h="",x;if($){let b=Os(d,$);b?h=b:x=$}else h=d[0]?.name??"";await ne(Ho(h,x),{display:$?`/draft ${$}`:"/draft",quietUser:!0});return}case"pull":{if(!no(c.trim()))return;let d=f.find(w=>w.startsWith("--"));try{if(d==="--status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let h=Date.now(),x=await Oi({cwd:e,profileName:s});u({kind:"note",tone:"info",text:Uo(x,Date.now()-h).join(`
407
- `)});return}if(d==="--baseline"){let h=f.find(M=>!M.startsWith("--")),x=h?h.replace(/\\/g,"/"):void 0;u({kind:"note",tone:"info",text:x?`Setting the sync baseline for ${x}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let b=await kw({cwd:e,profileName:s,relPaths:x?[x]:void 0}),U=x?{rebaselined:[],skipped:[]}:await bw({cwd:e,profileName:s});if(b.baselined.length===0&&b.skipped.length===0&&U.rebaselined.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}b.baselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Baselined ${b.baselined.length} article${b.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),U.rebaselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${U.rebaselined.length} article${U.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),b.skipped.length>0&&u({kind:"note",tone:"warn",text:`${b.skipped.length} skipped:
407
+ `)});return}if(d==="--baseline"){let h=f.find(M=>!M.startsWith("--")),x=h?h.replace(/\\/g,"/"):void 0;u({kind:"note",tone:"info",text:x?`Setting the sync baseline for ${x}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let b=await xw({cwd:e,profileName:s,relPaths:x?[x]:void 0}),U=x?{rebaselined:[],skipped:[]}:await vw({cwd:e,profileName:s});if(b.baselined.length===0&&b.skipped.length===0&&U.rebaselined.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}b.baselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Baselined ${b.baselined.length} article${b.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),U.rebaselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${U.rebaselined.length} article${U.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),b.skipped.length>0&&u({kind:"note",tone:"warn",text:`${b.skipped.length} skipped:
408
408
  ${b.skipped.map(M=>` - ${M.path} (${M.reason})`).join(`
409
- `)}`}),z(M=>M+1);return}if(d==="--compare"){u({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let h=await yw({cwd:e,profileName:s}),x=h.onlyInLegacy.length===0&&h.onlyInManifest.length===0&&h.mappedMissingFromManifest.length===0,b=[`Legacy listing: ${h.legacyCount} \xB7 Manifest: ${h.manifestCount} \xB7 in both: ${h.inBoth}`];x?b.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(h.mappedMissingFromManifest.length&&b.push(`\u2717 ${h.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${h.mappedMissingFromManifest.slice(0,5).join(", ")}`),h.onlyInLegacy.length&&b.push(`\u26A0 ${h.onlyInLegacy.length} only in the legacy listing: ${h.onlyInLegacy.slice(0,5).join(", ")}`),h.onlyInManifest.length&&b.push(`\u26A0 ${h.onlyInManifest.length} only in the manifest: ${h.onlyInManifest.slice(0,5).join(", ")}`),b.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),u({kind:"note",tone:x?"ok":"warn",text:b.join(`
410
- `)});return}if(d){u({kind:"note",tone:"error",text:`Unknown option: ${d} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let w=f[0];if(w){let h=await qd({cwd:e,profileName:s,relPath:w.replace(/\\/g,"/")});le.current=[{plan:h,mode:h.overwritesLocalChanges?"conflict":"pull"}],Ot.current=[],Yt();return}u({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let $=await gs({cwd:e,profileName:s});for(let h of ws($))u({kind:"note",tone:h.tone,text:h.text});z(h=>h+1)}catch(w){u({kind:"note",tone:"error",text:`Pull failed: ${w.message}`})}return}case"scope":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=$w(e);if(d.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Ft({cursor:0,rows:d.map(w=>({...w,checked:w.recommended}))});return}case"audit":{if(f[0]==="--auto"){let w=oe(e);if(!w){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=f[1]!=="off";Ud({...w,autoAudit:$},e),u({kind:"note",tone:"ok",text:$?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let d=await jn();d.kind==="forward-to-agent"&&d.prompt&&await ne(d.prompt,{display:d.display,quietUser:!0});return}case"check":{let d=f.find(h=>!h.startsWith("--")),w=d?` ${d}`:"",$=Hd({cwd:e,scope:d});if(f.includes("--fix")){if($.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}u({kind:"note",tone:"info",text:`Fixing ${$.length} doc issue${$.length===1?"":"s"}\u2026`});let h=Yd(e,d);await ne(ui($),{display:`/check${w} --fix`,quietUser:!0});try{Mi(e,h,{reviewedCap:Ui})}catch{}let x=Hd({cwd:e,scope:d});u({kind:"note",tone:x.length===0?"ok":"warn",text:x.length===0?"\u2713 Doc-checker: all issues resolved.":Jo(x).join(`
411
- `)}),Re(x.length===0?`Deterministic issues fixed. Next: /review${w} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${w} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${w} --fix`,reason:""});return}u({kind:"note",tone:$.length===0?"ok":"warn",text:Jo($).join(`
412
- `)}),$.length>0&&Re(`Found ${$.length} doc issue${$.length===1?"":"s"} above. /check${w} --fix has the agent fix them in place (or /review${w} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${w} --fix`,reason:""});return}case"structure":{let d=Mn(e,s);if(d.length===0){u({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}u({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...d].join(`
413
- `)});return}case"reorder":{let d=hi(e,f);if(!d){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ne(d.prompt,{display:d.display,quietUser:!0}),Re("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let d=pi(e,f);if(!d){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=f.includes("--fix"),$=f.find(x=>!x.startsWith("--")),h=w?Yd(e,$):[];if(await ne(d.prompt,{display:d.display,quietUser:!0}),w)try{Mi(e,h,{reviewedCap:Ui})}catch{}if(w)Re("\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 x=f.filter(b=>b!=="--fix").join(" ");Re(`The review listed issues above. /review${x?` ${x}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${x?` ${x}`:""} --fix`,reason:""})}return}case"capture-setup":{let d=await _n();d.kind==="forward-to-agent"&&d.prompt&&await ne(d.prompt,{display:d.display,quietUser:!0});let w=Js(e);w&&u({kind:"note",tone:"info",text:w.join(`
409
+ `)}`}),z(M=>M+1);return}if(d==="--compare"){u({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let h=await $w({cwd:e,profileName:s}),x=h.onlyInLegacy.length===0&&h.onlyInManifest.length===0&&h.mappedMissingFromManifest.length===0,b=[`Legacy listing: ${h.legacyCount} \xB7 Manifest: ${h.manifestCount} \xB7 in both: ${h.inBoth}`];x?b.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(h.mappedMissingFromManifest.length&&b.push(`\u2717 ${h.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${h.mappedMissingFromManifest.slice(0,5).join(", ")}`),h.onlyInLegacy.length&&b.push(`\u26A0 ${h.onlyInLegacy.length} only in the legacy listing: ${h.onlyInLegacy.slice(0,5).join(", ")}`),h.onlyInManifest.length&&b.push(`\u26A0 ${h.onlyInManifest.length} only in the manifest: ${h.onlyInManifest.slice(0,5).join(", ")}`),b.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),u({kind:"note",tone:x?"ok":"warn",text:b.join(`
410
+ `)});return}if(d){u({kind:"note",tone:"error",text:`Unknown option: ${d} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let w=f[0];if(w){let h=await Vd({cwd:e,profileName:s,relPath:w.replace(/\\/g,"/")});le.current=[{plan:h,mode:h.overwritesLocalChanges?"conflict":"pull"}],Ot.current=[],Yt();return}u({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let $=await gs({cwd:e,profileName:s});for(let h of ws($))u({kind:"note",tone:h.tone,text:h.text});z(h=>h+1)}catch(w){u({kind:"note",tone:"error",text:`Pull failed: ${w.message}`})}return}case"scope":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=Cw(e);if(d.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Ft({cursor:0,rows:d.map(w=>({...w,checked:w.recommended}))});return}case"audit":{if(f[0]==="--auto"){let w=oe(e);if(!w){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=f[1]!=="off";Fd({...w,autoAudit:$},e),u({kind:"note",tone:"ok",text:$?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let d=await jn();d.kind==="forward-to-agent"&&d.prompt&&await ne(d.prompt,{display:d.display,quietUser:!0});return}case"check":{let d=f.find(h=>!h.startsWith("--")),w=d?` ${d}`:"",$=Bd({cwd:e,scope:d});if(f.includes("--fix")){if($.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}u({kind:"note",tone:"info",text:`Fixing ${$.length} doc issue${$.length===1?"":"s"}\u2026`});let h=Kd(e,d);await ne(ui($),{display:`/check${w} --fix`,quietUser:!0});try{Mi(e,h,{reviewedCap:Ui})}catch{}let x=Bd({cwd:e,scope:d});u({kind:"note",tone:x.length===0?"ok":"warn",text:x.length===0?"\u2713 Doc-checker: all issues resolved.":Jo(x).join(`
411
+ `)}),ke(x.length===0?`Deterministic issues fixed. Next: /review${w} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${w} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${w} --fix`,reason:""});return}u({kind:"note",tone:$.length===0?"ok":"warn",text:Jo($).join(`
412
+ `)}),$.length>0&&ke(`Found ${$.length} doc issue${$.length===1?"":"s"} above. /check${w} --fix has the agent fix them in place (or /review${w} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${w} --fix`,reason:""});return}case"structure":{let d=Mn(e,s);if(d.length===0){u({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}u({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...d].join(`
413
+ `)});return}case"reorder":{let d=hi(e,f);if(!d){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ne(d.prompt,{display:d.display,quietUser:!0}),ke("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let d=pi(e,f);if(!d){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=f.includes("--fix"),$=f.find(x=>!x.startsWith("--")),h=w?Kd(e,$):[];if(await ne(d.prompt,{display:d.display,quietUser:!0}),w)try{Mi(e,h,{reviewedCap:Ui})}catch{}if(w)ke("\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 x=f.filter(b=>b!=="--fix").join(" ");ke(`The review listed issues above. /review${x?` ${x}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${x?` ${x}`:""} --fix`,reason:""})}return}case"capture-setup":{let d=await _n();d.kind==="forward-to-agent"&&d.prompt&&await ne(d.prompt,{display:d.display,quietUser:!0});let w=Js(e);w&&u({kind:"note",tone:"info",text:w.join(`
414
414
  `)});return}case"devhints":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:Zt(Jt(e)).join(`
415
- `)}),Bt(vt()),wn.current=Ie(e).status==="current",Vt.current=ze(e);return}case"discover":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ne(us(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Zs(e)===0){u({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await ne(ei(),{display:"/inbox",quietUser:!0});return}case"feedback":{let d=Gd(e),w="";try{w=sn(d)?gr(d,"utf8"):""}catch{w=""}if(!/^## /m.test(w)){u({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let $=await Ti(w.trim());u({kind:"note",tone:$?"ok":"warn",text:$?"\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 ${d} and copy it manually.`}),$&&jr(null);return}case"document":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:d,what:w}=Us(f);if(!w&&Ms(e)===0){u({kind:"note",tone:"info",text:Fs});return}let $=`/document${w?` ${w}`:""}${d?" --publish":""}`;await ne(Ws(w,d),{display:$,quietUser:!0});return}case"catch-up":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!no(c.trim()))return;let{publish:d}=ni(f);u({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let w=await ri({cwd:e,profileName:s});for(let h of si(w))u({kind:"note",tone:h.startsWith("\u2713")?"ok":h.startsWith("\u2139")?"info":"warn",text:h});let $=Ln(On(e));u({kind:"note",tone:"info",text:$?`Catching up on ${$}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ne(oi({publish:d}),{display:`/catch-up${d?" --publish":""}`,quietUser:!0});return}case"update":{Dr.current=!0,u({kind:"note",tone:"info",text:`Updating ${Pt}\u2026 (don\u2019t close this window)`}),zn(!0),(await Xo().finally(()=>zn(!1))).ok?(u({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),X("/exit"),Gi("")):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Ko}`});return}case"screenshot":{let d=Ys(f);if(d.mode==="list"){if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=St(e,d.scope);if(d.picker){if(h.length===0){u({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let b=xc(h);if(b.length===0){u({kind:"note",tone:"info",text:Vo(h,d.scope).join(`
416
- `)}),Re(`\u2713 All ${h.length} screenshots are captured. /publish puts them in the articles; /capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}wt({cursor:0,rows:b,title:"Screenshots \u2014 pick what to author or capture:"});return}u({kind:"note",tone:"info",text:Vo(h,d.scope).join(`
417
- `)});let x=h.filter(b=>b.state==="placeholder").length;if(x>0){let b=d.scope?`/screenshot ${d.scope}`:"/screenshot --all";Re(`${x} of ${h.length} still need${x===1?"s":""} a spec \u2014 /screenshot <id> authors one, ${b} authors them all in parallel.`,{kind:"cmd",cmd:b,reason:""})}return}if(d.mode==="single"){await la(d.id);return}if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=d.mode==="scope"?d.scope:void 0,$=Rw(e,{scope:w}).map(h=>h.id);if($.length===0){u({kind:"note",tone:"info",text:w?`No screenshot placeholders under ${w}.`:"No screenshot placeholders found in the docs."});return}await aa($,{setup:d.setup});return}case"capture":{let d=zs(f);if(!Yo(e)){u({kind:"note",tone:"warn",text:"Screenshot capture is not set up in this repo yet \u2014 run d360-capture init in this repo's terminal, then d360-capture auth (once per machine)."});return}if(d.mode==="single"){await _r([d.id]);return}if(d.mode==="all"||d.mode==="scope"){let{ready:$,captured:h}=Ks(e,d.mode==="scope"?d.scope:void 0),x=[...$,...h];if(x.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),X("/screenshot");return}await _r(x);return}let w=Sc(St(e));if(w.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),X("/screenshot");return}wt({cursor:0,rows:w,title:"Capture screenshots \u2014 pick what to shoot:"});return}case"reset":{let d=li(e);if(d.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Qn.current={repoName:qn(e),targets:d,hadDevhints:sn(Vd(e))},u({kind:"note",tone:"warn",text:di(e,d).join(`
418
- `)}),ge(qn(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Yt,Ur,u,Se,ne,Gt,Ir,ca]),uo=B(c=>{let l=(c??S).trim();if(v(""),Kn(null),Et(0),l.startsWith("/")&&(Vn.current=!1,Ue(),un(null),ut(f=>Sd(f,l))),!l||(Vi(!1),ua(l))||da(l))return;vr.current.push(l);let i=Ad(l,Yi.current);if(l.startsWith("/"))u({kind:"user",text:l}),Xe(!0),bn(i).finally(()=>Xe(!1));else if(_w(i)){u({kind:"user",text:l});let f=Ow(i);if(!f)ne(i,{display:l,quietUser:!0});else{try{Lw(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ne(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${f}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${f}" and the article path(s) you wrote.`,{display:l,quietUser:!0})}}else{let f=Kc(e,i);ne(f??i,{display:l})}},[S,ua,da,bn,ne]),pa=B(c=>{if(c.length>1){if(c.includes("\x1B"))return;let l=Pd(c);if(Td(l)){let i=Dd(++hu.current,l);Yi.current.set(i,l),I(i)}else I(l);return}I(c)},[I]),zt=Math.max(10,je-6),ha=Ni(()=>fr(k.text,zt),[k.text,zt]),Wr=B(c=>y(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+c))})),[]),po=B(c=>y(l=>({...l,pos:Ed(fr(l.text,zt),l.pos,c)})),[zt]),$n=B(c=>y(l=>({...l,pos:Nd(fr(l.text,zt),l.pos,c)})),[zt]),wu=["\x1B[H","\x1B[1~","\x1BOH"],yu=["\x1B[F","\x1B[4~","\x1BOF"],fa=B((c,l)=>l.leftArrow?(Wr(-1),!0):l.rightArrow?(Wr(1),!0):c&&wu.includes(c)?($n("start"),!0):c&&yu.includes(c)?($n("end"),!0):l.ctrl&&c==="a"?($n("start"),!0):l.ctrl&&c==="e"?($n("end"),!0):!1,[Wr,$n]);return Xg((c,l)=>{if(l.ctrl&&c==="c"){Ae.current?.close(),r();return}if(!L){if(E){if(l.escape){if(ye.current){if(!ye.current.signal.aborted){let i=(Jn?.verb??"work").toLowerCase(),f=Jn?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${f}s)\u2026`}),ye.current.abort()}return}pn.current||(pn.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Ae.current?.interrupt());return}if(l.return){let i=S.trim();if(!i)return;bt.current.push(i),Rr([...bt.current]),v("");return}if(fa(c,l))return;if(l.upArrow){po(-1);return}if(l.downArrow){po(1);return}if(l.backspace||l.delete){R();return}c&&!l.ctrl&&!l.meta&&pa(c);return}if(ft){if(l.upArrow){mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){mt(i=>i&&{...i,cursor:Math.min(Fe.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Fe.length){mt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Fe[ft.cursor];mt(null);let{lines:f,changed:d,effective:w}=Nn(e,i.value??"default");for(let $ of f)u({kind:"note",tone:$.startsWith("\u26A0")?"warn":$.startsWith("\u2713")?"ok":"info",text:$});d&&(ta($=>$+1),Ae.current?.setModel(w));return}if(c==="s"){let i=Fe[ft.cursor];mt(null),Ae.current?.setModel(i.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(l.escape){mt(null);return}return}if(Be){if(l.upArrow){Lt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Lt(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){Lt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return||c==="s"){let i=Be.rows[Be.cursor];Lt(null),Lr(i.name,l.return===!0);return}if(l.escape){Lt(null);return}return}if(eo){if(l.escape){mn(null);return}if(l.leftArrow||l.tab&&l.shift){mn(i=>i&&{tab:(i.tab-1+Ne.length)%Ne.length});return}if(l.rightArrow||l.tab){mn(i=>i&&{tab:(i.tab+1)%Ne.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ne.length){mn({tab:Number(c)-1});return}return}if(Ve){if(l.upArrow){Mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Mt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ve.rows.length){Mt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ve.rows[Ve.cursor].name;if(Mt(null),!Kr(e,i).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let d=!1;try{let w=Dt(i);d=!!w&&!(ct(w)&&!w.refreshToken)}catch{d=!1}u({kind:"note",tone:"info",text:d?`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.`}),X("/login"),z(w=>w+1);return}if(l.escape){Mt(null);return}return}if(me){if(l.upArrow){Ut(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ut(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=me.rows.length){Ut(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=me.rows[me.cursor],{profile:f,projectId:d}=me;Ut(null),ao(f,d,i);return}if(l.escape){Ut(null);return}return}if(xe){if(l.upArrow){gt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){gt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=xe.rows.length){gt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=xe.rows[xe.cursor],{profile:f}=xe;gt(null),co(f,i);return}if(l.escape){gt(null);return}return}if(we){if(l.upArrow){Ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ft(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){Ft(i=>i&&{...i,rows:i.rows.map((f,d)=>d===i.cursor?{...f,checked:!f.checked}:f)});return}if(l.return){let i=we.rows.filter(f=>f.checked).map(f=>f.path);if(Ft(null),i.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}ps(e,i),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of i)u({kind:"note",tone:"info",text:` ${f}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){Ft(null);return}return}if(Ge){if(l.upArrow){yt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){yt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ge.rows.length){yt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ge.rows[Ge.cursor],f=Ge.run;yt(null),f(i.token);return}if(l.escape){yt(null);return}return}if(Qe){if(l.upArrow){Wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Wt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Qe.rows.length){Wt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Qe.rows[Qe.cursor];Wt(null),i.conflict?Ur(i.paths[0]):i.kind==="article"?Ir(i.paths[0]):Gt(i.paths);return}if(l.escape){Wt(null);return}return}if(Je){if(l.upArrow){wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){wt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Je.rows.length){wt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Je.rows[Je.cursor];wt(null),i.action==="capture"?_r(i.ids):i.kind==="shot"?la(i.ids[0]):aa(i.ids,{setup:!0});return}if(l.escape){wt(null);return}return}if(ve){if(l.escape){kt(null);return}if(l.upArrow){kt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){kt(i=>i&&{...i,cursor:Math.min(Math.max(0,so.length-1),i.cursor+1)});return}if(l.return){let i=so[ve.cursor];if(i){kt(null);try{u({kind:"preview",name:qn(i),text:eu(gr(Ii(e,i),"utf8"))})}catch(f){u({kind:"note",tone:"error",text:`Could not read ${i}: ${f.message}`})}}return}if(l.backspace||l.delete){kt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){kt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(Ce){if(l.escape){$t(null);return}if(l.upArrow){$t(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){$t(i=>i&&{...i,cursor:Math.min(Math.max(0,io.length-1),i.cursor+1)});return}if(l.return){let i=io[Ce.cursor];if(i){$t(null),Se(i.uuid),qe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},ht(i.name),_i(i.uuid),It.current=[];let f=Ai(e,i.uuid);for(let d of f)u(d);u({kind:"note",tone:"ok",text:f.length?`Resumed "${i.name}" \u2014 restored ${f.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(l.backspace||l.delete){$t(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){$t(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(l.tab&&!S&&fe){v(fe),Ue();return}if(!S&&He.length>0&&!$r&&c&&/^[1-9]$/.test(c)){let i=He[Number(c)-1];if(i){v(Tt(i));return}}if(!S&&(oo||gn)&&c==="c"&&!l.ctrl&&!l.meta&&!l.return&&!l.tab){let i=oo!=null;Ti(oo??gn).then(d=>{u({kind:"note",tone:d?"ok":"warn",text:d?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."}),d&&i&&jr(null),d&&!i&&oa(!0)});return}if(!fa(c,l)){if(sa){if(l.upArrow){Et(i=>Math.max(0,i-1));return}if(l.downArrow){Et(i=>Math.min(kn.length-1,i+1));return}if(l.tab){v("/"+(kn[dn]?.name??"")+" "),Et(0);return}if(l.return){let i=kn[dn];if(i){let f=S.trim().slice(1).split(/\s+/).slice(1).join(" ");if(il(i.usage)&&!f){v("/"+i.name+" "),Et(0);return}uo("/"+i.name+(f?" "+f:""));return}}}else{if(l.upArrow){if(S!==""&&Nt===null){po(-1);return}let i=vr.current;if(!i.length)return;let f=Nt===null?i.length-1:Math.max(0,Nt-1);Kn(f),v(i[f]??"");return}if(l.downArrow){if(S!==""&&Nt===null){po(1);return}let i=vr.current;if(Nt===null)return;let f=Nt+1;f>=i.length?(Kn(null),v("")):(Kn(f),v(i[f]??""));return}}if(l.return){uo();return}if(l.backspace||l.delete){R();return}if(l.escape){v(""),Et(0),Ue(),ut([]),un(null),Vn.current=!0;return}c&&!l.ctrl&&!l.meta&&pa(c)}}}),De(()=>{if(E||L)return;let c=bt.current.shift();c!==void 0&&(Rr([...bt.current]),uo(c))},[E,L,uo]),V(re,{flexDirection:"column",width:je,children:[Nr!==null&&V(re,{marginTop:1,flexDirection:"column",children:[Nr.truncated&&A(D,{dimColor:!0,children:"\u2026"}),A(D,{children:Nr.text})]}),E&&(Jn?A(Yw,{p:Jn}):A(Bw,{startTime:pt.current,chars:pu})),!E&&Qi?A(Vw,{text:Qi}):null,A(re,{borderStyle:"round",borderColor:ra.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:S?ha.map((c,l)=>{let i=k.text.slice(c.start,c.end),f=l===mr(ha,k.pos),d=Math.min(k.pos,c.end)-c.start;return V(D,{children:[A(D,{color:q,children:l===0?"> ":" "}),f?V(Bn,{children:[i.slice(0,d),A(an,{ch:i[d]??" "}),i.slice(d+1)]}):i||" "]},`${l}-${c.start}`)}):V(D,{children:[A(D,{color:q,children:"> "}),Sr?A(an,{ch:" "}):fe&&!E&&$e?V(Bn,{children:[A(an,{ch:$e[0],dim:!0}),A(D,{color:"gray",children:$e.slice(1)})]}):fe&&!E?V(Bn,{children:[A(an,{ch:fe[0],dim:!0}),A(D,{color:"gray",children:fe.slice(1)}),A(D,{dimColor:!0,children:" (tab)"})]}):(Er.isSetup||!du)&&!E?V(Bn,{children:[A(an,{ch:Er.text[0],dim:!0}),A(D,{color:"gray",children:Er.text.slice(1)})]}):A(an,{ch:" "})]})}),Xi.length>0&&A(re,{flexDirection:"column",paddingX:1,children:Xi.map((c,l)=>A(D,{color:"gray",children:`\u29D7 queued: ${c}`},`${l}-${c.slice(0,24)}`))}),eo?A(bd,{tab:eo.tab,width:je,version:o,engineVersion:tu}):ft?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Select model"}),A(D,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Fe.map((c,l)=>V(D,{color:l===ft.cursor?q:void 0,children:[l===ft.cursor?"\u276F ":" ",`${l+1}. ${c.label}${l===ft.current?" \u2714":""}`.padEnd(16),A(D,{color:"gray",children:c.desc})]},c.label)),A(D,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Be?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Switch connection profile"}),Be.rows.map((c,l)=>V(D,{color:l===Be.cursor?q:void 0,children:[l===Be.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Be.current?" \u2714":""}`.padEnd(20),A(D,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?A(D,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),A(D,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ve?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Pick your Document360 environment"}),Ve.rows.map((c,l)=>V(D,{color:l===Ve.cursor?q:void 0,children:[l===Ve.cursor?"\u276F ":" ",`${l+1}. ${c.name}`.padEnd(16),A(D,{color:"gray",children:c.apiUrl})]},c.name)),A(D,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):me?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Switch workspace"}),A(D,{dimColor:!0,children:`environment ${me.environment} \xB7 project ${me.projectName??`${me.projectId.slice(0,8)}\u2026`}`}),me.rows.map((c,l)=>V(D,{color:l===me.cursor?q:void 0,children:[l===me.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===me.current?" \u2714":""}`.padEnd(30),A(D,{color:"gray",children:c.type??""})]},c.id)),A(D,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):xe?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Choose project"}),A(D,{dimColor:!0,children:`environment ${xe.environment}`}),xe.rows.map((c,l)=>V(D,{color:l===xe.cursor?q:void 0,children:[l===xe.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===xe.current?" \u2714":""}`.padEnd(30),A(D,{color:"gray",children:c.sub??""})]},c.id)),A(D,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):we?(()=>{let l=Math.min(Math.max(0,we.cursor-Math.floor(7)),Math.max(0,we.rows.length-14)),i=we.rows.slice(l,l+14),f=we.rows.filter(d=>d.checked).length;return V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:`Which folders back the user docs? (${f} selected of ${we.rows.length})`}),l>0?A(D,{dimColor:!0,children:` \u2191 ${l} more`}):null,i.map((d,w)=>{let $=l+w;return V(D,{color:$===we.cursor?q:void 0,children:[$===we.cursor?"\u276F ":" ",d.checked?"\u25C9 ":"\u25CB ",d.path.padEnd(Math.min(48,je-34)),A(D,{color:"gray",children:Mo(d)})]},d.path)}),l+14<we.rows.length?A(D,{dimColor:!0,children:` \u2193 ${we.rows.length-l-14} more`}):null,A(D,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Ge?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Which category? (pick one to scope to)"}),Ge.rows.map((c,l)=>{let i=l===Ge.cursor,f=`${l+1}.`.padEnd(3);return V(D,{color:i?q:void 0,children:[i?"\u276F ":" ",`${f} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,je-24))),A(D,{color:"gray",children:` ${c.token}`})]},c.token)}),A(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Qe?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Qe.rows.map((c,l)=>{let i=l===Qe.cursor,f=c.indent?" ":" ",d=`${l+1}.`.padEnd(3);return V(D,{color:i?q:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${f}${d} ${c.label}`.padEnd(Math.min(56,je-24)),c.note?A(D,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),A(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):Je?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:Je.title}),(()=>{let{rows:l,cursor:i}=Je,f=Math.max(0,Math.min(i-Math.floor(12/2),l.length-12)),d=l.slice(f,f+12);return V(Bn,{children:[f>0?A(D,{color:"gray",children:` \u2026 ${f} more above`}):null,d.map((w,$)=>{let h=f+$,x=h===i,b=w.indent?" ":" ",U=h<9?`${h+1}.`.padEnd(3):" ";return V(D,{color:x?q:void 0,bold:w.kind!=="shot"&&!x,children:[x?"\u276F ":" ",`${b}${U} ${w.label}`.padEnd(Math.min(56,je-24)),w.note?A(D,{color:"gray",children:w.note}):null]},`${w.kind}:${w.ids.join(",")}`)}),f+12<l.length?A(D,{color:"gray",children:` \u2026 ${l.length-f-12} more below`}):null]})})(),A(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):ve?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:`Preview article${ve.query?` \u2014 filter: ${ve.query}`:" (type to filter)"}`}),so.length===0?A(D,{color:"gray",children:"no articles match"}):so.map((c,l)=>V(D,{color:l===ve.cursor?q:void 0,children:[l===ve.cursor?"\u276F ":" ",c]},c)),A(D,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ce?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:`Resume session${Ce.query?` \u2014 filter: ${Ce.query}`:" (type to filter)"}`}),io.length===0?A(D,{color:"gray",children:"no sessions match"}):io.map((c,l)=>V(D,{color:l===Ce.cursor?q:void 0,children:[l===Ce.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),A(D,{color:l===Ce.cursor?q:"gray",children:c.firstPrompt.slice(0,Math.max(10,je-40))})]},c.uuid)),A(D,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):sa?V(re,{flexDirection:"column",children:[kn.map((c,l)=>V(D,{color:l===dn?q:void 0,children:[l===dn?"\u276F ":" ",c.usage.padEnd(22)," ",A(D,{color:l===dn?q:"gray",children:c.name==="model"&&Pr?`${c.desc} (currently ${Pr})`:c.desc})]},c.name)),A(D,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!E&&!S&&He.length>0?V(re,{flexDirection:"column",paddingX:1,children:[Ki?A(D,{color:q,children:Ki}):null,He.map((c,l)=>{let i=Tt(c),f=i.slice(0,Math.max(20,je-5)),d=je-f.length-7,w=d>=12?(Rd(c)??rl(i)).slice(0,d):"";return V(D,{children:[A(D,{color:q,children:l+1})," ",f,w?A(D,{dimColor:!0,children:` \u2014 ${w}`}):null]},i)}),A(D,{dimColor:!0,children:`press 1-${He.length} to fill \xB7 esc cancel`})]}):A(re,{paddingX:1,children:V(D,{color:"gray",children:[ra.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Pr??"model n/a"}${t.kind==="api"?ea>0?` \xB7 ${be(ea)}`:"":Zi>0?` \xB7 ${it(Zi)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Qw}from"react/jsx-runtime";async function ru(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Xw(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Kw(Qw(ou,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
419
- `),process.exit(0)}W();import{writeCrashLog as su,isBenignTransportError as Jw}from"document360-engine";var iu=!1;function Hi(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function au(e){if(iu)return;iu=!0;let t=(n,o)=>{if(Jw(o)){su({kind:n,level:"transport",message:Hi(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=su({kind:n,level:"fatal",message:Hi(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
415
+ `)}),Bt(vt()),wn.current=Ie(e).status==="current",Vt.current=ze(e);return}case"discover":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ne(us(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Zs(e)===0){u({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await ne(ei(),{display:"/inbox",quietUser:!0});return}case"feedback":{let d=zd(e),w="";try{w=sn(d)?gr(d,"utf8"):""}catch{w=""}if(!/^## /m.test(w)){u({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let $=await Ti(w.trim());u({kind:"note",tone:$?"ok":"warn",text:$?"\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 ${d} and copy it manually.`}),$&&jr(null);return}case"document":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:d,what:w}=Us(f);if(!w&&Ms(e)===0){u({kind:"note",tone:"info",text:Fs});return}let $=`/document${w?` ${w}`:""}${d?" --publish":""}`;await ne(Ws(w,d),{display:$,quietUser:!0});return}case"catch-up":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!no(c.trim()))return;let{publish:d}=ni(f);u({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let w=await ri({cwd:e,profileName:s});for(let h of si(w))u({kind:"note",tone:h.startsWith("\u2713")?"ok":h.startsWith("\u2139")?"info":"warn",text:h});let $=Ln(On(e));u({kind:"note",tone:"info",text:$?`Catching up on ${$}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ne(oi({publish:d}),{display:`/catch-up${d?" --publish":""}`,quietUser:!0});return}case"update":{Dr.current=!0,u({kind:"note",tone:"info",text:`Updating ${Pt}\u2026 (don\u2019t close this window)`}),zn(!0),(await Xo().finally(()=>zn(!1))).ok?(u({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),X("/exit"),Gi("")):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Ko}`});return}case"screenshot":{let d=Ys(f);if(d.mode==="list"){if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=St(e,d.scope);if(d.picker){if(h.length===0){u({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let b=xc(h);if(b.length===0){u({kind:"note",tone:"info",text:Vo(h,d.scope).join(`
416
+ `)}),ke(`\u2713 All ${h.length} screenshots are captured. /publish puts them in the articles; /capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}wt({cursor:0,rows:b,title:"Screenshots \u2014 pick what to author or capture:"});return}u({kind:"note",tone:"info",text:Vo(h,d.scope).join(`
417
+ `)});let x=h.filter(b=>b.state==="placeholder").length;if(x>0){let b=d.scope?`/screenshot ${d.scope}`:"/screenshot --all";ke(`${x} of ${h.length} still need${x===1?"s":""} a spec \u2014 /screenshot <id> authors one, ${b} authors them all in parallel.`,{kind:"cmd",cmd:b,reason:""})}return}if(d.mode==="single"){await la(d.id);return}if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=d.mode==="scope"?d.scope:void 0,$=Tw(e,{scope:w}).map(h=>h.id);if($.length===0){u({kind:"note",tone:"info",text:w?`No screenshot placeholders under ${w}.`:"No screenshot placeholders found in the docs."});return}await aa($,{setup:d.setup});return}case"capture":{let d=zs(f);if(!Yo(e)){u({kind:"note",tone:"warn",text:"Screenshot capture is not set up in this repo yet \u2014 run d360-capture init in this repo's terminal, then d360-capture auth (once per machine)."});return}if(d.mode==="single"){await _r([d.id]);return}if(d.mode==="all"||d.mode==="scope"){let{ready:$,captured:h}=Ks(e,d.mode==="scope"?d.scope:void 0),x=[...$,...h];if(x.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),X("/screenshot");return}await _r(x);return}let w=Sc(St(e));if(w.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),X("/screenshot");return}wt({cursor:0,rows:w,title:"Capture screenshots \u2014 pick what to shoot:"});return}case"reset":{let d=li(e);if(d.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Qn.current={repoName:qn(e),targets:d,hadDevhints:sn(Yd(e))},u({kind:"note",tone:"warn",text:di(e,d).join(`
418
+ `)}),ge(qn(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Yt,Ur,u,Se,ne,Gt,Ir,ca]),uo=B(c=>{let l=(c??S).trim();if(v(""),Kn(null),Et(0),l.startsWith("/")&&(Vn.current=!1,Ue(),un(null),ut(f=>Td(f,l))),!l||(Vi(!1),ua(l))||da(l))return;vr.current.push(l);let i=Ed(l,Yi.current);if(l.startsWith("/"))u({kind:"user",text:l}),Xe(!0),bn(i).finally(()=>Xe(!1));else if(Mw(i)){u({kind:"user",text:l});let f=Uw(i);if(!f)ne(i,{display:l,quietUser:!0});else{try{Ww(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ne(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${f}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${f}" and the article path(s) you wrote.`,{display:l,quietUser:!0})}}else{let f=Qc(e,i);ne(f??i,{display:l})}},[S,ua,da,bn,ne]),pa=B(c=>{if(c.length>1){if(c.includes("\x1B"))return;let l=Dd(c);if(Ad(l)){let i=jd(++mu.current,l);Yi.current.set(i,l),I(i)}else I(l);return}I(c)},[I]),zt=Math.max(10,je-6),ha=Ni(()=>fr(k.text,zt),[k.text,zt]),Wr=B(c=>y(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+c))})),[]),po=B(c=>y(l=>({...l,pos:Id(fr(l.text,zt),l.pos,c)})),[zt]),$n=B(c=>y(l=>({...l,pos:_d(fr(l.text,zt),l.pos,c)})),[zt]),ku=["\x1B[H","\x1B[1~","\x1BOH"],bu=["\x1B[F","\x1B[4~","\x1BOF"],fa=B((c,l)=>l.leftArrow?(Wr(-1),!0):l.rightArrow?(Wr(1),!0):c&&ku.includes(c)?($n("start"),!0):c&&bu.includes(c)?($n("end"),!0):l.ctrl&&c==="a"?($n("start"),!0):l.ctrl&&c==="e"?($n("end"),!0):!1,[Wr,$n]);return Zg((c,l)=>{if(l.ctrl&&c==="c"){Ae.current?.close(),r();return}if(!L){if(N){if(l.escape){if(ye.current){if(!ye.current.signal.aborted){let i=(Jn?.verb??"work").toLowerCase(),f=Jn?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${f}s)\u2026`}),ye.current.abort()}return}pn.current||(pn.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Ae.current?.interrupt());return}if(l.return){let i=S.trim();if(!i)return;bt.current.push(i),Rr([...bt.current]),v("");return}if(fa(c,l))return;if(l.upArrow){po(-1);return}if(l.downArrow){po(1);return}if(l.backspace||l.delete){R();return}c&&!l.ctrl&&!l.meta&&pa(c);return}if(ft){if(l.upArrow){mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){mt(i=>i&&{...i,cursor:Math.min(Fe.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Fe.length){mt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Fe[ft.cursor];mt(null);let{lines:f,changed:d,effective:w}=Nn(e,i.value??"default");for(let $ of f)u({kind:"note",tone:$.startsWith("\u26A0")?"warn":$.startsWith("\u2713")?"ok":"info",text:$});d&&(ta($=>$+1),Ae.current?.setModel(w));return}if(c==="s"){let i=Fe[ft.cursor];mt(null),Ae.current?.setModel(i.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(l.escape){mt(null);return}return}if(Be){if(l.upArrow){Lt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Lt(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){Lt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return||c==="s"){let i=Be.rows[Be.cursor];Lt(null),Lr(i.name,l.return===!0);return}if(l.escape){Lt(null);return}return}if(eo){if(l.escape){mn(null);return}if(l.leftArrow||l.tab&&l.shift){mn(i=>i&&{tab:(i.tab-1+Ne.length)%Ne.length});return}if(l.rightArrow||l.tab){mn(i=>i&&{tab:(i.tab+1)%Ne.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ne.length){mn({tab:Number(c)-1});return}return}if(Ve){if(l.upArrow){Mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Mt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ve.rows.length){Mt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ve.rows[Ve.cursor].name;if(Mt(null),!Kr(e,i).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let d=!1;try{let w=Dt(i);d=!!w&&!(ct(w)&&!w.refreshToken)}catch{d=!1}u({kind:"note",tone:"info",text:d?`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.`}),X("/login"),z(w=>w+1);return}if(l.escape){Mt(null);return}return}if(me){if(l.upArrow){Ut(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ut(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=me.rows.length){Ut(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=me.rows[me.cursor],{profile:f,projectId:d}=me;Ut(null),ao(f,d,i);return}if(l.escape){Ut(null);return}return}if(ve){if(l.upArrow){gt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){gt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ve.rows.length){gt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=ve.rows[ve.cursor],{profile:f}=ve;gt(null),co(f,i);return}if(l.escape){gt(null);return}return}if(we){if(l.upArrow){Ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ft(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){Ft(i=>i&&{...i,rows:i.rows.map((f,d)=>d===i.cursor?{...f,checked:!f.checked}:f)});return}if(l.return){let i=we.rows.filter(f=>f.checked).map(f=>f.path);if(Ft(null),i.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}ps(e,i),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of i)u({kind:"note",tone:"info",text:` ${f}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){Ft(null);return}return}if(Ge){if(l.upArrow){yt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){yt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ge.rows.length){yt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ge.rows[Ge.cursor],f=Ge.run;yt(null),f(i.token);return}if(l.escape){yt(null);return}return}if(Qe){if(l.upArrow){Wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Wt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Qe.rows.length){Wt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Qe.rows[Qe.cursor];Wt(null),i.conflict?Ur(i.paths[0]):i.kind==="article"?Ir(i.paths[0]):Gt(i.paths);return}if(l.escape){Wt(null);return}return}if(Je){if(l.upArrow){wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){wt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Je.rows.length){wt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Je.rows[Je.cursor];wt(null),i.action==="capture"?_r(i.ids):i.kind==="shot"?la(i.ids[0]):aa(i.ids,{setup:!0});return}if(l.escape){wt(null);return}return}if(Ce){if(l.escape){kt(null);return}if(l.upArrow){kt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){kt(i=>i&&{...i,cursor:Math.min(Math.max(0,so.length-1),i.cursor+1)});return}if(l.return){let i=so[Ce.cursor];if(i){kt(null);try{u({kind:"preview",name:qn(i),text:nu(gr(Ii(e,i),"utf8"))})}catch(f){u({kind:"note",tone:"error",text:`Could not read ${i}: ${f.message}`})}}return}if(l.backspace||l.delete){kt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){kt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(Re){if(l.escape){$t(null);return}if(l.upArrow){$t(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){$t(i=>i&&{...i,cursor:Math.min(Math.max(0,io.length-1),i.cursor+1)});return}if(l.return){let i=io[Re.cursor];if(i){$t(null),Se(i.uuid),qe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},ht(i.name),_i(i.uuid),It.current=[];let f=Ai(e,i.uuid);for(let d of f)u(d);u({kind:"note",tone:"ok",text:f.length?`Resumed "${i.name}" \u2014 restored ${f.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(l.backspace||l.delete){$t(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){$t(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(l.tab&&!S&&fe){v(fe),Ue();return}if(!S&&He.length>0&&!$r&&c&&/^[1-9]$/.test(c)){let i=He[Number(c)-1];if(i){v(Tt(i));return}}if(!S&&(oo||gn)&&c==="c"&&!l.ctrl&&!l.meta&&!l.return&&!l.tab){let i=oo!=null;Ti(oo??gn).then(d=>{u({kind:"note",tone:d?"ok":"warn",text:d?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."}),d&&i&&jr(null),d&&!i&&oa(!0)});return}if(!fa(c,l)){if(sa){if(l.upArrow){Et(i=>Math.max(0,i-1));return}if(l.downArrow){Et(i=>Math.min(kn.length-1,i+1));return}if(l.tab){v("/"+(kn[dn]?.name??"")+" "),Et(0);return}if(l.return){let i=kn[dn];if(i){let f=S.trim().slice(1).split(/\s+/).slice(1).join(" ");if(il(i.usage)&&!f){v("/"+i.name+" "),Et(0);return}uo("/"+i.name+(f?" "+f:""));return}}}else{if(l.upArrow){if(S!==""&&Nt===null){po(-1);return}let i=vr.current;if(!i.length)return;let f=Nt===null?i.length-1:Math.max(0,Nt-1);Kn(f),v(i[f]??"");return}if(l.downArrow){if(S!==""&&Nt===null){po(1);return}let i=vr.current;if(Nt===null)return;let f=Nt+1;f>=i.length?(Kn(null),v("")):(Kn(f),v(i[f]??""));return}}if(l.return){uo();return}if(l.backspace||l.delete){R();return}if(l.escape){v(""),Et(0),Ue(),ut([]),un(null),Vn.current=!0;return}c&&!l.ctrl&&!l.meta&&pa(c)}}}),De(()=>{if(N||L)return;let c=bt.current.shift();c!==void 0&&(Rr([...bt.current]),uo(c))},[N,L,uo]),V(re,{flexDirection:"column",width:je,children:[Nr!==null&&V(re,{marginTop:1,flexDirection:"column",children:[Nr.truncated&&A(D,{dimColor:!0,children:"\u2026"}),A(D,{children:Nr.text})]}),N&&(Jn?A(Xw,{p:Jn}):A(Yw,{startTime:pt.current,chars:fu})),!N&&Qi?A(zw,{text:Qi}):null,A(re,{borderStyle:"round",borderColor:ra.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:S?ha.map((c,l)=>{let i=k.text.slice(c.start,c.end),f=l===mr(ha,k.pos),d=Math.min(k.pos,c.end)-c.start;return V(D,{children:[A(D,{color:q,children:l===0?"> ":" "}),f?V(Bn,{children:[i.slice(0,d),A(an,{ch:i[d]??" "}),i.slice(d+1)]}):i||" "]},`${l}-${c.start}`)}):V(D,{children:[A(D,{color:q,children:"> "}),Sr?A(an,{ch:" "}):fe&&!N&&xe?V(Bn,{children:[A(an,{ch:xe[0],dim:!0}),A(D,{color:"gray",children:xe.slice(1)})]}):fe&&!N?V(Bn,{children:[A(an,{ch:fe[0],dim:!0}),A(D,{color:"gray",children:fe.slice(1)}),A(D,{dimColor:!0,children:" (tab)"})]}):(Er.isSetup||!pu)&&!N?V(Bn,{children:[A(an,{ch:Er.text[0],dim:!0}),A(D,{color:"gray",children:Er.text.slice(1)})]}):A(an,{ch:" "})]})}),Xi.length>0&&A(re,{flexDirection:"column",paddingX:1,children:Xi.map((c,l)=>A(D,{color:"gray",children:`\u29D7 queued: ${c}`},`${l}-${c.slice(0,24)}`))}),eo?A(xd,{tab:eo.tab,width:je,version:o,engineVersion:ou}):ft?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Select model"}),A(D,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Fe.map((c,l)=>V(D,{color:l===ft.cursor?q:void 0,children:[l===ft.cursor?"\u276F ":" ",`${l+1}. ${c.label}${l===ft.current?" \u2714":""}`.padEnd(16),A(D,{color:"gray",children:c.desc})]},c.label)),A(D,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Be?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Switch connection profile"}),Be.rows.map((c,l)=>V(D,{color:l===Be.cursor?q:void 0,children:[l===Be.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Be.current?" \u2714":""}`.padEnd(20),A(D,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?A(D,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),A(D,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ve?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Pick your Document360 environment"}),Ve.rows.map((c,l)=>V(D,{color:l===Ve.cursor?q:void 0,children:[l===Ve.cursor?"\u276F ":" ",`${l+1}. ${c.name}`.padEnd(16),A(D,{color:"gray",children:c.apiUrl})]},c.name)),A(D,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):me?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Switch workspace"}),A(D,{dimColor:!0,children:`environment ${me.environment} \xB7 project ${me.projectName??`${me.projectId.slice(0,8)}\u2026`}`}),me.rows.map((c,l)=>V(D,{color:l===me.cursor?q:void 0,children:[l===me.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===me.current?" \u2714":""}`.padEnd(30),A(D,{color:"gray",children:c.type??""})]},c.id)),A(D,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ve?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Choose project"}),A(D,{dimColor:!0,children:`environment ${ve.environment}`}),ve.rows.map((c,l)=>V(D,{color:l===ve.cursor?q:void 0,children:[l===ve.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===ve.current?" \u2714":""}`.padEnd(30),A(D,{color:"gray",children:c.sub??""})]},c.id)),A(D,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):we?(()=>{let l=Math.min(Math.max(0,we.cursor-Math.floor(7)),Math.max(0,we.rows.length-14)),i=we.rows.slice(l,l+14),f=we.rows.filter(d=>d.checked).length;return V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:`Which folders back the user docs? (${f} selected of ${we.rows.length})`}),l>0?A(D,{dimColor:!0,children:` \u2191 ${l} more`}):null,i.map((d,w)=>{let $=l+w;return V(D,{color:$===we.cursor?q:void 0,children:[$===we.cursor?"\u276F ":" ",d.checked?"\u25C9 ":"\u25CB ",d.path.padEnd(Math.min(48,je-34)),A(D,{color:"gray",children:Mo(d)})]},d.path)}),l+14<we.rows.length?A(D,{dimColor:!0,children:` \u2193 ${we.rows.length-l-14} more`}):null,A(D,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Ge?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Which category? (pick one to scope to)"}),Ge.rows.map((c,l)=>{let i=l===Ge.cursor,f=`${l+1}.`.padEnd(3);return V(D,{color:i?q:void 0,children:[i?"\u276F ":" ",`${f} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,je-24))),A(D,{color:"gray",children:` ${c.token}`})]},c.token)}),A(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Qe?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Qe.rows.map((c,l)=>{let i=l===Qe.cursor,f=c.indent?" ":" ",d=`${l+1}.`.padEnd(3);return V(D,{color:i?q:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${f}${d} ${c.label}`.padEnd(Math.min(56,je-24)),c.note?A(D,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),A(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):Je?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:Je.title}),(()=>{let{rows:l,cursor:i}=Je,f=Math.max(0,Math.min(i-Math.floor(12/2),l.length-12)),d=l.slice(f,f+12);return V(Bn,{children:[f>0?A(D,{color:"gray",children:` \u2026 ${f} more above`}):null,d.map((w,$)=>{let h=f+$,x=h===i,b=w.indent?" ":" ",U=h<9?`${h+1}.`.padEnd(3):" ";return V(D,{color:x?q:void 0,bold:w.kind!=="shot"&&!x,children:[x?"\u276F ":" ",`${b}${U} ${w.label}`.padEnd(Math.min(56,je-24)),w.note?A(D,{color:"gray",children:w.note}):null]},`${w.kind}:${w.ids.join(",")}`)}),f+12<l.length?A(D,{color:"gray",children:` \u2026 ${l.length-f-12} more below`}):null]})})(),A(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):Ce?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:`Preview article${Ce.query?` \u2014 filter: ${Ce.query}`:" (type to filter)"}`}),so.length===0?A(D,{color:"gray",children:"no articles match"}):so.map((c,l)=>V(D,{color:l===Ce.cursor?q:void 0,children:[l===Ce.cursor?"\u276F ":" ",c]},c)),A(D,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Re?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:`Resume session${Re.query?` \u2014 filter: ${Re.query}`:" (type to filter)"}`}),io.length===0?A(D,{color:"gray",children:"no sessions match"}):io.map((c,l)=>V(D,{color:l===Re.cursor?q:void 0,children:[l===Re.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),A(D,{color:l===Re.cursor?q:"gray",children:c.firstPrompt.slice(0,Math.max(10,je-40))})]},c.uuid)),A(D,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):sa?V(re,{flexDirection:"column",children:[kn.map((c,l)=>V(D,{color:l===dn?q:void 0,children:[l===dn?"\u276F ":" ",c.usage.padEnd(22)," ",A(D,{color:l===dn?q:"gray",children:c.name==="model"&&Pr?`${c.desc} (currently ${Pr})`:c.desc})]},c.name)),A(D,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!S&&He.length>0?V(re,{flexDirection:"column",paddingX:1,children:[Ki?A(D,{color:q,children:Ki}):null,He.map((c,l)=>{let i=Tt(c),f=i.slice(0,Math.max(20,je-5)),d=je-f.length-7,w=d>=12?(Pd(c)??rl(i)).slice(0,d):"";return V(D,{children:[A(D,{color:q,children:l+1})," ",f,w?A(D,{dimColor:!0,children:` \u2014 ${w}`}):null]},i)}),A(D,{dimColor:!0,children:`press 1-${He.length} to fill \xB7 esc cancel`})]}):A(re,{paddingX:1,children:V(D,{color:"gray",children:[ra.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Pr??"model n/a"}${t.kind==="api"?ea>0?` \xB7 ${$e(ea)}`:"":Zi>0?` \xB7 ${it(Zi)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as ey}from"react/jsx-runtime";async function iu(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Zw(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Jw(ey(su,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
419
+ `),process.exit(0)}W();import{writeCrashLog as au,isBenignTransportError as ty}from"document360-engine";var lu=!1;function Hi(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function cu(e){if(lu)return;lu=!0;let t=(n,o)=>{if(ty(o)){au({kind:n,level:"transport",message:Hi(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=au({kind:n,level:"fatal",message:Hi(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
420
420
  `+C(`\u2717 d360-writer crashed: ${Hi(o)}`)+`
421
421
  `),r&&process.stderr.write(m(` Crash details: ${r}`)+`
422
422
  `+m(" Run: d360-writer logs")+`
423
- `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var ny=ey(import.meta.url),kr=ny("../package.json");au("d360-writer");var Le=new Zw;function qi(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Le.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{qi(e),await $o({profile:e.profile,manual:e.manual})});Le.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{qi(e),await Sa({profile:e.profile})});Le.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{qi(e),await Ra({profile:e.profile})});var Bi=Le.command("profile").description("Manage connection profiles for the current repo");Bi.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>xo(process.cwd()));Bi.command("use <name>").description("Set the default profile for this repo").action(e=>vo(process.cwd(),e));Bi.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Co(process.cwd(),e));var lu=Le.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");lu.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Kt(process.cwd(),e.profile));lu.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await ya(process.cwd(),e,t.profile)});var cu=Le.command("project").description("Choose the Document360 project for this repo (active profile's identity)");cu.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>yo(process.cwd(),e.profile));cu.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await ba(process.cwd(),e,t.profile)});Le.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Ao(),tl));await e()});Le.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>Aa());Le.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(Bo(),cc)),n=await t(process.cwd(),kr.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Le.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(kr.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(ty.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 ja(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 pd(e.cwd,e.auth,e.profile,kr.version):await ru(e.cwd,e.auth,e.profile,kr.version)});Le.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
423
+ `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var sy=oy(import.meta.url),kr=sy("../package.json");cu("d360-writer");var Le=new ny;function qi(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Le.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{qi(e),await $o({profile:e.profile,manual:e.manual})});Le.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{qi(e),await Sa({profile:e.profile})});Le.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{qi(e),await Ra({profile:e.profile})});var Bi=Le.command("profile").description("Manage connection profiles for the current repo");Bi.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>xo(process.cwd()));Bi.command("use <name>").description("Set the default profile for this repo").action(e=>vo(process.cwd(),e));Bi.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Co(process.cwd(),e));var du=Le.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");du.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Kt(process.cwd(),e.profile));du.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await ya(process.cwd(),e,t.profile)});var uu=Le.command("project").description("Choose the Document360 project for this repo (active profile's identity)");uu.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>yo(process.cwd(),e.profile));uu.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await ba(process.cwd(),e,t.profile)});Le.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Ao(),tl));await e()});Le.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>Aa());Le.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(Bo(),cc)),n=await t(process.cwd(),kr.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Le.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(kr.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(ry.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 ja(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 fd(e.cwd,e.auth,e.profile,kr.version):await iu(e.cwd,e.auth,e.profile,kr.version)});Le.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});