document360-writer 0.5.153 → 0.5.155

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 +116 -116
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var Rp=Object.defineProperty;var Tn=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var rl=(e,t)=>{for(var n in t)Rp(e,n,{get:t[n],enumerable:!0})};import lt from"picocolors";var K,Sp,Pp,Tp,sl,Dn,g,S,B,_,F,ue,Re,Y=Tn(()=>{"use strict";K="#7f56d9",[Sp,Pp,Tp]=[127,86,217],sl=e=>lt.isColorSupported?`\x1B[38;2;${Sp};${Pp};${Tp}m${e}\x1B[39m`:e,Dn=e=>lt.bold(sl(e)),g=e=>lt.dim(e),S=e=>lt.red(e),B=e=>lt.yellow(e),_=e=>lt.green(e),F=sl,ue=e=>lt.gray(e),Re=e=>lt.bold(e)});import{existsSync as en,writeFileSync as ut,readFileSync as hh,readdirSync as fh}from"node:fs";import{join as vl}from"node:path";import{devHintsGuidePath as Wo,hintsDir as Cl,hooksDir as Rl,architectureDir as Al,messagesDir as bs,creatorNotesPath as Sl,devhintsStatePath as El,directivesPath as Pl,DIRECTIVES_HEADER as mh,roadmapPath as Tl,ROADMAP_HEADER as gh,ensureDir as jn,writeMessage as yh,listOpenForDev as wh}from"document360-engine";function jl(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var Pp=Object.defineProperty;var An=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var il=(e,t)=>{for(var n in t)Pp(e,n,{get:t[n],enumerable:!0})};import lt from"picocolors";var K,Tp,Dp,Ap,al,En,g,S,B,_,F,ue,Re,Y=An(()=>{"use strict";K="#7f56d9",[Tp,Dp,Ap]=[127,86,217],al=e=>lt.isColorSupported?`\x1B[38;2;${Tp};${Dp};${Ap}m${e}\x1B[39m`:e,En=e=>lt.bold(al(e)),g=e=>lt.dim(e),S=e=>lt.red(e),B=e=>lt.yellow(e),_=e=>lt.green(e),F=al,ue=e=>lt.gray(e),Re=e=>lt.bold(e)});import{existsSync as tn,writeFileSync as ut,readFileSync as mh,readdirSync as gh}from"node:fs";import{join as Rl}from"node:path";import{devHintsGuidePath as Bo,hintsDir as Sl,hooksDir as Pl,architectureDir as jl,messagesDir as $s,creatorNotesPath as Tl,devhintsStatePath as Nl,directivesPath as Dl,DIRECTIVES_HEADER as yh,roadmapPath as Al,ROADMAP_HEADER as wh,ensureDir as In,writeMessage as kh,listOpenForDev as bh}from"document360-engine";function Il(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
3
3
 
4
4
  <!-- devhints script v${de} \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 bh(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
221
+ `}function xh(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
222
222
 
223
223
  <!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
224
224
  The builder agent reads this FIRST and treats it as authoritative when writing the architecture
@@ -232,12 +232,12 @@ Anything only a human knows that would help document this product. For example:
232
232
  - Gotchas or non-obvious behavior.
233
233
 
234
234
  (Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
235
- `}function nn(e){jn(Cl(e)),jn(Al(e)),jn(bs(e));for(let n of[Cl(e),bs(e)]){let o=vl(n,".gitkeep");en(o)||ut(o,`# Keeps this document360-writer inbox tracked in git even when empty.
236
- `)}en(Sl(e))||ut(Sl(e),bh()),en(Pl(e))||ut(Pl(e),mh),en(Tl(e))||ut(Tl(e),gh),ut(Wo(e),jl()),jn(Rl(e)),ut(vl(Rl(e),"open-questions.mjs"),kh);let t=Le(e);return Il(e,new Date().toISOString()),t}async function Nl(e,t){for(let n of on(nn(t.cwd)))console.log(n);return{kind:"continue"}}function jt(){return[`This is document360-writer's dev hand-off setup (v${de}).`,'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": ${de},`,' "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 $s(e){try{let t=hh(El(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Il(e,t){let o={...$s(e)??{},emittedVersion:de,emittedAt:t};ut(El(e),`${JSON.stringify(o,null,2)}
238
- `)}function nt(e){try{return fh(Al(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Le(e){let n=$s(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<de?"stale":"current",completedVersion:n}}function Bo(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:de};try{if(!en(Wo(e)))return n;let o=$s(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;de>r&&(jn(bs(e)),ut(Wo(e),jl()),Il(e,t),n.guideRefreshed=!0),de>s&&(wh(e).some(u=>u.kind==="request"&&u.subject.startsWith(Dl))||(yh(e,{id:`onb${de}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Dl}${de})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${de}${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:","",jt()].join(`
239
- `)}),n.notifiedBuilder=!0))}catch{}return n}function Ho(e){if(!en(Wo(e)))return[];let t=Le(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${de}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,tn,jt(),tn,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function xs(){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 qo(){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):",tn,xs(),tn]}function on(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${de}.`," 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):",tn,jt(),tn,"","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 tn,de,kh,Dl,dt=Tn(()=>{"use strict";tn="-".repeat(64),de=10,kh=`#!/usr/bin/env node
235
+ `}function on(e){In(Sl(e)),In(jl(e)),In($s(e));for(let n of[Sl(e),$s(e)]){let o=Rl(n,".gitkeep");tn(o)||ut(o,`# Keeps this document360-writer inbox tracked in git even when empty.
236
+ `)}tn(Tl(e))||ut(Tl(e),xh()),tn(Dl(e))||ut(Dl(e),yh),tn(Al(e))||ut(Al(e),wh),ut(Bo(e),Il()),In(Pl(e)),ut(Rl(Pl(e),"open-questions.mjs"),$h);let t=Le(e);return Ol(e,new Date().toISOString()),t}async function _l(e,t){for(let n of rn(on(t.cwd)))console.log(n);return{kind:"continue"}}function Nt(){return[`This is document360-writer's dev hand-off setup (v${de}).`,'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": ${de},`,' "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 xs(e){try{let t=mh(Nl(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Ol(e,t){let o={...xs(e)??{},emittedVersion:de,emittedAt:t};ut(Nl(e),`${JSON.stringify(o,null,2)}
238
+ `)}function nt(e){try{return gh(jl(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Le(e){let n=xs(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<de?"stale":"current",completedVersion:n}}function Ho(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:de};try{if(!tn(Bo(e)))return n;let o=xs(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;de>r&&(In($s(e)),ut(Bo(e),Il()),Ol(e,t),n.guideRefreshed=!0),de>s&&(bh(e).some(u=>u.kind==="request"&&u.subject.startsWith(El))||(kh(e,{id:`onb${de}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${El}${de})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${de}${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:","",Nt()].join(`
239
+ `)}),n.notifiedBuilder=!0))}catch{}return n}function qo(e){if(!tn(Bo(e)))return[];let t=Le(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${de}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,nn,Nt(),nn,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function vs(){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 Vo(){return['\u{1F9F9} One leftover: your builder still has the "Documentation hand-off" rule in its CLAUDE.md / AGENTS.md'," (reset only clears d360-writer's own .d360-writer/ folder \u2014 never your repo's files)."," To restore it, paste this prompt into your repo's coding agent (Claude Code / Codex / Cursor):",nn,vs(),nn]}function rn(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${de}.`," 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):",nn,Nt(),nn,"","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 nn,de,$h,El,dt=An(()=>{"use strict";nn="-".repeat(64),de=10,$h=`#!/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,61 +275,61 @@ try {
275
275
  } catch {
276
276
  /* a session-start nudge must never break the session */
277
277
  }
278
- `;Dl="Re-run dev\u2194docs onboarding (protocol v"});var ql={};rl(ql,{initCommand:()=>Cs,scaffoldInit:()=>vs});import{input as Nn,confirm as $h}from"@inquirer/prompts";import{basename as _l,join as Vo}from"node:path";import{existsSync as rn,readFileSync as xh,readdirSync as vh,writeFileSync as Ch}from"node:fs";import{writeProjectConfig as Ol,readProjectConfig as Rh,projectConfigPath as Ll,writerDir as Sh,DEFAULT_DOCS_DIR as Ml,DEFAULT_CAPTURE_DIR as Ul,DEFAULT_OUTPUT_DIR as Fl}from"document360-engine";function vs(e,t="berlin"){let n=Ll(e);if(rn(n))return{created:!1,path:n,profileName:""};let o={projectId:Bl(e)??_l(e),docsDir:Ml,captureDir:Ul,outputDir:Fl,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Hl(e)};return Ol(o,e),Wl(e),{created:!0,path:n,profileName:t}}function Wl(e){let t=Vo(Sh(e),".gitignore");rn(t)||Ch(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
279
- `),"utf8")}async function Cs(){let e=process.cwd(),t=Ll(e);if(rn(t)&&!await $h({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(g("init cancelled.")),{kind:"continue"};let n=Bl(e)??_l(e),o=await Nn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Nn({message:"Capture directory (where document360-capture .spec.ts files live):",default:Ul}),s=await Nn({message:"Screenshot output directory:",default:Fl}),a=await Nn({message:"Default connection profile name:",default:"berlin"}),u=await Nn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),h={projectId:o,docsDir:Ml,captureDir:r,outputDir:s,profiles:{[a]:{connection:{environment:u},production:!1}},defaultProfile:a,authoritativeSourceFiles:Hl(e)},k=Rh(e);k?.terminologyGlossary&&(h.terminologyGlossary=k.terminologyGlossary),Ol(h,e),Wl(e);let b=nn(e);console.log(""),console.log(_(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${F(`d360-writer login --profile ${a}`)} ${g("(sign in; project & workspace auto-selected)")}`),console.log("");for(let x of on(b))console.log(x);return console.log(""),console.log(`${g("Then ask:")} ${F('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Bl(e){let t=Vo(e,"package.json");if(!rn(t))return null;try{return JSON.parse(xh(t,"utf8")).name??null}catch{return null}}function Hl(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])rn(Vo(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Vo(e,n);rn(o)&&!Ph(o)&&t.push(n)}return t}function Ph(e){try{return vh(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Go=Tn(()=>{"use strict";Y();dt()});import{createRequire as Lm}from"node:module";import{existsSync as Mm,readFileSync as Um}from"node:fs";import{dirname as fu,join as mu}from"node:path";function gr(){let e;try{e=Fm.resolve("document360-capture/helpers")}catch{return null}let t=fu(e);for(let n=0;n<5&&!Mm(mu(t,"package.json"));n++)t=fu(t);try{let n=JSON.parse(Um(mu(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var Fm,Di=Tn(()=>{"use strict";Fm=Lm(import.meta.url)});var bu={};rl(bu,{doctorCommand:()=>Vn,renderDoctorChecks:()=>ku,runDoctorChecks:()=>wu});import{existsSync as Wm}from"node:fs";import{d360GetAll as Bm,getAccessToken as Hm,isExpired as Ai,loadProfileMap as qm,loadTokens as Vm,packageSkillsDir as gu,ENGINE_VERSION as Gm,projectConfigPath as Ym,readProjectConfig as zm,DEFAULT_DOCS_DIR as Km,fetchManifestSummary as Xm,resolveActiveProfile as Qm,classifyClaudeAuth as Jm,CLAUDE_CODE_SETUP_HINT as yu,resolveModelSetting as Zm,probeModel as eg,detectAppType as tg,playbookSkillName as ng,D360AuthError as og}from"document360-engine";async function wu(e,t){let n=[],o=gr();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Gm}${o?` \xB7 capture v${o}`:" \xB7 capture not installed"}`});let r=Number(process.versions.node.split(".")[0]);n.push(r>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let s=Jm();s.state==="ready"?n.push({level:"ok",label:`Claude auth: ${s.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):s.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${yu}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:yu});let a=Zm(e);if(n.push({level:"ok",label:`Model: ${a.model} (${a.source==="auto"?"auto \u2014 right-sized for docs; /model to change":a.source})`}),s.state==="ready"){let T=await eg(e,a.model??void 0);T.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(T.latencyMs/1e3).toFixed(1)}s`}):T.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 ${T.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 u=zm(e);if(!u)return n.push({level:"fail",label:`No ${Ym(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${u.projectId}`});let h=(u.docsDir??Km).replace(/\/+$/,"");n.push(u.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 ${h}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let k=u.authoritativeSourceFiles??[];n.push(k.length>0?{level:"ok",label:`Sources: docs grounded in ${k.length} path(s) (${k.slice(0,3).join(", ")}${k.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let b=u.appType??tg(e);if(b){let T=u.appType?"from config":"auto-detected",E=b==="web"||b==="cli";n.push({level:"ok",label:`Genre: ${b} (${T})${E?` \u2192 ${ng(b)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let x;try{x=Qm(e),n.push({level:"ok",label:`Profile: ${x.name} (${x.connection.name})${x.production?" \u26A0 PRODUCTION":""}`})}catch(T){return n.push({level:"fail",label:`Profile config: ${T.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let $=Vm(x.name);$?Ai($)&&!$.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Ai($)?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($.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${x.name})`}),n.push(x.project.workspaceId?{level:"ok",label:`Workspace: ${x.project.workspaceName??x.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let j=qm(e,x.name);j?j.projectId&&x.project.projectId&&j.projectId!==x.project.projectId?n.push({level:"fail",label:`Category map projectId (${j.projectId}) \u2260 profile projectId (${x.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(j.articles).length} articles, ${Object.keys(j.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${x.name}" (created on first /publish)`}),n.push(Wm(gu())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${gu()}`,fix:"Reinstall document360-writer (broken install)"});let v=Le(e);if(v.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${de})`}):v.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${v.completedVersion}, current is v${de}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),$&&(!Ai($)||$.refreshToken)){let T={profile:x.name,connection:x.connection};try{await Hm(T);let U=await Bm(T,"/v3/projects");n.push({level:"ok",label:`API reachable (${x.connection.apiUrl}) \u2014 ${U.length} project(s) visible`})}catch(U){n.push({level:"fail",label:`API call failed: ${U.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let E=j?.projectId??x.project.projectId;if(E&&x.project.workspaceId)try{let U=await Xm(T,E,x.project.workspaceId);if(U){let L=(U.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${x.connection.name} (${U.languages?.length??0} language${(U.languages?.length??0)===1?"":"s"}) \xB7 hash ${L||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${x.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(U){U instanceof og||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(U.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${x.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 (${U.message.slice(0,80)})`})}}return n}function ku(e){let t=[""];for(let r of e){let s=r.level==="ok"?_("\u2713"):r.level==="warn"?B("\u26A0"):S("\u2717");t.push(` ${s} ${r.label}${r.detail?g(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${g("fix:")} ${F(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?_(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):S(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Vn(e,t){console.log(g("Running checks\u2026"));for(let n of ku(await wu(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var yr=Tn(()=>{"use strict";dt();Y();Di()});import{Command as Pk}from"commander";import{createRequire as Tk}from"node:module";import{AUTH_MODES as Dk}from"document360-engine";import{input as Bp}from"@inquirer/prompts";import{loginPkce as Hp,refreshTokens as qp,toStoredTokens as dl,clearTokens as Vp,decodeJwtClaims as ul,isExpired as Gp,loadTokens as Yp,saveTokens as pl,resolveActiveProfile as _o,setProfileProject as zp,readProjectConfig as Kp}from"document360-engine";Y();import{select as Dp}from"@inquirer/prompts";import{resolveActiveProfile as Ap,setProfileProject as Ep,resolveProjectId as jp,listWorkspaces as Np}from"document360-engine";async function An(e,t){let n=Ap(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??jp(o);return{workspaces:await Np(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var il=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function ms(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 jo(e,t,n,o,r){Ep(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function al(e,t,n){let o;try{o=await An(e,n)}catch(s){return console.log(S(`Could not list workspaces: ${s.message}`)),1}let r=ms(o.workspaces,t);return r?(jo(e,o.profile,o.projectId,r.id,r.name),console.log(_(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(S(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Zt(e,t){let n;try{n=await An(e,t)}catch(k){console.log(S(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:a}=n;if(o.length===0){console.log(g("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===a?F("\u25CF"):" "} ${il(k)} ${g(k.id)}`);console.log(g("Run: d360-writer workspace use <name>"));return}let u=await Dp({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${il(k)}${k.id===a?" (current)":""}`,value:k.id}))}),h=o.find(k=>k.id===u);jo(e,s,r,u,h?.name),console.log(_(`\u2713 Workspace set to "${h?.name??u}" for profile "${s}".`))}Y();import{select as Ip}from"@inquirer/prompts";import{resolveActiveProfile as _p,setProfileProject as Op,listProjects as Lp}from"document360-engine";async function ct(e,t){let n=_p(e,t),o={profile:n.name,connection:n.connection};return{projects:await Lp(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ll=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function gs(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 No(e,t,n,o){Op(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function cl(e,t,n){let o;try{o=await ct(e,n)}catch(s){return console.log(S(`Could not list projects: ${s.message}`)),1}let r=gs(o.projects,t);return r?(No(e,o.profile,r.id,r.name),console.log(_(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(S(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Io(e,t){let n;try{n=await ct(e,t)}catch(h){console.log(S(`Could not list projects: ${h.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(g("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===s?F("\u25CF"):" "} ${ll(h)} ${g(h.id)}`);console.log(g("Run: d360-writer project use <name>"));return}let a=await Ip({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${ll(h)}${h.id===s?" (current)":""}`,value:h.id}))}),u=o.find(h=>h.id===a);No(e,r,a,u?.name),console.log(_(`\u2713 Project set to "${u?.name??a}" for profile "${r}". Next: pick a workspace.`))}Y();import Mp from"picocolors";function Up(e=process.env){return e.FORCE_HYPERLINK==="0"||!Mp.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 Fp(e,t=e,n){return Up(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Wp=/https?:\/\/[^\s\x1b]+/g;function En(e,t){return e.replace(Wp,n=>Fp(n,n,t))}function hl(e){return{...ul(e.idToken)??{},...ul(e.accessToken)??{}}}function Oo(e){let t=hl(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 Lo(e){let t=_o(process.cwd(),e.profile),n=t.connection;console.log(g(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Hp(n,{manual:e.manual,promptForRedirect:s=>Bp({message:s})},s=>console.log(En(s))),r=dl(t.name,o);if(pl(r),await ys(r,t.name,s=>console.log(g(s))),console.log(""),console.log(_(`\u2713 Logged in to "${t.name}" as ${Oo(r)}`)),console.log(g(` access token expires: ${r.expiresAt}`)),console.log(g(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Kp(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Zt(process.cwd(),t.name))}catch{}}async function ys(e,t,n){let r=hl(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(_o(process.cwd(),t).project.projectId)return;let a;try{let{projects:u}=await ct(process.cwd(),t);a=u.find(h=>h.id===r)?.name}catch{}zp(process.cwd(),t,{projectId:r,projectName:a}),n(` Project "${a??r}" written to profile "${t}".`)}catch{}}async function fl(e){let t=_o(process.cwd(),e.profile),n=t.connection,o=Yp(t.name);if(!o){console.log(S(`Not logged in to Document360 (profile "${t.name}").`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${F(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Oo(o)}`),Gp(o))if(o.refreshToken)try{let r=dl(t.name,await qp(n,o.refreshToken));pl(r),console.log(_(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(B(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(B("Session expired (no refresh token).")),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(g(` expires: ${o.expiresAt}`))}async function ml(e){let t=_o(process.cwd(),e.profile);Vp(t.name)?console.log(_(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(g(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}Y();import{readProjectConfig as gl,writeProjectConfig as Xp,resolveActiveProfile as Qp,loadTokens as Jp,isExpired as Zp}from"document360-engine";function Mo(e){let t=gl(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(S("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?F("\u25CF "):" ",s=o.production?B(" \u26A0 PRODUCTION"):"",a=o.connection.environment??"(inline)",u=Jp(n),h=u?Zp(u)&&!u.refreshToken?B("expired"):g("logged in"):g("not logged in");console.log(`${r}${F(n)} \u2192 ${a}${s} [${h}]`)}console.log(""),console.log(g("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Uo(e,t){let n=gl(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(S(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Xp(n,e);let o=n.profiles[t].production?B(" \u26A0 PRODUCTION"):"";console.log(_(`\u2713 Default profile is now "${t}"${o}`))}function Fo(e,t){try{let n=Qp(e,t);console.log(""),console.log(`Profile ${F(n.name)}${n.production?B(" \u26A0 PRODUCTION"):""}`),console.log(g(` api: ${n.connection.apiUrl}`)),console.log(g(` identity: ${n.connection.authorizationUrl}`)),console.log(g(` clientId: ${n.connection.clientId}`)),console.log(g(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(g(` project: ${n.project.projectId??"(set at login)"}`)),console.log(g(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(S(n.message)),process.exitCode=1}}Y();import{existsSync as eh,readdirSync as th,statSync as yl}from"node:fs";import{join as wl}from"node:path";import{apiLogDir as nh}from"document360-engine";function kl(){let e=nh();if(console.log(""),console.log(`Document360 API logs: ${F(e)}`),!eh(e)){console.log(g(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=th(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(g(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(yl(wl(e,r)).size/1024).toFixed(1);console.log(` ${r} ${g(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${g("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(yl(wl(e,r)).size/1024).toFixed(1);console.log(` ${S(r)} ${g(`${s} KB`)}`)}}console.log(""),console.log(g("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(g("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}Y();import{createSession as oh,resolveAuth as rh,findByName as sh,slugify as ih,touchSession as ah,upsertSession as lh,resolveActiveProfile as ch}from"document360-engine";async function bl(e,t,n,o,r,s){let a=rh(n);a.kind==="none"&&(console.error(""),console.error(S("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${F("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${F("d360-writer --auth subscription")}`),process.exit(2)),a.kind==="subscription"&&console.error(g("Using your Claude subscription (no API key set)."));let u=null;try{u=ch(e,r)}catch($){console.error(S(`Document360 profile error: ${$.message}`)),process.exit(2)}u.production&&(console.error(B(`\u26A0 Profile "${u.name}" is PRODUCTION.`)),s||(console.error(S("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(g(" --yes given \u2014 proceeding against production.")));let h;if(o){let $=sh(e,o);$||(console.error(S(`No saved session matches "${o}" in this repo.`)),console.error(g("List sessions inside the REPL with /resume.")),process.exit(2)),h=$.uuid,console.error(g(`Resuming "${$.name}"`))}let k=oh({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),b=h??null,x=1;for await(let $ of k.send(t))switch($.type){case"session":if(!b){b=$.sessionId;let j=new Date().toISOString();lh({uuid:b,name:ih(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:j,updatedAt:j})}break;case"text":process.stdout.write($.delta);break;case"tool":console.error(ue(` \u2699 ${$.name}`));break;case"result":x=$.ok?0:1,console.error(g(`(${$.inputTokens}\u2192${$.outputTokens} tokens`+($.costUsd>0?`, $${$.costUsd<.01?$.costUsd.toFixed(4):$.costUsd.toFixed(2)}`:"")+")")),$.ok||console.error(S("agent finished with an error result"));break;case"error":console.error(""),console.error(S(`agent error: ${$.message}`)),process.exit(1)}b&&ah(b),process.stdout.write(`
280
- `),process.exit(x)}import{createInterface as _y}from"node:readline/promises";import{createSession as fa,resolveAuth as Oy,getSession as Ly,setTitle as My,slugify as Uy,touchSession as gd,upsertSession as Fy,generateTitle as Wy,resolveActiveProfile as yd,resolveModelSetting as By,readProjectConfig as Hy,resolveAndPersistAppType as qy,decodeJwtClaims as md,isExpired as Vy,loadTokens as Gy,isDirectiveMention as Yy,stripDirectiveMention as zy,appendDirective as Ky,reconcileUpgradeActions as Xy,stampArticles as Qy,listArticleFiles as Jy,CONTENT_CAP_VERSION as Zy}from"document360-engine";import{ENGINE_VERSION as dh}from"document360-engine";var Oe=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot author --all to write the capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then /screenshot capture \u2014 the writer drives a real browser that signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Run /publish --screenshots \u2014 it re-saves the articles with captured shots so the images embed on Document360."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Bare: pick what to do next (author or capture, per shot)."},{t:"cmd",name:"/screenshot author",s:"Write capture specs (<id>, a path, or --all)."},{t:"cmd",name:"/screenshot capture",s:"Take the screenshots (<id>, a path, or --all; bare = pick ready specs)."},{t:"cmd",name:"/screenshot capture --failed",s:"Re-run just the shots whose last run failed \u2014 the follow-up after re-authoring their specs."},{t:"cmd",name:"/screenshot capture --all --retry-blocked",s:"Include shots that skipped on missing data last run (a bulk run leaves them out by default)."},{t:"cmd",name:"/screenshot checklist",s:"What to stage + dev test-id requests (a report; auto-runs after bulk authoring)."},{t:"cmd",name:"/screenshot list",s:'Progress by chapter (\u25CF captured \xB7 \u25D0 ready \xB7 \u2298 blocked \xB7 \u2717 broken \xB7 \u25CB to-spec) plus the grouped "stage this data" worklist; list <chapter#> or --detail drills in.'},{t:"gap"},{t:"sub",s:"When a shot does not produce an image"},{t:"text",s:"\u2298 blocked means your app lacked the data the shot needs \u2014 /screenshot list groups every blocker into the handful of things to go and stage."},{t:"text",s:"\u2717 broken means the spec itself is out of date. Re-author it with /screenshot <id> (which carries the error into the fix); re-running the capture would fail the same way."},{t:"gap"},{t:"dim",s:"One-time setup in the app repo: npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth (real login, once per machine)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress + the next step (`done` marks the next step finished)."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"The screenshot pipeline: bare = pick; author / capture / checklist / list."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function uh(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 $l(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 Oe){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(uh(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function ws(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:dh}:void 0;for(let o of $l(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"}}Y();import{getSession as ph}from"document360-engine";async function xl(e,t){let n=t.currentUuid(),o=n?ph(n):void 0;return console.log(o?g(`
278
+ `;El="Re-run dev\u2194docs onboarding (protocol v"});var Gl={};il(Gl,{initCommand:()=>Rs,scaffoldInit:()=>Cs});import{input as _n,confirm as vh}from"@inquirer/prompts";import{basename as Ll,join as Go}from"node:path";import{existsSync as sn,readFileSync as Ch,readdirSync as Rh,writeFileSync as Sh}from"node:fs";import{writeProjectConfig as Ml,readProjectConfig as Ph,projectConfigPath as Ul,writerDir as Th,DEFAULT_DOCS_DIR as Fl,DEFAULT_CAPTURE_DIR as Wl,DEFAULT_OUTPUT_DIR as Bl}from"document360-engine";function Cs(e,t="berlin"){let n=Ul(e);if(sn(n))return{created:!1,path:n,profileName:""};let o={projectId:ql(e)??Ll(e),docsDir:Fl,captureDir:Wl,outputDir:Bl,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Vl(e)};return Ml(o,e),Hl(e),{created:!0,path:n,profileName:t}}function Hl(e){let t=Go(Th(e),".gitignore");sn(t)||Sh(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
279
+ `),"utf8")}async function Rs(){let e=process.cwd(),t=Ul(e);if(sn(t)&&!await vh({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(g("init cancelled.")),{kind:"continue"};let n=ql(e)??Ll(e),o=await _n({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await _n({message:"Capture directory (where document360-capture .spec.ts files live):",default:Wl}),s=await _n({message:"Screenshot output directory:",default:Bl}),a=await _n({message:"Default connection profile name:",default:"berlin"}),u=await _n({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),h={projectId:o,docsDir:Fl,captureDir:r,outputDir:s,profiles:{[a]:{connection:{environment:u},production:!1}},defaultProfile:a,authoritativeSourceFiles:Vl(e)},k=Ph(e);k?.terminologyGlossary&&(h.terminologyGlossary=k.terminologyGlossary),Ml(h,e),Hl(e);let b=on(e);console.log(""),console.log(_(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${F(`d360-writer login --profile ${a}`)} ${g("(sign in; project & workspace auto-selected)")}`),console.log("");for(let x of rn(b))console.log(x);return console.log(""),console.log(`${g("Then ask:")} ${F('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function ql(e){let t=Go(e,"package.json");if(!sn(t))return null;try{return JSON.parse(Ch(t,"utf8")).name??null}catch{return null}}function Vl(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])sn(Go(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Go(e,n);sn(o)&&!Dh(o)&&t.push(n)}return t}function Dh(e){try{return Rh(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Yo=An(()=>{"use strict";Y();dt()});import{createRequire as Um}from"node:module";import{existsSync as Fm,readFileSync as Wm}from"node:fs";import{dirname as gu,join as yu}from"node:path";function yr(){let e;try{e=Bm.resolve("document360-capture/helpers")}catch{return null}let t=gu(e);for(let n=0;n<5&&!Fm(yu(t,"package.json"));n++)t=gu(t);try{let n=JSON.parse(Wm(yu(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var Bm,Ai=An(()=>{"use strict";Bm=Um(import.meta.url)});var xu={};il(xu,{doctorCommand:()=>Yn,renderDoctorChecks:()=>$u,runDoctorChecks:()=>bu});import{existsSync as Hm}from"node:fs";import{d360GetAll as qm,getAccessToken as Vm,isExpired as Ei,loadProfileMap as Gm,loadTokens as Ym,packageSkillsDir as wu,ENGINE_VERSION as zm,projectConfigPath as Km,readProjectConfig as Xm,DEFAULT_DOCS_DIR as Qm,fetchManifestSummary as Jm,resolveActiveProfile as Zm,classifyClaudeAuth as eg,CLAUDE_CODE_SETUP_HINT as ku,resolveModelSetting as tg,probeModel as ng,detectAppType as og,playbookSkillName as rg,D360AuthError as sg}from"document360-engine";async function bu(e,t){let n=[],o=yr();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${zm}${o?` \xB7 capture v${o}`:" \xB7 capture not installed"}`});let r=Number(process.versions.node.split(".")[0]);n.push(r>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let s=eg();s.state==="ready"?n.push({level:"ok",label:`Claude auth: ${s.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):s.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${ku}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ku});let a=tg(e);if(n.push({level:"ok",label:`Model: ${a.model} (${a.source==="auto"?"auto \u2014 right-sized for docs; /model to change":a.source})`}),s.state==="ready"){let T=await ng(e,a.model??void 0);T.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(T.latencyMs/1e3).toFixed(1)}s`}):T.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 ${T.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 u=Xm(e);if(!u)return n.push({level:"fail",label:`No ${Km(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${u.projectId}`});let h=(u.docsDir??Qm).replace(/\/+$/,"");n.push(u.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 ${h}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let k=u.authoritativeSourceFiles??[];n.push(k.length>0?{level:"ok",label:`Sources: docs grounded in ${k.length} path(s) (${k.slice(0,3).join(", ")}${k.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let b=u.appType??og(e);if(b){let T=u.appType?"from config":"auto-detected",E=b==="web"||b==="cli";n.push({level:"ok",label:`Genre: ${b} (${T})${E?` \u2192 ${rg(b)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let x;try{x=Zm(e),n.push({level:"ok",label:`Profile: ${x.name} (${x.connection.name})${x.production?" \u26A0 PRODUCTION":""}`})}catch(T){return n.push({level:"fail",label:`Profile config: ${T.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let $=Ym(x.name);$?Ei($)&&!$.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Ei($)?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($.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${x.name})`}),n.push(x.project.workspaceId?{level:"ok",label:`Workspace: ${x.project.workspaceName??x.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let j=Gm(e,x.name);j?j.projectId&&x.project.projectId&&j.projectId!==x.project.projectId?n.push({level:"fail",label:`Category map projectId (${j.projectId}) \u2260 profile projectId (${x.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(j.articles).length} articles, ${Object.keys(j.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${x.name}" (created on first /publish)`}),n.push(Hm(wu())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${wu()}`,fix:"Reinstall document360-writer (broken install)"});let v=Le(e);if(v.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${de})`}):v.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${v.completedVersion}, current is v${de}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),$&&(!Ei($)||$.refreshToken)){let T={profile:x.name,connection:x.connection};try{await Vm(T);let U=await qm(T,"/v3/projects");n.push({level:"ok",label:`API reachable (${x.connection.apiUrl}) \u2014 ${U.length} project(s) visible`})}catch(U){n.push({level:"fail",label:`API call failed: ${U.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let E=j?.projectId??x.project.projectId;if(E&&x.project.workspaceId)try{let U=await Jm(T,E,x.project.workspaceId);if(U){let L=(U.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${x.connection.name} (${U.languages?.length??0} language${(U.languages?.length??0)===1?"":"s"}) \xB7 hash ${L||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${x.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(U){U instanceof sg||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(U.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${x.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 (${U.message.slice(0,80)})`})}}return n}function $u(e){let t=[""];for(let r of e){let s=r.level==="ok"?_("\u2713"):r.level==="warn"?B("\u26A0"):S("\u2717");t.push(` ${s} ${r.label}${r.detail?g(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${g("fix:")} ${F(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?_(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):S(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Yn(e,t){console.log(g("Running checks\u2026"));for(let n of $u(await bu(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var wr=An(()=>{"use strict";dt();Y();Ai()});import{Command as Dk}from"commander";import{createRequire as Ak}from"node:module";import{AUTH_MODES as Ek}from"document360-engine";import{input as qp}from"@inquirer/prompts";import{loginPkce as Vp,refreshTokens as Gp,toStoredTokens as hl,clearTokens as Yp,decodeJwtClaims as pl,isExpired as zp,loadTokens as Kp,saveTokens as fl,resolveActiveProfile as Oo,setProfileProject as Xp,readProjectConfig as Qp}from"document360-engine";Y();import{select as Ep}from"@inquirer/prompts";import{resolveActiveProfile as jp,setProfileProject as Np,resolveProjectId as Ip,listWorkspaces as _p}from"document360-engine";async function jn(e,t){let n=jp(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Ip(o);return{workspaces:await _p(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var ll=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function gs(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 No(e,t,n,o,r){Np(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function cl(e,t,n){let o;try{o=await jn(e,n)}catch(s){return console.log(S(`Could not list workspaces: ${s.message}`)),1}let r=gs(o.workspaces,t);return r?(No(e,o.profile,o.projectId,r.id,r.name),console.log(_(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(S(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function en(e,t){let n;try{n=await jn(e,t)}catch(k){console.log(S(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:a}=n;if(o.length===0){console.log(g("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===a?F("\u25CF"):" "} ${ll(k)} ${g(k.id)}`);console.log(g("Run: d360-writer workspace use <name>"));return}let u=await Ep({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${ll(k)}${k.id===a?" (current)":""}`,value:k.id}))}),h=o.find(k=>k.id===u);No(e,s,r,u,h?.name),console.log(_(`\u2713 Workspace set to "${h?.name??u}" for profile "${s}".`))}Y();import{select as Op}from"@inquirer/prompts";import{resolveActiveProfile as Lp,setProfileProject as Mp,listProjects as Up}from"document360-engine";async function ct(e,t){let n=Lp(e,t),o={profile:n.name,connection:n.connection};return{projects:await Up(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ul=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function ys(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 Io(e,t,n,o){Mp(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function dl(e,t,n){let o;try{o=await ct(e,n)}catch(s){return console.log(S(`Could not list projects: ${s.message}`)),1}let r=ys(o.projects,t);return r?(Io(e,o.profile,r.id,r.name),console.log(_(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(S(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function _o(e,t){let n;try{n=await ct(e,t)}catch(h){console.log(S(`Could not list projects: ${h.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(g("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===s?F("\u25CF"):" "} ${ul(h)} ${g(h.id)}`);console.log(g("Run: d360-writer project use <name>"));return}let a=await Op({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${ul(h)}${h.id===s?" (current)":""}`,value:h.id}))}),u=o.find(h=>h.id===a);Io(e,r,a,u?.name),console.log(_(`\u2713 Project set to "${u?.name??a}" for profile "${r}". Next: pick a workspace.`))}Y();import Fp from"picocolors";function Wp(e=process.env){return e.FORCE_HYPERLINK==="0"||!Fp.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 Bp(e,t=e,n){return Wp(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Hp=/https?:\/\/[^\s\x1b]+/g;function Nn(e,t){return e.replace(Hp,n=>Bp(n,n,t))}function ml(e){return{...pl(e.idToken)??{},...pl(e.accessToken)??{}}}function Lo(e){let t=ml(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 Mo(e){let t=Oo(process.cwd(),e.profile),n=t.connection;console.log(g(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Vp(n,{manual:e.manual,promptForRedirect:s=>qp({message:s})},s=>console.log(Nn(s))),r=hl(t.name,o);if(fl(r),await ws(r,t.name,s=>console.log(g(s))),console.log(""),console.log(_(`\u2713 Logged in to "${t.name}" as ${Lo(r)}`)),console.log(g(` access token expires: ${r.expiresAt}`)),console.log(g(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Qp(process.cwd())?.profiles?.[t.name]&&(console.log(""),await en(process.cwd(),t.name))}catch{}}async function ws(e,t,n){let r=ml(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Oo(process.cwd(),t).project.projectId)return;let a;try{let{projects:u}=await ct(process.cwd(),t);a=u.find(h=>h.id===r)?.name}catch{}Xp(process.cwd(),t,{projectId:r,projectName:a}),n(` Project "${a??r}" written to profile "${t}".`)}catch{}}async function gl(e){let t=Oo(process.cwd(),e.profile),n=t.connection,o=Kp(t.name);if(!o){console.log(S(`Not logged in to Document360 (profile "${t.name}").`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${F(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Lo(o)}`),zp(o))if(o.refreshToken)try{let r=hl(t.name,await Gp(n,o.refreshToken));fl(r),console.log(_(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(B(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(B("Session expired (no refresh token).")),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(g(` expires: ${o.expiresAt}`))}async function yl(e){let t=Oo(process.cwd(),e.profile);Yp(t.name)?console.log(_(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(g(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}Y();import{readProjectConfig as wl,writeProjectConfig as Jp,resolveActiveProfile as Zp,loadTokens as eh,isExpired as th}from"document360-engine";function Uo(e){let t=wl(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(S("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?F("\u25CF "):" ",s=o.production?B(" \u26A0 PRODUCTION"):"",a=o.connection.environment??"(inline)",u=eh(n),h=u?th(u)&&!u.refreshToken?B("expired"):g("logged in"):g("not logged in");console.log(`${r}${F(n)} \u2192 ${a}${s} [${h}]`)}console.log(""),console.log(g("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Fo(e,t){let n=wl(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(S(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Jp(n,e);let o=n.profiles[t].production?B(" \u26A0 PRODUCTION"):"";console.log(_(`\u2713 Default profile is now "${t}"${o}`))}function Wo(e,t){try{let n=Zp(e,t);console.log(""),console.log(`Profile ${F(n.name)}${n.production?B(" \u26A0 PRODUCTION"):""}`),console.log(g(` api: ${n.connection.apiUrl}`)),console.log(g(` identity: ${n.connection.authorizationUrl}`)),console.log(g(` clientId: ${n.connection.clientId}`)),console.log(g(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(g(` project: ${n.project.projectId??"(set at login)"}`)),console.log(g(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(S(n.message)),process.exitCode=1}}Y();import{existsSync as nh,readdirSync as oh,statSync as kl}from"node:fs";import{join as bl}from"node:path";import{apiLogDir as rh}from"document360-engine";function $l(){let e=rh();if(console.log(""),console.log(`Document360 API logs: ${F(e)}`),!nh(e)){console.log(g(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=oh(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(g(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(kl(bl(e,r)).size/1024).toFixed(1);console.log(` ${r} ${g(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${g("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(kl(bl(e,r)).size/1024).toFixed(1);console.log(` ${S(r)} ${g(`${s} KB`)}`)}}console.log(""),console.log(g("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(g("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}Y();import{createSession as sh,resolveAuth as ih,findByName as ah,slugify as lh,touchSession as ch,upsertSession as uh,resolveActiveProfile as dh}from"document360-engine";async function xl(e,t,n,o,r,s){let a=ih(n);a.kind==="none"&&(console.error(""),console.error(S("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${F("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${F("d360-writer --auth subscription")}`),process.exit(2)),a.kind==="subscription"&&console.error(g("Using your Claude subscription (no API key set)."));let u=null;try{u=dh(e,r)}catch($){console.error(S(`Document360 profile error: ${$.message}`)),process.exit(2)}u.production&&(console.error(B(`\u26A0 Profile "${u.name}" is PRODUCTION.`)),s||(console.error(S("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(g(" --yes given \u2014 proceeding against production.")));let h;if(o){let $=ah(e,o);$||(console.error(S(`No saved session matches "${o}" in this repo.`)),console.error(g("List sessions inside the REPL with /resume.")),process.exit(2)),h=$.uuid,console.error(g(`Resuming "${$.name}"`))}let k=sh({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),b=h??null,x=1;for await(let $ of k.send(t))switch($.type){case"session":if(!b){b=$.sessionId;let j=new Date().toISOString();uh({uuid:b,name:lh(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:j,updatedAt:j})}break;case"text":process.stdout.write($.delta);break;case"tool":console.error(ue(` \u2699 ${$.name}`));break;case"result":x=$.ok?0:1,console.error(g(`(${$.inputTokens}\u2192${$.outputTokens} tokens`+($.costUsd>0?`, $${$.costUsd<.01?$.costUsd.toFixed(4):$.costUsd.toFixed(2)}`:"")+")")),$.ok||console.error(S("agent finished with an error result"));break;case"error":console.error(""),console.error(S(`agent error: ${$.message}`)),process.exit(1)}b&&ch(b),process.stdout.write(`
280
+ `),process.exit(x)}import{createInterface as Ly}from"node:readline/promises";import{createSession as ga,resolveAuth as My,getSession as Uy,setTitle as Fy,slugify as Wy,touchSession as wd,upsertSession as By,generateTitle as Hy,resolveActiveProfile as kd,resolveModelSetting as qy,readProjectConfig as Vy,resolveAndPersistAppType as Gy,decodeJwtClaims as yd,isExpired as Yy,loadTokens as zy,isDirectiveMention as Ky,stripDirectiveMention as Xy,appendDirective as Qy,reconcileUpgradeActions as Jy,stampArticles as Zy,listArticleFiles as ew,CONTENT_CAP_VERSION as tw}from"document360-engine";import{ENGINE_VERSION as hh}from"document360-engine";var Oe=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot author --all to write the capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then /screenshot capture \u2014 the writer drives a real browser that signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Run /publish --screenshots \u2014 it re-saves the articles with captured shots so the images embed on Document360."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Bare: pick what to do next (author or capture, per shot)."},{t:"cmd",name:"/screenshot author",s:"Write capture specs (<id>, a path, or --all)."},{t:"cmd",name:"/screenshot capture",s:"Take the screenshots (<id>, a path, or --all; bare = pick ready specs)."},{t:"cmd",name:"/screenshot capture --failed",s:"Re-run just the shots whose last run failed \u2014 the follow-up after re-authoring their specs."},{t:"cmd",name:"/screenshot capture --all --retry-blocked",s:"Include shots that skipped on missing data last run (a bulk run leaves them out by default)."},{t:"cmd",name:"/screenshot checklist",s:"What to stage + dev test-id requests (a report; auto-runs after bulk authoring)."},{t:"cmd",name:"/screenshot list",s:'Progress by chapter (\u25CF captured \xB7 \u25D0 ready \xB7 \u2298 blocked \xB7 \u2717 broken \xB7 \u25CB to-spec) plus the grouped "stage this data" worklist; list <chapter#> or --detail drills in.'},{t:"gap"},{t:"sub",s:"When a shot does not produce an image"},{t:"text",s:"\u2298 blocked means your app lacked the data the shot needs \u2014 /screenshot list groups every blocker into the handful of things to go and stage."},{t:"text",s:"\u2717 broken means the spec itself is out of date. Re-author it with /screenshot <id> (which carries the error into the fix); re-running the capture would fail the same way."},{t:"gap"},{t:"dim",s:"One-time setup in the app repo: npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth (real login, once per machine)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress + the next step (`done` marks the next step finished)."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"The screenshot pipeline: bare = pick; author / capture / checklist / list."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function ph(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 vl(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 Oe){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(ph(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function ks(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:hh}:void 0;for(let o of vl(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"}}Y();import{getSession as fh}from"document360-engine";async function Cl(e,t){let n=t.currentUuid(),o=n?fh(n):void 0;return console.log(o?g(`
281
281
  (conversation reset \u2014 "${o.name}" is still available via /resume)
282
282
  `):g(`
283
283
  (conversation reset \u2014 agent will start fresh on the next prompt)
284
- `)),{kind:"clear"}}async function ks(){return{kind:"exit"}}Go();Y();import{readMcpConfig as Rs,writeMcpConfig as Vl}from"document360-engine";async function Yo(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Th(),{kind:"continue"}):t==="add"?(Dh(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Ah(e.slice(1)),{kind:"continue"}):(console.log(S(`Unknown /mcp subcommand: ${t}`)),console.log(g("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Th(){let e=Rs(),t=Object.keys(e.servers);if(t.length===0){console.log(g(`
284
+ `)),{kind:"clear"}}async function bs(){return{kind:"exit"}}Yo();Y();import{readMcpConfig as Ss,writeMcpConfig as Yl}from"document360-engine";async function zo(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Ah(),{kind:"continue"}):t==="add"?(Eh(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(jh(e.slice(1)),{kind:"continue"}):(console.log(S(`Unknown /mcp subcommand: ${t}`)),console.log(g("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Ah(){let e=Ss(),t=Object.keys(e.servers);if(t.length===0){console.log(g(`
285
285
  No MCP servers registered. Add one with /mcp add <name> <type> <ref>
286
- `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${F(n)} ${g("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?g(` [headers: ${r.join(", ")}]`):"";console.log(` ${F(n)} ${g(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Dh(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(S("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(S(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Rs(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let a={};for(let u=1;u<o.length;u++)if(o[u]==="-H"||o[u]==="--header"){let h=o[++u],k=h?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(S(`-H expects key:value (no spaces). Got: ${h??"(nothing)"}`));return}a[k[1].trim()]=k[2].trim()}else{console.log(S(`Unexpected argument: ${o[u]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(a).length>0?a:void 0}}r.servers[t]=s,Vl(r),console.log(""),console.log(_(`\u2713 Registered "${t}" (${n})`)),console.log(B(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(g(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Ah(e){let t=e[0];if(!t){console.log(S("Usage: /mcp remove <name>"));return}let n=Rs();if(!n.servers[t]){console.log(S(`No server named "${t}".`));return}delete n.servers[t],Vl(n),console.log(_(`\u2713 Removed "${t}".`)),console.log(g(" Run /clear to drop it from the current session immediately."))}Y();import{readFileSync as df}from"node:fs";import{join as pf}from"node:path";import{select as hf}from"@inquirer/prompts";import{computeSyncStatus as sr,planPartitions as ff,relatedArticlePaths as mf,resolveModelForOperation as gf,runPartitioned as yf,loadProfileMap as wf,resolveActiveProfile as kf,resolveCrossLinks as bf,applyStructureOrder as Sc,orderSyncLine as Pc,applyRelatedArticles as Tc,relatedSyncLine as Dc}from"document360-engine";import ne from"picocolors";import nc from"wrap-ansi";import Es from"string-width";Y();import pt from"picocolors";import Ss from"wrap-ansi";import Ps from"string-width";var sn=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|checklist|list] [id|path|--all|--failed|--retry-blocked]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots (--failed re-runs broken ones; --retry-blocked re-tries shots waiting on data); checklist: what to stage + dev test-id requests; list: status + what to stage",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all|--screenshots]",desc:"Publish to Document360 (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"roadmap",usage:"/roadmap [done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (publish), take portal (pull), or skip \u2014 for each. Bare: walk them all",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer \u2014 and d360-capture when installed \u2014 to the latest versions (then relaunch)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],Gl={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"work the screenshot pipeline (author specs, take shots)","/doctor":"run a health check"};function Yl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Gl[n])return Gl[n];let o=sn.find(r=>r.name===t);return o?o.desc:""}function zl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return sn.filter(n=>n.name.startsWith(t))}function Kl(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Eh=new RegExp(`^\\s*/(?:${sn.map(e=>e.name).join("|")})(?:\\s|$)`),Xl=e=>Eh.test(e),Ql=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Jl=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Zl=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function jh(e){let t=e.replace(/\r/g,"").split(`
287
- `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let u=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)u.push(t[o++]);o++,n.push({kind:"code",lines:u});continue}if(Ql(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Jl(t[o+1])){let u=Zl(r);o+=2;let h=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)h.push(Zl(t[o++]));n.push({kind:"table",header:u,rows:h});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let u=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let h=t[o++];u.push({ordered:/^\s*\d+\.\s+/.test(h),text:h.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:u});continue}if(r.trim()===""){o++;continue}if(Xl(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])&&!Xl(t[o])&&!Ql(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Jl(t[o+1]));)a.push(t[o++]);n.push({kind:"para",text:a.join(" ")})}return n}function Ts(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?pt.bold(t.slice(2,-2)):t.startsWith("`")?F(t.slice(1,-1)):pt.italic(t.slice(1,-1)))}var Nh=(e,t)=>e+" ".repeat(Math.max(0,t-Ps(e)));function Ih(e,t,n){let o=e.length,r=e.map((v,T)=>Math.max(Ps(v),...t.map(E=>Ps(E[T]??"")))),s=Math.max(24,n),a=3*o+1,u=[...r],h=()=>u.reduce((v,T)=>v+T,0)+a,k=0;for(;h()>s&&k++<1e4;){let v=-1,T=6;for(let E=0;E<o;E++)u[E]>T&&(T=u[E],v=E);if(v===-1)break;u[v]-=1}let b=(v,T,E)=>pt.gray(v+u.map(U=>"\u2500".repeat(U+2)).join(T)+E),x=pt.gray("\u2502"),$=(v,T)=>{let E=u.map((V,q)=>{let re=v[q]??"",We=T?pt.bold(re):Ts(re);return Ss(We,V,{hard:!0}).split(`
288
- `)}),U=Math.max(...E.map(V=>V.length)),L=[];for(let V=0;V<U;V++)L.push(u.map((q,re)=>`${x} ${Nh(E[re][V]??"",q)} `).join("")+x);return L.join(`
286
+ `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${F(n)} ${g("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?g(` [headers: ${r.join(", ")}]`):"";console.log(` ${F(n)} ${g(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Eh(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(S("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(S(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Ss(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let a={};for(let u=1;u<o.length;u++)if(o[u]==="-H"||o[u]==="--header"){let h=o[++u],k=h?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(S(`-H expects key:value (no spaces). Got: ${h??"(nothing)"}`));return}a[k[1].trim()]=k[2].trim()}else{console.log(S(`Unexpected argument: ${o[u]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(a).length>0?a:void 0}}r.servers[t]=s,Yl(r),console.log(""),console.log(_(`\u2713 Registered "${t}" (${n})`)),console.log(B(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(g(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function jh(e){let t=e[0];if(!t){console.log(S("Usage: /mcp remove <name>"));return}let n=Ss();if(!n.servers[t]){console.log(S(`No server named "${t}".`));return}delete n.servers[t],Yl(n),console.log(_(`\u2713 Removed "${t}".`)),console.log(g(" Run /clear to drop it from the current session immediately."))}Y();import{readFileSync as hf}from"node:fs";import{join as ff}from"node:path";import{select as mf}from"@inquirer/prompts";import{computeSyncStatus as ir,planPartitions as gf,relatedArticlePaths as yf,resolveModelForOperation as wf,runPartitioned as kf,loadProfileMap as bf,resolveActiveProfile as $f,resolveCrossLinks as xf,applyStructureOrder as Tc,orderSyncLine as Dc,applyRelatedArticles as Ac,relatedSyncLine as Ec}from"document360-engine";import ne from"picocolors";import rc from"wrap-ansi";import js from"string-width";Y();import pt from"picocolors";import Ps from"wrap-ansi";import Ts from"string-width";var an=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|checklist|list] [id|path|--all|--failed|--retry-blocked]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots (--failed re-runs broken ones; --retry-blocked re-tries shots waiting on data); checklist: what to stage + dev test-id requests; list: status + what to stage",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all|--screenshots]",desc:"Publish to Document360 (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"roadmap",usage:"/roadmap [done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (publish), take portal (pull), or skip \u2014 for each. Bare: walk them all",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer \u2014 and d360-capture when installed \u2014 to the latest versions (then relaunch)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],zl={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"work the screenshot pipeline (author specs, take shots)","/doctor":"run a health check"};function Kl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(zl[n])return zl[n];let o=an.find(r=>r.name===t);return o?o.desc:""}function Xl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return an.filter(n=>n.name.startsWith(t))}function Ql(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Nh=new RegExp(`^\\s*/(?:${an.map(e=>e.name).join("|")})(?:\\s|$)`),Jl=e=>Nh.test(e),Zl=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),ec=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),tc=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Ih(e){let t=e.replace(/\r/g,"").split(`
287
+ `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let u=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)u.push(t[o++]);o++,n.push({kind:"code",lines:u});continue}if(Zl(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&ec(t[o+1])){let u=tc(r);o+=2;let h=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)h.push(tc(t[o++]));n.push({kind:"table",header:u,rows:h});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let u=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let h=t[o++];u.push({ordered:/^\s*\d+\.\s+/.test(h),text:h.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:u});continue}if(r.trim()===""){o++;continue}if(Jl(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])&&!Jl(t[o])&&!Zl(t[o])&&!(t[o].includes("|")&&o+1<t.length&&ec(t[o+1]));)a.push(t[o++]);n.push({kind:"para",text:a.join(" ")})}return n}function Ds(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?pt.bold(t.slice(2,-2)):t.startsWith("`")?F(t.slice(1,-1)):pt.italic(t.slice(1,-1)))}var _h=(e,t)=>e+" ".repeat(Math.max(0,t-Ts(e)));function Oh(e,t,n){let o=e.length,r=e.map((v,T)=>Math.max(Ts(v),...t.map(E=>Ts(E[T]??"")))),s=Math.max(24,n),a=3*o+1,u=[...r],h=()=>u.reduce((v,T)=>v+T,0)+a,k=0;for(;h()>s&&k++<1e4;){let v=-1,T=6;for(let E=0;E<o;E++)u[E]>T&&(T=u[E],v=E);if(v===-1)break;u[v]-=1}let b=(v,T,E)=>pt.gray(v+u.map(U=>"\u2500".repeat(U+2)).join(T)+E),x=pt.gray("\u2502"),$=(v,T)=>{let E=u.map((V,q)=>{let re=v[q]??"",We=T?pt.bold(re):Ds(re);return Ps(We,V,{hard:!0}).split(`
288
+ `)}),U=Math.max(...E.map(V=>V.length)),L=[];for(let V=0;V<U;V++)L.push(u.map((q,re)=>`${x} ${_h(E[re][V]??"",q)} `).join("")+x);return L.join(`
289
289
  `)},j=[b("\u250C","\u252C","\u2510"),$(e,!0)];return j.push(t.length===0?b("\u2514","\u2534","\u2518"):b("\u251C","\u253C","\u2524")),t.forEach((v,T)=>{j.push($(v,!1)),j.push(T===t.length-1?b("\u2514","\u2534","\u2518"):b("\u251C","\u253C","\u2524"))}),j.join(`
290
- `)}function _h(e,t){switch(e.kind){case"heading":return pt.bold(e.text);case"hr":return pt.gray("\u2500".repeat(t));case"para":return Ss(Ts(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",s=" ".repeat(2+r.length+1),[a="",...u]=Ss(Ts(o.text),Math.max(10,t-s.length)).split(`
290
+ `)}function Lh(e,t){switch(e.kind){case"heading":return pt.bold(e.text);case"hr":return pt.gray("\u2500".repeat(t));case"para":return Ps(Ds(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",s=" ".repeat(2+r.length+1),[a="",...u]=Ps(Ds(o.text),Math.max(10,t-s.length)).split(`
291
291
  `);return` ${r} ${a}`+u.map(h=>`
292
292
  ${s}${h}`).join("")}).join(`
293
293
  `)}case"code":return e.lines.map(n=>pt.gray(" "+n)).join(`
294
- `);case"table":return Ih(e.header,e.rows,t)}}function Ds(e,t){let n=Math.max(20,t);return jh(e).map(o=>_h(o,n)).join(`
294
+ `);case"table":return Oh(e.header,e.rows,t)}}function As(e,t){let n=Math.max(20,t);return Ih(e).map(o=>Lh(o,n)).join(`
295
295
 
296
- `)}Y();import Oh from"picocolors";var Lh=[127,86,217],Mh=[22,38,43],ec={T:Lh,E:Mh},In=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],As=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Uh=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function tc(){if(!Oh.isColorSupported)return[];let e=In[0].length,t=[];for(let n=0;n<In.length;n+=2){let o="";for(let r=0;r<e;r++){let s=ec[In[n][r]],a=n+1<In.length?ec[In[n+1][r]]:void 0;s&&a?o+=`${As(s)}${Uh(a)}\u2580\x1B[49m\x1B[39m`:s?o+=`${As(s)}\u2580\x1B[39m`:a?o+=`${As(a)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function _n(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 On(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Se(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function ht(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var an=(e,t)=>` ${e.padEnd(13)}${t}`;function Fh(e,t){let n=[Dn("\u270E document360-writer")+ne.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),ne.gray(" Reads your code, writes your docs."),"",an("Claude:",`${e.claude}${ne.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),an("Document360:",e.configured?e.loggedOut?ne.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?ne.gray(` (${e.sessionHint})`):""}`:ne.yellow("not set up \u2014 run /init")),an("Profile:",e.configured?`${e.profile}${ne.gray(` (${e.apiUrl})`)}${e.prod?ne.bold(ne.yellow(" \u26A0 PRODUCTION")):""}`:ne.gray("\u2014 (run /init)")),an("Project:",e.project),an("Mode:",ne.gray(e.mode)),an("cwd:",ne.gray(e.cwd))],o=tc();if(o.length===0)return n.join(`
297
- `);let r=2,s=3,a=Es(o[0]);if(!(t>=r+a+s+Math.max(...n.map(b=>Es(b)))))return[...o.map(b=>" "+b),...n].join(`
296
+ `)}Y();import Mh from"picocolors";var Uh=[127,86,217],Fh=[22,38,43],nc={T:Uh,E:Fh},On=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Es=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Wh=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function oc(){if(!Mh.isColorSupported)return[];let e=On[0].length,t=[];for(let n=0;n<On.length;n+=2){let o="";for(let r=0;r<e;r++){let s=nc[On[n][r]],a=n+1<On.length?nc[On[n+1][r]]:void 0;s&&a?o+=`${Es(s)}${Wh(a)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Es(s)}\u2580\x1B[39m`:a?o+=`${Es(a)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Ln(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 Mn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Se(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function ht(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var ln=(e,t)=>` ${e.padEnd(13)}${t}`;function Bh(e,t){let n=[En("\u270E document360-writer")+ne.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),ne.gray(" Reads your code, writes your docs."),"",ln("Claude:",`${e.claude}${ne.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),ln("Document360:",e.configured?e.loggedOut?ne.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?ne.gray(` (${e.sessionHint})`):""}`:ne.yellow("not set up \u2014 run /init")),ln("Profile:",e.configured?`${e.profile}${ne.gray(` (${e.apiUrl})`)}${e.prod?ne.bold(ne.yellow(" \u26A0 PRODUCTION")):""}`:ne.gray("\u2014 (run /init)")),ln("Project:",e.project),ln("Mode:",ne.gray(e.mode)),ln("cwd:",ne.gray(e.cwd))],o=oc();if(o.length===0)return n.join(`
297
+ `);let r=2,s=3,a=js(o[0]);if(!(t>=r+a+s+Math.max(...n.map(b=>js(b)))))return[...o.map(b=>" "+b),...n].join(`
298
298
  `);let h=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let b=0;b<Math.max(o.length+h,n.length);b++){let x=o[b-h]??" ".repeat(a);k.push((" ".repeat(r)+x+" ".repeat(s)+(n[b]??"")).trimEnd())}return k.join(`
299
- `)}var Wh={error:ne.red,warn:ne.yellow,ok:ne.green,info:ne.gray};function js(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1$2 ")}function Ns(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Fh(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),a=50,u=e.text.split(`
300
- `).flatMap(k=>nc(k,s,{hard:!0}).split(`
299
+ `)}var Hh={error:ne.red,warn:ne.yellow,ok:ne.green,info:ne.gray};function Ns(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1$2 ")}function Is(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Bh(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),a=50,u=e.text.split(`
300
+ `).flatMap(k=>rc(k,s,{hard:!0}).split(`
301
301
  `)),h=Math.max(0,u.length-a);return h>0&&(u=[...u.slice(0,a),ne.dim(`\u2026 +${h} more lines`)]),`
302
- `+u.map((k,b)=>o+(b===0?F(" \u276F "):" ")+k+" ".repeat(Math.max(0,s-Es(k))+1)+r).join(`
302
+ `+u.map((k,b)=>o+(b===0?F(" \u276F "):" ")+k+" ".repeat(Math.max(0,s-js(k))+1)+r).join(`
303
303
  `)}case"assistant":return`
304
- `+Ds(e.text,n);case"tool":{let o=e.arg!==null?ne.gray(`${e.sep}(${e.arg})`):"";return`
305
- `+nc(ne.green("\u25CF ")+ne.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?ne.red:ne.gray,r=e.lines.map((s,a)=>o((a===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(ne.dim(` \u2026 +${e.hidden} lines`)),r.join(`
304
+ `+As(e.text,n);case"tool":{let o=e.arg!==null?ne.gray(`${e.sep}(${e.arg})`):"";return`
305
+ `+rc(ne.green("\u25CF ")+ne.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?ne.red:ne.gray,r=e.lines.map((s,a)=>o((a===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(ne.dim(` \u2026 +${e.hidden} lines`)),r.join(`
306
306
  `)}case"diff":{let o=a=>a===1?"":"s",s=[ne.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(ne.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
307
- `)}case"link":return e.lines.map(o=>F(En(` \u2B95 ${o}`))).join(`
307
+ `)}case"link":return e.lines.map(o=>F(Nn(` \u2B95 ${o}`))).join(`
308
308
  `);case"preview":return`
309
- `+Dn(`\u25A3 Preview \u2014 ${e.name}`)+`
310
-
311
- `+Ds(e.text,n);case"note":return`
312
- `+Wh[e.tone](En(js(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${_n(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
313
- `+(e.ok?ne.magenta("\u2736 "):ne.red("\u2736 "))+ne.gray(`Cooked for ${On(e.seconds)} \xB7 ${_n(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${Se(e.costUsd)}`:""))}}}function oc(e,t){return e.map(n=>Ns(n,t)).join(`
314
- `)}import{resolveActiveProfile as Bh,loadTokens as Hh,isExpired as qh,decodeJwtClaims as rc}from"document360-engine";function Vh(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Me(e,t){try{let n=Bh(e,t),o=Hh(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(qh(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={...rc(o.idToken)??{},...rc(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 ${Vh(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}import{existsSync as Os,readFileSync as Us}from"node:fs";import{isAbsolute as Qo,join as Jo,resolve as Zo}from"node:path";import O from"picocolors";function Ln(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 zo(e){if(e.length===0)return[];let t=(s,a)=>`${s}${"\u2500".repeat(78)}${a}`,n=(s="")=>`\u2502 ${s.padEnd(76)} \u2502`,o=[`\u2B06 d360-writer upgraded \u2014 ${e.length===1?"one improvement affects":`${e.length} improvements affect`} the docs you've already written:`,"",t("\u250C","\u2510")];e.forEach((s,a)=>{a>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let u of Ln(`${a+1}. ${s.feature}`,76))o.push(n(u));o.push(n());for(let u of Ln(s.why,73))o.push(n(` ${u}`));o.push(n())}),o.push(t("\u2514","\u2518")),o.push("");let r=e.length>1;return o.push(`\u2713 ${r?"These are":"This is"} now on your docs roadmap \u2014 each launch shows your next step below (/roadmap shows the full campaign).`),o}import{readProjectConfig as ln,screenshotPlaceholderIds as hc,DEFAULT_CAPTURE_DIR as er,DEFAULT_OUTPUT_DIR as Qh,DEFAULT_DOCS_DIR as Fs}from"document360-engine";import{createHash as Gh}from"node:crypto";import{readFileSync as Yh,writeFileSync as zh}from"node:fs";import{captureStatePath as ic}from"document360-engine";var sc={version:1,shots:{}};function ac(e){return Gh("sha1").update(e).digest("hex").slice(0,12)}function Mn(e){try{let t=JSON.parse(Yh(ic(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...sc,shots:{}}:{version:1,shots:t.shots}}catch{return{...sc,shots:{}}}}function Kh(e,t){zh(ic(e),`${JSON.stringify(t,null,2)}
315
- `,"utf8")}function Xh(e){return e&&/^\s*\/\/\s*CAPTURE-TODO:/m.test(e)?"testid":"data"}function lc(e,t,n){if(t.length===0)return;let o=Mn(e);for(let r of t){let s=r.specSource?ac(r.specSource):void 0;o.shots[r.id]={outcome:r.outcome,at:n,...r.reason?{reason:r.reason}:{},...r.outcome==="skipped"?{blockedBy:Xh(r.specSource??null)}:{},...s?{specHash:s}:{}}}Kh(e,o)}function Is(e,t,n){let o=e.shots[t];return!o||n===null||!o.specHash||o.specHash!==ac(n)?null:o}function cc(e){let t=Mn(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function _s(e,t,n){let o=Is(Mn(e),t,n);return o?.outcome==="failed"?o.reason??null:null}var fc=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function uc(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?fc(n):void 0,...t?{detail:!0}:{}}}function Un(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="checklist"||t==="setup")return{mode:"checklist"};if(t==="list")return uc(e.slice(1));t==="author"&&(e=e.slice(1));let n=!e.includes("--no-setup"),o=e.filter(s=>s!=="--no-setup");if(o[0]==="--list")return uc(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:fc(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function Ye(e,t){let n=ln(e),o=n?.captureDir??er,r=n?.outputDir??Qh,s=(u,h)=>Qo(u)?Jo(u,h):Zo(e,u,h),a=Mn(e);return hc(e,{scope:t}).map(({id:u,file:h})=>{let k=s(o,`${u}.spec.ts`),b=null;if(Os(k))try{b=Us(k,"utf8")}catch{}let x=Os(s(r,`${u}.png`)),$=b===null?null:Is(a,u,b),j=b!==null&&Jh(b),v=x?"captured":b===null?"placeholder":j||$?.outcome==="skipped"?"blocked":$?.outcome==="failed"?"broken":"spec",T=b===null?void 0:gc(b),E=j?Zh(b):$?.reason,U=j?"testid":$?.blockedBy;return{id:u,file:h,state:v,...T?{mutates:T.mutates,...T.declared?{}:{undeclared:!0}}:{},...v==="blocked"||v==="broken"?{...E?{reason:E}:{},...U?{blockedBy:U}:{}}:{}}})}function tr(e,t){let n=ln(e)?.captureDir??er,o=Qo(n)?Jo(n,`${t}.spec.ts`):Zo(e,n,`${t}.spec.ts`);try{return Us(o,"utf8")}catch{return null}}function mc(e,t){let n=ln(e)?.captureDir??er;return Os(Qo(n)?Jo(n,`${t}.spec.ts`):Zo(e,n,`${t}.spec.ts`))}function gc(e){let t=/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/im.exec(e);if(t)return{mutates:t[1].toLowerCase()==="mutates",declared:!0,what:t[2]?.trim()||void 0};let n=/setInputFiles/.test(e),o=/\{\s*name:\s*['"][^'"]*\b(create|import|save|apply|confirm|delete|submit|send|mint)\b[^'"]*['"][^}]*\}\s*\)\s*\.click\(/i.test(e),r=/\.fill\(/.test(e);return{mutates:n||r&&o,declared:!1}}function Jh(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function Zh(e){let t=/\/\/\s*CAPTURE-TODO:\s*(\{.*\})\s*$/m.exec(e),n,o;if(t)try{let s=JSON.parse(t[1]);n=s.testid,o=s.file}catch{}return`Inert until your developers add ${n?`data-testid="${n}"${o?` in ${o}`:""}`:"a stable data-testid"} \u2014 the spec is skipped at compile time, so no capture run can produce this shot. /screenshot checklist builds the hand-off.`}function yc(e,t){let n=ln(e)?.captureDir??er,o=Qo(n)?Jo(n,`${t}.spec.ts`):Zo(e,n,`${t}.spec.ts`);try{return gc(Us(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}function nr(e){return[...new Set(e.filter(t=>t.state==="captured").map(t=>t.file))].sort()}var ef={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF"},tf={placeholder:O.gray,spec:O.yellow,blocked:O.cyan,broken:O.red,captured:O.green},wc=` ${O.green("\u25CF captured")} ${O.yellow("\u25D0 ready")} ${O.cyan("\u2298 blocked")} ${O.red("\u2717 broken")} ${O.gray("\u25CB to spec")}`;function Ws(e){let t=new Map;for(let n of e){if(n.state!=="blocked")continue;let o=(n.reason??"No reason recorded \u2014 re-run this capture to find out why.").replace(/\s+/g," ").trim(),r=n.blockedBy??"data",s=`${r}\0${o}`,a=t.get(s)??{reason:o,blockedBy:r,ids:[]};t.has(s)||t.set(s,a),a.ids.push(n.id)}return[...t.values()].sort((n,o)=>o.ids.length-n.ids.length||n.reason.localeCompare(o.reason))}function kc(e){let t=Ws(e);if(t.length===0)return[];let n=t.filter(s=>s.blockedBy==="data"),o=t.filter(s=>s.blockedBy==="testid"),r=[""];if(n.length>0){let s=n.reduce((u,h)=>u+h.ids.length,0);r.push(` ${O.bold("Stage this data")} ${O.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let a=8;for(let u of n.slice(0,a)){let h=Ln(u.reason,86);r.push(` ${O.cyan(ft(`${u.ids.length}\xD7`,4))} ${h[0]??""}`);for(let b of h.slice(1))r.push(` ${b}`);let k=u.ids.slice(0,4).join(" \xB7 ");r.push(O.gray(` ${k}${u.ids.length>4?` \xB7 +${u.ids.length-4} more`:""}`))}n.length>a&&r.push(O.gray(` \u2026 ${n.length-a} more staging action${n.length-a===1?"":"s"} \u2014 /screenshot list --detail`))}if(o.length>0){let s=o.reduce((a,u)=>a+u.ids.length,0);r.push(` ${O.cyan("\u2298")} ${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${O.bold("/screenshot checklist")} builds the hand-off.`)}return r}function bc(e){let t=e.filter(o=>o.undeclared);if(t.length===0)return[];let n=t.filter(o=>o.mutates);return["",` ${O.yellow("\u26A0")} ${t.length} spec${t.length===1?"":"s"} carr${t.length===1?"ies":"y"} no CAPTURE-SAFETY declaration`+(n.length>0?O.gray(` \u2014 ${n.length} of them read as "writes real data" by heuristic, so bulk capture benches ${n.length===1?"it":"them"}`):""),O.gray(` ${t.slice(0,6).map(o=>o.id).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),O.gray(` Re-author them to declare it: ${O.bold("/screenshot author <id>")}`)]}var Ko=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),ft=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function $c(e,t){let n=e.replace(/\\/g,"/"),o=t.replace(/\\/g,"/").replace(/\/+$/,"");o&&(n===o||n.startsWith(`${o}/`))&&(n=n.slice(o.length+1));let r=n.split("/").filter(Boolean);return r.length>1?r[0]:""}var nf=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),of=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function rf(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return of.has(r)?r.toUpperCase():o>0&&nf.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function Ls(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:rf(t?t[2]:e)}}function sf(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function dc(e,t,n){let o=t>0?Math.round(e/t*n):0;return O.green("\u2588".repeat(o))+O.gray("\u2591".repeat(Math.max(0,n-o)))}function af(e,t){let n=t>0?Math.round(e/t*100):0,o=ft(`${n}%`,4);return n===100?O.green(o):n>0?O.yellow(o):O.gray(o)}function xc(e,t){let n=new Map;for(let o of e){let r=$c(o.file,t),s=n.get(r)??[];n.has(r)||n.set(r,s),s.push(o)}return[...n.keys()].sort().map(o=>[o,n.get(o)])}function lf(e,t){let n=(L,V)=>L.filter(q=>q.state===V).length,o=e.length,r=n(e,"captured"),s=n(e,"spec"),a=n(e,"blocked"),u=n(e,"broken"),h=n(e,"placeholder"),k=new Set(e.map(L=>L.file)).size,b=xc(e,t),x=[];x.push(` ${O.bold("Screenshots")} ${O.green(`${r}/${o} captured`)} ${O.gray("\xB7")} ${s>0?O.yellow(`${s} ready`):O.gray("0 ready")}`+(a>0?` ${O.gray("\xB7")} ${O.cyan(`${a} blocked`)}`:"")+(u>0?` ${O.gray("\xB7")} ${O.red(`${u} broken`)}`:"")+` ${O.gray("\xB7")} ${h>0?O.red(`${h} to spec`):O.gray("0 to spec")} `+O.gray(`across ${k} article${k===1?"":"s"}`));let $=o>0?Math.round(r/o*100):0;x.push(` [${dc(r,o,32)}] ${O.bold(`${$}%`)}`),x.push("");let j=b.map(([L])=>Ls(L)),v=Math.min(32,Math.max(7,...j.map(L=>L.name.length))),T=L=>L.length>v?`${L.slice(0,v-1)}\u2026`:Ko(L,v),E=[{head:"Ready",w:5,state:"spec",color:O.yellow},...a>0?[{head:"Blocked",w:7,state:"blocked",color:O.cyan}]:[],...u>0?[{head:"Broken",w:6,state:"broken",color:O.red}]:[],{head:"To spec",w:7,state:"placeholder",color:O.red}];x.push(O.gray(` ${Ko("#",2)} ${Ko("Chapter",v)} ${ft("Shots",6)} ${E.map(L=>ft(L.head,L.w)).join(" ")} Progress`));for(let[L,[,V]]of b.entries()){let q=n(V,"captured"),re=V.length,{num:We,name:fe}=j[L],Ke=q===re,me=T(fe),Xe=E.map(be=>{let Be=n(V,be.state);return Be>0?be.color(ft(String(Be),be.w)):O.gray(ft("\u2014",be.w))}).join(" ");x.push(` ${O.cyan(Ko(We,2))} ${Ke?O.green(me):q>0?me:O.gray(me)} ${Ke?O.green(ft(`${q}/${re}`,6)):ft(`${q}/${re}`,6)} ${Xe} ${dc(q,re,10)} ${af(q,re)}`)}x.push("");let U=u>0?` ${O.gray("\xB7")} ${u} spec${u===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(L=>L.state==="broken").id}`)} re-authors ${u===1?"it":"the first"}`:"";if(h>0)x.push(` ${O.yellow("\u2192")} ${h} placeholder${h===1?"":"s"} still need a spec \u2014 run ${O.bold("/screenshot author --all")}${U}`);else if(s>0){let L=e.filter(q=>q.state==="spec"&&q.mutates).length,V=L>0?O.gray(` \u2014 ${s-L} in one go; ${L} write${L===1?"s":""} real data and run${L===1?"s":""} one at a time`):"";x.push(` ${O.yellow("\u2192")} ${s} spec${s===1?"":"s"} ready to capture \u2014 run ${O.bold("/screenshot capture")}${V}${U}`)}else a>0?x.push(` ${O.cyan("\u2192")} ${a} shot${a===1?"":"s"} blocked \u2014 stage the data below, then ${O.bold("/screenshot capture --all --retry-blocked")}${U}`):u>0?x.push(` ${O.red("\u2192")} ${u} spec${u===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(L=>L.state==="broken").id}`)} re-authors ${u===1?"it":"the first"} (re-capturing fails the same way)`):x.push(` ${O.green("\u2713")} all ${o} captured \u2014 ${O.bold("/publish")} embeds them in the articles`);if(r>0&&r<o){let L=b.filter(([,V])=>V.every(q=>q.state!=="captured")).map(([V])=>{let{num:q,name:re}=Ls(V);return q?`${q} ${re}`:re});L.length>0&&x.push(O.gray(` Furthest behind: ${L.slice(0,5).join(" \xB7 ")}${L.length>5?" \u2026":""} (0% captured)`))}return x.push(...kc(e),...bc(e)),x.push(""),x.push(wc),x.push(O.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),x}function cf(e,t,n){let o=new Set(e.map(a=>a.file)),r=e.filter(a=>a.state==="captured").length,s=[` ${O.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${O.green(`${r} captured`)}${n?O.gray(` \xB7 scope ${n}`):""}`,""];for(let[a,u]of xc(e,t)){let h=u.filter(j=>j.state==="captured").length,{num:k,name:b}=Ls(a),x=k?`${k} \xB7 ${b}`:b;s.push(` ${O.bold(x)} ${O.gray(`(${h}/${u.length})`)}`);let $=new Map;for(let j of u){let v=sf(j.file),T=$.get(v)??[];$.has(v)||$.set(v,T),T.push(j)}for(let j of[...$.keys()].sort()){s.push(O.gray(` ${j}`));for(let v of $.get(j)){let T=tf[v.state];if(s.push(` ${T(ef[v.state])} ${T(v.id)}`),(v.state==="blocked"||v.state==="broken")&&v.reason)for(let E of Ln(v.reason,84))s.push(O.gray(` ${E}`))}}}return s.push(...kc(e),...bc(e)),s.push("",wc),s}function or(e,t){let n=t?.scope;if(e.length===0)return[n?`No screenshot placeholders under ${n}.`:"No screenshot placeholders found in the docs."];let o=t?.docsDir??Fs;return t?.detail||n?cf(e,o,n):lf(e,o)}function Bs(e,t){if(!t||!/^\d+$/.test(t))return t;let n=ln(e)?.docsDir??Fs,o=String(Number(t));for(let{file:r}of hc(e)){let s=$c(r,n),a=/^(\d+)/.exec(s);if(a&&String(Number(a[1]))===o)return s}return t}function uf(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function Xo(e,t,n){let o=new Map;for(let s of t){let{category:a,article:u}=uf(s.file),h=o.get(a)??new Map;o.set(a,h);let k=h.get(u)??[];h.set(u,k),k.push(s)}let r=s=>n==="author"||!s.mutates;for(let s of[...o.keys()].sort()){let a=o.get(s),u=[...a.values()].flat().filter(r).map(h=>h.id);u.length>0&&e.push({kind:"category",action:n,label:`${s} (${u.length})`,ids:u,depth:1});for(let h of[...a.keys()].sort()){let k=a.get(h),b=k.filter(r).map(x=>x.id);b.length>0&&e.push({kind:"article",action:n,label:`${h} (${b.length})`,ids:b,depth:2});for(let x of k){let $=n==="capture"&&x.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:x.id,ids:[x.id],depth:3,...$?{note:$}:{}})}}}}function pc(e,t=58){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function Hs(e,t,n){let o=t.filter(r=>!r.mutates);o.length>1&&e.push({kind:"all",action:"capture",label:`Retry ${o.length} blocked shots (stage the data first)`,ids:o.map(r=>r.id),depth:0});for(let r of[...t].sort((s,a)=>s.id.localeCompare(a.id)))e.push({kind:"shot",action:"capture",label:r.id,ids:[r.id],depth:1,note:` \u2298 ${pc(r.reason)}`});n.length>1&&e.push({kind:"all",action:"author",label:`Re-author ${n.length} broken specs`,ids:n.map(r=>r.id),depth:0});for(let r of[...n].sort((s,a)=>s.id.localeCompare(a.id)))e.push({kind:"shot",action:"author",label:r.id,ids:[r.id],depth:1,note:` \u2717 ${pc(r.reason)} \u2014 re-authors`})}function vc(e){let t=e.filter(s=>s.state==="placeholder"),n=e.filter(s=>s.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(s=>s.id),depth:0}),Xo(o,t,"author");let r=n.filter(s=>!s.mutates);return r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),Xo(o,n,"capture"),Hs(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken")),o}var Ms="MANDATORY, check before you finish: every spec you write or touch must carry exactly one `// CAPTURE-SAFETY: readonly` or `// CAPTURE-SAFETY: mutates \u2014 <what it creates>; cleanup: <how>` line at the top. Re-read each file you wrote and add it if missing \u2014 a spec without it is classified by guesswork. A fail-by-design spec (the app rejects the input) is `readonly`.";function Cc(e,t){let n=e.paths.filter(o=>t?.get(o));return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(o=>`- ${o}`).join(`
316
- `),"",...n.length>0?["REPAIR \u2014 these already have a spec, and it FAILED its last capture. Read the existing spec","first and fix the named failure specifically; do not re-emit the same locator and hope. A",'"strict mode violation" means the locator matched 2+ elements (scope it to a stable container',"or take .first()); a click timeout means the element was absent or unreachable (if the data","simply is not staged, the spec must test.skip with a reason naming what to stage, not time out).",...n.map(o=>`- ${o}: ${t.get(o).replace(/\s+/g," ").trim()}`),""]:[],"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.",Ms].join(`
317
- `)}async function rr(e,t,n){let o=Un(e);if(o.mode==="list"){let u=t?.cwd??process.cwd(),h=Bs(u,o.scope),k=ln(u)?.docsDir??Fs,b=Ye(u,h);for(let x of or(b,{scope:h,detail:o.detail,docsDir:k}))console.log(x);return{kind:"continue"}}if(o.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${o.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>/${o.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.",Ms,...n?.lastFailure?["","REPAIR \u2014 the existing spec FAILED its last capture with:",n.lastFailure,'Read the existing spec first and fix that failure specifically. A "strict mode violation" means the',"locator matched 2+ elements \u2014 scope it to a stable container or take .first(); a click timeout means","the element was absent or unreachable \u2014 if that's because the data isn't staged, the spec must","test.skip with a reason naming what to stage, not time out. Re-verify every selector you keep","against the product source; do not re-emit the same locator and hope."]:[]].join(`
318
- `),display:`/screenshot ${o.id}`};if(o.mode==="capture"||o.mode==="checklist")return{kind:"continue"};let s=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${o.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${o.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.${o.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`,Ms].join(`
319
- `),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:s,display:a}}var Fn=3;function qs(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, normalize cross-article links). For each <!-- SCREENSHOT ... --> block, read its id BEFORE stripping the block: when <outputDir>/<id>.png exists (the annotated capture), upload it (d360_search_drive first to reuse, else d360_upload_drive_file) and replace the visible [Screenshot: ...] line with the image markdown; only when no PNG exists does the visible line stay as text.","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself \u2014 do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
320
- `)}var Rc={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Vs(e){return e.filter(t=>t.path!==null&&t.status in Rc&&!t.link).map(t=>({path:t.path,label:Rc[t.status]}))}function ir(e){let t=Vs(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 ar(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 lr(e){return e.filter(t=>t.link).length}function Gs(e,t){try{let n=wf(e,kf(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=bf(df(pf(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 $f(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 Ac(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let s=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),a=o.get(s);a?a.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((a,u)=>a.path.localeCompare(u.path));n.push({kind:"category",label:`${$f(r)} (${s.length})`,paths:s.map(a=>a.path),indent:!1});for(let a of s){let u=a.path.replace(/\\/g,"/").split("/").pop()??a.path;n.push({kind:"article",label:u,paths:[a.path],indent:!0,note:a.label})}}for(let r of[...t].sort((s,a)=>s.path.localeCompare(a.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function Wn(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(`
321
- `)}function Ys(e,t,n){let o=$=>t[$.index]?.paths.length??0,r=e.filter($=>$.ok),s=e.filter($=>!$.ok),a=e.reduce(($,j)=>$+o(j),0),u=r.reduce(($,j)=>$+o(j),0),h=n==="api"?`${Se(e.reduce(($,j)=>$+j.costUsd,0))} total`:ht(e.reduce(($,j)=>$+j.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,b=$=>`${$} article${$===1?"":"s"}`,x=[];if(s.length===0)x.push(`Published ${b(a)} (${k}) successfully \xB7 ${h}.`),x.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{x.push(`Published ${u}/${b(a)} (${k}) \xB7 ${h}.`),x.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let $ of s)x.push(` \u2717 ${$.label}${$.error?` \u2014 ${$.error}`:""}`)}return x}async function mt(e,t){let{model:n}=gf(e.cwd,"standard"),o=async(r,s)=>{let a=ff(r);console.log(g(s?`Resolving cross-links in ${r.length} article${r.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${r.length} article${r.length===1?"":"s"} across ${a.length} partition${a.length===1?"":"s"} (\u2264${Fn} agents at once) on ${n}\u2026`)),s||console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let u=!1;for await(let h of yf({cwd:e.cwd,partitions:a,promptFor:k=>Wn(k.paths),concurrency:Fn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(h.type==="partition_status")h.status==="running"?console.log(g(` \u25B8 ${h.label} \u2014 publishing\u2026`)):h.status==="done"?console.log(_(` \u2713 ${h.label}`)):console.log(S(` \u2717 ${h.label}`));else if(h.type==="run_done"){u=h.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let x of Ys(h.results,a,k))console.log(h.ok?_(x):B(x));let b=Gs(e.cwd,e.profileName);b&&console.log(g(b));try{let x=Pc(await Sc({cwd:e.cwd,profileName:e.profileName}));x&&console.log(g(x))}catch{}try{let x=Dc(await Tc({cwd:e.cwd,profileName:e.profileName}));x&&console.log(g(x))}catch{}}return u};try{if(!await o(t,!1)){let s=await zs(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(S(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function cr(e,t,n){let o=mf(e,n);if(o.length===0)return[];let r=new Set(Vs((await sr({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function zs(e,t,n){try{let o=new Set(n),r=await sr({cwd:e,profileName:t});return Vs(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function Ec(e,t){let n=Me(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(S(n.reason)),{kind:"continue"};let o=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let r=t?.cwd??process.cwd(),s=nr(Ye(r));return s.length===0?(console.log(g("No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}):t?await mt(t,s):{kind:"forward-to-agent",prompt:Wn(s),display:"/publish --screenshots"}}if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await cr(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(_("\u2713 All related articles are already published.")),{kind:"continue"}):await mt(t,r)}if(o==="--all"){console.log(g("Checking what needs publishing\u2026"));try{let r=await sr({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:a}=ir(r.entries),u=lr(r.entries),h=e.includes("--force")&&a.length>0;u>0&&console.log(B(`\u26A0 ${u} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),a.length>0&&!h&&console.log(B(ar(a.length)));let k=h?[...s,...a]:s;if(k.length===0){if(a.length>0)return console.log(g("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(_(u>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let b=Pc(await Sc({cwd:t.cwd,profileName:t.profileName}));b&&console.log(g(b));let x=Dc(await Tc({cwd:t.cwd,profileName:t.profileName}));x&&console.log(g(x))}catch{}return{kind:"continue"}}return t?await mt(t,k.map(b=>b.path)):{kind:"forward-to-agent",prompt:Wn(k.map(b=>b.path)),display:"/publish --all"}}catch(r){return console.log(S(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(g("Checking what needs publishing\u2026"));let r;try{let s=await sr({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:u}=ir(s.entries);r=a;let h=lr(s.entries);if(h>0&&console.log(B(`\u26A0 ${h} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),u.length>0&&console.log(B(ar(u.length))),r.length===0&&u.length>0)return console.log(g("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(S(`Could not compute sync status: ${s.message}`)),console.log(g("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(_("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(g(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${g(`(${s.label})`)}`);return console.log(g("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>hf({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}if(o==="--all")return await mt(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:qs(o),display:`/publish ${o}`}}async function Bn(){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(`
322
- `),display:"/audit"}}Y();import{readProjectConfig as xf}from"document360-engine";function Ks(){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(`
323
- `)}async function jc(e,t){let n=t?.cwd??process.cwd();return xf(n)?{kind:"forward-to-agent",prompt:Ks(),display:"/discover"}:(console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"})}Y();import{checkbox as vf}from"@inquirer/prompts";import{inventoryRepo as Cf,readProjectConfig as Nc,writeProjectConfig as Rf}from"document360-engine";function Xs(e,t){let n=Nc(e);n&&(n.authoritativeSourceFiles=t,Rf(n,e))}function ur(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 Ic(e,t){let n=t?.cwd??process.cwd();if(!Nc(n))return console.log(S("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Cf(n);if(o.length===0)return console.log(g('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(F("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${g(ur(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>vf({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${ur(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(g("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};Xs(n,r),console.log(_(`\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"}}Y();import{confirm as _f}from"@inquirer/prompts";import{applyPull as Zs,computeSyncStatus as Hc,compareRemoteSources as Of,planPull as qc,planImport as Lf,applyImport as Mf,establishBaselines as Uf,rebaselineServerMeta as Ff,D360AuthError as Wf}from"document360-engine";Y();var _c=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:S,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:B,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:F,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:S,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:S,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ue,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:g,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:g,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:ue,mark:"\xB7"}];function Sf(e){return e.path?e.path:`${e.title??"(untitled)"} ${ue(`[${e.articleId}]`)}`}function Pf(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 dr(e,t){let n=[],o=e.entries.filter(b=>b.link);if(o.length>0){n.push(""),n.push(Re("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let b of o)n.push(` ${B("~")} ${B(b.path??"")} ${ue(`\u2192 "${b.link.title}"`)}`)}for(let b of _c){let x=e.entries.filter($=>$.status===b.status&&!(b.status==="untracked-local"&&$.link));if(x.length!==0){n.push(""),n.push(Re(b.header));for(let $ of x)n.push(` ${b.paint(b.mark)} ${b.paint(Sf($))}${$.detail?ue(` (${$.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let a={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},u=o.length,h=s===r?_("\u2713 everything up to date"):[r>0?_(`\u2713 ${r} up to date`):null,u>0?`${u} to link`:null,..._c.map(b=>{let x=(e.counts[b.status]??0)-(b.status==="untracked-local"?u:0);return x>0?`${x} ${a[b.status]}`:null})].filter(Boolean).join(ue(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${Pf(t)}`:"";return n.push(h+ue(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as Tf}from"diff";import Oc from"picocolors";var Lc=80,Df="\x1B[48;2;74;28;28m",Af="\x1B[48;2;24;66;24m",Mc="\x1B[49m",Qs=e=>String(e).padStart(5);function Uc(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function Fc(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 ot(e,t,n){let o=$=>{let j=$.replace(/\r\n/g,`
309
+ `+En(`\u25A3 Preview \u2014 ${e.name}`)+`
310
+
311
+ `+As(e.text,n);case"note":return`
312
+ `+Hh[e.tone](Nn(Ns(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${Ln(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
313
+ `+(e.ok?ne.magenta("\u2736 "):ne.red("\u2736 "))+ne.gray(`Cooked for ${Mn(e.seconds)} \xB7 ${Ln(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${Se(e.costUsd)}`:""))}}}function sc(e,t){return e.map(n=>Is(n,t)).join(`
314
+ `)}import{resolveActiveProfile as qh,loadTokens as Vh,isExpired as Gh,decodeJwtClaims as ic}from"document360-engine";function Yh(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Me(e,t){try{let n=qh(e,t),o=Vh(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Gh(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={...ic(o.idToken)??{},...ic(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 ${Yh(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}import{existsSync as Ls,readFileSync as Fs}from"node:fs";import{isAbsolute as Jo,join as Zo,resolve as er}from"node:path";import O from"picocolors";function Un(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 Ko(e){if(e.length===0)return[];let t=(s,a)=>`${s}${"\u2500".repeat(78)}${a}`,n=(s="")=>`\u2502 ${s.padEnd(76)} \u2502`,o=[`\u2B06 d360-writer upgraded \u2014 ${e.length===1?"one improvement affects":`${e.length} improvements affect`} the docs you've already written:`,"",t("\u250C","\u2510")];e.forEach((s,a)=>{a>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let u of Un(`${a+1}. ${s.feature}`,76))o.push(n(u));o.push(n());for(let u of Un(s.why,73))o.push(n(` ${u}`));o.push(n())}),o.push(t("\u2514","\u2518")),o.push("");let r=e.length>1;return o.push(`\u2713 ${r?"These are":"This is"} now on your docs roadmap \u2014 each launch shows your next step below (/roadmap shows the full campaign).`),o}import{readProjectConfig as cn,screenshotPlaceholderIds as mc,DEFAULT_CAPTURE_DIR as tr,DEFAULT_OUTPUT_DIR as Zh,DEFAULT_DOCS_DIR as Ws}from"document360-engine";import{createHash as zh}from"node:crypto";import{readFileSync as Kh,writeFileSync as Xh}from"node:fs";import{captureStatePath as lc}from"document360-engine";var ac={version:1,shots:{}};function cc(e){return zh("sha1").update(e).digest("hex").slice(0,12)}function Fn(e){try{let t=JSON.parse(Kh(lc(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...ac,shots:{}}:{version:1,shots:t.shots}}catch{return{...ac,shots:{}}}}function Qh(e,t){Xh(lc(e),`${JSON.stringify(t,null,2)}
315
+ `,"utf8")}function Jh(e){return e&&/^\s*\/\/\s*CAPTURE-TODO:/m.test(e)?"testid":"data"}function uc(e,t,n){if(t.length===0)return;let o=Fn(e);for(let r of t){let s=r.specSource?cc(r.specSource):void 0;o.shots[r.id]={outcome:r.outcome,at:n,...r.reason?{reason:r.reason}:{},...r.outcome==="skipped"?{blockedBy:Jh(r.specSource??null)}:{},...s?{specHash:s}:{}}}Qh(e,o)}function _s(e,t,n){let o=e.shots[t];return!o||n===null||!o.specHash||o.specHash!==cc(n)?null:o}function dc(e){let t=Fn(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function Os(e,t,n){let o=_s(Fn(e),t,n);return o?.outcome==="failed"?o.reason??null:null}var gc=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function pc(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?gc(n):void 0,...t?{detail:!0}:{}}}function Wn(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="checklist"||t==="setup")return{mode:"checklist"};if(t==="list")return pc(e.slice(1));t==="author"&&(e=e.slice(1));let n=!e.includes("--no-setup"),o=e.filter(s=>s!=="--no-setup");if(o[0]==="--list")return pc(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:gc(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function Ye(e,t){let n=cn(e),o=n?.captureDir??tr,r=n?.outputDir??Zh,s=(u,h)=>Jo(u)?Zo(u,h):er(e,u,h),a=Fn(e);return mc(e,{scope:t}).map(({id:u,file:h})=>{let k=s(o,`${u}.spec.ts`),b=null;if(Ls(k))try{b=Fs(k,"utf8")}catch{}let x=Ls(s(r,`${u}.png`)),$=b===null?null:_s(a,u,b),j=b!==null&&ef(b),v=x?"captured":b===null?"placeholder":j||$?.outcome==="skipped"?"blocked":$?.outcome==="failed"?"broken":"spec",T=b===null?void 0:wc(b),E=j?tf(b):$?.reason,U=j?"testid":$?.blockedBy;return{id:u,file:h,state:v,...T?{mutates:T.mutates,...T.declared?{}:{undeclared:!0}}:{},...v==="blocked"||v==="broken"?{...E?{reason:E}:{},...U?{blockedBy:U}:{}}:{}}})}function nr(e,t){let n=cn(e)?.captureDir??tr,o=Jo(n)?Zo(n,`${t}.spec.ts`):er(e,n,`${t}.spec.ts`);try{return Fs(o,"utf8")}catch{return null}}function yc(e,t){let n=cn(e)?.captureDir??tr;return Ls(Jo(n)?Zo(n,`${t}.spec.ts`):er(e,n,`${t}.spec.ts`))}function wc(e){let t=/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/im.exec(e);if(t)return{mutates:t[1].toLowerCase()==="mutates",declared:!0,what:t[2]?.trim()||void 0};let n=/setInputFiles/.test(e),o=/\{\s*name:\s*['"][^'"]*\b(create|import|save|apply|confirm|delete|submit|send|mint)\b[^'"]*['"][^}]*\}\s*\)\s*\.click\(/i.test(e),r=/\.fill\(/.test(e);return{mutates:n||r&&o,declared:!1}}function ef(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function tf(e){let t=/\/\/\s*CAPTURE-TODO:\s*(\{.*\})\s*$/m.exec(e),n,o;if(t)try{let s=JSON.parse(t[1]);n=s.testid,o=s.file}catch{}return`Inert until your developers add ${n?`data-testid="${n}"${o?` in ${o}`:""}`:"a stable data-testid"} \u2014 the spec is skipped at compile time, so no capture run can produce this shot. /screenshot checklist builds the hand-off.`}function kc(e,t){let n=cn(e)?.captureDir??tr,o=Jo(n)?Zo(n,`${t}.spec.ts`):er(e,n,`${t}.spec.ts`);try{return wc(Fs(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}function or(e){return[...new Set(e.filter(t=>t.state==="captured").map(t=>t.file))].sort()}var nf={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF"},of={placeholder:O.gray,spec:O.yellow,blocked:O.cyan,broken:O.red,captured:O.green},bc=` ${O.green("\u25CF captured")} ${O.yellow("\u25D0 ready")} ${O.cyan("\u2298 blocked")} ${O.red("\u2717 broken")} ${O.gray("\u25CB to spec")}`;function mt(e,t=n=>n){return`${t(e)} `}function Bs(e){let t=new Map;for(let n of e){if(n.state!=="blocked")continue;let o=(n.reason??"No reason recorded \u2014 re-run this capture to find out why.").replace(/\s+/g," ").trim(),r=n.blockedBy??"data",s=`${r}\0${o}`,a=t.get(s)??{reason:o,blockedBy:r,ids:[]};t.has(s)||t.set(s,a),a.ids.push(n.id)}return[...t.values()].sort((n,o)=>o.ids.length-n.ids.length||n.reason.localeCompare(o.reason))}function $c(e){let t=Bs(e);if(t.length===0)return[];let n=t.filter(s=>s.blockedBy==="data"),o=t.filter(s=>s.blockedBy==="testid"),r=[""];if(n.length>0){let s=n.reduce((u,h)=>u+h.ids.length,0);r.push(` ${O.bold("Stage this data")} ${O.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let a=8;for(let u of n.slice(0,a)){let h=Un(u.reason,86);r.push(` ${O.cyan(ft(`${u.ids.length}\xD7`,4))} ${h[0]??""}`);for(let b of h.slice(1))r.push(` ${b}`);let k=u.ids.slice(0,4).join(" \xB7 ");r.push(O.gray(` ${k}${u.ids.length>4?` \xB7 +${u.ids.length-4} more`:""}`))}n.length>a&&r.push(O.gray(` \u2026 ${n.length-a} more staging action${n.length-a===1?"":"s"} \u2014 /screenshot list --detail`))}if(o.length>0){let s=o.reduce((a,u)=>a+u.ids.length,0);r.push(` ${mt("\u2298",O.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${O.bold("/screenshot checklist")} builds the hand-off.`)}return r}function xc(e){let t=e.filter(o=>o.undeclared);if(t.length===0)return[];let n=t.filter(o=>o.mutates);return["",` ${mt("\u26A0",O.yellow)}${t.length} spec${t.length===1?"":"s"} carr${t.length===1?"ies":"y"} no CAPTURE-SAFETY declaration`+(n.length>0?O.gray(` \u2014 ${n.length} of them read as "writes real data" by heuristic, so bulk capture benches ${n.length===1?"it":"them"}`):""),O.gray(` ${t.slice(0,6).map(o=>o.id).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),O.gray(` Re-author them to declare it: ${O.bold("/screenshot author <id>")}`)]}var Xo=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),ft=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function vc(e,t){let n=e.replace(/\\/g,"/"),o=t.replace(/\\/g,"/").replace(/\/+$/,"");o&&(n===o||n.startsWith(`${o}/`))&&(n=n.slice(o.length+1));let r=n.split("/").filter(Boolean);return r.length>1?r[0]:""}var rf=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),sf=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function af(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return sf.has(r)?r.toUpperCase():o>0&&rf.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function Ms(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:af(t?t[2]:e)}}function lf(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function hc(e,t,n){let o=t>0?Math.round(e/t*n):0;return O.green("\u2588".repeat(o))+O.gray("\u2591".repeat(Math.max(0,n-o)))}function cf(e,t){let n=t>0?Math.round(e/t*100):0,o=ft(`${n}%`,4);return n===100?O.green(o):n>0?O.yellow(o):O.gray(o)}function Cc(e,t){let n=new Map;for(let o of e){let r=vc(o.file,t),s=n.get(r)??[];n.has(r)||n.set(r,s),s.push(o)}return[...n.keys()].sort().map(o=>[o,n.get(o)])}function uf(e,t){let n=(L,V)=>L.filter(q=>q.state===V).length,o=e.length,r=n(e,"captured"),s=n(e,"spec"),a=n(e,"blocked"),u=n(e,"broken"),h=n(e,"placeholder"),k=new Set(e.map(L=>L.file)).size,b=Cc(e,t),x=[];x.push(` ${O.bold("Screenshots")} ${O.green(`${r}/${o} captured`)} ${O.gray("\xB7")} ${s>0?O.yellow(`${s} ready`):O.gray("0 ready")}`+(a>0?` ${O.gray("\xB7")} ${O.cyan(`${a} blocked`)}`:"")+(u>0?` ${O.gray("\xB7")} ${O.red(`${u} broken`)}`:"")+` ${O.gray("\xB7")} ${h>0?O.red(`${h} to spec`):O.gray("0 to spec")} `+O.gray(`across ${k} article${k===1?"":"s"}`));let $=o>0?Math.round(r/o*100):0;x.push(` [${hc(r,o,32)}] ${O.bold(`${$}%`)}`),x.push("");let j=b.map(([L])=>Ms(L)),v=Math.min(32,Math.max(7,...j.map(L=>L.name.length))),T=L=>L.length>v?`${L.slice(0,v-1)}\u2026`:Xo(L,v),E=[{head:"Ready",w:5,state:"spec",color:O.yellow},...a>0?[{head:"Blocked",w:7,state:"blocked",color:O.cyan}]:[],...u>0?[{head:"Broken",w:6,state:"broken",color:O.red}]:[],{head:"To spec",w:7,state:"placeholder",color:O.red}];x.push(O.gray(` ${Xo("#",2)} ${Xo("Chapter",v)} ${ft("Captured",8)} ${E.map(L=>ft(L.head,L.w)).join(" ")} Progress`));for(let[L,[,V]]of b.entries()){let q=n(V,"captured"),re=V.length,{num:We,name:fe}=j[L],Ke=q===re,me=T(fe),Xe=E.map(be=>{let Be=n(V,be.state);return Be>0?be.color(ft(String(Be),be.w)):O.gray(ft("\u2014",be.w))}).join(" ");x.push(` ${O.cyan(Xo(We,2))} ${Ke?O.green(me):q>0?me:O.gray(me)} ${Ke?O.green(ft(`${q}/${re}`,8)):ft(`${q}/${re}`,8)} ${Xe} ${hc(q,re,10)} ${cf(q,re)}`)}x.push("");let U=u>0?` ${O.gray("\xB7")} ${u} spec${u===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(L=>L.state==="broken").id}`)} re-authors ${u===1?"it":"the first"}`:"";if(h>0)x.push(` ${mt("\u2192",O.yellow)}${h} placeholder${h===1?"":"s"} still need a spec \u2014 run ${O.bold("/screenshot author --all")}${U}`);else if(s>0){let L=e.filter(q=>q.state==="spec"&&q.mutates).length,V=L>0?O.gray(` \u2014 ${s-L} in one go; ${L} write${L===1?"s":""} real data and run${L===1?"s":""} one at a time`):"";x.push(` ${mt("\u2192",O.yellow)}${s} spec${s===1?"":"s"} ready to capture \u2014 run ${O.bold("/screenshot capture")}${V}${U}`)}else a>0?x.push(` ${mt("\u2192",O.cyan)}${a} shot${a===1?"":"s"} blocked \u2014 stage the data below, then ${O.bold("/screenshot capture --all --retry-blocked")}${U}`):u>0?x.push(` ${mt("\u2192",O.red)}${u} spec${u===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(L=>L.state==="broken").id}`)} re-authors ${u===1?"it":"the first"} (re-capturing fails the same way)`):x.push(` ${mt("\u2713",O.green)}all ${o} captured \u2014 ${O.bold("/publish")} embeds them in the articles`);if(r>0&&r<o){let L=b.filter(([,V])=>V.every(q=>q.state!=="captured")).map(([V])=>{let{num:q,name:re}=Ms(V);return q?`${q} ${re}`:re});L.length>0&&x.push(O.gray(` Furthest behind: ${L.slice(0,5).join(" \xB7 ")}${L.length>5?" \u2026":""} (0% captured)`))}return x.push(...$c(e),...xc(e)),x.push(""),x.push(bc),x.push(O.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),x}function df(e,t,n){let o=new Set(e.map(a=>a.file)),r=e.filter(a=>a.state==="captured").length,s=[` ${O.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${O.green(`${r} captured`)}${n?O.gray(` \xB7 scope ${n}`):""}`,""];for(let[a,u]of Cc(e,t)){let h=u.filter(j=>j.state==="captured").length,{num:k,name:b}=Ms(a),x=k?`${k} \xB7 ${b}`:b;s.push(` ${O.bold(x)} ${O.gray(`(${h}/${u.length})`)}`);let $=new Map;for(let j of u){let v=lf(j.file),T=$.get(v)??[];$.has(v)||$.set(v,T),T.push(j)}for(let j of[...$.keys()].sort()){s.push(O.gray(` ${j}`));for(let v of $.get(j)){let T=of[v.state];if(s.push(` ${mt(nf[v.state],T)}${T(v.id)}`),(v.state==="blocked"||v.state==="broken")&&v.reason)for(let E of Un(v.reason,84))s.push(O.gray(` ${E}`))}}}return s.push(...$c(e),...xc(e)),s.push("",bc),s}function rr(e,t){let n=t?.scope;if(e.length===0)return[n?`No screenshot placeholders under ${n}.`:"No screenshot placeholders found in the docs."];let o=t?.docsDir??Ws;return t?.detail||n?df(e,o,n):uf(e,o)}function Hs(e,t){if(!t||!/^\d+$/.test(t))return t;let n=cn(e)?.docsDir??Ws,o=String(Number(t));for(let{file:r}of mc(e)){let s=vc(r,n),a=/^(\d+)/.exec(s);if(a&&String(Number(a[1]))===o)return s}return t}function pf(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function Qo(e,t,n){let o=new Map;for(let s of t){let{category:a,article:u}=pf(s.file),h=o.get(a)??new Map;o.set(a,h);let k=h.get(u)??[];h.set(u,k),k.push(s)}let r=s=>n==="author"||!s.mutates;for(let s of[...o.keys()].sort()){let a=o.get(s),u=[...a.values()].flat().filter(r).map(h=>h.id);u.length>0&&e.push({kind:"category",action:n,label:`${s} (${u.length})`,ids:u,depth:1});for(let h of[...a.keys()].sort()){let k=a.get(h),b=k.filter(r).map(x=>x.id);b.length>0&&e.push({kind:"article",action:n,label:`${h} (${b.length})`,ids:b,depth:2});for(let x of k){let $=n==="capture"&&x.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:x.id,ids:[x.id],depth:3,...$?{note:$}:{}})}}}}function fc(e,t=58){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function qs(e,t,n){let o=t.filter(r=>!r.mutates);o.length>1&&e.push({kind:"all",action:"capture",label:`Retry ${o.length} blocked shots (stage the data first)`,ids:o.map(r=>r.id),depth:0});for(let r of[...t].sort((s,a)=>s.id.localeCompare(a.id)))e.push({kind:"shot",action:"capture",label:r.id,ids:[r.id],depth:1,note:` \u2298 ${fc(r.reason)}`});n.length>1&&e.push({kind:"all",action:"author",label:`Re-author ${n.length} broken specs`,ids:n.map(r=>r.id),depth:0});for(let r of[...n].sort((s,a)=>s.id.localeCompare(a.id)))e.push({kind:"shot",action:"author",label:r.id,ids:[r.id],depth:1,note:` \u2717 ${fc(r.reason)} \u2014 re-authors`})}function Rc(e){let t=e.filter(s=>s.state==="placeholder"),n=e.filter(s=>s.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(s=>s.id),depth:0}),Qo(o,t,"author");let r=n.filter(s=>!s.mutates);return r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),Qo(o,n,"capture"),qs(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken")),o}var Us="MANDATORY, check before you finish: every spec you write or touch must carry exactly one `// CAPTURE-SAFETY: readonly` or `// CAPTURE-SAFETY: mutates \u2014 <what it creates>; cleanup: <how>` line at the top. Re-read each file you wrote and add it if missing \u2014 a spec without it is classified by guesswork. A fail-by-design spec (the app rejects the input) is `readonly`.";function Sc(e,t){let n=e.paths.filter(o=>t?.get(o));return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(o=>`- ${o}`).join(`
316
+ `),"",...n.length>0?["REPAIR \u2014 these already have a spec, and it FAILED its last capture. Read the existing spec","first and fix the named failure specifically; do not re-emit the same locator and hope. A",'"strict mode violation" means the locator matched 2+ elements (scope it to a stable container',"or take .first()); a click timeout means the element was absent or unreachable (if the data","simply is not staged, the spec must test.skip with a reason naming what to stage, not time out).",...n.map(o=>`- ${o}: ${t.get(o).replace(/\s+/g," ").trim()}`),""]:[],"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.",Us].join(`
317
+ `)}async function sr(e,t,n){let o=Wn(e);if(o.mode==="list"){let u=t?.cwd??process.cwd(),h=Hs(u,o.scope),k=cn(u)?.docsDir??Ws,b=Ye(u,h);for(let x of rr(b,{scope:h,detail:o.detail,docsDir:k}))console.log(x);return{kind:"continue"}}if(o.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${o.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>/${o.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.",Us,...n?.lastFailure?["","REPAIR \u2014 the existing spec FAILED its last capture with:",n.lastFailure,'Read the existing spec first and fix that failure specifically. A "strict mode violation" means the',"locator matched 2+ elements \u2014 scope it to a stable container or take .first(); a click timeout means","the element was absent or unreachable \u2014 if that's because the data isn't staged, the spec must","test.skip with a reason naming what to stage, not time out. Re-verify every selector you keep","against the product source; do not re-emit the same locator and hope."]:[]].join(`
318
+ `),display:`/screenshot ${o.id}`};if(o.mode==="capture"||o.mode==="checklist")return{kind:"continue"};let s=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${o.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${o.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.${o.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`,Us].join(`
319
+ `),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:s,display:a}}var Bn=3;function Vs(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, normalize cross-article links). For each <!-- SCREENSHOT ... --> block, read its id BEFORE stripping the block: when <outputDir>/<id>.png exists (the annotated capture), upload it (d360_search_drive first to reuse, else d360_upload_drive_file) and replace the visible [Screenshot: ...] line with the image markdown; only when no PNG exists does the visible line stay as text.","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself \u2014 do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
320
+ `)}var Pc={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Gs(e){return e.filter(t=>t.path!==null&&t.status in Pc&&!t.link).map(t=>({path:t.path,label:Pc[t.status]}))}function ar(e){let t=Gs(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 lr(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 cr(e){return e.filter(t=>t.link).length}function Ys(e,t){try{let n=bf(e,$f(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=xf(hf(ff(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 vf(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 jc(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let s=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),a=o.get(s);a?a.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((a,u)=>a.path.localeCompare(u.path));n.push({kind:"category",label:`${vf(r)} (${s.length})`,paths:s.map(a=>a.path),indent:!1});for(let a of s){let u=a.path.replace(/\\/g,"/").split("/").pop()??a.path;n.push({kind:"article",label:u,paths:[a.path],indent:!0,note:a.label})}}for(let r of[...t].sort((s,a)=>s.path.localeCompare(a.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function Hn(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(`
321
+ `)}function zs(e,t,n){let o=$=>t[$.index]?.paths.length??0,r=e.filter($=>$.ok),s=e.filter($=>!$.ok),a=e.reduce(($,j)=>$+o(j),0),u=r.reduce(($,j)=>$+o(j),0),h=n==="api"?`${Se(e.reduce(($,j)=>$+j.costUsd,0))} total`:ht(e.reduce(($,j)=>$+j.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,b=$=>`${$} article${$===1?"":"s"}`,x=[];if(s.length===0)x.push(`Published ${b(a)} (${k}) successfully \xB7 ${h}.`),x.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{x.push(`Published ${u}/${b(a)} (${k}) \xB7 ${h}.`),x.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let $ of s)x.push(` \u2717 ${$.label}${$.error?` \u2014 ${$.error}`:""}`)}return x}async function gt(e,t){let{model:n}=wf(e.cwd,"standard"),o=async(r,s)=>{let a=gf(r);console.log(g(s?`Resolving cross-links in ${r.length} article${r.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${r.length} article${r.length===1?"":"s"} across ${a.length} partition${a.length===1?"":"s"} (\u2264${Bn} agents at once) on ${n}\u2026`)),s||console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let u=!1;for await(let h of kf({cwd:e.cwd,partitions:a,promptFor:k=>Hn(k.paths),concurrency:Bn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(h.type==="partition_status")h.status==="running"?console.log(g(` \u25B8 ${h.label} \u2014 publishing\u2026`)):h.status==="done"?console.log(_(` \u2713 ${h.label}`)):console.log(S(` \u2717 ${h.label}`));else if(h.type==="run_done"){u=h.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let x of zs(h.results,a,k))console.log(h.ok?_(x):B(x));let b=Ys(e.cwd,e.profileName);b&&console.log(g(b));try{let x=Dc(await Tc({cwd:e.cwd,profileName:e.profileName}));x&&console.log(g(x))}catch{}try{let x=Ec(await Ac({cwd:e.cwd,profileName:e.profileName}));x&&console.log(g(x))}catch{}}return u};try{if(!await o(t,!1)){let s=await Ks(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(S(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function ur(e,t,n){let o=yf(e,n);if(o.length===0)return[];let r=new Set(Gs((await ir({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Ks(e,t,n){try{let o=new Set(n),r=await ir({cwd:e,profileName:t});return Gs(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function Nc(e,t){let n=Me(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(S(n.reason)),{kind:"continue"};let o=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let r=t?.cwd??process.cwd(),s=or(Ye(r));return s.length===0?(console.log(g("No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}):t?await gt(t,s):{kind:"forward-to-agent",prompt:Hn(s),display:"/publish --screenshots"}}if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await ur(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(_("\u2713 All related articles are already published.")),{kind:"continue"}):await gt(t,r)}if(o==="--all"){console.log(g("Checking what needs publishing\u2026"));try{let r=await ir({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:a}=ar(r.entries),u=cr(r.entries),h=e.includes("--force")&&a.length>0;u>0&&console.log(B(`\u26A0 ${u} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),a.length>0&&!h&&console.log(B(lr(a.length)));let k=h?[...s,...a]:s;if(k.length===0){if(a.length>0)return console.log(g("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(_(u>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let b=Dc(await Tc({cwd:t.cwd,profileName:t.profileName}));b&&console.log(g(b));let x=Ec(await Ac({cwd:t.cwd,profileName:t.profileName}));x&&console.log(g(x))}catch{}return{kind:"continue"}}return t?await gt(t,k.map(b=>b.path)):{kind:"forward-to-agent",prompt:Hn(k.map(b=>b.path)),display:"/publish --all"}}catch(r){return console.log(S(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(g("Checking what needs publishing\u2026"));let r;try{let s=await ir({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:u}=ar(s.entries);r=a;let h=cr(s.entries);if(h>0&&console.log(B(`\u26A0 ${h} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),u.length>0&&console.log(B(lr(u.length))),r.length===0&&u.length>0)return console.log(g("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(S(`Could not compute sync status: ${s.message}`)),console.log(g("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(_("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(g(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${g(`(${s.label})`)}`);return console.log(g("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>mf({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}if(o==="--all")return await gt(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Vs(o),display:`/publish ${o}`}}async function qn(){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(`
322
+ `),display:"/audit"}}Y();import{readProjectConfig as Cf}from"document360-engine";function Xs(){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(`
323
+ `)}async function Ic(e,t){let n=t?.cwd??process.cwd();return Cf(n)?{kind:"forward-to-agent",prompt:Xs(),display:"/discover"}:(console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"})}Y();import{checkbox as Rf}from"@inquirer/prompts";import{inventoryRepo as Sf,readProjectConfig as _c,writeProjectConfig as Pf}from"document360-engine";function Qs(e,t){let n=_c(e);n&&(n.authoritativeSourceFiles=t,Pf(n,e))}function dr(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 Oc(e,t){let n=t?.cwd??process.cwd();if(!_c(n))return console.log(S("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Sf(n);if(o.length===0)return console.log(g('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(F("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${g(dr(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Rf({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${dr(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(g("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};Qs(n,r),console.log(_(`\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"}}Y();import{confirm as Lf}from"@inquirer/prompts";import{applyPull as ei,computeSyncStatus as Vc,compareRemoteSources as Mf,planPull as Gc,planImport as Uf,applyImport as Ff,establishBaselines as Wf,rebaselineServerMeta as Bf,D360AuthError as Hf}from"document360-engine";Y();var Lc=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:S,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:B,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:F,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:S,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:S,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ue,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:g,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:g,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:ue,mark:"\xB7"}];function Tf(e){return e.path?e.path:`${e.title??"(untitled)"} ${ue(`[${e.articleId}]`)}`}function Df(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 pr(e,t){let n=[],o=e.entries.filter(b=>b.link);if(o.length>0){n.push(""),n.push(Re("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let b of o)n.push(` ${B("~")} ${B(b.path??"")} ${ue(`\u2192 "${b.link.title}"`)}`)}for(let b of Lc){let x=e.entries.filter($=>$.status===b.status&&!(b.status==="untracked-local"&&$.link));if(x.length!==0){n.push(""),n.push(Re(b.header));for(let $ of x)n.push(` ${b.paint(b.mark)} ${b.paint(Tf($))}${$.detail?ue(` (${$.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let a={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},u=o.length,h=s===r?_("\u2713 everything up to date"):[r>0?_(`\u2713 ${r} up to date`):null,u>0?`${u} to link`:null,...Lc.map(b=>{let x=(e.counts[b.status]??0)-(b.status==="untracked-local"?u:0);return x>0?`${x} ${a[b.status]}`:null})].filter(Boolean).join(ue(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${Df(t)}`:"";return n.push(h+ue(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as Af}from"diff";import Mc from"picocolors";var Uc=80,Ef="\x1B[48;2;74;28;28m",jf="\x1B[48;2;24;66;24m",Fc="\x1B[49m",Js=e=>String(e).padStart(5);function Wc(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function Bc(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 ot(e,t,n){let o=$=>{let j=$.replace(/\r\n/g,`
324
324
  `);return j.endsWith(`
325
325
  `)||j===""?j:j+`
326
- `},r=o(e),s=o(t);if(r===s)return null;let a=Math.max(20,n-10),u=Tf("a","b",r,s,"","",{context:3}),h=0,k=0,b=[];u.hunks.forEach(($,j)=>{j>0&&b.push(Oc.gray(" \u2026"));let v=$.oldStart,T=$.newStart,E=[],U=[],L=()=>{for(let V=0;V<E.length;V++){let q=V<U.length?Uc(E[V],U[V]):void 0;k++,b.push(`${Df}${Qs(v++)} - ${Fc(E[V],a,q)}${Mc}`)}for(let V=0;V<U.length;V++){let q=V<E.length?Uc(E[V],U[V]):void 0;h++,b.push(`${Af}${Qs(T++)} + ${Fc(U[V],a,q)}${Mc}`)}E=[],U=[]};for(let V of $.lines){let q=V[0],re=V.slice(1);q==="-"?E.push(re):q==="+"?U.push(re):(L(),b.push(Oc.gray(Qs(T))+" "+re.slice(0,a)),v++,T++)}L()});let x=b.slice(0,Lc);return{added:h,removed:k,lines:x,hidden:Math.max(0,b.length-Lc)}}Y();import{select as Ef}from"@inquirer/prompts";import{applyPull as jf,computeSyncStatus as Nf,planPull as If}from"document360-engine";var Wc=e=>e===1?"":"s";async function Js(e,t){console.log(""),console.log(`${F("\u25CF")} ${Re(t.title)} ${ue(`(${t.path})`)}`);for(let r of t.notes)console.log(B(` \u26A0 ${r}`));let n=ot(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(ue(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${Wc(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(g(` \u2026 +${n.hidden} more diff lines`))}else console.log(g(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>Ef({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"?(jf({cwd:e.cwd,profileName:e.profileName},t),console.log(_(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(g(" Skipped \u2014 still a conflict.")),"skipped")}async function Bc(e,t){let n=Me(t.cwd,t.profileName);if(!n.ok)return console.log(S(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Nf({cwd:t.cwd,profileName:t.profileName})).entries.filter(u=>u.status==="conflict"&&u.path).map(u=>u.path);if(o){if(!s.includes(o))return console.log(_(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(_("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let a=[];for(let u of s){let h=await If({cwd:t.cwd,profileName:t.profileName,relPath:u});await Js(t,h)==="keep-local"&&a.push(u)}if(a.length>0)return console.log(g(`Publishing ${a.length} kept-local article${Wc(a.length)} over the portal\u2026`)),await mt(t,a)}catch(r){console.log(S(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Vc(e,t){let n=Me(t.cwd,t.profileName);if(!n.ok)return console.log(S(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Bf(t),{kind:"continue"};if(o==="--baseline")return await Hf(t,e.filter(a=>a!=="--baseline")),{kind:"continue"};if(o==="--compare")return await qf(t),{kind:"continue"};if(o)return console.log(S(`Unknown option: ${o}`)),console.log(g("Usage: /pull pull portal edits + import new portal articles")),console.log(g(" /pull <path> pull one article (or resolve a conflict)")),console.log(g(" /pull --status drift report only (no writes)")),console.log(g(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Vf(t,r),{kind:"continue"};console.log(g("Pulling changes from Document360\u2026"));let s=await ei({cwd:t.cwd,profileName:t.profileName});for(let a of ti(s))console.log(a.tone==="ok"?_(a.text):a.tone==="warn"?B(a.text):g(a.text));console.log("")}catch(r){r instanceof Wf?console.log(S(r.message)):console.log(S(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function ei(e){let t=await Hc({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 qc({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Zs({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 Lf({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Mf({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 pr=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Nt=e=>e===1?"":"s";function ti(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Nt(e.pulled.length)} into local: ${pr(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Nt(e.imported.length)}: ${pr(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Nt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Nt(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). (${pr(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Nt(e.failed.length)} failed: ${pr(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 Bf(e){console.log(g("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Hc({cwd:e.cwd,profileName:e.profileName});for(let o of dr(n,Date.now()-t))console.log(o);console.log("")}async function Hf(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(g(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Uf({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Ff({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(_("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(_(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(_(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(B(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(g(` - ${s.path} (${s.reason})`))}}async function qf(e){console.log(g("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Of({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Re(String(t.legacyCount))} \xB7 Manifest: ${Re(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(_("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(S(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(B(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(B(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(g(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Vf(e,t){let n=t.replace(/\\/g,"/"),o=await qc({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Js(e,o)==="keep-local"&&(console.log(g(`Publishing ${o.path} over the portal\u2026`)),await mt(e,[o.path]));return}console.log(""),console.log(`${F("\u25CF")} ${Re(o.title)} ${ue(`(${o.path})`)}`);for(let a of o.notes)console.log(B(` \u26A0 ${a}`));let r=ot(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(g(" Local file already matches the remote content \u2014 advancing the sync base only.")),Zs({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ue(` \u23BF Added ${r.added} line${Nt(r.added)}, removed ${r.removed} line${Nt(r.removed)}`));for(let a of r.lines)console.log(a);if(r.hidden>0&&console.log(g(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>_f({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(g(" Skipped."));return}Zs({cwd:e.cwd,profileName:e.profileName},o),console.log(_(` \u2713 Pulled ${o.path} (sync base advanced).`))}Y();import{statSync as Gf}from"node:fs";import{resolve as Yf}from"node:path";import{estimateBulkCost as zf,planPartitions as Kf,readProjectConfig as Xf,resolveModelForOperation as Qf,runPartitioned as Jf,trackedArticlePaths as Zf}from"document360-engine";var ni=3;function oi(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 ri(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function si(e,t){return t.map(n=>{let o=0;try{o=Gf(Yf(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ii(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite \u2014 be efficient:
326
+ `},r=o(e),s=o(t);if(r===s)return null;let a=Math.max(20,n-10),u=Af("a","b",r,s,"","",{context:3}),h=0,k=0,b=[];u.hunks.forEach(($,j)=>{j>0&&b.push(Mc.gray(" \u2026"));let v=$.oldStart,T=$.newStart,E=[],U=[],L=()=>{for(let V=0;V<E.length;V++){let q=V<U.length?Wc(E[V],U[V]):void 0;k++,b.push(`${Ef}${Js(v++)} - ${Bc(E[V],a,q)}${Fc}`)}for(let V=0;V<U.length;V++){let q=V<E.length?Wc(E[V],U[V]):void 0;h++,b.push(`${jf}${Js(T++)} + ${Bc(U[V],a,q)}${Fc}`)}E=[],U=[]};for(let V of $.lines){let q=V[0],re=V.slice(1);q==="-"?E.push(re):q==="+"?U.push(re):(L(),b.push(Mc.gray(Js(T))+" "+re.slice(0,a)),v++,T++)}L()});let x=b.slice(0,Uc);return{added:h,removed:k,lines:x,hidden:Math.max(0,b.length-Uc)}}Y();import{select as Nf}from"@inquirer/prompts";import{applyPull as If,computeSyncStatus as _f,planPull as Of}from"document360-engine";var Hc=e=>e===1?"":"s";async function Zs(e,t){console.log(""),console.log(`${F("\u25CF")} ${Re(t.title)} ${ue(`(${t.path})`)}`);for(let r of t.notes)console.log(B(` \u26A0 ${r}`));let n=ot(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(ue(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${Hc(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(g(` \u2026 +${n.hidden} more diff lines`))}else console.log(g(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>Nf({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"?(If({cwd:e.cwd,profileName:e.profileName},t),console.log(_(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(g(" Skipped \u2014 still a conflict.")),"skipped")}async function qc(e,t){let n=Me(t.cwd,t.profileName);if(!n.ok)return console.log(S(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await _f({cwd:t.cwd,profileName:t.profileName})).entries.filter(u=>u.status==="conflict"&&u.path).map(u=>u.path);if(o){if(!s.includes(o))return console.log(_(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(_("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let a=[];for(let u of s){let h=await Of({cwd:t.cwd,profileName:t.profileName,relPath:u});await Zs(t,h)==="keep-local"&&a.push(u)}if(a.length>0)return console.log(g(`Publishing ${a.length} kept-local article${Hc(a.length)} over the portal\u2026`)),await gt(t,a)}catch(r){console.log(S(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Yc(e,t){let n=Me(t.cwd,t.profileName);if(!n.ok)return console.log(S(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await qf(t),{kind:"continue"};if(o==="--baseline")return await Vf(t,e.filter(a=>a!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Gf(t),{kind:"continue"};if(o)return console.log(S(`Unknown option: ${o}`)),console.log(g("Usage: /pull pull portal edits + import new portal articles")),console.log(g(" /pull <path> pull one article (or resolve a conflict)")),console.log(g(" /pull --status drift report only (no writes)")),console.log(g(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Yf(t,r),{kind:"continue"};console.log(g("Pulling changes from Document360\u2026"));let s=await ti({cwd:t.cwd,profileName:t.profileName});for(let a of ni(s))console.log(a.tone==="ok"?_(a.text):a.tone==="warn"?B(a.text):g(a.text));console.log("")}catch(r){r instanceof Hf?console.log(S(r.message)):console.log(S(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function ti(e){let t=await Vc({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 Gc({cwd:e.cwd,profileName:e.profileName,relPath:o.path});ei({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 Uf({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Ff({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 hr=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,It=e=>e===1?"":"s";function ni(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${It(e.pulled.length)} into local: ${hr(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${It(e.imported.length)}: ${hr(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${It(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${It(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). (${hr(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${It(e.failed.length)} failed: ${hr(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 qf(e){console.log(g("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Vc({cwd:e.cwd,profileName:e.profileName});for(let o of pr(n,Date.now()-t))console.log(o);console.log("")}async function Vf(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(g(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Wf({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Bf({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(_("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(_(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(_(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(B(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(g(` - ${s.path} (${s.reason})`))}}async function Gf(e){console.log(g("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Mf({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Re(String(t.legacyCount))} \xB7 Manifest: ${Re(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(_("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(S(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(B(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(B(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(g(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Yf(e,t){let n=t.replace(/\\/g,"/"),o=await Gc({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Zs(e,o)==="keep-local"&&(console.log(g(`Publishing ${o.path} over the portal\u2026`)),await gt(e,[o.path]));return}console.log(""),console.log(`${F("\u25CF")} ${Re(o.title)} ${ue(`(${o.path})`)}`);for(let a of o.notes)console.log(B(` \u26A0 ${a}`));let r=ot(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(g(" Local file already matches the remote content \u2014 advancing the sync base only.")),ei({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ue(` \u23BF Added ${r.added} line${It(r.added)}, removed ${r.removed} line${It(r.removed)}`));for(let a of r.lines)console.log(a);if(r.hidden>0&&console.log(g(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Lf({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(g(" Skipped."));return}ei({cwd:e.cwd,profileName:e.profileName},o),console.log(_(` \u2713 Pulled ${o.path} (sync base advanced).`))}Y();import{statSync as zf}from"node:fs";import{resolve as Kf}from"node:path";import{estimateBulkCost as Xf,planPartitions as Qf,readProjectConfig as Jf,resolveModelForOperation as Zf,runPartitioned as em,trackedArticlePaths as tm}from"document360-engine";var oi=3;function ri(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 si(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function ii(e,t){return t.map(n=>{let o=0;try{o=zf(Kf(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ai(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:
327
327
  - 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.
328
328
  - 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.
329
329
  - 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.
330
330
  - Work only on these files:
331
331
  `+e.paths.map(t=>`- ${t}`).join(`
332
- `)}function ai(e,t,n){let o=e.reduce((u,h)=>u+h.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(u=>` \u2022 ${u.label} \u2014 ${u.paths.length} article${u.paths.length===1?"":"s"}`),"",`Estimated cost: ${Se(r)}\u2013${Se(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function li(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,T)=>v+o(T),0),u=r.reduce((v,T)=>v+o(T),0),h=e.reduce((v,T)=>v+T.costUsd,0),k=e.reduce((v,T)=>v+T.outputTokens,0),b=n==="api"?`${Se(h)} total`:ht(k),x=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,$=v=>`${v} article${v===1?"":"s"}`,j=[];if(s.length===0)j.push(`Converted ${$(a)} (${x}) successfully \xB7 ${b}.`);else{j.push(`Converted ${u}/${$(a)} (${x}) \xB7 ${b}.`),j.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let v of s)j.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return j}async function Gc(e,t){if(!Xf(t.cwd))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=oi(e),r=Zf(t.cwd,t.profileName);if(r.length===0)return console.log(S("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=ri(r,n);if(s.length===0)return console.log(S(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let a=Kf(s),u=`/convert${n?` --scope ${n}`:""} --run`,{model:h,forced:k}=Qf(t.cwd,"light");if(!o){let b=zf({files:si(t.cwd,s),op:"convert",model:h});n&&console.log(g(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let x of ai(a,b,ni))console.log(x);return console.log(g(`Model: ${h}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(g(`Run ${u} to start.`)),console.log(""),{kind:"continue"}}console.log(g(`Converting ${s.length} articles across ${a.length} partitions (\u2264${ni} agents at once) on ${h}\u2026`)),console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let b of Jf({cwd:t.cwd,partitions:a,promptFor:ii,concurrency:ni,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:h}))if(b.type==="partition_status")b.status==="running"?console.log(g(` \u25B8 ${b.label} \u2014 converting\u2026`)):b.status==="done"?console.log(_(` \u2713 ${b.label}`)):console.log(S(` \u2717 ${b.label}`));else if(b.type==="run_done"){console.log("");let x=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let $ of li(b.results,a,x))console.log(b.ok?_($):B($))}}catch(b){console.log(S(`Convert run failed: ${b.message}`))}return console.log(""),{kind:"continue"}}Y();import{statSync as Kc}from"node:fs";import{resolve as Xc}from"node:path";import{estimateBulkCost as lm,lintDocs as cm,planPartitions as um,readDocsPlan as dm,readProjectConfig as Qc,DEFAULT_DOCS_DIR as pm,resolveModelForOperation as hm,runPartitioned as fm,stampArticles as mm,CONTENT_CAP_VERSION as gm}from"document360-engine";import{readProjectConfig as em,loadProfileMap as tm,resolveActiveProfile as nm,desiredCategoryOrder as om,desiredArticleOrder as rm,DEFAULT_DOCS_DIR as sm}from"document360-engine";var ci=e=>e.replace(/\\/g,"/"),im=e=>ci(e).split("/").pop()??e;function am(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function Hn(e,t){try{let n=em(e);if(!n)return[];let o=nm(e,t),r=tm(e,o.name);if(!r)return[];let s=ci(n.docsDir??sm).replace(/\/+$/,""),a=new Map;for(let h of rm(r))a.set(h.categoryPath,(a.get(h.categoryPath)??0)+1);let u=[];for(let h of om(r)){let k=ci(h.path),b=k.startsWith(`${s}/`)?k.slice(s.length+1):k===s?"":k;b&&u.push({token:b,label:am(im(k)),count:a.get(h.path)??0})}return u}catch{return[]}}function Yc(e,t){let n=Hn(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 gt(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function cn(e,t,n,o){let r=Hn(e,o);if(r.length<=1)return[];let s=n.filter(k=>k.startsWith("--")).join(" "),a=s?` ${s}`:"",u=`/${t}${a} --all`.replace(/\s+/g," "),h=k=>t==="write"?`/write --scope ${k}${a}`:`/${t} ${k}${a}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((k,b)=>k+b.count,0)} articles). Pick a target:`,` ${u} (everything)`,...r.map(k=>` ${h(k.token)} (${k.label} \xB7 ${k.count} article${k.count===1?"":"s"})`)]}function hr(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function zc(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 ym=3,wm=8;function ui(e){return e===void 0||!Number.isFinite(e)?ym:Math.max(1,Math.min(Math.floor(e),wm))}function di(e){let t,n,o=!1,r=!1,s,a=h=>{let k=Number(h);return h!==void 0&&Number.isFinite(k)?k:void 0};for(let h=0;h<e.length;h++){let k=e[h];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[++h]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?s=a(e[++h]):k?.startsWith("--concurrency=")?s=a(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let u=h=>h?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:u(t),path:u(n),preview:o,concurrency:s,rewrite:r}}function km(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function bm(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function pi(e,t,n){return n.filter(o=>{try{return Kc(Xc(e,t,o)).size===0}catch{return!0}})}function hi(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+=Kc(Xc(e,a)).size}catch{}return{path:r,bytes:s}})}function fi(e,t,n={}){let o=n.rewrite?`- Some or all of these articles ALREADY EXIST on disk \u2014 this is a re-author (rewrite/upgrade), NOT a first draft. For any that exist, do NOT preserve or lightly-edit the current file: RE-AUTHOR it from scratch against the plan + sources + the active doc-type playbook standard. The existing file is what you're replacing \u2014 its structure is NOT the target; match only the project's voice/terminology.
332
+ `)}function li(e,t,n){let o=e.reduce((u,h)=>u+h.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(u=>` \u2022 ${u.label} \u2014 ${u.paths.length} article${u.paths.length===1?"":"s"}`),"",`Estimated cost: ${Se(r)}\u2013${Se(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function ci(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,T)=>v+o(T),0),u=r.reduce((v,T)=>v+o(T),0),h=e.reduce((v,T)=>v+T.costUsd,0),k=e.reduce((v,T)=>v+T.outputTokens,0),b=n==="api"?`${Se(h)} total`:ht(k),x=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,$=v=>`${v} article${v===1?"":"s"}`,j=[];if(s.length===0)j.push(`Converted ${$(a)} (${x}) successfully \xB7 ${b}.`);else{j.push(`Converted ${u}/${$(a)} (${x}) \xB7 ${b}.`),j.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let v of s)j.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return j}async function zc(e,t){if(!Jf(t.cwd))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=ri(e),r=tm(t.cwd,t.profileName);if(r.length===0)return console.log(S("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=si(r,n);if(s.length===0)return console.log(S(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let a=Qf(s),u=`/convert${n?` --scope ${n}`:""} --run`,{model:h,forced:k}=Zf(t.cwd,"light");if(!o){let b=Xf({files:ii(t.cwd,s),op:"convert",model:h});n&&console.log(g(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let x of li(a,b,oi))console.log(x);return console.log(g(`Model: ${h}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(g(`Run ${u} to start.`)),console.log(""),{kind:"continue"}}console.log(g(`Converting ${s.length} articles across ${a.length} partitions (\u2264${oi} agents at once) on ${h}\u2026`)),console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let b of em({cwd:t.cwd,partitions:a,promptFor:ai,concurrency:oi,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:h}))if(b.type==="partition_status")b.status==="running"?console.log(g(` \u25B8 ${b.label} \u2014 converting\u2026`)):b.status==="done"?console.log(_(` \u2713 ${b.label}`)):console.log(S(` \u2717 ${b.label}`));else if(b.type==="run_done"){console.log("");let x=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let $ of ci(b.results,a,x))console.log(b.ok?_($):B($))}}catch(b){console.log(S(`Convert run failed: ${b.message}`))}return console.log(""),{kind:"continue"}}Y();import{statSync as Qc}from"node:fs";import{resolve as Jc}from"node:path";import{estimateBulkCost as um,lintDocs as dm,planPartitions as pm,readDocsPlan as hm,readProjectConfig as Zc,DEFAULT_DOCS_DIR as fm,resolveModelForOperation as mm,runPartitioned as gm,stampArticles as ym,CONTENT_CAP_VERSION as wm}from"document360-engine";import{readProjectConfig as nm,loadProfileMap as om,resolveActiveProfile as rm,desiredCategoryOrder as sm,desiredArticleOrder as im,DEFAULT_DOCS_DIR as am}from"document360-engine";var ui=e=>e.replace(/\\/g,"/"),lm=e=>ui(e).split("/").pop()??e;function cm(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function Vn(e,t){try{let n=nm(e);if(!n)return[];let o=rm(e,t),r=om(e,o.name);if(!r)return[];let s=ui(n.docsDir??am).replace(/\/+$/,""),a=new Map;for(let h of im(r))a.set(h.categoryPath,(a.get(h.categoryPath)??0)+1);let u=[];for(let h of sm(r)){let k=ui(h.path),b=k.startsWith(`${s}/`)?k.slice(s.length+1):k===s?"":k;b&&u.push({token:b,label:cm(lm(k)),count:a.get(h.path)??0})}return u}catch{return[]}}function Kc(e,t){let n=Vn(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 yt(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function un(e,t,n,o){let r=Vn(e,o);if(r.length<=1)return[];let s=n.filter(k=>k.startsWith("--")).join(" "),a=s?` ${s}`:"",u=`/${t}${a} --all`.replace(/\s+/g," "),h=k=>t==="write"?`/write --scope ${k}${a}`:`/${t} ${k}${a}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((k,b)=>k+b.count,0)} articles). Pick a target:`,` ${u} (everything)`,...r.map(k=>` ${h(k.token)} (${k.label} \xB7 ${k.count} article${k.count===1?"":"s"})`)]}function fr(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Xc(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 km=3,bm=8;function di(e){return e===void 0||!Number.isFinite(e)?km:Math.max(1,Math.min(Math.floor(e),bm))}function pi(e){let t,n,o=!1,r=!1,s,a=h=>{let k=Number(h);return h!==void 0&&Number.isFinite(k)?k:void 0};for(let h=0;h<e.length;h++){let k=e[h];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[++h]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?s=a(e[++h]):k?.startsWith("--concurrency=")?s=a(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let u=h=>h?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:u(t),path:u(n),preview:o,concurrency:s,rewrite:r}}function $m(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function xm(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function hi(e,t,n){return n.filter(o=>{try{return Qc(Jc(e,t,o)).size===0}catch{return!0}})}function fi(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+=Qc(Jc(e,a)).size}catch{}return{path:r,bytes:s}})}function mi(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.
333
333
  `:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
334
334
  - 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).
335
335
  - 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).
@@ -339,95 +339,95 @@ ${s}${h}`).join("")}).join(`
339
339
  - 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.
340
340
  Articles:
341
341
  `+e.paths.map(r=>`- ${r}`).join(`
342
- `)}function mi(e,t,n){let o=e.reduce((a,u)=>a+u.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.paths.length===1?"":"s"}`),"",`Estimated cost: ${Se(r)}\u2013${Se(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function gi(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,T)=>v+o(T),0),u=r.reduce((v,T)=>v+o(T),0),h=e.reduce((v,T)=>v+T.costUsd,0),k=e.reduce((v,T)=>v+T.outputTokens,0),b=n==="api"?`${Se(h)} total`:ht(k),x=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,$=v=>`${v} article${v===1?"":"s"}`,j=[];if(s.length===0)j.push(`Wrote ${$(a)} (${x}) successfully \xB7 ${b}.`),j.push("Next \u2014 push them to Document360:"),j.push("/publish --all"),j.push("Or add screenshots first with /screenshot author --all. Drafts are reviewable in the portal after publishing.");else{j.push(`Wrote ${u}/${$(a)} (${x}) \xB7 ${b}.`),j.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let v of s)j.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return j}function yi(e,t,n){try{let o=cm({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 wi(e,t,n){let o=(Qc(e)?.docsDir??pm).replace(/\/+$/,""),r=t.map(u=>u.path);if(n.path){let u=km(n.path,o);return r.includes(u)?{docsDir:o,targets:[u],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${u}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=bm(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=pi(e,o,s);if(a.length===0){let u=n.scope?` under "${n.scope}"`:"",h=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${u} are already written. Use /write <path> to rewrite one, or /write${h} --rewrite to regenerate them all.`}}return{docsDir:o,targets:a,planCount:r.length}}async function Jc(e,t){if(!Qc(t.cwd))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};if(hr(e)){for(let U of Yc(t.cwd,t.profileName))console.log(g(U));return{kind:"continue"}}if(gt("write",e)){let U=cn(t.cwd,"write",e,t.profileName);if(U.length>0){for(let L of U)console.log(g(L));return{kind:"continue"}}}let n=dm(t.cwd);if(n.length===0)return console.log(S("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:a,rewrite:u}=di(e),{docsDir:h,targets:k,reason:b,rewriting:x}=wi(t.cwd,n,{scope:o,path:r,rewrite:u});if(k.length===0)return console.log(b?B(b):B("Nothing to write.")),{kind:"continue"};x&&console.log(B(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let $=um(k),j=ui(a),{model:v,forced:T}=hm(t.cwd,"standard"),E=!!r;if(s&&!E){let U=lm({files:hi(t.cwd,n,k),op:"write",model:v});o&&console.log(g(`Scope: ${o} (${k.length} pending).`));for(let L of mi($,U,j))console.log(L);return console.log(g(`Model: ${v}${T?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(g(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(g(`Writing ${k.length} article${k.length===1?"":"s"} across ${$.length} partition${$.length===1?"":"s"} (\u2264${j} agents at once) on ${v}\u2026`)),console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let U of fm({cwd:t.cwd,partitions:$,promptFor:L=>fi(L,h,{rewrite:x||E}),concurrency:j,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:v}))if(U.type==="partition_status")U.status==="running"?console.log(g(` \u25B8 ${U.label} \u2014 writing\u2026`)):U.status==="done"?console.log(_(` \u2713 ${U.label}`)):console.log(S(` \u2717 ${U.label}`));else if(U.type==="run_done"){console.log("");let L=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let q of gi(U.results,$,L))console.log(U.ok?_(q):B(q));if(U.ok)try{mm(t.cwd,k.map(q=>`${h}/${q}`),{writtenCap:gm})}catch{}let V=yi(t.cwd,h,k);V&&console.log(B(V))}}catch(U){console.log(S(`Write run failed: ${U.message}`))}return console.log(""),{kind:"continue"}}Y();import{existsSync as $m,readdirSync as Zc,statSync as eu}from"node:fs";import{join as tu}from"node:path";import{inputDir as xm,readProjectConfig as vm}from"document360-engine";var nu=/\.(md|markdown|pdf|txt)$/i;function ki(e){let t=xm(e);if(!$m(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Zc(t)){let s=tu(t,r),a=!1;try{a=eu(s).isDirectory()}catch{continue}if(a){if(r.startsWith("."))continue;let u=Cm(s);u>0&&n.push({name:r,docCount:u})}else nu.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Cm(e){let t=0;for(let n of Zc(e))try{eu(tu(e,n)).isFile()&&nu.test(n)&&t++}catch{}return t}function bi(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 fr(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(`
343
- `)}var $i="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function ou(e,t){let n=t?.cwd??process.cwd();if(!vm(n))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=ki(n);if(o.length===0&&r===0)return console.log(g($i)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(g("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let h of o)console.log(` ${h.name} ${g(`(${h.docCount} doc${h.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let u=o[0]?.name??"";return{kind:"forward-to-agent",prompt:fr(u),display:u?`/draft ${u}`:"/draft"}}let a=bi(o,s);return{kind:"forward-to-agent",prompt:fr(a??"",a?void 0:s),display:`/draft ${s}`}}Y();import{listOpenForDocs as Rm,readProjectConfig as Sm}from"document360-engine";function xi(e){try{return Rm(e).filter(t=>t.kind==="request").length}catch{return 0}}function vi(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Ci(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(`
344
- `)}var Ri="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function ru(e,t){let n=t?.cwd??process.cwd();if(!Sm(n))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=vi(e);if(!r&&xi(n)===0)return console.log(g(Ri)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Ci(r,o),display:s}}Y();import{search as Pm}from"@inquirer/prompts";import{findByName as Tm,getSession as Dm,listSessions as Am,relativeTime as iu}from"document360-engine";async function au(e,t){let n=Am(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(g("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=Tm(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(S(`No session matches "${o}".`)),su(n),{kind:"continue"})}if(!process.stdin.isTTY)return su(n),console.log(g("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Pm({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let a=(s??"").toLowerCase();return n.filter(u=>!a||u.name.toLowerCase().includes(a)||u.firstPrompt.toLowerCase().includes(a)).map(u=>({name:`${u.name} ${iu(u.updatedAt)}`,value:u.uuid,description:u.firstPrompt.slice(0,100)}))}})),r=Dm(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function su(e){console.log("");for(let t of e.slice(0,15))console.log(` ${F(t.name)} ${g(iu(t.updatedAt))}`),console.log(` ${g(t.firstPrompt.slice(0,80))}`);console.log("")}Y();import{renameSession as Em}from"document360-engine";function Si(e){let t=e.trim();return t.length>=2&&(t[0]==='"'&&t.endsWith('"')||t[0]==="'"&&t.endsWith("'"))?t.slice(1,-1).trim():t}async function lu(e,t){let n=Si(e.join(" "));if(!n)return console.log(S("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Em(o,n)?console.log(_(`\u2713 Session renamed to "${n}"`)):console.log(S("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(_(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as cu,readProjectConfig as jm,writeProjectConfig as Nm}from"document360-engine";Y();function Pi(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=jm(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 cu().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Nm(o,e),null):`Unknown environment "${r}". Known: ${cu().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function uu(e,t){let n=e[0];if(!n)return Mo(t.cwd),{kind:"continue"};if(n==="add"){let o=Pi(t.cwd,e[1],e[2]);return o?(console.log(S(o)),{kind:"continue"}):(console.log(_(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${F(`/profile ${e[1]}`)} then ${F("/login")}`),{kind:"continue"})}return Uo(t.cwd,n),Fo(t.cwd,n),console.log(g(" Restarting agent for the new profile\u2026")),{kind:"clear"}}Y();import{select as Im}from"@inquirer/prompts";import{readProjectConfig as _m,readUserConfig as du,resolveModelSetting as Ti,writeUserConfig as pu}from"document360-engine";var ze=[{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 mr(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=ze.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Om(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 qn(e,t){let n=()=>Ti(e).model;if(t==="default"){let s=du();return s.defaultModel?(delete s.defaultModel,pu(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Ti(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}}pu({...du(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=_m(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 hu(e,t){let n=e[0]?.trim();if(!n){let a=Ti(t.cwd);if(!process.stdin.isTTY)return console.log(`${Re("Model:")} ${F(a.model)}${a.source==="auto"?g(" (auto)"):""}`),console.log(g(` source: ${Om(a)}`)),console.log(g(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let u=mr(a),h;try{h=await t.withPausedInput(()=>Im({message:`Select model (current: ${a.model}${a.source==="auto"?" \xB7 auto":""})`,default:ze[u].value,choices:ze.map(($,j)=>({name:`${$.label}${j===u?" \u2714":""}`,value:$.value,description:$.desc}))}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}let{lines:k,changed:b,effective:x}=qn(t.cwd,h??"default");for(let $ of k)console.log($.startsWith("\u26A0")?B($):$.startsWith("\u2713")?_($):g($));return b&&await t.setModel(x),{kind:"continue"}}let{lines:o,changed:r,effective:s}=qn(t.cwd,n);for(let a of o)console.log(a.startsWith("\u26A0")?B(a):a.startsWith("\u2713")?_(a):g(a));return r&&await t.setModel(s),{kind:"continue"}}yr();async function $u(e,t){return await t.withPausedInput(()=>Zt(t.cwd)),{kind:"clear"}}async function xu(e,t){return await t.withPausedInput(()=>Io(t.cwd,t.profileName)),{kind:"clear"}}Y();import{resolveActiveProfile as rg}from"document360-engine";async function vu(e,t){let n=!1;try{n=rg(t.cwd).production}catch{}return n?(console.log(B("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(g("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}Y();var Cu=async(e,t)=>{try{await t.withPausedInput(()=>Lo({}))}catch(n){console.log(S(`Login failed: ${n.message}`))}return{kind:"continue"}};Y();import{resolveActiveProfile as sg,clearTokens as ig,clearProfileProject as ag}from"document360-engine";async function Ru(e,t){let n;try{n=sg(t.cwd,t.profileName).name}catch(r){return console.log(S(r.message)),{kind:"continue"}}let o=ig(n);return ag(t.cwd,n),console.log(o?_(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):g(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(g("Run /login to sign in and pick a project.")),{kind:"continue"}}import{spawn as Pu}from"node:child_process";import{existsSync as Ei,readFileSync as Su,statSync as lg}from"node:fs";import{homedir as cg}from"node:os";import{basename as ug,isAbsolute as dg,join as Gn,resolve as pg}from"node:path";import{readProjectConfig as hg,DEFAULT_OUTPUT_DIR as fg}from"document360-engine";var mg=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function ji(e){let t=e.find(o=>!o.startsWith("--")),n=e.includes("--retry-blocked");return e.includes("--failed")?{mode:"failed"}:e.includes("--all")?{mode:"all",retryBlocked:n}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:mg(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function wr(e,t){let n=Ye(e,t),o=r=>n.filter(s=>s.state===r).map(s=>s.id);return{ready:o("spec"),captured:o("captured"),blocked:o("blocked"),broken:o("broken"),rows:n}}function Tu(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"),o=[],r=t.filter(s=>!s.mutates);r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),Xo(o,t,"capture"),Hs(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"));for(let s of[...n].sort((a,u)=>a.id.localeCompare(u.id)))o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:" \u25CF captured \u2014 re-capture"});return o}function Ni(e,t){let n=new Set(t.filter(o=>o.state!=="placeholder").map(o=>o.id));return cc(e).filter(o=>n.has(o))}function Ii(e,t){let n=e.length;if(n===0)return null;let o=Ws(e).length;return[`\u2298 ${n} shot${n===1?"":"s"} excluded \u2014 ${n===1?"its data prerequisite wasn't":"their data prerequisites weren't"} met last run. Stage the data, then:`,` ${t}`,` /screenshot list shows what to stage (${o} action${o===1?"":"s"}).`].join(`
345
- `)}function gg(e,t){let n=hg(e)?.outputDir??fg;return dg(n)?Gn(n,`${t}.png`):pg(e,n,`${t}.png`)}function _i(e,t,n,o){let r=gg(e,t);return Ei(r)&&lg(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function Du(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}function Au(e){let n=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).filter(o=>/\b\w*Error\b|Cannot navigate|Timeout \d+m?s (exceeded|waiting)|net::|browser has been closed/i.test(o)&&!/^Error Context:/i.test(o));return n.length>0?[...new Set(n)].slice(0,3).join(`
346
- `):Oi(e)}function Oi(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(`
347
- `)}var yg=/^[A-Za-z0-9._-]+$/;function Li(e){return new Promise((t,n)=>{if(!yg.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=Pu(`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 Eu(e,t=cg()){try{let n=JSON.parse(Su(Gn(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(Su(Gn(e,"package.json"),"utf8")).name}catch{}o||=ug(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?Ei(Gn(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function ju(e){return new Promise((t,n)=>{let o=Pu("d360-capture auth --auto",{cwd:e.cwd,shell:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";o.stdout?.on("data",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 Mi(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function kr(e){return Ei(Gn(e,".d360-writer","capture.json"))}function Ui(){return["Screenshot capture is not configured in this repo yet (no `.d360-writer/capture.json`). Set it up","conversationally \u2014 never tell the user to run `d360-capture init`:","","1. Find the live app URL yourself first: `.d360-writer/config.json` `appUrl`, the product brief, the"," architecture brief, the repo (README, deploy config). Present what you found for confirmation \u2014 or"," ask for it if unknown. In the SAME message also ask: (a) is that URL the production environment?"," (b) which prepared demo context should screenshots enter \u2014 the capture scope (read the product"," source to know what this product scopes by: project / workspace / org; a single-context product"," needs none). One short numbered message, then END YOUR TURN and wait for the answers.","2. On the answers, write `.d360-writer/capture.json` in exactly this shape (fill the values):","```json","{",' "projectId": "<projectId from .d360-writer/config.json>",',' "profiles": {',' "<production or staging, matching their answer>": {',' "connection": { "startUrl": "<the app URL>" },',' "production": <true when they said production>,',' "scope": { "<scopeKey>": "<their demo context>" }'," }"," },",' "defaultProfile": "<the same profile name>"',"}","```"," Omit `scope` for a single-context product. Do not add captureDir/outputDir (defaults apply).","3. Also record the app URL as `appUrl` in `.d360-writer/config.json` \u2014 add/update just that key,",' preserving everything else. It is the canonical "where the product lives" fact (you may use it to'," deep-link stable app screens from articles).","4. Close with the ONE remaining external step, then the retry:"," `d360-capture auth` (run in this repo's terminal; first time also `npm i -g document360-capture`)"," then `/screenshot capture`."].join(`
348
- `)}function Nu(e){let t=e.results.filter(u=>u.outcome==="captured"),n=e.results.filter(u=>u.outcome==="skipped"),o=e.results.filter(u=>u.outcome==="failed"),r=(u,h,k)=>u===1?h:k,s=e.articles.length===1?`/publish ${e.articles[0]}`:"/publish --screenshots",a=t.length>0?`${t.length} PNG${r(t.length," is","s are")} saved \u2014 ${s} re-saves the ${r(e.articles.length,"article","articles")} so ${r(t.length,"it embeds","they embed")}.`:null;if(o.length>0){let[u,...h]=o.map(b=>b.id),k=h.length>0?` (then ${h.join(", ")})`:"";return{note:`${o.length} spec${r(o.length,"","s")} failed \u2014 that's a broken spec (a selector that no longer matches, or a step that timed out), not missing data, so re-running the capture will fail the same way. /screenshot ${u} re-authors it against the current UI${k}.`+(a?` ${a}`:""),cmd:`/screenshot ${u}`,tone:"warn"}}return t.length>0?{note:a,cmd:s,tone:"info"}:n.length>0?{note:null,cmd:e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",tone:"info"}:null}function Iu(e,t){let n=new Map(Ye(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function Fi(e,t){let n=t?.cwd??process.cwd(),o=ji(e);if(!kr(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,blocked:a,rows:u}=wr(n,o.mode==="scope"?o.scope:void 0),h=Ni(n,u),k=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,b=o.mode==="single"?[o.id]:o.mode==="failed"?h:o.mode==="picker"?r:[...r,...s,...k?a:[]];if(b.length===0)return o.mode==="failed"?console.log("No broken specs to re-run \u2014 /screenshot list shows where things stand."):console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};if(!k&&o.mode!=="single"&&o.mode!=="failed"){let v=Ii(u.filter(T=>T.state==="blocked"),"/screenshot capture --all --retry-blocked");v&&console.log(v)}let x=Date.now(),$=[];for(let v of b){console.log(`\u25B6 ${v}`);try{let{exitCode:T}=await Li({cwd:n,id:v,stdio:"inherit"});$.push({id:v,outcome:_i(n,v,T,x)})}catch(T){if(T.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};$.push({id:v,outcome:"failed",detail:T.message})}}let j=v=>$.filter(T=>T.outcome===v).length;return console.log(`\u2713 ${j("captured")} captured \xB7 \u2298 ${j("skipped")} skipped \xB7 \u2717 ${j("failed")} failed`),{kind:"continue"}}import{existsSync as wg,readFileSync as kg}from"node:fs";import{isAbsolute as bg,join as $g,resolve as xg}from"node:path";import{readProjectConfig as vg,DEFAULT_CAPTURE_DIR as Cg}from"document360-engine";async function un(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-writer/capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-CHECKLIST.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
349
- `),display:"/screenshot checklist"}}var _u="-".repeat(64);function Wi(e){let t=Cg;try{let b=vg(e);b?.captureDir&&(t=b.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=bg(t)?$g(t,"CAPTURE-TESTID-REQUESTS.json"):xg(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!wg(n))return null;let o;try{let b=JSON.parse(kg(n,"utf8").replace(/^/,""));o=Array.isArray(b?.requests)?b.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(b=>b.file).filter(Boolean)).size,s=o.length,a=`${s} data-testid attribute${s===1?"":"s"}`,u=`${r} source file${r===1?"":"s"}`,h=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${a} requested across ${u}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",_u,`Read ${h} 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.",_u]}dt();Y();import{listOpenForDocs as Rg,readProjectConfig as Sg}from"document360-engine";function Bi(e){try{return Rg(e).length}catch{return 0}}function Hi(){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(`
350
- `)}async function Ou(e,t){let n=t?.cwd??process.cwd();return Sg(n)?Bi(n)===0?(console.log(g("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:Hi(),display:"/inbox"}:(console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"})}Y();import{listOpenHints as Pg,listOpenForDocs as Tg,listOpenDirectives as Dg,readProjectConfig as Ag,computeSyncStatus as Eg,planPull as jg,applyPull as Ng,planImport as Ig,applyImport as _g}from"document360-engine";function Yn(e){let t=0,n=0,o=0,r=0;try{t=Pg(e).length}catch{}try{let s=Tg(e);n=s.filter(a=>a.kind==="request").length,o=s.filter(a=>a.kind==="answer").length}catch{}try{r=Dg(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function zn(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 Vi(e){return{publish:e.includes("--publish")}}function Gi({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(`
351
- `)}var Og={status:Eg,plan:jg,apply:Ng,planImport:Ig,applyImport:_g};async function Yi(e,t=Og){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 qi=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,br=e=>e===1?"":"s";function zi(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${br(e.pulled.length)} into local: ${qi(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${br(e.imported.length)} into local drafts: ${qi(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${br(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${qi(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${br(e.failed.length)} failed \u2014 left for /pull.`),t}async function Lu(e,t){let n=t?.cwd??process.cwd();if(!Ag(n))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Me(n,t?.profileName);if(!o.ok)return console.log(S(o.reason)),{kind:"continue"};let{publish:r}=Vi(e);console.log(g("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await Yi({cwd:n,profileName:t?.profileName});for(let u of zi(s))console.log(u.startsWith("\u2713")?_(u):u.startsWith("\u2139")?g(u):B(u));let a=zn(Yn(n));return console.log(g(a?`Catching up on ${a}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Gi({publish:r}),display:`/catch-up${r?" --publish":""}`}}Y();import{spawn as Mu}from"node:child_process";var dn="document360-writer",$r=`npm i -g ${dn}@latest`,Lg="document360-capture";function Mg(){return new Promise(e=>{try{let t=Mu("d360-capture --version",{stdio:"ignore",shell:!0,windowsHide:!0});t.on("error",()=>e(!1)),t.on("close",n=>e(n===0))}catch{e(!1)}})}async function xr(){let e=process.platform==="win32",n=await Mg()?[dn,Lg]:[dn];return new Promise(o=>{try{let r=Mu(`npm i -g ${n.map(s=>`${s}@latest`).join(" ")}`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});r.on("error",s=>o({ok:!1,output:String(s),packages:n})),r.on("close",s=>o({ok:s===0,output:"",packages:n})),e||r.unref()}catch(r){o({ok:!1,output:String(r),packages:n})}})}async function Uu(){console.log(g("Updating the d360-writer toolchain\u2026"));let e=await xr();return e.ok?console.log(_(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)):console.log(S(`Update failed \u2014 run manually: ${$r}`)),{kind:"continue"}}Y();dt();import{existsSync as Ki,rmSync as Ug}from"node:fs";import{basename as Fu,resolve as Xi}from"node:path";import{execFileSync as Fg}from"node:child_process";import{input as Wg}from"@inquirer/prompts";import{readProjectConfig as Bg,devHintsGuidePath as Hg}from"document360-engine";var qg=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Vg=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),vr=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Wu=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Bu(e){let t=vr(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Wu(t)?!0:Vg.has(t)}function Qi(e){let t=null;try{t=Bg(e)}catch{t=null}let n=new Set(qg);for(let o of[vr(t?.docsDir),vr(t?.captureDir),vr(t?.outputDir)])o&&Wu(o)&&n.add(o);return[...n].filter(o=>Bu(o)&&Ki(Xi(e,o)))}function Ji(e,t){let n=[],o=[];for(let r of t){if(!Bu(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Ug(Xi(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Hu(e,t){try{return Fg("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
352
- `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Gg(e){return Hu(e,".d360-writer/hints")}function Yg(e){return Hu(e,".d360-writer/messages")}function Zi(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Gg(e),o=Yg(e),r=Ki(Xi(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: ${Fu(e)}`]}async function qu(e,t){let n=Qi(t.cwd);for(let h of Zi(t.cwd,n))console.log(n.length===0?g(h):h);if(n.length===0)return{kind:"continue"};let o=Fu(t.cwd);if((await t.withPausedInput(()=>Wg({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(B("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Ki(Hg(t.cwd)),{removed:a,failed:u}=Ji(t.cwd,n);console.log(_(`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`));for(let h of u)console.log(S(` \u2717 ${h.path}: ${h.error}`));if(s){for(let h of qo())console.log(h);console.log(g("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(g("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}Y();import{lintDocs as zg}from"document360-engine";function Cr(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 ea(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(`
342
+ `)}function gi(e,t,n){let o=e.reduce((a,u)=>a+u.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.paths.length===1?"":"s"}`),"",`Estimated cost: ${Se(r)}\u2013${Se(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function yi(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,T)=>v+o(T),0),u=r.reduce((v,T)=>v+o(T),0),h=e.reduce((v,T)=>v+T.costUsd,0),k=e.reduce((v,T)=>v+T.outputTokens,0),b=n==="api"?`${Se(h)} total`:ht(k),x=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,$=v=>`${v} article${v===1?"":"s"}`,j=[];if(s.length===0)j.push(`Wrote ${$(a)} (${x}) successfully \xB7 ${b}.`),j.push("Next \u2014 push them to Document360:"),j.push("/publish --all"),j.push("Or add screenshots first with /screenshot author --all. Drafts are reviewable in the portal after publishing.");else{j.push(`Wrote ${u}/${$(a)} (${x}) \xB7 ${b}.`),j.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let v of s)j.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return j}function wi(e,t,n){try{let o=dm({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 ki(e,t,n){let o=(Zc(e)?.docsDir??fm).replace(/\/+$/,""),r=t.map(u=>u.path);if(n.path){let u=$m(n.path,o);return r.includes(u)?{docsDir:o,targets:[u],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${u}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=xm(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=hi(e,o,s);if(a.length===0){let u=n.scope?` under "${n.scope}"`:"",h=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${u} are already written. Use /write <path> to rewrite one, or /write${h} --rewrite to regenerate them all.`}}return{docsDir:o,targets:a,planCount:r.length}}async function eu(e,t){if(!Zc(t.cwd))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};if(fr(e)){for(let U of Kc(t.cwd,t.profileName))console.log(g(U));return{kind:"continue"}}if(yt("write",e)){let U=un(t.cwd,"write",e,t.profileName);if(U.length>0){for(let L of U)console.log(g(L));return{kind:"continue"}}}let n=hm(t.cwd);if(n.length===0)return console.log(S("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:a,rewrite:u}=pi(e),{docsDir:h,targets:k,reason:b,rewriting:x}=ki(t.cwd,n,{scope:o,path:r,rewrite:u});if(k.length===0)return console.log(b?B(b):B("Nothing to write.")),{kind:"continue"};x&&console.log(B(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let $=pm(k),j=di(a),{model:v,forced:T}=mm(t.cwd,"standard"),E=!!r;if(s&&!E){let U=um({files:fi(t.cwd,n,k),op:"write",model:v});o&&console.log(g(`Scope: ${o} (${k.length} pending).`));for(let L of gi($,U,j))console.log(L);return console.log(g(`Model: ${v}${T?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(g(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(g(`Writing ${k.length} article${k.length===1?"":"s"} across ${$.length} partition${$.length===1?"":"s"} (\u2264${j} agents at once) on ${v}\u2026`)),console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let U of gm({cwd:t.cwd,partitions:$,promptFor:L=>mi(L,h,{rewrite:x||E}),concurrency:j,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:v}))if(U.type==="partition_status")U.status==="running"?console.log(g(` \u25B8 ${U.label} \u2014 writing\u2026`)):U.status==="done"?console.log(_(` \u2713 ${U.label}`)):console.log(S(` \u2717 ${U.label}`));else if(U.type==="run_done"){console.log("");let L=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let q of yi(U.results,$,L))console.log(U.ok?_(q):B(q));if(U.ok)try{ym(t.cwd,k.map(q=>`${h}/${q}`),{writtenCap:wm})}catch{}let V=wi(t.cwd,h,k);V&&console.log(B(V))}}catch(U){console.log(S(`Write run failed: ${U.message}`))}return console.log(""),{kind:"continue"}}Y();import{existsSync as vm,readdirSync as tu,statSync as nu}from"node:fs";import{join as ou}from"node:path";import{inputDir as Cm,readProjectConfig as Rm}from"document360-engine";var ru=/\.(md|markdown|pdf|txt)$/i;function bi(e){let t=Cm(e);if(!vm(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of tu(t)){let s=ou(t,r),a=!1;try{a=nu(s).isDirectory()}catch{continue}if(a){if(r.startsWith("."))continue;let u=Sm(s);u>0&&n.push({name:r,docCount:u})}else ru.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Sm(e){let t=0;for(let n of tu(e))try{nu(ou(e,n)).isFile()&&ru.test(n)&&t++}catch{}return t}function $i(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 mr(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(`
343
+ `)}var xi="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function su(e,t){let n=t?.cwd??process.cwd();if(!Rm(n))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=bi(n);if(o.length===0&&r===0)return console.log(g(xi)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(g("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let h of o)console.log(` ${h.name} ${g(`(${h.docCount} doc${h.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let u=o[0]?.name??"";return{kind:"forward-to-agent",prompt:mr(u),display:u?`/draft ${u}`:"/draft"}}let a=$i(o,s);return{kind:"forward-to-agent",prompt:mr(a??"",a?void 0:s),display:`/draft ${s}`}}Y();import{listOpenForDocs as Pm,readProjectConfig as Tm}from"document360-engine";function vi(e){try{return Pm(e).filter(t=>t.kind==="request").length}catch{return 0}}function Ci(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Ri(e,t=!1){let n=["Run the document-handoff skill.",""];return e?n.push(`The builder hand-off (what was shipped this session): "${e}".`,"Treat this as the Stage 1 hand-off: ground it in the cited/changed code + the architecture brief,","then decide and APPLY the right doc action \u2014 a new section, a new article, an update to existing","article(s), or a retirement, or a mix. No fixed shape; pick the smallest set that keeps the docs correct."):n.push("No description was given \u2014 call d360_inbox and act on the OPEN `request` messages the builder left:","for each, run the document-handoff flow (ground \u2192 decide \u2192 apply) and mark the request `status: done`","with `resulting_articles` when finished."),n.push("","Draft only \u2014 do not publish. If you would create multiple new articles (a section), call","d360_estimate_cost and present the count + cost band first, then wait for the go-ahead."),t&&n.push("","After the drafts exist and the user confirms any bulk gate, publish the new/updated articles to","Document360 (the publish-to-d360 skill). On a production profile, respect the write-guard."),n.join(`
344
+ `)}var Si="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function iu(e,t){let n=t?.cwd??process.cwd();if(!Tm(n))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Ci(e);if(!r&&vi(n)===0)return console.log(g(Si)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Ri(r,o),display:s}}Y();import{search as Dm}from"@inquirer/prompts";import{findByName as Am,getSession as Em,listSessions as jm,relativeTime as lu}from"document360-engine";async function cu(e,t){let n=jm(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(g("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=Am(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(S(`No session matches "${o}".`)),au(n),{kind:"continue"})}if(!process.stdin.isTTY)return au(n),console.log(g("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Dm({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let a=(s??"").toLowerCase();return n.filter(u=>!a||u.name.toLowerCase().includes(a)||u.firstPrompt.toLowerCase().includes(a)).map(u=>({name:`${u.name} ${lu(u.updatedAt)}`,value:u.uuid,description:u.firstPrompt.slice(0,100)}))}})),r=Em(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function au(e){console.log("");for(let t of e.slice(0,15))console.log(` ${F(t.name)} ${g(lu(t.updatedAt))}`),console.log(` ${g(t.firstPrompt.slice(0,80))}`);console.log("")}Y();import{renameSession as Nm}from"document360-engine";function Pi(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 uu(e,t){let n=Pi(e.join(" "));if(!n)return console.log(S("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Nm(o,n)?console.log(_(`\u2713 Session renamed to "${n}"`)):console.log(S("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(_(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as du,readProjectConfig as Im,writeProjectConfig as _m}from"document360-engine";Y();function Ti(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Im(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 du().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},_m(o,e),null):`Unknown environment "${r}". Known: ${du().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function pu(e,t){let n=e[0];if(!n)return Uo(t.cwd),{kind:"continue"};if(n==="add"){let o=Ti(t.cwd,e[1],e[2]);return o?(console.log(S(o)),{kind:"continue"}):(console.log(_(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${F(`/profile ${e[1]}`)} then ${F("/login")}`),{kind:"continue"})}return Fo(t.cwd,n),Wo(t.cwd,n),console.log(g(" Restarting agent for the new profile\u2026")),{kind:"clear"}}Y();import{select as Om}from"@inquirer/prompts";import{readProjectConfig as Lm,readUserConfig as hu,resolveModelSetting as Di,writeUserConfig as fu}from"document360-engine";var ze=[{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 gr(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=ze.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Mm(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 Gn(e,t){let n=()=>Di(e).model;if(t==="default"){let s=hu();return s.defaultModel?(delete s.defaultModel,fu(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Di(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}}fu({...hu(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Lm(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 mu(e,t){let n=e[0]?.trim();if(!n){let a=Di(t.cwd);if(!process.stdin.isTTY)return console.log(`${Re("Model:")} ${F(a.model)}${a.source==="auto"?g(" (auto)"):""}`),console.log(g(` source: ${Mm(a)}`)),console.log(g(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let u=gr(a),h;try{h=await t.withPausedInput(()=>Om({message:`Select model (current: ${a.model}${a.source==="auto"?" \xB7 auto":""})`,default:ze[u].value,choices:ze.map(($,j)=>({name:`${$.label}${j===u?" \u2714":""}`,value:$.value,description:$.desc}))}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}let{lines:k,changed:b,effective:x}=Gn(t.cwd,h??"default");for(let $ of k)console.log($.startsWith("\u26A0")?B($):$.startsWith("\u2713")?_($):g($));return b&&await t.setModel(x),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Gn(t.cwd,n);for(let a of o)console.log(a.startsWith("\u26A0")?B(a):a.startsWith("\u2713")?_(a):g(a));return r&&await t.setModel(s),{kind:"continue"}}wr();async function vu(e,t){return await t.withPausedInput(()=>en(t.cwd)),{kind:"clear"}}async function Cu(e,t){return await t.withPausedInput(()=>_o(t.cwd,t.profileName)),{kind:"clear"}}Y();import{resolveActiveProfile as ig}from"document360-engine";async function Ru(e,t){let n=!1;try{n=ig(t.cwd).production}catch{}return n?(console.log(B("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(g("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}Y();var Su=async(e,t)=>{try{await t.withPausedInput(()=>Mo({}))}catch(n){console.log(S(`Login failed: ${n.message}`))}return{kind:"continue"}};Y();import{resolveActiveProfile as ag,clearTokens as lg,clearProfileProject as cg}from"document360-engine";async function Pu(e,t){let n;try{n=ag(t.cwd,t.profileName).name}catch(r){return console.log(S(r.message)),{kind:"continue"}}let o=lg(n);return cg(t.cwd,n),console.log(o?_(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):g(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(g("Run /login to sign in and pick a project.")),{kind:"continue"}}import{spawn as Tu}from"node:child_process";import{existsSync as Ni,readFileSync as ji,statSync as ug}from"node:fs";import{homedir as dg}from"node:os";import{basename as pg,isAbsolute as hg,join as dn,resolve as fg}from"node:path";import{readProjectConfig as mg,DEFAULT_OUTPUT_DIR as gg}from"document360-engine";var yg=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ii(e){let t=e.find(o=>!o.startsWith("--")),n=e.includes("--retry-blocked");return e.includes("--failed")?{mode:"failed"}:e.includes("--all")?{mode:"all",retryBlocked:n}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:yg(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function kr(e,t){let n=Ye(e,t),o=r=>n.filter(s=>s.state===r).map(s=>s.id);return{ready:o("spec"),captured:o("captured"),blocked:o("blocked"),broken:o("broken"),rows:n}}function Du(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"),o=[],r=t.filter(s=>!s.mutates);r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),Qo(o,t,"capture"),qs(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"));for(let s of[...n].sort((a,u)=>a.id.localeCompare(u.id)))o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:" \u25CF captured \u2014 re-capture"});return o}function _i(e,t){let n=new Set(t.filter(o=>o.state!=="placeholder").map(o=>o.id));return dc(e).filter(o=>n.has(o))}function Oi(e,t){let n=e.length;if(n===0)return null;let o=Bs(e).length;return[`\u2298 ${n} shot${n===1?"":"s"} excluded \u2014 ${n===1?"its data prerequisite wasn't":"their data prerequisites weren't"} met last run. Stage the data, then:`,` ${t}`,` /screenshot list shows what to stage (${o} action${o===1?"":"s"}).`].join(`
345
+ `)}function wg(e,t){let n=mg(e)?.outputDir??gg;return hg(n)?dn(n,`${t}.png`):fg(e,n,`${t}.png`)}function Li(e,t,n,o){let r=wg(e,t);return Ni(r)&&ug(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function Au(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}function Eu(e){let n=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).filter(o=>/\b\w*Error\b|Cannot navigate|Timeout \d+m?s (exceeded|waiting)|net::|browser has been closed/i.test(o)&&!/^Error Context:/i.test(o));return n.length>0?[...new Set(n)].slice(0,3).join(`
346
+ `):Mi(e)}function Mi(e,t=4){let n=/captured\s+·|^▶ Annotating|^✓ \d+ captured|^\s*[⊘✗]\s+\S+\s*$|^▶ Running \d+ spec/;return e.split(/\r?\n/).map(r=>r.trimEnd()).filter(r=>r.trim().length>0&&!n.test(r.trim())).slice(-t).join(`
347
+ `)}var kg=/^[A-Za-z0-9._-]+$/;function Ui(e){return new Promise((t,n)=>{if(!kg.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=Tu(`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 ju(e,t=dg()){try{let n=JSON.parse(ji(dn(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(ji(dn(e,"package.json"),"utf8")).name}catch{}o||=pg(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?Ni(dn(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function Nu(e){return new Promise((t,n)=>{let o=Tu("d360-capture auth --auto",{cwd:e.cwd,shell:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";o.stdout?.on("data",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 Fi(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function Iu(e){try{let t=JSON.parse(ji(dn(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),n=Object.keys(t.profiles??{}),o=t.defaultProfile??(n.length===1?n[0]:n.includes("staging")?"staging":n[0]),r=o?t.profiles?.[o]:void 0;return{production:!!r?.production,name:o,url:r?.connection?.startUrl}}catch{return{production:!1}}}function br(e){return Ni(dn(e,".d360-writer","capture.json"))}function Wi(){return["Screenshot capture is not configured in this repo yet (no `.d360-writer/capture.json`). Set it up","conversationally \u2014 never tell the user to run `d360-capture init`:","","1. Find the live app URL yourself first: `.d360-writer/config.json` `appUrl`, the product brief, the"," architecture brief, the repo (README, deploy config). Present what you found for confirmation \u2014 or"," ask for it if unknown. In the SAME message also ask: (a) is that URL the production environment?"," (b) which prepared demo context should screenshots enter \u2014 the capture scope (read the product"," source to know what this product scopes by: project / workspace / org; a single-context product"," needs none). One short numbered message, then END YOUR TURN and wait for the answers.","2. On the answers, write `.d360-writer/capture.json` in exactly this shape (fill the values):","```json","{",' "projectId": "<projectId from .d360-writer/config.json>",',' "profiles": {',' "<production or staging, matching their answer>": {',' "connection": { "startUrl": "<the app URL>" },',' "production": <true when they said production>,',' "scope": { "<scopeKey>": "<their demo context>" }'," }"," },",' "defaultProfile": "<the same profile name>"',"}","```"," Omit `scope` for a single-context product. Do not add captureDir/outputDir (defaults apply).","3. Also record the app URL as `appUrl` in `.d360-writer/config.json` \u2014 add/update just that key,",' preserving everything else. It is the canonical "where the product lives" fact (you may use it to'," deep-link stable app screens from articles).","4. Close with the ONE remaining external step, then the retry:"," `d360-capture auth` (run in this repo's terminal; first time also `npm i -g document360-capture`)"," then `/screenshot capture`."].join(`
348
+ `)}function _u(e){let t=e.results.filter(u=>u.outcome==="captured"),n=e.results.filter(u=>u.outcome==="skipped"),o=e.results.filter(u=>u.outcome==="failed"),r=(u,h,k)=>u===1?h:k,s=e.articles.length===1?`/publish ${e.articles[0]}`:"/publish --screenshots",a=t.length>0?`${t.length} PNG${r(t.length," is","s are")} saved \u2014 ${s} re-saves the ${r(e.articles.length,"article","articles")} so ${r(t.length,"it embeds","they embed")}.`:null;if(o.length>0){let[u,...h]=o.map(b=>b.id),k=h.length>0?` (then ${h.join(", ")})`:"";return{note:`${o.length} spec${r(o.length,"","s")} failed \u2014 that's a broken spec (a selector that no longer matches, or a step that timed out), not missing data, so re-running the capture will fail the same way. /screenshot ${u} re-authors it against the current UI${k}.`+(a?` ${a}`:""),cmd:`/screenshot ${u}`,tone:"warn"}}return t.length>0?{note:a,cmd:s,tone:"info"}:n.length>0?{note:null,cmd:e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",tone:"info"}:null}function Ou(e,t){let n=new Map(Ye(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function Bi(e,t){let n=t?.cwd??process.cwd(),o=Ii(e);if(!br(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,blocked:a,rows:u}=kr(n,o.mode==="scope"?o.scope:void 0),h=_i(n,u),k=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,b=o.mode==="single"?[o.id]:o.mode==="failed"?h:o.mode==="picker"?r:[...r,...s,...k?a:[]];if(b.length===0)return o.mode==="failed"?console.log("No broken specs to re-run \u2014 /screenshot list shows where things stand."):console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};if(!k&&o.mode!=="single"&&o.mode!=="failed"){let v=Oi(u.filter(T=>T.state==="blocked"),"/screenshot capture --all --retry-blocked");v&&console.log(v)}let x=Date.now(),$=[];for(let v of b){console.log(`\u25B6 ${v}`);try{let{exitCode:T}=await Ui({cwd:n,id:v,stdio:"inherit"});$.push({id:v,outcome:Li(n,v,T,x)})}catch(T){if(T.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};$.push({id:v,outcome:"failed",detail:T.message})}}let j=v=>$.filter(T=>T.outcome===v).length;return console.log(`\u2713 ${j("captured")} captured \xB7 \u2298 ${j("skipped")} skipped \xB7 \u2717 ${j("failed")} failed`),{kind:"continue"}}import{existsSync as bg,readFileSync as $g}from"node:fs";import{isAbsolute as xg,join as vg,resolve as Cg}from"node:path";import{readProjectConfig as Rg,DEFAULT_CAPTURE_DIR as Sg}from"document360-engine";async function pn(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-writer/capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-CHECKLIST.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
349
+ `),display:"/screenshot checklist"}}var Lu="-".repeat(64);function Hi(e){let t=Sg;try{let b=Rg(e);b?.captureDir&&(t=b.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=xg(t)?vg(t,"CAPTURE-TESTID-REQUESTS.json"):Cg(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!bg(n))return null;let o;try{let b=JSON.parse($g(n,"utf8").replace(/^/,""));o=Array.isArray(b?.requests)?b.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(b=>b.file).filter(Boolean)).size,s=o.length,a=`${s} data-testid attribute${s===1?"":"s"}`,u=`${r} source file${r===1?"":"s"}`,h=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${a} requested across ${u}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",Lu,`Read ${h} 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.",Lu]}dt();Y();import{listOpenForDocs as Pg,readProjectConfig as Tg}from"document360-engine";function qi(e){try{return Pg(e).length}catch{return 0}}function Vi(){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(`
350
+ `)}async function Mu(e,t){let n=t?.cwd??process.cwd();return Tg(n)?qi(n)===0?(console.log(g("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:Vi(),display:"/inbox"}:(console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"})}Y();import{listOpenHints as Dg,listOpenForDocs as Ag,listOpenDirectives as Eg,readProjectConfig as jg,computeSyncStatus as Ng,planPull as Ig,applyPull as _g,planImport as Og,applyImport as Lg}from"document360-engine";function zn(e){let t=0,n=0,o=0,r=0;try{t=Dg(e).length}catch{}try{let s=Ag(e);n=s.filter(a=>a.kind==="request").length,o=s.filter(a=>a.kind==="answer").length}catch{}try{r=Eg(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function Kn(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 Yi(e){return{publish:e.includes("--publish")}}function zi({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(`
351
+ `)}var Mg={status:Ng,plan:Ig,apply:_g,planImport:Og,applyImport:Lg};async function Ki(e,t=Mg){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 Gi=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,$r=e=>e===1?"":"s";function Xi(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${$r(e.pulled.length)} into local: ${Gi(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${$r(e.imported.length)} into local drafts: ${Gi(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${$r(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Gi(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${$r(e.failed.length)} failed \u2014 left for /pull.`),t}async function Uu(e,t){let n=t?.cwd??process.cwd();if(!jg(n))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Me(n,t?.profileName);if(!o.ok)return console.log(S(o.reason)),{kind:"continue"};let{publish:r}=Yi(e);console.log(g("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await Ki({cwd:n,profileName:t?.profileName});for(let u of Xi(s))console.log(u.startsWith("\u2713")?_(u):u.startsWith("\u2139")?g(u):B(u));let a=Kn(zn(n));return console.log(g(a?`Catching up on ${a}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:zi({publish:r}),display:`/catch-up${r?" --publish":""}`}}Y();import{spawn as Fu}from"node:child_process";var hn="document360-writer",xr=`npm i -g ${hn}@latest`,Ug="document360-capture";function Fg(){return new Promise(e=>{try{let t=Fu("d360-capture --version",{stdio:"ignore",shell:!0,windowsHide:!0});t.on("error",()=>e(!1)),t.on("close",n=>e(n===0))}catch{e(!1)}})}async function vr(){let e=process.platform==="win32",n=await Fg()?[hn,Ug]:[hn];return new Promise(o=>{try{let r=Fu(`npm i -g ${n.map(s=>`${s}@latest`).join(" ")}`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});r.on("error",s=>o({ok:!1,output:String(s),packages:n})),r.on("close",s=>o({ok:s===0,output:"",packages:n})),e||r.unref()}catch(r){o({ok:!1,output:String(r),packages:n})}})}async function Wu(){console.log(g("Updating the d360-writer toolchain\u2026"));let e=await vr();return e.ok?console.log(_(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)):console.log(S(`Update failed \u2014 run manually: ${xr}`)),{kind:"continue"}}Y();dt();import{existsSync as Qi,rmSync as Wg}from"node:fs";import{basename as Bu,resolve as Ji}from"node:path";import{execFileSync as Bg}from"node:child_process";import{input as Hg}from"@inquirer/prompts";import{readProjectConfig as qg,devHintsGuidePath as Vg}from"document360-engine";var Gg=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Yg=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Cr=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Hu=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function qu(e){let t=Cr(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Hu(t)?!0:Yg.has(t)}function Zi(e){let t=null;try{t=qg(e)}catch{t=null}let n=new Set(Gg);for(let o of[Cr(t?.docsDir),Cr(t?.captureDir),Cr(t?.outputDir)])o&&Hu(o)&&n.add(o);return[...n].filter(o=>qu(o)&&Qi(Ji(e,o)))}function ea(e,t){let n=[],o=[];for(let r of t){if(!qu(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Wg(Ji(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Vu(e,t){try{return Bg("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
352
+ `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function zg(e){return Vu(e,".d360-writer/hints")}function Kg(e){return Vu(e,".d360-writer/messages")}function ta(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=zg(e),o=Kg(e),r=Qi(Ji(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: ${Bu(e)}`]}async function Gu(e,t){let n=Zi(t.cwd);for(let h of ta(t.cwd,n))console.log(n.length===0?g(h):h);if(n.length===0)return{kind:"continue"};let o=Bu(t.cwd);if((await t.withPausedInput(()=>Hg({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(B("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Qi(Vg(t.cwd)),{removed:a,failed:u}=ea(t.cwd,n);console.log(_(`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`));for(let h of u)console.log(S(` \u2717 ${h.path}: ${h.error}`));if(s){for(let h of Vo())console.log(h);console.log(g("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(g("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}Y();import{lintDocs as Xg}from"document360-engine";function Rr(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 na(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(`
353
353
  `)).join(`
354
354
  `)].join(`
355
- `)}async function Vu(e,t){let n=e.includes("--fix"),o=e.find(a=>!a.startsWith("--")),r=o?` ${o}`:"",s=zg({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(_("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(g(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:ea(s),display:`/check${r} --fix`});console.log(g("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let a of Cr(s))console.log(s.length===0?_(a):B(a));return s.length>0&&console.log(g("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}Y();import{lintDocs as ey,loadStyleGuide as ty,buildReviewPrompt as ny,readProjectConfig as oy,DEFAULT_DOCS_DIR as ry}from"document360-engine";Y();import{readProjectConfig as Kg,loadProfileMap as Xg,resolveActiveProfile as Qg,desiredCategoryOrder as Jg,desiredArticleOrder as Zg}from"document360-engine";function Gu(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Yu=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Kn(e,t){try{if(!Kg(e))return[];let n=Qg(e,t),o=Xg(e,n.name);if(!o)return[];let r=new Map;for(let a of Zg(o)){let u=r.get(a.categoryPath);u?u.push(a):r.set(a.categoryPath,[a])}let s=[];for(let a of Jg(o)){s.push(Gu(Yu(a.path)));for(let u of(r.get(a.path)??[]).sort((h,k)=>h.order-k.order))s.push(` ${Gu(Yu(u.path))}`)}return s}catch{return[]}}async function zu(e,t){let n=Kn(t.cwd,t.profileName);if(n.length===0)return console.log(g("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(F("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function ta(e,t){let n=oy(e);if(!n)return null;let o=(n.docsDir??ry).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(b=>!b.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=ey({cwd:e}),u=s?a.filter(b=>b.path===`${o}/${s}`||b.path.startsWith(`${o}/${s}/`)):a,h=s?"":Kn(e).join(`
356
- `);return{prompt:ny({docsRoot:o,scope:s,styleGuide:ty(e),deterministicFindings:u,fix:r,structure:h||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function Ku(e,t){if(gt("review",e)){let o=cn(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(g(r));return{kind:"continue"}}}let n=ta(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"})}Y();import{readProjectConfig as sy}from"document360-engine";function na(e,t){if(!sy(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(`
357
- `),display:`/reorder${n?` ${n}`:""}`}}async function Xu(e,t){if(gt("reorder",e)){let o=cn(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(g(r));return{kind:"continue"}}}let n=na(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"})}Y();import{readProjectConfig as iy,writeProjectConfig as Qu,isAppType as ay,playbookSkillName as ly,detectAppType as Ju}from"document360-engine";var Zu=["web","cli","service","library"],cy=new Set(["web","cli"]);function oa(e){return cy.has(e)?`${ly(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Rr(e,t){let n=t.cwd,o=iy(n);if(!o)return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??Ju(n);if(s){let a=o.appType?"set in config":"auto-detected";console.log(`${F("Genre:")} ${s} (${a}) \u2014 ${oa(s)}`)}else console.log(B("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(g(`Set it: /genre <${Zu.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(g("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...a}=o;Qu(a,n);let u=Ju(n);return console.log(_(`\u2713 Genre reset to auto-detect \u2014 now: ${u?`${u} (${oa(u)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return ay(r)?(Qu({...o,appType:r},n),console.log(_(`\u2713 Genre set to ${r} \u2014 ${oa(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(S(`Unknown genre "${r}". Choose one of: ${Zu.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}Y();import{listRoadmap as Sr,roadmapProgress as ed,stampRoadmapDone as uy}from"document360-engine";function ra(e){let t=Sr(e);if(t.length===0)return["No docs roadmap yet \u2014 the docs agent seeds .d360-writer/roadmap.md when it pins a structure,","and adds steps as the app changes. You can also write steps by hand (## [open] <step>), or ask:",'"propose the docs roadmap for this repo".'];let n=ed(e),o=[`Docs roadmap \u2014 ${n.done} of ${n.total} step${n.total===1?"":"s"} done:`,""];for(let r of t)o.push(` ${r.status==="done"?"\u2713":"\u25CB"} ${r.title}${r.run?` \xB7 ${r.run}`:""}`);return o.push(""),o.push(n.next?`Next: ${n.next.title}${n.next.run?` \u2014 ${n.next.run}`:""}`:"Campaign complete \u2014 the docs agent adds new steps as the app changes."),o.push("(Edit .d360-writer/roadmap.md freely \xB7 /roadmap done marks the next step you finished yourself \u2014 add words from a title to pick another.)"),o}function Pr(e,t){let n=Sr(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:
355
+ `)}async function Yu(e,t){let n=e.includes("--fix"),o=e.find(a=>!a.startsWith("--")),r=o?` ${o}`:"",s=Xg({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(_("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(g(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:na(s),display:`/check${r} --fix`});console.log(g("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let a of Rr(s))console.log(s.length===0?_(a):B(a));return s.length>0&&console.log(g("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}Y();import{lintDocs as ny,loadStyleGuide as oy,buildReviewPrompt as ry,readProjectConfig as sy,DEFAULT_DOCS_DIR as iy}from"document360-engine";Y();import{readProjectConfig as Qg,loadProfileMap as Jg,resolveActiveProfile as Zg,desiredCategoryOrder as ey,desiredArticleOrder as ty}from"document360-engine";function zu(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Ku=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Xn(e,t){try{if(!Qg(e))return[];let n=Zg(e,t),o=Jg(e,n.name);if(!o)return[];let r=new Map;for(let a of ty(o)){let u=r.get(a.categoryPath);u?u.push(a):r.set(a.categoryPath,[a])}let s=[];for(let a of ey(o)){s.push(zu(Ku(a.path)));for(let u of(r.get(a.path)??[]).sort((h,k)=>h.order-k.order))s.push(` ${zu(Ku(u.path))}`)}return s}catch{return[]}}async function Xu(e,t){let n=Xn(t.cwd,t.profileName);if(n.length===0)return console.log(g("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(F("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function oa(e,t){let n=sy(e);if(!n)return null;let o=(n.docsDir??iy).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(b=>!b.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=ny({cwd:e}),u=s?a.filter(b=>b.path===`${o}/${s}`||b.path.startsWith(`${o}/${s}/`)):a,h=s?"":Xn(e).join(`
356
+ `);return{prompt:ry({docsRoot:o,scope:s,styleGuide:oy(e),deterministicFindings:u,fix:r,structure:h||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function Qu(e,t){if(yt("review",e)){let o=un(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(g(r));return{kind:"continue"}}}let n=oa(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"})}Y();import{readProjectConfig as ay}from"document360-engine";function ra(e,t){if(!ay(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(`
357
+ `),display:`/reorder${n?` ${n}`:""}`}}async function Ju(e,t){if(yt("reorder",e)){let o=un(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(g(r));return{kind:"continue"}}}let n=ra(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"})}Y();import{readProjectConfig as ly,writeProjectConfig as Zu,isAppType as cy,playbookSkillName as uy,detectAppType as ed}from"document360-engine";var td=["web","cli","service","library"],dy=new Set(["web","cli"]);function sa(e){return dy.has(e)?`${uy(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Sr(e,t){let n=t.cwd,o=ly(n);if(!o)return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??ed(n);if(s){let a=o.appType?"set in config":"auto-detected";console.log(`${F("Genre:")} ${s} (${a}) \u2014 ${sa(s)}`)}else console.log(B("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(g(`Set it: /genre <${td.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(g("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...a}=o;Zu(a,n);let u=ed(n);return console.log(_(`\u2713 Genre reset to auto-detect \u2014 now: ${u?`${u} (${sa(u)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return cy(r)?(Zu({...o,appType:r},n),console.log(_(`\u2713 Genre set to ${r} \u2014 ${sa(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(S(`Unknown genre "${r}". Choose one of: ${td.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}Y();import{listRoadmap as Pr,roadmapProgress as nd,stampRoadmapDone as py}from"document360-engine";function ia(e){let t=Pr(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=nd(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 Tr(e,t){let n=Pr(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:
358
358
  ${a.map(k=>` \u25CB ${k.title}`).join(`
359
359
  `)}`};if(a.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
360
360
  ${n.map(k=>` \u25CB ${k.title}`).join(`
361
- `)}`};let u=a[0].title;uy(e,u,{doneAt:new Date().toISOString()});let h=ed(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${u}${h?` \u2014 next up: ${h.title}${h.run?` (${h.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function sa(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?Sr(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function td(e,t){let n=sa(e,t);return n?[`Note: this command executes the open docs-roadmap step "${n.title}".`,`Close the loop IN THE SAME TURN the step's goal state is reached: call d360_roadmap_done with exactly the title "${n.title}", then tell the user it is marked done \u2014 including when you find the goal already holds ("no action needed" completes the STEP, not just the turn). Leave it open ONLY if the work is genuinely incomplete, and say exactly what remains.`].join(`
362
- `):null}function nd(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=Sr(e).find(r=>r.status==="open"&&r.title.trim().toLowerCase()===n);return o?[`Execute this open docs-roadmap step: "${o.title}".`,o.run?`Its run command: ${o.run}`:"",o.body?`Step detail:
361
+ `)}`};let u=a[0].title;py(e,u,{doneAt:new Date().toISOString()});let h=nd(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${u}${h?` \u2014 next up: ${h.title}${h.run?` (${h.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function aa(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?Pr(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function od(e,t){let n=aa(e,t);return n?[`Note: this command executes the open docs-roadmap step "${n.title}".`,`Close the loop IN THE SAME TURN the step's goal state is reached: call d360_roadmap_done with exactly the title "${n.title}", then tell the user it is marked done \u2014 including when you find the goal already holds ("no action needed" completes the STEP, not just the turn). Leave it open ONLY if the work is genuinely incomplete, and say exactly what remains.`].join(`
362
+ `):null}function rd(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=Pr(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:
363
363
  ${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(`
364
- `):null}async function od(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Pr(n,e.slice(1).join(" ").trim());return console.log(r.ok?_(r.line):B(r.line)),{kind:"continue"}}let o=ra(n);console.log(F(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?g(r):r);return{kind:"continue"}}var rd={help:ws,"?":ws,clear:xl,exit:ks,quit:ks,init:Cs,mcp:Yo,publish:Ec,audit:Bn,discover:jc,scope:Ic,pull:Vc,resolve:Bc,convert:Gc,write:Jc,draft:ou,document:ru,resume:au,rename:lu,profile:uu,model:hu,doctor:Vn,workspace:$u,project:xu,"allow-prod":vu,login:Cu,logout:Ru,screenshot:async(e,t)=>{let n=Un(e);return n.mode==="capture"?Fi(n.rest,t):n.mode==="checklist"?un():rr(e,t)},capture:Fi,"capture-setup":un,devhints:Nl,inbox:Ou,"catch-up":Lu,update:Uu,reset:qu,check:Vu,review:Ku,reorder:Xu,structure:zu,genre:Rr,roadmap:od};function sd(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),o=(n[0]??"").toLowerCase();return o?{name:o,args:n.slice(1)}:null}dt();var dy="Or just tell me what to write or update.",py='\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 ge(e){return e===1?"":"s"}function Tr(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Xn(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var hy={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 fy(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:hy,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${ge(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${ge(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
365
- \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${ge(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${ge(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ge(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${ge(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${ge(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${ge(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${ge(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${ge(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${ge(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${ge(n)}.`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${ge(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function id(e){return e.find(t=>t.lead||t.picker)??null}function ia(e,t){let n=t.filter(a=>a.bullet).map(a=>` \u2022 ${a.bullet}`),o=id(t),r=[];o?.lead?r.push(Xn(o.lead)):o?.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let a of t.filter(u=>u!==o).slice(0,2))a.follow&&r.push(a.follow);let s=[[e,...n].join(`
366
- `)];return r.length&&s.push(r.join(" ")),s.push(dy),s.join(`
367
-
368
- `)}function Qn(e){if(!e.ready)return{kind:"idle"};let t=fy(e);if(!e.hasDocs){let s=id(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:ia("\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:py,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${ge(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${ge(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${ge(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:ia("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:ia("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as aa,readdirSync as ca}from"node:fs";import{spawnSync as my}from"node:child_process";import{join as Dr}from"node:path";import{readProjectConfig as ld,resolveActiveProfile as cd,loadTokens as gy,isExpired as yy,loadProfileMap as ud,localAheadPaths as wy,loadKnownConflicts as ky,readDocsPlan as by,devHintsGuidePath as $y,DEFAULT_DOCS_DIR as la,roadmapProgress as xy,listRoadmap as vy,readProductBriefState as Cy,reconcileCommitRequest as Ry}from"document360-engine";dt();function ad(e){try{return ca(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ua(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>ad(Dr(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&ad(Dr(e,o)))}function da(e,t){try{let n=ld(e);if(!n)return!1;let o=cd(e,t),r=ud(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Dr(e,(n.docsDir??la).replace(/\/+$/,""));return!!(aa(s)&&ca(s).length>0||aa($y(e)))}catch{return!1}}function Jn(e,t,n){try{let o=ld(e);if(!o)return null;let r=cd(e,t),s=gy(r.name),a=!!s&&(!yy(s)||!!s.refreshToken),u=da(e,t)||!ua(e,o.authoritativeSourceFiles),h=ud(e,r.name),k=h?Object.keys(h.articles).length:0,b=Dr(e,(o.docsDir??la).replace(/\/+$/,"")),x=!1;try{x=aa(b)&&ca(b).length>0}catch{}let $=0;if(h?.lastAnalyzedCommit)try{let me=my("git",["rev-list","--count",`${h.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});me.status===0&&($=parseInt((me.stdout||"").trim(),10)||0)}catch{}let j=0;try{let me=by(e);if(me.length>0){let Xe=(o.docsDir??la).replace(/\/+$/,"");j=pi(e,Xe,me.map(be=>be.path)).length}}catch{}let v=Yn(e),T=zn({...v,directives:0}),E=wy(e,t),U=new Set(ky(e,r.name)),L=E.filter(me=>U.has(me)).length,V=E.length-L,q=Le(e),re=xy(e),We=Ry(e,new Date().toISOString()),fe=Cy(e),Ke=fe?{status:fe.status,openQuestions:fe.openQuestions}:null;return!Ke&&x&&vy(e).some(Xe=>Xe.status==="open"&&(Xe.run??"").trim()==="/discover")&&(Ke={status:"pending",openQuestions:0}),{ready:a&&u&&!n.claudeMissing,hasDocs:x,tracked:k,pendingText:T,directives:v.directives,behind:$,pendingWrites:j,localAhead:V,conflicts:L,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:q.status,devhintsCompletedVersion:q.completedVersion,devhintsToVersion:de,builderStarted:nt(e),genreUnknown:n.genreUnknown,roadmap:re,discovery:Ke,uncommittedDocs:We.dirty.length}}catch{return null}}Y();var Sy={Bash:"command",PowerShell:"command",Read:"file_path",Write:"file_path",Edit:"file_path",NotebookEdit:"notebook_path",Glob:"pattern",Grep:"pattern",WebFetch:"url",WebSearch:"query",Agent:"description",Task:"description",Skill:"skill"},pd=160,ha=200,hd=40;function Ee(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function dd(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}: ${Ee(typeof r=="string"?r:JSON.stringify(r),hd)}`);return t.length>4&&n.push("\u2026"),Ee(n.join(", "),pd)}var Py=new Set(["file_path","notebook_path"]);function Ty(e,t){if(!t)return e;let n=a=>a.replace(/\\/g,"/").replace(/\/+$/,""),o=n(e),r=`${n(t)}/`;return(process.platform==="win32"?o.toLowerCase().startsWith(r.toLowerCase()):o.startsWith(r))?o.slice(r.length):e}var yt=e=>typeof e=="string"&&e?e:null,pa=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Dy(e){let t=yt(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 Ay(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=yt(t.title);if(!o)return null;let r=Dy(t.local_path);return n("Create article",`"${Ee(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=yt(t.title),r=pa(t.article_id);return n("Update article",o?`"${Ee(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",pa(t.article_id)?`id ${pa(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",yt(t.name)?`"${Ee(yt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=yt(t.file_path);return n("Upload image",o?Ee(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Ar(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...a]=e.split("__"),u=a.join("__");if(s==="document360"){let b=Ay(u,t);if(b)return b}let h=u.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${h}`,sep:" ",arg:dd(t)}}let o=Sy[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&Py.has(o)?Ty(r,n):r;return{title:e,sep:"",arg:Ee(s,pd)}}return{title:e,sep:"",arg:dd(t)}}function Ey(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 jy(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Ey).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Ee(r,ha))]}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}: ${Ee(String(r),hd)}`);return n.length>0?[Ee(n.join(" \xB7 "),ha)]:null}return null}function Ny(e){let t=yt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Iy(e,t,n){switch(e){case"d360_create_article":{let o=Ny(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=yt(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 ${Ee(o[0],120)}`:""}`]}default:return null}}function Er(e,t=4,n,o){let r=e.replace(/\r\n/g,`
369
- `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let a=Iy(n.slice(18),o,r);if(a)return{lines:a,hidden:0}}let s=jy(r)??r.split(`
370
- `);return{lines:s.slice(0,t).map(a=>Ee(a,ha)),hidden:Math.max(0,s.length-t)}}function jr(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Nr(e,t){if(typeof e.article_id=="string"&&e.article_id)return e.article_id;try{let n=JSON.parse(t),r=(Array.isArray(n)?n[0]:n)?.id;return typeof r=="string"&&r?r:null}catch{return null}}function fd(e,t){try{let n=JSON.parse(e),r=(Array.isArray(n)?n[0]:n)?.[t];return typeof r=="string"&&/^https?:\/\//.test(r)?r:null}catch{return null}}function Ir(e){return fd(e,"url")}function _r(e){return fd(e,"preview_url")}var ew=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function tw(e,t,n,o){if(ew.test(e))try{let r=yd(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,a=Nr(t,n),u=Ir(n);e.endsWith("publish_article")&&u&&console.log(F(` \u2B95 Live: ${u}`));let h=_r(n);h?console.log(F(` \u2B95 Preview: ${h}`)):a&&s&&console.log(F(` \u2B95 Preview: ${jr(r.connection.portalUrl,s,a,r.project.languageCode??"en")}`))}catch{}}async function wd(e=process.cwd(),t="auto",n,o){let r=Oy(t);r.kind==="none"&&(console.error(""),console.error(S("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${F("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${F('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${F("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${F("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),nw(e,n),r.kind==="subscription"&&(r.stored?console.log(g(" Using your Claude subscription (no API key set).")):console.log(g(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,a=fa({cwd:e,profileName:n,allowProdWrites:s}),u={uuid:null,firstPrompt:null,titleFired:!1},h=_y({input:process.stdin,output:process.stdout}),k=[],b=null,x=!1;h.on("line",v=>{if(b){let T=b;b=null,T(v)}else k.push(v)}),h.on("close",()=>{if(x=!0,b){let v=b;b=null,v(null)}});function $(){return k.length>0?Promise.resolve(k.shift()):x?Promise.resolve(null):(process.stdout.write(F("> ")),new Promise(v=>{b=v}))}let j={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{a.close(),a=fa({cwd:e,profileName:n,allowProdWrites:s}),u={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>u.uuid,setPendingName:v=>{u.pendingName=v},setModel:async v=>a.setModel(v),withPausedInput:async v=>{h.pause();try{return await v()}finally{h.resume()}}};try{for(;;){let v=await $();if(v===null)break;let T=v.trim();if(T){if(T.startsWith("/")){let E=sd(T);if(!E)continue;let U=rd[E.name];if(!U){console.log(S(`Unknown command: /${E.name}`)),console.log(g("Type /help for the list."));continue}let L=await U(E.args,j);if(L.kind==="exit")break;if(L.kind==="clear"){j.restartAgent();continue}if(L.kind==="allow-prod"){s=!0,j.restartAgent(),console.log(_("\u2713 Production writes authorized for this session.")),console.log("");continue}if(L.kind==="resume"){a.close(),a=fa({cwd:e,resume:L.uuid,profileName:n,allowProdWrites:s});let V=Ly(L.uuid);u={uuid:L.uuid,firstPrompt:V?.firstPrompt??null,titleFired:!0},gd(L.uuid),console.log(_(`\u2713 Resumed "${L.name}"`)),console.log("");continue}if(L.kind==="forward-to-agent"){u.firstPrompt||(u.firstPrompt=L.display??L.prompt);let V=(L.display??"").trim().split(/\s+/),q=(V[0]==="/check"||V[0]==="/review")&&V.includes("--fix"),re=V.slice(1).find(fe=>!fe.startsWith("--")),We=q?Jy(e,re):[];if(await ma(a,L.prompt,r,u,e),q)try{Qy(e,We,{reviewedCap:Zy})}catch{}}else ow(e,n);continue}if(Yy(T)){let E=zy(T);if(E){try{Ky(e,{title:E,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}u.firstPrompt||(u.firstPrompt=T),await ma(a,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${E}". 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 "${E}" and the article path(s) you wrote.`,r,u,e);continue}}u.firstPrompt||(u.firstPrompt=T),await ma(a,T,r,u,e)}}}finally{a.close(),h.close()}}function nw(e,t){console.log(""),console.log(Dn("document360-writer")),console.log(g(` cwd: ${e}`));let n=By(e);if(console.log(g(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(rw(e,t)),!Hy(e))console.log(B(" 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(Bo(e),!nt(e))for(let r of Ho(e))console.log(B(` ${r}`))}catch{}try{let r=qy(e);r.persisted&&r.appType?console.log(g(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=Xy(e);for(let s of zo(r.applied))console.log(B(` ${s}`))}catch{}try{let r=Jn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Qn(r):null;if(s?.kind==="recommend"&&s.rec.note){let a=s.rec.tone==="warn"?B:g;for(let u of js(s.rec.note).split(`
371
- `))console.log(a(` ${u}`));s.rec.picker&&console.log(F(` Pick one: ${s.rec.picker.options.map(u=>u.cmd).join(" \xB7 ")}`))}}catch{}}console.log(g(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function ow(e,t){try{let n=Jn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Qn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(g(` Next: ${Xn(o.rec.lead)}`))}catch{}}function rw(e,t){try{let n=yd(e,t),o=n.production?B(" \u26A0 PRODUCTION"):"",r=Gy(n.name);if(!r)return g(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...md(r.idToken)??{},...md(r.accessToken)??{}},a=s.email??s.preferred_username??"signed in";return Vy(r)&&!r.refreshToken?B(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):g(` Document360: ${a} \xB7 profile "${n.name}"${o}`)}catch(n){return g(` Document360: ${n.message.split(".")[0]}`)}}function sw(){console.error(""),console.error(`Sign in with your Claude subscription: run ${F("claude")} once, then retry.`),console.error(` (No Claude Code? ${F("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${F("https://console.anthropic.com/settings/keys")}`)}function iw(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Fy({uuid:t,name:r??Uy(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function aw(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Wy(o,t).then(r=>{r&&My(n,r)}).catch(()=>{})}async function ma(e,t,n,o,r){let s=new Map;for await(let a of e.send(t))lw(a,o,r,n,s)}function lw(e,t,n,o,r){switch(e.type){case"session":t.uuid||iw(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Ar(e.name,e.input,process.cwd());s&&(process.stdout.write(`
372
-
373
- `),console.log(`${_("\u25CF")} ${Re(s.title)}${s.arg!==null?ue(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=ot(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let a=u=>u===1?"":"s";console.log(ue(` \u23BF Added ${s.added} line${a(s.added)}, removed ${s.removed} line${a(s.removed)}`));for(let u of s.lines)console.log(u);s.hidden>0&&console.log(g(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let a=Er(e.output,4,e.isError?void 0:s.name,s.input),u=e.isError?S:ue;a.lines.forEach((h,k)=>console.log(u((k===0?" \u23BF ":" ")+h))),a.hidden>0&&console.log(g(` \u2026 +${a.hidden} lines`)),e.isError||tw(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
374
- `);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(g(` (${_n(s)}\u2192${_n(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(gd(t.uuid),t.titleFired||aw(t,n));break}case"error":console.error(""),console.error(S(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&sw();break}}import{render as vk}from"ink";import{resolveAuth as Ck}from"document360-engine";import{useCallback as X,useEffect as Ne,useMemo as $a,useRef as te,useState as z}from"react";import{Box as ae,Text as N,useApp as vw,useInput as Cw,useStdout as Rw}from"ink";import{existsSync as hn,readFileSync as Hr,readdirSync as Sw}from"node:fs";import{basename as eo,isAbsolute as Pw,join as xa}from"node:path";import{createSession as Hd,classifyClaudeAuth as Ta,CLAUDE_CODE_SETUP_HINT as Tw,loginPkce as Dw,toStoredTokens as Aw,saveTokens as Ew,getAccessToken as jw,resolveActiveProfile as je,resolveProjectId as Nw,getArticle as Iw,decodeJwtClaims as mn,isExpired as wt,loadTokens as _t,clearTokens as _w,clearProfileProject as Ow,setTitle as Lw,slugify as Mw,touchSession as va,upsertSession as Uw,generateTitle as qd,findByName as Fw,listSessions as Ww,renameSession as Bw,suggestNextAction as Hw,readProjectConfig as ie,writeProjectConfig as Vd,resolveAndPersistAppType as qw,detectAppType as Vw,resolveModelSetting as Da,loadProfileMap as Gd,applyPull as Yd,computeSyncStatus as Ca,lintDocs as zd,compareRemoteSources as Gw,planPull as Kd,establishBaselines as Yw,rebaselineServerMeta as zw,inventoryRepo as Kw,knownEnvironments as Xw,resolveEnvironment as Qw,planPartitions as Ra,partitionEvenly as Jw,screenshotPlaceholderIds as Zw,trackedArticlePaths as ek,runPartitioned as qr,estimateBulkCost as Xd,resolveModelForOperation as Vr,readDocsPlan as tk,checkForUpdate as nk,detectInstallKind as ok,isSelfUpdatable as rk,devHintsGuidePath as Qd,toolFeedbackPath as Jd,reconcileToolFeedback as sk,reconcileUpgradeActions as ik,stampArticles as Sa,listArticleFiles as Zd,CONTENT_CAP_VERSION as Pa,ENGINE_VERSION as ap,DEFAULT_DOCS_DIR as Aa,setProfileProject as ak,writeCrashLog as lk,applyStructureOrder as ep,orderSyncLine as tp,applyRelatedArticles as np,relatedSyncLine as op}from"document360-engine";Di();dt();import{spawn as kd}from"node:child_process";function cw(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function uw(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?kd([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):kd(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",a=>o(a===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function ga(e){for(let[t,n]of cw())if(await uw(t,n,e))return!0;return!1}var dw=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function ya(e,t){if(t.closed)return e;let n=e.split(`
375
- `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){dw.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(`
376
- `)}import{existsSync as pw,mkdirSync as hw,readFileSync as fw,writeFileSync as mw}from"node:fs";import{join as bd}from"node:path";import{writerDir as gw}from"document360-engine";function $d(e){return bd(gw(e),".sessions")}function xd(e,t){return bd($d(e),`${t}.json`)}function vd(e,t,n){try{hw($d(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");mw(xd(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function wa(e,t){try{let n=xd(e,t);if(!pw(n))return[];let o=JSON.parse(fw(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var yw=e=>`\x1B]0;${e}\x07`,ww=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Cd(e){process.stdout.isTTY&&process.stdout.write(e)}function pn(e){Cd(yw(e))}function Or(e){Cd(ww(e))}var Lr=["\xB7 "," \xB7"],Mr="\u{1F7E3}";yr();Go();Y();import{Box as Rd,Text as he}from"ink";import{jsx as ye,jsxs as Ur}from"react/jsx-runtime";function kw({row:e}){switch(e.t){case"head":return ye(he,{color:K,bold:!0,children:e.s});case"text":return ye(he,{children:e.s});case"dim":return ye(he,{dimColor:!0,children:e.s});case"sub":return ye(he,{bold:!0,dimColor:!0,children:e.s});case"good":return ye(he,{color:"green",children:e.s});case"step":return Ur(he,{children:[ye(he,{color:K,children:`${e.n}. `}),e.s]});case"cmd":return Ur(he,{children:[" ",ye(he,{color:K,children:e.name.padEnd(20)}),ye(he,{dimColor:!0,children:e.s})]});case"gap":return ye(he,{children:" "})}}function Sd({tab:e,width:t,version:n,engineVersion:o}){let r=Oe[e]??Oe[0],s=6+Oe.reduce((u,h)=>u+h.label.length+4,0),a="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return Ur(Rd,{flexDirection:"column",paddingX:1,children:[Ur(he,{children:[ye(he,{color:K,bold:!0,children:"Help "}),Oe.map((u,h)=>h===e?ye(he,{color:"white",backgroundColor:K,bold:!0,children:` ${u.label} `},u.key):ye(he,{dimColor:!0,children:` ${u.label} `},u.key))]}),ye(he,{color:K,children:a}),ye(Rd,{flexDirection:"column",marginTop:1,children:r.rows.map((u,h)=>ye(kw,{row:u},h))}),ye(he,{dimColor:!0,children:`
377
- \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var bw=/^(?:\d+[.)]|[-*•])\s+/;function Pd(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
378
- `)){let a=s.trim().replace(bw,""),u=a.match(/^`([^`]+)`$/);u&&(a=u[1].trim());let h=a.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!h||!o.has(h[1].toLowerCase()))continue;let k=`/${h[1].toLowerCase()}${h[2]?` ${h[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}Y();function Zn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Ue(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Td(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var $w=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Dd(e,t,n){if(!$w.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 ka(e){return e.replace(/^[\w.-]+\//,"")}var Fr=16,Ad={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function It(e){return typeof e=="string"?e:e.cmd}function Ed(e){return typeof e=="string"?void 0:e.desc}function ba(e){return e.trim().split(/\s+/).slice(1).join(" ")}function jd(e,t){let n=ba(t);return e.some(r=>It(r).trim()===t.trim()||!!n&&ba(It(r))===n)?e.filter(r=>It(r).trim()!==t.trim()&&!(n&&ba(It(r))===n)):[]}import{isDirectiveMention as ck,stripDirectiveMention as uk,appendDirective as dk}from"document360-engine";var xw=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Nd(e){return e.replace(/\r\n?/g,`
379
- `)}function Id(e){return e.includes(`
380
- `)||e.length>200}function _d(e,t){let n=t.split(`
381
- `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Od(e,t){return e.replace(xw,n=>t.get(n)??n)}function Ld(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Wr(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
382
- `)){if(s.length===0)o.push({start:r,end:r});else for(let a=0;a<s.length;a+=n)o.push({start:r+a,end:r+Math.min(a+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function Br(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Md(e,t,n){let o=Br(e,t),r=o+n;if(r<0||r>=e.length)return t;let s=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+s,e[r].end)}function Ud(e,t,n){let o=e[Br(e,t)];return n==="start"?o.start:o.end}function Fd(e,t,n){let o=Math.max(1,n),r=e.split(`
364
+ `):null}async function sd(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Tr(n,e.slice(1).join(" ").trim());return console.log(r.ok?_(r.line):B(r.line)),{kind:"continue"}}let o=ia(n);console.log(F(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?g(r):r);return{kind:"continue"}}var id={help:ks,"?":ks,clear:Cl,exit:bs,quit:bs,init:Rs,mcp:zo,publish:Nc,audit:qn,discover:Ic,scope:Oc,pull:Yc,resolve:qc,convert:zc,write:eu,draft:su,document:iu,resume:cu,rename:uu,profile:pu,model:mu,doctor:Yn,workspace:vu,project:Cu,"allow-prod":Ru,login:Su,logout:Pu,screenshot:async(e,t)=>{let n=Wn(e);return n.mode==="capture"?Bi(n.rest,t):n.mode==="checklist"?pn():sr(e,t)},capture:Bi,"capture-setup":pn,devhints:_l,inbox:Mu,"catch-up":Uu,update:Wu,reset:Gu,check:Yu,review:Qu,reorder:Ju,structure:Xu,genre:Sr,roadmap:sd};function ad(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}dt();var hy="Or just tell me what to write or update.",fy='\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 ge(e){return e===1?"":"s"}function Dr(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Qn(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var my={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 gy(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:my,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${ge(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${ge(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
365
+ \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${ge(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${ge(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ge(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${ge(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${ge(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${ge(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${ge(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${ge(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${ge(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${ge(n)}.`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${ge(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function ld(e){return e.find(t=>t.lead||t.picker)??null}function la(e,t){let n=t.filter(a=>a.bullet).map(a=>` \u2022 ${a.bullet}`),o=ld(t),r=[];o?.lead?r.push(Qn(o.lead)):o?.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let a of t.filter(u=>u!==o).slice(0,2))a.follow&&r.push(a.follow);let s=[[e,...n].join(`
366
+ `)];return r.length&&s.push(r.join(" ")),s.push(hy),s.join(`
367
+
368
+ `)}function Jn(e){if(!e.ready)return{kind:"idle"};let t=gy(e);if(!e.hasDocs){let s=ld(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:la("\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:fy,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${ge(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${ge(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${ge(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:la("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:la("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as ca,readdirSync as da}from"node:fs";import{spawnSync as yy}from"node:child_process";import{join as Ar}from"node:path";import{readProjectConfig as ud,resolveActiveProfile as dd,loadTokens as wy,isExpired as ky,loadProfileMap as pd,localAheadPaths as by,loadKnownConflicts as $y,readDocsPlan as xy,devHintsGuidePath as vy,DEFAULT_DOCS_DIR as ua,roadmapProgress as Cy,listRoadmap as Ry,readProductBriefState as Sy,reconcileCommitRequest as Py}from"document360-engine";dt();function cd(e){try{return da(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function pa(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>cd(Ar(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&cd(Ar(e,o)))}function ha(e,t){try{let n=ud(e);if(!n)return!1;let o=dd(e,t),r=pd(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Ar(e,(n.docsDir??ua).replace(/\/+$/,""));return!!(ca(s)&&da(s).length>0||ca(vy(e)))}catch{return!1}}function Zn(e,t,n){try{let o=ud(e);if(!o)return null;let r=dd(e,t),s=wy(r.name),a=!!s&&(!ky(s)||!!s.refreshToken),u=ha(e,t)||!pa(e,o.authoritativeSourceFiles),h=pd(e,r.name),k=h?Object.keys(h.articles).length:0,b=Ar(e,(o.docsDir??ua).replace(/\/+$/,"")),x=!1;try{x=ca(b)&&da(b).length>0}catch{}let $=0;if(h?.lastAnalyzedCommit)try{let me=yy("git",["rev-list","--count",`${h.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});me.status===0&&($=parseInt((me.stdout||"").trim(),10)||0)}catch{}let j=0;try{let me=xy(e);if(me.length>0){let Xe=(o.docsDir??ua).replace(/\/+$/,"");j=hi(e,Xe,me.map(be=>be.path)).length}}catch{}let v=zn(e),T=Kn({...v,directives:0}),E=by(e,t),U=new Set($y(e,r.name)),L=E.filter(me=>U.has(me)).length,V=E.length-L,q=Le(e),re=Cy(e),We=Py(e,new Date().toISOString()),fe=Sy(e),Ke=fe?{status:fe.status,openQuestions:fe.openQuestions}:null;return!Ke&&x&&Ry(e).some(Xe=>Xe.status==="open"&&(Xe.run??"").trim()==="/discover")&&(Ke={status:"pending",openQuestions:0}),{ready:a&&u&&!n.claudeMissing,hasDocs:x,tracked:k,pendingText:T,directives:v.directives,behind:$,pendingWrites:j,localAhead:V,conflicts:L,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:q.status,devhintsCompletedVersion:q.completedVersion,devhintsToVersion:de,builderStarted:nt(e),genreUnknown:n.genreUnknown,roadmap:re,discovery:Ke,uncommittedDocs:We.dirty.length}}catch{return null}}Y();var Ty={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"},fd=160,ma=200,md=40;function Ee(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function hd(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}: ${Ee(typeof r=="string"?r:JSON.stringify(r),md)}`);return t.length>4&&n.push("\u2026"),Ee(n.join(", "),fd)}var Dy=new Set(["file_path","notebook_path"]);function Ay(e,t){if(!t)return e;let n=a=>a.replace(/\\/g,"/").replace(/\/+$/,""),o=n(e),r=`${n(t)}/`;return(process.platform==="win32"?o.toLowerCase().startsWith(r.toLowerCase()):o.startsWith(r))?o.slice(r.length):e}var wt=e=>typeof e=="string"&&e?e:null,fa=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Ey(e){let t=wt(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 jy(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=wt(t.title);if(!o)return null;let r=Ey(t.local_path);return n("Create article",`"${Ee(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=wt(t.title),r=fa(t.article_id);return n("Update article",o?`"${Ee(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",fa(t.article_id)?`id ${fa(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",wt(t.name)?`"${Ee(wt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=wt(t.file_path);return n("Upload image",o?Ee(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Er(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...a]=e.split("__"),u=a.join("__");if(s==="document360"){let b=jy(u,t);if(b)return b}let h=u.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${h}`,sep:" ",arg:hd(t)}}let o=Ty[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&Dy.has(o)?Ay(r,n):r;return{title:e,sep:"",arg:Ee(s,fd)}}return{title:e,sep:"",arg:hd(t)}}function Ny(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 Iy(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Ny).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Ee(r,ma))]}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}: ${Ee(String(r),md)}`);return n.length>0?[Ee(n.join(" \xB7 "),ma)]:null}return null}function _y(e){let t=wt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Oy(e,t,n){switch(e){case"d360_create_article":{let o=_y(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=wt(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 ${Ee(o[0],120)}`:""}`]}default:return null}}function jr(e,t=4,n,o){let r=e.replace(/\r\n/g,`
369
+ `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let a=Oy(n.slice(18),o,r);if(a)return{lines:a,hidden:0}}let s=Iy(r)??r.split(`
370
+ `);return{lines:s.slice(0,t).map(a=>Ee(a,ma)),hidden:Math.max(0,s.length-t)}}function Nr(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 gd(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 _r(e){return gd(e,"url")}function Or(e){return gd(e,"preview_url")}var nw=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function ow(e,t,n,o){if(nw.test(e))try{let r=kd(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,a=Ir(t,n),u=_r(n);e.endsWith("publish_article")&&u&&console.log(F(` \u2B95 Live: ${u}`));let h=Or(n);h?console.log(F(` \u2B95 Preview: ${h}`)):a&&s&&console.log(F(` \u2B95 Preview: ${Nr(r.connection.portalUrl,s,a,r.project.languageCode??"en")}`))}catch{}}async function bd(e=process.cwd(),t="auto",n,o){let r=My(t);r.kind==="none"&&(console.error(""),console.error(S("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${F("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${F('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${F("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${F("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),rw(e,n),r.kind==="subscription"&&(r.stored?console.log(g(" Using your Claude subscription (no API key set).")):console.log(g(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,a=ga({cwd:e,profileName:n,allowProdWrites:s}),u={uuid:null,firstPrompt:null,titleFired:!1},h=Ly({input:process.stdin,output:process.stdout}),k=[],b=null,x=!1;h.on("line",v=>{if(b){let T=b;b=null,T(v)}else k.push(v)}),h.on("close",()=>{if(x=!0,b){let v=b;b=null,v(null)}});function $(){return k.length>0?Promise.resolve(k.shift()):x?Promise.resolve(null):(process.stdout.write(F("> ")),new Promise(v=>{b=v}))}let j={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{a.close(),a=ga({cwd:e,profileName:n,allowProdWrites:s}),u={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>u.uuid,setPendingName:v=>{u.pendingName=v},setModel:async v=>a.setModel(v),withPausedInput:async v=>{h.pause();try{return await v()}finally{h.resume()}}};try{for(;;){let v=await $();if(v===null)break;let T=v.trim();if(T){if(T.startsWith("/")){let E=ad(T);if(!E)continue;let U=id[E.name];if(!U){console.log(S(`Unknown command: /${E.name}`)),console.log(g("Type /help for the list."));continue}let L=await U(E.args,j);if(L.kind==="exit")break;if(L.kind==="clear"){j.restartAgent();continue}if(L.kind==="allow-prod"){s=!0,j.restartAgent(),console.log(_("\u2713 Production writes authorized for this session.")),console.log("");continue}if(L.kind==="resume"){a.close(),a=ga({cwd:e,resume:L.uuid,profileName:n,allowProdWrites:s});let V=Uy(L.uuid);u={uuid:L.uuid,firstPrompt:V?.firstPrompt??null,titleFired:!0},wd(L.uuid),console.log(_(`\u2713 Resumed "${L.name}"`)),console.log("");continue}if(L.kind==="forward-to-agent"){u.firstPrompt||(u.firstPrompt=L.display??L.prompt);let V=(L.display??"").trim().split(/\s+/),q=(V[0]==="/check"||V[0]==="/review")&&V.includes("--fix"),re=V.slice(1).find(fe=>!fe.startsWith("--")),We=q?ew(e,re):[];if(await ya(a,L.prompt,r,u,e),q)try{Zy(e,We,{reviewedCap:tw})}catch{}}else sw(e,n);continue}if(Ky(T)){let E=Xy(T);if(E){try{Qy(e,{title:E,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}u.firstPrompt||(u.firstPrompt=T),await ya(a,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${E}". 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 "${E}" and the article path(s) you wrote.`,r,u,e);continue}}u.firstPrompt||(u.firstPrompt=T),await ya(a,T,r,u,e)}}}finally{a.close(),h.close()}}function rw(e,t){console.log(""),console.log(En("document360-writer")),console.log(g(` cwd: ${e}`));let n=qy(e);if(console.log(g(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(iw(e,t)),!Vy(e))console.log(B(" 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(Ho(e),!nt(e))for(let r of qo(e))console.log(B(` ${r}`))}catch{}try{let r=Gy(e);r.persisted&&r.appType?console.log(g(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=Jy(e);for(let s of Ko(r.applied))console.log(B(` ${s}`))}catch{}try{let r=Zn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Jn(r):null;if(s?.kind==="recommend"&&s.rec.note){let a=s.rec.tone==="warn"?B:g;for(let u of Ns(s.rec.note).split(`
371
+ `))console.log(a(` ${u}`));s.rec.picker&&console.log(F(` Pick one: ${s.rec.picker.options.map(u=>u.cmd).join(" \xB7 ")}`))}}catch{}}console.log(g(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function sw(e,t){try{let n=Zn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Jn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(g(` Next: ${Qn(o.rec.lead)}`))}catch{}}function iw(e,t){try{let n=kd(e,t),o=n.production?B(" \u26A0 PRODUCTION"):"",r=zy(n.name);if(!r)return g(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...yd(r.idToken)??{},...yd(r.accessToken)??{}},a=s.email??s.preferred_username??"signed in";return Yy(r)&&!r.refreshToken?B(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):g(` Document360: ${a} \xB7 profile "${n.name}"${o}`)}catch(n){return g(` Document360: ${n.message.split(".")[0]}`)}}function aw(){console.error(""),console.error(`Sign in with your Claude subscription: run ${F("claude")} once, then retry.`),console.error(` (No Claude Code? ${F("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${F("https://console.anthropic.com/settings/keys")}`)}function lw(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;By({uuid:t,name:r??Wy(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function cw(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Hy(o,t).then(r=>{r&&Fy(n,r)}).catch(()=>{})}async function ya(e,t,n,o,r){let s=new Map;for await(let a of e.send(t))uw(a,o,r,n,s)}function uw(e,t,n,o,r){switch(e.type){case"session":t.uuid||lw(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Er(e.name,e.input,process.cwd());s&&(process.stdout.write(`
372
+
373
+ `),console.log(`${_("\u25CF")} ${Re(s.title)}${s.arg!==null?ue(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=ot(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let a=u=>u===1?"":"s";console.log(ue(` \u23BF Added ${s.added} line${a(s.added)}, removed ${s.removed} line${a(s.removed)}`));for(let u of s.lines)console.log(u);s.hidden>0&&console.log(g(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let a=jr(e.output,4,e.isError?void 0:s.name,s.input),u=e.isError?S:ue;a.lines.forEach((h,k)=>console.log(u((k===0?" \u23BF ":" ")+h))),a.hidden>0&&console.log(g(` \u2026 +${a.hidden} lines`)),e.isError||ow(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
374
+ `);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(g(` (${Ln(s)}\u2192${Ln(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(wd(t.uuid),t.titleFired||cw(t,n));break}case"error":console.error(""),console.error(S(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&aw();break}}import{render as Rk}from"ink";import{resolveAuth as Sk}from"document360-engine";import{useCallback as X,useEffect as Ne,useMemo as va,useRef as te,useState as z}from"react";import{Box as ae,Text as N,useApp as Rw,useInput as Sw,useStdout as Pw}from"ink";import{existsSync as mn,readFileSync as qr,readdirSync as Tw}from"node:fs";import{basename as to,isAbsolute as Dw,join as Ca}from"node:path";import{createSession as Vd,classifyClaudeAuth as Aa,CLAUDE_CODE_SETUP_HINT as Aw,loginPkce as Ew,toStoredTokens as jw,saveTokens as Nw,getAccessToken as Iw,resolveActiveProfile as je,resolveProjectId as _w,getArticle as Ow,decodeJwtClaims as yn,isExpired as kt,loadTokens as Ot,clearTokens as Lw,clearProfileProject as Mw,setTitle as Uw,slugify as Fw,touchSession as Ra,upsertSession as Ww,generateTitle as Gd,findByName as Bw,listSessions as Hw,renameSession as qw,suggestNextAction as Vw,readProjectConfig as ie,writeProjectConfig as Yd,resolveAndPersistAppType as Gw,detectAppType as Yw,resolveModelSetting as Ea,loadProfileMap as zd,applyPull as Kd,computeSyncStatus as Sa,lintDocs as Xd,compareRemoteSources as zw,planPull as Qd,establishBaselines as Kw,rebaselineServerMeta as Xw,inventoryRepo as Qw,knownEnvironments as Jw,resolveEnvironment as Zw,planPartitions as Pa,partitionEvenly as ek,screenshotPlaceholderIds as tk,trackedArticlePaths as nk,runPartitioned as Vr,estimateBulkCost as Jd,resolveModelForOperation as Gr,readDocsPlan as ok,checkForUpdate as rk,detectInstallKind as sk,isSelfUpdatable as ik,devHintsGuidePath as Zd,toolFeedbackPath as ep,reconcileToolFeedback as ak,reconcileUpgradeActions as lk,stampArticles as Ta,listArticleFiles as tp,CONTENT_CAP_VERSION as Da,ENGINE_VERSION as cp,DEFAULT_DOCS_DIR as ja,setProfileProject as ck,writeCrashLog as uk,applyStructureOrder as np,orderSyncLine as op,applyRelatedArticles as rp,relatedSyncLine as sp}from"document360-engine";Ai();dt();import{spawn as $d}from"node:child_process";function dw(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function pw(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?$d([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):$d(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 wa(e){for(let[t,n]of dw())if(await pw(t,n,e))return!0;return!1}var hw=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function ka(e,t){if(t.closed)return e;let n=e.split(`
375
+ `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){hw.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(`
376
+ `)}import{existsSync as fw,mkdirSync as mw,readFileSync as gw,writeFileSync as yw}from"node:fs";import{join as xd}from"node:path";import{writerDir as ww}from"document360-engine";function vd(e){return xd(ww(e),".sessions")}function Cd(e,t){return xd(vd(e),`${t}.json`)}function Rd(e,t,n){try{mw(vd(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");yw(Cd(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function ba(e,t){try{let n=Cd(e,t);if(!fw(n))return[];let o=JSON.parse(gw(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var kw=e=>`\x1B]0;${e}\x07`,bw=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Sd(e){process.stdout.isTTY&&process.stdout.write(e)}function fn(e){Sd(kw(e))}function Lr(e){Sd(bw(e))}var Mr=["\xB7 "," \xB7"],Ur="\u{1F7E3}";wr();Yo();Y();import{Box as Pd,Text as he}from"ink";import{jsx as ye,jsxs as Fr}from"react/jsx-runtime";function $w({row:e}){switch(e.t){case"head":return ye(he,{color:K,bold:!0,children:e.s});case"text":return ye(he,{children:e.s});case"dim":return ye(he,{dimColor:!0,children:e.s});case"sub":return ye(he,{bold:!0,dimColor:!0,children:e.s});case"good":return ye(he,{color:"green",children:e.s});case"step":return Fr(he,{children:[ye(he,{color:K,children:`${e.n}. `}),e.s]});case"cmd":return Fr(he,{children:[" ",ye(he,{color:K,children:e.name.padEnd(20)}),ye(he,{dimColor:!0,children:e.s})]});case"gap":return ye(he,{children:" "})}}function Td({tab:e,width:t,version:n,engineVersion:o}){let r=Oe[e]??Oe[0],s=6+Oe.reduce((u,h)=>u+h.label.length+4,0),a="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return Fr(Pd,{flexDirection:"column",paddingX:1,children:[Fr(he,{children:[ye(he,{color:K,bold:!0,children:"Help "}),Oe.map((u,h)=>h===e?ye(he,{color:"white",backgroundColor:K,bold:!0,children:` ${u.label} `},u.key):ye(he,{dimColor:!0,children:` ${u.label} `},u.key))]}),ye(he,{color:K,children:a}),ye(Pd,{flexDirection:"column",marginTop:1,children:r.rows.map((u,h)=>ye($w,{row:u},h))}),ye(he,{dimColor:!0,children:`
377
+ \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var xw=/^(?:\d+[.)]|[-*•])\s+/;function Dd(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
378
+ `)){let a=s.trim().replace(xw,""),u=a.match(/^`([^`]+)`$/);u&&(a=u[1].trim());let h=a.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!h||!o.has(h[1].toLowerCase()))continue;let k=`/${h[1].toLowerCase()}${h[2]?` ${h[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}Y();function eo(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Ue(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Ad(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var vw=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Ed(e,t,n){if(!vw.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 $a(e){return e.replace(/^[\w.-]+\//,"")}var Wr=16,jd={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function _t(e){return typeof e=="string"?e:e.cmd}function Nd(e){return typeof e=="string"?void 0:e.desc}function xa(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Id(e,t){let n=xa(t);return e.some(r=>_t(r).trim()===t.trim()||!!n&&xa(_t(r))===n)?e.filter(r=>_t(r).trim()!==t.trim()&&!(n&&xa(_t(r))===n)):[]}import{isDirectiveMention as dk,stripDirectiveMention as pk,appendDirective as hk}from"document360-engine";var Cw=/\[Pasted text #\d+ \+\d+ lines?\]/g;function _d(e){return e.replace(/\r\n?/g,`
379
+ `)}function Od(e){return e.includes(`
380
+ `)||e.length>200}function Ld(e,t){let n=t.split(`
381
+ `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Md(e,t){return e.replace(Cw,n=>t.get(n)??n)}function Ud(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Br(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
382
+ `)){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 Hr(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Fd(e,t,n){let o=Hr(e,t),r=o+n;if(r<0||r>=e.length)return t;let s=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+s,e[r].end)}function Wd(e,t,n){let o=e[Hr(e,t)];return n==="start"?o.start:o.end}function Bd(e,t,n){let o=Math.max(1,n),r=e.split(`
383
383
  `),s=0;for(let a=r.length-1;a>=0;a--){let u=r[a];if(s+=Math.max(1,Math.ceil(u.length/o)),s>=t){let h=s-t;return{text:[h>0?u.slice(h*o):u,...r.slice(a+1)].join(`
384
- `),truncated:a>0||h>0}}}return{text:e,truncated:!1}}function Wd(e,t){if(t||e.length===0||/\s$/.test(e)||/[.!?:…]["')\]]?$/.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 Bd(e){let t=!1,n=0,o=0;for(let r of e.split(`
385
- `)){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 to,jsx as I,jsxs as Q}from"react/jsx-runtime";var pk={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},rp=` 1. /init \u2014 pick your Document360 environment & scaffold config
384
+ `),truncated:a>0||h>0}}}return{text:e,truncated:!1}}function Hd(e,t){if(t||e.length===0||/\s$/.test(e)||/[.!?:…]["')\]]?$/.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 qd(e){let t=!1,n=0,o=0;for(let r of e.split(`
385
+ `)){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 no,jsx as I,jsxs as Q}from"react/jsx-runtime";var fk={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},ip=` 1. /init \u2014 pick your Document360 environment & scaffold config
386
386
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
387
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function hk(e,t,n,o){let r=Ta(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=Da(e),u=ie(e),h=(u?.docsDir??Aa).replace(/\/+$/,""),k=u?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${h}/ + config`,b={version:t,engineVersion:ap,captureVersion:gr(),claude:s,model:a.model,modelSource:pk[a.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:u!==null,mode:k};if(u===null)return b;try{let x=je(e,o);b.profile=x.name,b.apiUrl=x.connection.apiUrl,b.prod=x.production,b.project=x.project.projectName??x.project.projectId??"(chosen at login)";let $=_t(x.name);if($){let j={...mn($.idToken)??{},...mn($.accessToken)??{}},v=j.email??j.preferred_username??"signed in";wt($)?$.refreshToken&&(b.who=v,b.loggedOut=!1,b.sessionHint="session expired \u2014 refreshing\u2026"):(b.who=v,b.loggedOut=!1,b.sessionHint=`session valid until ${new Date($.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return b}function fk(e,t){try{let n=je(e,t),o=_t(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...mn(o.idToken)??{},...mn(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return wt(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 sp=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],gn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],mk="Ask me to write or update an article\u2026";function fn({ch:e,dim:t}){let[n,o]=z(!0);return Ne(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),I(N,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var gk=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function ip(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var yk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function wk({startTime:e,chars:t}){let[n,o]=z(0);Ne(()=>{let h=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(h)},[]);let r=gn[n%gn.length],s=sp[Math.floor(n/16)%sp.length],a=Math.floor((Date.now()-e)/1e3),u=Math.round(t/4);return Q(ae,{children:[I(N,{color:K,children:` ${r} ${s}\u2026 `}),I(N,{color:"gray",children:`(${On(a)} \xB7 ~${u} tokens \xB7 esc to interrupt)`})]})}function kk({text:e}){let[t,n]=z(0);return Ne(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),I(ae,{paddingX:1,children:I(N,{color:K,children:`${gn[t%gn.length]} ${e}`})})}var bk=12e4;function $k({p:e}){let[t,n]=z(0);Ne(()=>{let E=setInterval(()=>n(U=>U+1),150);return()=>clearInterval(E)},[]);let o=gn[t%gn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),a=Math.round(e.chars/4),u=Date.now()-e.lastAt>=bk,h=e.verb??"Converting",k=e.unit??"article",b=e.rows.reduce((E,U)=>E+U.items,0),x=h.toLowerCase(),$=e.rows,j=0;if($.length>Fr){let E=$.findIndex(L=>L.status==="active"||L.status==="pending"),U=Math.max(0,Math.min(E-2,$.length-Fr));j=$.slice(0,U).filter(L=>L.status==="done").length,$=$.slice(U,U+Fr)}let v=Math.min(40,Math.max(...$.map(E=>ka(E.label).length),0)),T=E=>E==="failed"?"red":E==="active"?K:void 0;return Q(ae,{flexDirection:"column",children:[Q(ae,{children:[I(N,{color:K,children:` ${o} ${h} ${b} ${k}${b===1?"":"s"} `}),I(N,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${a} tokens \xB7 ${On(r)} \xB7 esc to stop`})]}),j>0&&I(N,{dimColor:!0,children:` \u2714 +${j} done`}),$.map(E=>Q(N,{color:T(E.status),dimColor:E.status==="done"||E.status==="pending",children:[` ${Ad[E.status]} ${ka(E.label).padEnd(v)}`,E.status==="active"&&E.itemsDone!==void 0?` (${E.itemsDone}/${E.items} ${k}${E.items===1?"":"s"})`:E.status!=="pending"?` (${E.items} ${k}${E.items===1?"":"s"})`:"",E.status==="active"?` \u2190 ${x}\u2026`:""]},E.label)),u&&I(N,{color:"yellow",children:` \u26A0 no activity for ${On(s)} \u2014 press esc to stop if it's wedged`})]})}var xk=10800*1e3;function lp({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=vw(),[s,a]=z(n),[u,h]=z(null),[k,b]=z({text:"",pos:0}),x=k.text,$=X(c=>{b(l=>{let i=typeof c=="function"?c(l.text):c;return{text:i,pos:i.length}})},[]),j=X(c=>{b(l=>({text:l.text.slice(0,l.pos)+c+l.text.slice(l.pos),pos:l.pos+c.length}))},[]),v=X(()=>{b(c=>{if(c.pos===0)return c;let l=c.text.slice(0,c.pos),i=Ld(l)??l.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[T,E]=z(!1),[U,L]=z(!1),[V,q]=z(0),[re,We]=z(!1),[fe,Ke]=z(null),[me,Xe]=z(null),[be,Be]=z([]),no=te(!1),yn=te(!1),Yr=te(!1),[zr,Ia]=z(!1),oo=te(0),[mp,ro]=z(!1),[gp,so]=z(!1),[Kr,_a]=z(null),[yp,Ot]=z(0),kt=te(0),[Xr,Lt]=z(0),[Mt,io]=z(null),Oa=te(new Map),wp=te(0),Ut=te([]),Ie=te(null);Ie.current===null&&(Ie.current=Hd({cwd:e,profileName:s,allowProdWrites:!1}));let Qe=te({uuid:null,firstPrompt:null,titleFired:!1}),ao=te(new Map),La=te(null),Ft=te(!1),Qr=te([]),pe=te([]),Wt=te([]),lo=te(null),[Ma,bt]=z(null),Jr=te(null),[$t,xt]=z(null),[Je,Bt]=z(null),[Ze,Ht]=z(null),[$e,qt]=z(null),[Pe,vt]=z(null),[rt,Vt]=z(null),[st,Ct]=z(null),[et,Rt]=z(null),[Ua,wn]=z(null),[Te,St]=z(null),[Ce,Gt]=z(null),[Fa,Zr]=z([]),Pt=te([]),kn=te(!1),we=te(null),[co,se]=z(null),[Wa,uo]=z(null),po=te(!1),bn=te(null),$n=te(null),[De,Tt]=z(null),[ho,xn]=z(null),es=!!(Ze||$e||Pe||rt||st||et||Te||Ce||De||ho),[Ba,Yt]=z(0),[Ha,zt]=z(0),[kp,qa]=z(0),ts=$a(()=>{try{let c=Da(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,kp]),{stdout:_e}=Rw(),[,bp]=z(0),Va=te(`${_e.columns??80}x${_e.rows??24}`),it=X(()=>Math.max(20,(_e.columns??80)-1),[_e]),d=X(c=>{Ut.current.push(c),console.log(Ns(c,it()))},[it]),xe=X((c,l)=>{oo.current++,Ke(c),Xe(l??null)},[]),He=X(()=>{oo.current++,Ke(null),Xe(null)},[]),Z=X(c=>xe(c,Tr({kind:"cmd",cmd:c,reason:""})),[xe]),fo=X((c,l)=>{!l?.silent&&c.note&&d({kind:"note",tone:c.tone,text:c.note}),c.picker&&(Be(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),wn(c.picker.title)),c.lead&&xe(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,Tr(c.lead))},[d,xe]),ve=X((c,l,i="info")=>{c&&d({kind:"note",tone:i,text:c}),l&&xe(l.kind==="cmd"?l.cmd:l.text,Tr(l))},[d,xe]),[vn,ns]=z(null),[$p,Ga]=z(!1),Kt=X(c=>{ns(c),Ga(!1),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),os=te(!1),rs=X(async()=>{try{if(os.current||!rk(ok())||ie(e)?.mode==="engineer")return;let c=await nk({pkg:dn,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;os.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${dn} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),so(!0),(await xr().finally(()=>so(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),Z("/exit"),_a(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${$r}`})}catch{}},[e,o,d,Z]),mo=X(c=>{let l=Me(e,s);return l.ok?!0:(d({kind:"note",tone:"warn",text:l.reason}),$n.current=c,Z("/login"),!1)},[e,s,d,Z]),[go,ss]=z(null),Dt=X(c=>{let l=Jn(e,s,{claudeMissing:Ta(t).state==="missing",allowAutoAudit:c,genreUnknown:Yr.current});return l?Qn(l):{kind:"idle"}},[e,s,t]),Cn=te(!0),Xt=te(!1),yo=te(0),Rn=te(0);Ne(()=>{let c=setInterval(()=>{if(Cn.current){yo.current=0,Rn.current=0;return}if(!T)try{if(!hn(Qd(e)))return;if(Le(e).status==="current"){Cn.current=!0,yo.current=0,Rn.current=0;let i=Dt(!1),f=i.kind==="recommend"?i.rec:null,P=Xt.current?`\u2713 Your builder finished the protocol update (v${de}) \u2014 the dev\u2194docs hand-off is current again.`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs.";d({kind:"note",tone:"ok",text:`${P}${f?.lead?` ${Xn(f.lead)}`:""}`}),ns(null),f&&(f.lead||f.picker)?fo(f,{silent:!0}):Xt.current||xe("write the docs for this repo"),q(G=>G+1);return}if(Xt.current)return;yo.current+=1;let l=yo.current;if((l===4||l%15===0)&&Rn.current<3){Rn.current+=1;let i=Rn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:nt(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,T,d,Dt,fo,xe]),Ne(()=>{let c=Ma??eo(e);if(!T){Or(0),pn(`${Mr} ${c}`);return}Or(3);let l=0;pn(`${Lr[0]} ${c}`);let i=setInterval(()=>{l=(l+1)%Lr.length,pn(`${Lr[l]} ${c}`)},400);return()=>clearInterval(i)},[T,e,Ma]),Ne(()=>()=>Or(0),[]),Ne(()=>{let c=performance.now(),l=[],i=(y,w)=>{let m=performance.now();try{return w()}finally{let D=Math.round(performance.now()-m);D>=80&&l.push(`${y}: ${D}ms`)}};d({kind:"banner",info:i("banner",()=>hk(e,o,t,s))});let f=Ta(t).state==="missing";if(f&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
388
- ${Tw}
387
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function mk(e,t,n,o){let r=Aa(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",a=Ea(e),u=ie(e),h=(u?.docsDir??ja).replace(/\/+$/,""),k=u?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${h}/ + config`,b={version:t,engineVersion:cp,captureVersion:yr(),claude:s,model:a.model,modelSource:fk[a.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:u!==null,mode:k};if(u===null)return b;try{let x=je(e,o);b.profile=x.name,b.apiUrl=x.connection.apiUrl,b.prod=x.production,b.project=x.project.projectName??x.project.projectId??"(chosen at login)";let $=Ot(x.name);if($){let j={...yn($.idToken)??{},...yn($.accessToken)??{}},v=j.email??j.preferred_username??"signed in";kt($)?$.refreshToken&&(b.who=v,b.loggedOut=!1,b.sessionHint="session expired \u2014 refreshing\u2026"):(b.who=v,b.loggedOut=!1,b.sessionHint=`session valid until ${new Date($.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return b}function gk(e,t){try{let n=je(e,t),o=Ot(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...yn(o.idToken)??{},...yn(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return kt(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 ap=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],wn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],yk="Ask me to write or update an article\u2026";function gn({ch:e,dim:t}){let[n,o]=z(!0);return Ne(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),I(N,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var wk=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function lp(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var kk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function bk({startTime:e,chars:t}){let[n,o]=z(0);Ne(()=>{let h=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(h)},[]);let r=wn[n%wn.length],s=ap[Math.floor(n/16)%ap.length],a=Math.floor((Date.now()-e)/1e3),u=Math.round(t/4);return Q(ae,{children:[I(N,{color:K,children:` ${r} ${s}\u2026 `}),I(N,{color:"gray",children:`(${Mn(a)} \xB7 ~${u} tokens \xB7 esc to interrupt)`})]})}function $k({text:e}){let[t,n]=z(0);return Ne(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),I(ae,{paddingX:1,children:I(N,{color:K,children:`${wn[t%wn.length]} ${e}`})})}var xk=12e4;function vk({p:e}){let[t,n]=z(0);Ne(()=>{let E=setInterval(()=>n(U=>U+1),150);return()=>clearInterval(E)},[]);let o=wn[t%wn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),a=Math.round(e.chars/4),u=Date.now()-e.lastAt>=xk,h=e.verb??"Converting",k=e.unit??"article",b=e.rows.reduce((E,U)=>E+U.items,0),x=h.toLowerCase(),$=e.rows,j=0;if($.length>Wr){let E=$.findIndex(L=>L.status==="active"||L.status==="pending"),U=Math.max(0,Math.min(E-2,$.length-Wr));j=$.slice(0,U).filter(L=>L.status==="done").length,$=$.slice(U,U+Wr)}let v=Math.min(40,Math.max(...$.map(E=>$a(E.label).length),0)),T=E=>E==="failed"?"red":E==="active"?K:void 0;return Q(ae,{flexDirection:"column",children:[Q(ae,{children:[I(N,{color:K,children:` ${o} ${h} ${b} ${k}${b===1?"":"s"} `}),I(N,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${a} tokens \xB7 ${Mn(r)} \xB7 esc to stop`})]}),j>0&&I(N,{dimColor:!0,children:` \u2714 +${j} done`}),$.map(E=>Q(N,{color:T(E.status),dimColor:E.status==="done"||E.status==="pending",children:[` ${jd[E.status]} ${$a(E.label).padEnd(v)}`,E.status==="active"&&E.itemsDone!==void 0?` (${E.itemsDone}/${E.items} ${k}${E.items===1?"":"s"})`:E.status!=="pending"?` (${E.items} ${k}${E.items===1?"":"s"})`:"",E.status==="active"?` \u2190 ${x}\u2026`:""]},E.label)),u&&I(N,{color:"yellow",children:` \u26A0 no activity for ${Mn(s)} \u2014 press esc to stop if it's wedged`})]})}var Ck=10800*1e3;function up({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Rw(),[s,a]=z(n),[u,h]=z(null),[k,b]=z({text:"",pos:0}),x=k.text,$=X(c=>{b(l=>{let i=typeof c=="function"?c(l.text):c;return{text:i,pos:i.length}})},[]),j=X(c=>{b(l=>({text:l.text.slice(0,l.pos)+c+l.text.slice(l.pos),pos:l.pos+c.length}))},[]),v=X(()=>{b(c=>{if(c.pos===0)return c;let l=c.text.slice(0,c.pos),i=Ud(l)??l.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[T,E]=z(!1),[U,L]=z(!1),[V,q]=z(0),[re,We]=z(!1),[fe,Ke]=z(null),[me,Xe]=z(null),[be,Be]=z([]),oo=te(!1),kn=te(!1),zr=te(!1),[Kr,Oa]=z(!1),ro=te(0),[yp,so]=z(!1),[wp,io]=z(!1),[Xr,La]=z(null),[kp,Lt]=z(0),bt=te(0),[Qr,Mt]=z(0),[Ut,ao]=z(null),Ma=te(new Map),bp=te(0),Ft=te([]),Ie=te(null);Ie.current===null&&(Ie.current=Vd({cwd:e,profileName:s,allowProdWrites:!1}));let Qe=te({uuid:null,firstPrompt:null,titleFired:!1}),lo=te(new Map),Ua=te(null),Wt=te(!1),Jr=te([]),pe=te([]),Bt=te([]),co=te(null),[Fa,$t]=z(null),Zr=te(null),[xt,vt]=z(null),[Je,Ht]=z(null),[Ze,qt]=z(null),[$e,Vt]=z(null),[Pe,Ct]=z(null),[rt,Gt]=z(null),[st,Rt]=z(null),[et,St]=z(null),[Wa,bn]=z(null),[Te,Pt]=z(null),[Ce,Yt]=z(null),[Ba,es]=z([]),Tt=te([]),$n=te(!1),we=te(null),[uo,se]=z(null),[Ha,po]=z(null),ho=te(!1),xn=te(null),vn=te(null),[De,Dt]=z(null),[fo,Cn]=z(null),ts=!!(Ze||$e||Pe||rt||st||et||Te||Ce||De||fo),[qa,zt]=z(0),[Va,Kt]=z(0),[$p,Ga]=z(0),ns=va(()=>{try{let c=Ea(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,$p]),{stdout:_e}=Pw(),[,xp]=z(0),Ya=te(`${_e.columns??80}x${_e.rows??24}`),it=X(()=>Math.max(20,(_e.columns??80)-1),[_e]),d=X(c=>{Ft.current.push(c),console.log(Is(c,it()))},[it]),xe=X((c,l)=>{ro.current++,Ke(c),Xe(l??null)},[]),He=X(()=>{ro.current++,Ke(null),Xe(null)},[]),Z=X(c=>xe(c,Dr({kind:"cmd",cmd:c,reason:""})),[xe]),mo=X((c,l)=>{!l?.silent&&c.note&&d({kind:"note",tone:c.tone,text:c.note}),c.picker&&(Be(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),bn(c.picker.title)),c.lead&&xe(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,Dr(c.lead))},[d,xe]),ve=X((c,l,i="info")=>{c&&d({kind:"note",tone:i,text:c}),l&&xe(l.kind==="cmd"?l.cmd:l.text,Dr(l))},[d,xe]),[Rn,os]=z(null),[vp,za]=z(!1),Xt=X(c=>{os(c),za(!1),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),rs=te(!1),ss=X(async()=>{try{if(rs.current||!ik(sk())||ie(e)?.mode==="engineer")return;let c=await rk({pkg:hn,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;rs.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${hn} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),io(!0),(await vr().finally(()=>io(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),Z("/exit"),La(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${xr}`})}catch{}},[e,o,d,Z]),go=X(c=>{let l=Me(e,s);return l.ok?!0:(d({kind:"note",tone:"warn",text:l.reason}),vn.current=c,Z("/login"),!1)},[e,s,d,Z]),[yo,is]=z(null),At=X(c=>{let l=Zn(e,s,{claudeMissing:Aa(t).state==="missing",allowAutoAudit:c,genreUnknown:zr.current});return l?Jn(l):{kind:"idle"}},[e,s,t]),Sn=te(!0),Qt=te(!1),wo=te(0),Pn=te(0);Ne(()=>{let c=setInterval(()=>{if(Sn.current){wo.current=0,Pn.current=0;return}if(!T)try{if(!mn(Zd(e)))return;if(Le(e).status==="current"){Sn.current=!0,wo.current=0,Pn.current=0;let i=At(!1),f=i.kind==="recommend"?i.rec:null,P=Qt.current?`\u2713 Your builder finished the protocol update (v${de}) \u2014 the dev\u2194docs hand-off is current again.`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs.";d({kind:"note",tone:"ok",text:`${P}${f?.lead?` ${Qn(f.lead)}`:""}`}),os(null),f&&(f.lead||f.picker)?mo(f,{silent:!0}):Qt.current||xe("write the docs for this repo"),q(G=>G+1);return}if(Qt.current)return;wo.current+=1;let l=wo.current;if((l===4||l%15===0)&&Pn.current<3){Pn.current+=1;let i=Pn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:nt(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,T,d,At,mo,xe]),Ne(()=>{let c=Fa??to(e);if(!T){Lr(0),fn(`${Ur} ${c}`);return}Lr(3);let l=0;fn(`${Mr[0]} ${c}`);let i=setInterval(()=>{l=(l+1)%Mr.length,fn(`${Mr[l]} ${c}`)},400);return()=>clearInterval(i)},[T,e,Fa]),Ne(()=>()=>Lr(0),[]),Ne(()=>{let c=performance.now(),l=[],i=(y,w)=>{let m=performance.now();try{return w()}finally{let D=Math.round(performance.now()-m);D>=80&&l.push(`${y}: ${D}ms`)}};d({kind:"banner",info:i("banner",()=>mk(e,o,t,s))});let f=Aa(t).state==="missing";if(f&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
388
+ ${Aw}
389
389
  Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!ie(e)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
390
- ${rp}`}),Z(f?"/doctor":"/init");return}f&&Z("/doctor");try{let y=je(e,s),w=_t(y.name);w&&wt(w)&&w.refreshToken?jw({profile:y.name,connection:y.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),q(m=>m+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Z("/login")}):(!w||wt(w))&&(d({kind:"note",tone:"warn",text:`Profile "${y.name}" is not signed in \u2014 sign in with /login.`}),Z("/login"))}catch{}try{let y=ie(e),w=je(e,s),m=_t(w.name);y&&m&&!wt(m)&&ua(e,y.authoritativeSourceFiles)&&!da(e,s)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),Z("/scope"))}catch{}try{let y=i("resolve-genre",()=>qw(e));y.persisted&&y.appType?d({kind:"note",tone:"ok",text:`\u2713 Detected a ${y.appType} app \u2014 enabled the ${y.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):y.source==="unknown"&&ie(e)&&(Yr.current=!0)}catch{}let P=Le(e);try{if(i("reconcile-devhints",()=>Bo(e)),P.status!=="current"&&!nt(e)){let y=Ho(e);y.length&&(d({kind:"note",tone:"warn",text:y.join(`
391
- `)}),Kt(jt()),Cn.current=!1,Xt.current=!1)}}catch{}try{let y=i("reconcile-feedback",()=>sk(e));y.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${y.archived} resolved item${y.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${y.open>0?`; ${y.open} still open`:""}.`})}catch{}try{let y=i("upgrade-actions",()=>ik(e));y.applied.length>0&&d({kind:"note",tone:"warn",text:zo(y.applied).join(`
392
- `)})}catch{}let G=i("ready-decision",()=>Dt(!0));G.kind==="autoAudit"?(d({kind:"note",tone:"info",text:G.note}),Bn().then(y=>{y.kind==="forward-to-agent"&&y.prompt&&oe(y.prompt,{display:y.display,quietUser:!0})})):G.kind==="recommend"&&fo(G.rec);let p=Math.round(performance.now()-c);p>=800&&lk({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${p}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${l.length?l.join(`
390
+ ${ip}`}),Z(f?"/doctor":"/init");return}f&&Z("/doctor");try{let y=je(e,s),w=Ot(y.name);w&&kt(w)&&w.refreshToken?Iw({profile:y.name,connection:y.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),q(m=>m+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Z("/login")}):(!w||kt(w))&&(d({kind:"note",tone:"warn",text:`Profile "${y.name}" is not signed in \u2014 sign in with /login.`}),Z("/login"))}catch{}try{let y=ie(e),w=je(e,s),m=Ot(w.name);y&&m&&!kt(m)&&pa(e,y.authoritativeSourceFiles)&&!ha(e,s)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),Z("/scope"))}catch{}try{let y=i("resolve-genre",()=>Gw(e));y.persisted&&y.appType?d({kind:"note",tone:"ok",text:`\u2713 Detected a ${y.appType} app \u2014 enabled the ${y.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):y.source==="unknown"&&ie(e)&&(zr.current=!0)}catch{}let P=Le(e);try{if(i("reconcile-devhints",()=>Ho(e)),P.status!=="current"&&!nt(e)){let y=qo(e);y.length&&(d({kind:"note",tone:"warn",text:y.join(`
391
+ `)}),Xt(Nt()),Sn.current=!1,Qt.current=!1)}}catch{}try{let y=i("reconcile-feedback",()=>ak(e));y.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${y.archived} resolved item${y.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${y.open>0?`; ${y.open} still open`:""}.`})}catch{}try{let y=i("upgrade-actions",()=>lk(e));y.applied.length>0&&d({kind:"note",tone:"warn",text:Ko(y.applied).join(`
392
+ `)})}catch{}let G=i("ready-decision",()=>At(!0));G.kind==="autoAudit"?(d({kind:"note",tone:"info",text:G.note}),qn().then(y=>{y.kind==="forward-to-agent"&&y.prompt&&oe(y.prompt,{display:y.display,quietUser:!0})})):G.kind==="recommend"&&mo(G.rec);let p=Math.round(performance.now()-c);p>=800&&uk({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${p}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${l.length?l.join(`
393
393
  `):"no single phase \u226580ms"}
394
- cwd: ${e}`}),rs()},[]),Ne(()=>{let c=setInterval(()=>{rs()},xk);return()=>clearInterval(c)},[rs]),Ne(()=>{if(T||re||zr||no.current||yn.current||fe!==null||be.length>0||x!==""||vn!==null||pe.current.length>0||lo.current||es)return;let c=Dt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&fo(c.rec,{silent:!0})},[T,re,fe,be,x,vn,es,V,Dt,zr]),Ne(()=>{let c=null,l=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let f=`${_e.columns??80}x${_e.rows??24}`;f!==Va.current&&(Va.current=f,bp(P=>P+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+oc(Ut.current,it())+"\x1B[?2026l")},80))},400)};return _e.on("resize",i),()=>{c&&clearTimeout(c),l&&clearTimeout(l),_e.off("resize",i)}},[_e,it]);let qe=Math.max(20,(_e.columns??80)-1),Ya=$a(()=>fk(e,s),[e,s,V]),is=(()=>{if(gp)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Kr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Kr?` v${Kr}`:""}\u2026`,isSetup:!0};if(go)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(vn)return $p?{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(pe.current.length>0)return pe.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=ie(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let l=xa(e,(c.docsDir??Aa).replace(/\/+$/,"")),i=(()=>{try{return hn(l)&&Sw(l).length>0}catch{return!1}})();try{let f=je(e,s),P=_t(f.name);if(!(!!P&&!(wt(P)&&!P.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:mk,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Ve=zl(x),za=Ve.length>0&&!T,wo=Math.max(3,Math.min(12,(_e.rows??24)-8)),ko=Math.min(Xr,Math.max(0,Ve.length-1)),At=Ve.length<=wo?0:Math.min(Math.max(0,ko-Math.floor(wo/2)),Ve.length-wo),as=Ve.slice(At,At+wo),ls=u!==null?Fd(u,8,qe):null,bo=Te?Te.paths.filter(c=>!Te.query||c.toLowerCase().includes(Te.query.toLowerCase())).slice(0,8):[],$o=De?De.sessions.filter(c=>{let l=De.query.toLowerCase();return!l||c.name.toLowerCase().includes(l)||c.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],Ae=X((c,l)=>{Ie.current?.close(),Ie.current=Hd({cwd:e,resume:c,profileName:l??s,allowProdWrites:Ft.current}),c||(Qe.current={uuid:null,firstPrompt:null,titleFired:!1},bt(null)),Yt(0),zt(0)},[e,s]),Ka=X((c,l,i)=>{if(gk.test(c))try{let f=je(e,s),P=typeof l.project_id=="string"&&l.project_id||f.project.projectId,G=Nr(l,i),p=[],y=Ir(i);c.endsWith("publish_article")&&y&&p.push(`Live: ${y}`);let w=_r(i);w?p.push(`Preview: ${w}`):G&&P&&p.push(`Preview: ${jr(f.connection.portalUrl,P,G,f.project.languageCode??"en")}`),p.length>0&&d({kind:"link",lines:p})}catch{}},[e,s,d]),oe=X(async(c,l)=>{ro(!0),no.current=!1,yn.current=!1,He(),Be([]),wn(null),ns(null);let i=oo.current;if(l?.display?.startsWith("/"))try{let C=td(e,l.display);C&&(c=`${c}
394
+ cwd: ${e}`}),ss()},[]),Ne(()=>{let c=setInterval(()=>{ss()},Ck);return()=>clearInterval(c)},[ss]),Ne(()=>{if(T||re||Kr||oo.current||kn.current||fe!==null||be.length>0||x!==""||Rn!==null||pe.current.length>0||co.current||ts)return;let c=At(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&mo(c.rec,{silent:!0})},[T,re,fe,be,x,Rn,ts,V,At,Kr]),Ne(()=>{let c=null,l=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let f=`${_e.columns??80}x${_e.rows??24}`;f!==Ya.current&&(Ya.current=f,xp(P=>P+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+sc(Ft.current,it())+"\x1B[?2026l")},80))},400)};return _e.on("resize",i),()=>{c&&clearTimeout(c),l&&clearTimeout(l),_e.off("resize",i)}},[_e,it]);let qe=Math.max(20,(_e.columns??80)-1),Ka=va(()=>gk(e,s),[e,s,V]),as=(()=>{if(wp)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(yo)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(Rn)return vp?{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(pe.current.length>0)return pe.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=ie(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let l=Ca(e,(c.docsDir??ja).replace(/\/+$/,"")),i=(()=>{try{return mn(l)&&Tw(l).length>0}catch{return!1}})();try{let f=je(e,s),P=Ot(f.name);if(!(!!P&&!(kt(P)&&!P.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:yk,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Ve=Xl(x),Xa=Ve.length>0&&!T,ko=Math.max(3,Math.min(12,(_e.rows??24)-8)),bo=Math.min(Qr,Math.max(0,Ve.length-1)),Et=Ve.length<=ko?0:Math.min(Math.max(0,bo-Math.floor(ko/2)),Ve.length-ko),ls=Ve.slice(Et,Et+ko),cs=u!==null?Bd(u,8,qe):null,$o=Te?Te.paths.filter(c=>!Te.query||c.toLowerCase().includes(Te.query.toLowerCase())).slice(0,8):[],xo=De?De.sessions.filter(c=>{let l=De.query.toLowerCase();return!l||c.name.toLowerCase().includes(l)||c.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],Ae=X((c,l)=>{Ie.current?.close(),Ie.current=Vd({cwd:e,resume:c,profileName:l??s,allowProdWrites:Wt.current}),c||(Qe.current={uuid:null,firstPrompt:null,titleFired:!1},$t(null)),zt(0),Kt(0)},[e,s]),Qa=X((c,l,i)=>{if(wk.test(c))try{let f=je(e,s),P=typeof l.project_id=="string"&&l.project_id||f.project.projectId,G=Ir(l,i),p=[],y=_r(i);c.endsWith("publish_article")&&y&&p.push(`Live: ${y}`);let w=Or(i);w?p.push(`Preview: ${w}`):G&&P&&p.push(`Preview: ${Nr(f.connection.portalUrl,P,G,f.project.languageCode??"en")}`),p.length>0&&d({kind:"link",lines:p})}catch{}},[e,s,d]),oe=X(async(c,l)=>{so(!0),oo.current=!1,kn.current=!1,He(),Be([]),bn(null),os(null);let i=ro.current;if(l?.display?.startsWith("/"))try{let C=od(e,l.display);C&&(c=`${c}
395
395
 
396
- ${C}`)}catch{}l?.quietUser||d({kind:"user",text:l?.echoDisplay&&l.display?l.display:c});let f=Qe.current;f.firstPrompt||(f.firstPrompt=l?.display??c),kt.current=Date.now(),Ot(0),E(!0),ao.current.clear();let P="",G=!1,p=!1,y="",w={num:0,closed:!1,cueSeen:!1},m=null,D=()=>{m||(m=setTimeout(()=>{m=null,h(y.length>0?y:null)},60))},A=()=>{m&&clearTimeout(m),m=null,h(null)},R=(C=!1)=>{let{head:W,keep:M}=Wd(y,C);W.trim()&&d({kind:"assistant",text:ya(W.trimEnd(),w)}),y=M,A()};try{for await(let C of Ie.current.send(c))if(C.type==="session"){if(!f.uuid){f.uuid=C.sessionId;let W=new Date().toISOString(),M=Jr.current,H=M??Mw(f.firstPrompt??"session");Uw({uuid:C.sessionId,name:H,renamed:!!M,titled:!1,cwd:e,firstPrompt:f.firstPrompt??"",createdAt:W,updatedAt:W}),bt(H),Jr.current=null}}else if(C.type==="text"){y+=C.delta,P+=C.delta;let W=Bd(y);if(W>0){let M=y.slice(0,W).trimEnd();M&&d({kind:"assistant",text:ya(M,w)}),y=y.slice(W)}D(),Ot(M=>M+C.delta.length)}else if(C.type==="tool"){G=!0;let M=(le=>typeof le=="string"&&le?le.replace(/\\/g,"/").toLowerCase():null)(C.input.file_path??C.input.notebook_path),H=["Edit","Write","MultiEdit","NotebookEdit"].includes(C.name),J=C.name==="Read"&&M!==null&&M===La.current;if(La.current=H?M:null,J)R(),d({kind:"tool",title:"Read",sep:"",arg:"(re-checking the file it just edited)"});else{let le=Ar(C.name,C.input,e);le&&(R(),d({kind:"tool",title:le.title,sep:le.sep,arg:le.arg}),ao.current.set(C.id,{name:C.name,input:C.input}))}}else if(C.type==="article_diff"){let W=ot(C.oldContent,C.newContent,it());W&&(R(),d({kind:"diff",added:W.added,removed:W.removed,lines:W.lines,hidden:W.hidden}))}else if(C.type==="tool_result"){C.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(C.output)&&(po.current=!0);let W=ao.current.get(C.id);if(W){ao.current.delete(C.id),R();let M=Er(C.output,4,C.isError?void 0:W.name,W.input);d({kind:"tool-result",lines:M.lines,hidden:M.hidden,isError:C.isError}),C.isError||Ka(W.name,W.input,C.output)}}else if(C.type==="result"){R(!0),Yt(M=>M+C.outputTokens),zt(M=>M+C.costUsd);let W=C.inputTokens+C.cacheReadTokens+C.cacheCreationTokens;if(d({kind:"done",seconds:Math.round((Date.now()-kt.current)/1e3),tokens:C.outputTokens,costUsd:C.costUsd,ok:C.ok,...W>0?{inTokens:W,cachedPct:Math.round(C.cacheReadTokens/W*100)}:{}}),!p&&!G&&!P.trim()&&!kn.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),C.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(P))try{let M=Jd(e);if(hn(M)){let H=Hr(M,"utf8").trim();H&&(ss(H),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(yn.current=C.ok&&/\?[\s*_"')\]]*$/.test(P.trimEnd()),C.ok&&w.cueSeen)Ia(!0),Be([]);else{let M=C.ok?Pd(P,sn.map(H=>H.name)):[];if(M.length>0)Z(M[0]);else if(C.ok&&P.trim()&&!yn.current){let H=Dt(!1);H.kind==="recommend"&&(H.rec.lead||H.rec.picker)||Hw(c,P,e).then(J=>{J&&oo.current===i&&xe(J)}).catch(()=>{})}}if(f.uuid&&(va(f.uuid),!f.titleFired)){f.titleFired=!0;let M=f.uuid,H=f.firstPrompt;H&&qd(H,e).then(J=>{J&&(Lw(M,J),bt(J))}).catch(()=>{})}}else C.type==="error"&&(R(!0),p=!0,C.kind==="auth"&&(po.current=!0),d({kind:"note",text:`agent error: ${C.message}`,tone:"error"}))}finally{E(!1),A(),q(C=>C+1),Qe.current.uuid&&vd(e,Qe.current.uuid,Ut.current),po.current?(po.current=!1,bn.current=l?.display??c,xe("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):bn.current=null,kn.current&&(kn.current=!1,Pt.current.length>0&&(d({kind:"note",tone:"info",text:`(${Pt.current.length} queued message(s) discarded)`}),Pt.current=[],Zr([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Ka,it,xe,Z,He,Dt]),Et=X(async c=>{let l=Vr(e,"standard");kt.current=Date.now(),Ot(0),E(!0);let i=new AbortController;we.current=i;let f=async(P,G)=>{let p=Ra(P);se({verb:"Publishing",total:p.length,done:0,active:[],rows:Zn(p),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:G?`Resolving cross-links in ${P.length} article${P.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${P.length} article${P.length===1?"":"s"} across ${p.length} partition${p.length===1?"":"s"} (\u2264${Fn} agents at once) on ${l.model}\u2026 (esc to stop)`});let y=!1;for await(let w of qr({cwd:e,partitions:p,promptFor:m=>Wn(m.paths),concurrency:Fn,profileName:s,allowProdWrites:Ft.current,model:l.model,signal:i.signal}))if(w.type==="partition_status")w.status==="running"?se(m=>m&&{...m,active:[...m.active,w.label],rows:Ue(m.rows,w.label,"active"),lastAt:Date.now()}):se(m=>m&&{...m,active:m.active.filter(D=>D!==w.label),done:m.done+1,rows:Ue(m.rows,w.label,w.status==="done"?"done":"failed"),lastAt:Date.now()});else if(w.type==="partition_event")se(m=>{if(!m)return m;let D={...m,lastAt:Date.now()};return w.event.type==="tool"?D.tools=m.tools+1:w.event.type==="text"&&(D.chars=m.chars+w.event.delta.length),D});else if(w.type==="run_done"){y=w.aborted,zt(R=>R+w.totalCostUsd),Yt(R=>R+w.results.reduce((C,W)=>C+W.outputTokens,0));let m=w.aborted?"Stopped. ":"",D=t.kind==="api"?"api":"subscription";d({kind:"note",tone:w.aborted?"warn":w.ok?"ok":"warn",text:m+Ys(w.results,p,D).join(`
397
- `)});let A=Gs(e,s);if(A&&d({kind:"note",tone:"info",text:A}),!w.aborted){try{let R=await ep({cwd:e,profileName:s}),C=tp(R);C?d({kind:"note",tone:"info",text:C}):R.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${R.skipped}`})}catch(R){d({kind:"note",tone:"warn",text:`Order sync failed: ${R.message}`})}try{let R=op(await np({cwd:e,profileName:s}));R&&d({kind:"note",tone:"info",text:R})}catch(R){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${R.message}`})}}}return y};try{if(!await f(c,!1)){let G=await zs(e,s,c);G.length>0&&await f(G,!0)}}catch(P){d({kind:"note",tone:"error",text:`Publish run failed: ${P.message}`})}finally{we.current=null,se(null),E(!1),q(P=>P+1)}},[e,s,d,t]),cs=X(async c=>{await oe(qs(c),{display:`/publish ${c}`,quietUser:!0});try{let l=await cr(e,s,c.replace(/\\/g,"/"));l.length>0&&(wn(`Related articles not yet published (${l.length}):`),Be([`/publish --related ${c}`,...l.map(i=>`/publish ${i}`)]))}catch{}},[e,s,oe]),xo=X(c=>{if(c)try{for(let l of Array.isArray(c)?c:[c]){let i=sa(e,l);if(!i)continue;Pr(e,i.title).ok&&d({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${i.title}`});return}}catch{}},[e,d]),Xa=X(async(c,l)=>{let f=Jw(c,3),P=Vr(e,"standard"),G=new Map;for(let w of c){let m=_s(e,w,tr(e,w));m&&G.set(w,m)}kt.current=Date.now(),Ot(0),E(!0);let p=new AbortController;we.current=p,se({verb:"Authoring",unit:"spec",total:f.length,done:0,active:[],rows:Zn(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${c.length} screenshot spec${c.length===1?"":"s"} across ${f.length} partition${f.length===1?"":"s"} (\u22646 agents at once) on ${P.model}${P.forced?" (forced)":""}\u2026 (esc to stop)`});let y=!1;try{for await(let w of qr({cwd:e,partitions:f,promptFor:m=>Cc(m,G),concurrency:6,profileName:s,allowProdWrites:Ft.current,model:P.model,signal:p.signal}))if(w.type==="partition_status")w.status==="running"?se(m=>m&&{...m,active:[...m.active,w.label],rows:Ue(m.rows,w.label,"active"),lastAt:Date.now()}):se(m=>m&&{...m,active:m.active.filter(D=>D!==w.label),done:m.done+1,rows:Ue(m.rows,w.label,w.status==="done"?"done":"failed"),lastAt:Date.now()});else if(w.type==="partition_event")se(m=>{if(!m)return m;let D={...m,lastAt:Date.now()};return w.event.type==="tool"?D.tools=m.tools+1:w.event.type==="text"&&(D.chars=m.chars+w.event.delta.length),D});else if(w.type==="run_done"){zt(R=>R+w.totalCostUsd),Yt(R=>R+w.results.reduce((C,W)=>C+W.outputTokens,0));let m=w.results.filter(R=>R.ok).length,D=w.aborted?"Stopped. ":"";y=!w.aborted&&l.setup;let A=w.aborted?"":y?" Refreshing the capture-setup checklist\u2026":" Next: /screenshot capture --all (or /screenshot checklist first for the staging checklist).";d({kind:"note",tone:w.aborted?"warn":w.ok?"ok":"warn",text:`${D}Authored specs \u2014 ${m}/${w.results.length} batches ok.${A}`}),!w.aborted&&w.ok&&xo(l.runLine)}}catch(w){d({kind:"note",tone:"error",text:`Spec authoring failed: ${w.message}`})}finally{we.current=null,se(null),E(!1),q(w=>w+1)}if(y){let w=await un();w.kind==="forward-to-agent"&&w.prompt&&await oe(w.prompt,{display:w.display,quietUser:!0});let m=Wi(e);m&&d({kind:"note",tone:"info",text:m.join(`
398
- `)})}},[e,s,d,oe,xo]),Qa=X(async c=>{let l=_s(e,c,tr(e,c))??void 0,i=await rr([c],void 0,{lastFailure:l});i.kind==="forward-to-agent"&&i.prompt&&await oe(i.prompt,{display:i.display,quietUser:!0}),mc(e,c)&&ve(`Spec ready \u2014 /screenshot capture ${c} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${c}`,reason:""})},[e,oe,ve]),vo=X(async(c,l)=>{if(!kr(e)){await oe(Ui(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!Eu(e)){d({kind:"note",tone:"info",text:"No saved login for screenshot capture yet \u2014 opening a browser window. Sign in to your app (MFA included); I'll continue automatically once the session saves. (esc cancels)"}),E(!0),uo("Waiting for you to finish logging in (browser window)\u2026");let R=new AbortController;we.current=R;let C;try{C=await ju({cwd:e,signal:R.signal})}catch(W){d({kind:"note",tone:"error",text:`Could not launch the login: ${W.message}`});return}finally{we.current=null,uo(null),E(!1)}if(C.exitCode!==0){Mi(C.exitCode,C.output)?d({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."}):/unknown option/i.test(C.output)?d({kind:"note",tone:"warn",text:"Your d360-capture is older than this writer. Update it: npm i -g document360-capture \u2014 then /screenshot capture again."}):d({kind:"note",tone:R.signal.aborted?"warn":"error",text:R.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
399
- ${Oi(C.output)}`});return}d({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let i=new Map(c.map(R=>[R,yc(e,R)]));if(c.length>1){let R=c.filter(C=>i.get(C).mutates);if(R.length>0&&(c=c.filter(C=>!i.get(C).mutates),d({kind:"note",tone:"warn",text:`\u26A0 ${R.length} spec${R.length===1?"":"s"} perform${R.length===1?"s":""} a REAL write in your app and ${R.length===1?"is":"are"} excluded from bulk capture. Run each deliberately, on its own:
396
+ ${C}`)}catch{}l?.quietUser||d({kind:"user",text:l?.echoDisplay&&l.display?l.display:c});let f=Qe.current;f.firstPrompt||(f.firstPrompt=l?.display??c),bt.current=Date.now(),Lt(0),E(!0),lo.current.clear();let P="",G=!1,p=!1,y="",w={num:0,closed:!1,cueSeen:!1},m=null,D=()=>{m||(m=setTimeout(()=>{m=null,h(y.length>0?y:null)},60))},A=()=>{m&&clearTimeout(m),m=null,h(null)},R=(C=!1)=>{let{head:W,keep:M}=Hd(y,C);W.trim()&&d({kind:"assistant",text:ka(W.trimEnd(),w)}),y=M,A()};try{for await(let C of Ie.current.send(c))if(C.type==="session"){if(!f.uuid){f.uuid=C.sessionId;let W=new Date().toISOString(),M=Zr.current,H=M??Fw(f.firstPrompt??"session");Ww({uuid:C.sessionId,name:H,renamed:!!M,titled:!1,cwd:e,firstPrompt:f.firstPrompt??"",createdAt:W,updatedAt:W}),$t(H),Zr.current=null}}else if(C.type==="text"){y+=C.delta,P+=C.delta;let W=qd(y);if(W>0){let M=y.slice(0,W).trimEnd();M&&d({kind:"assistant",text:ka(M,w)}),y=y.slice(W)}D(),Lt(M=>M+C.delta.length)}else if(C.type==="tool"){G=!0;let M=(le=>typeof le=="string"&&le?le.replace(/\\/g,"/").toLowerCase():null)(C.input.file_path??C.input.notebook_path),H=["Edit","Write","MultiEdit","NotebookEdit"].includes(C.name),J=C.name==="Read"&&M!==null&&M===Ua.current;if(Ua.current=H?M:null,J)R(),d({kind:"tool",title:"Read",sep:"",arg:"(re-checking the file it just edited)"});else{let le=Er(C.name,C.input,e);le&&(R(),d({kind:"tool",title:le.title,sep:le.sep,arg:le.arg}),lo.current.set(C.id,{name:C.name,input:C.input}))}}else if(C.type==="article_diff"){let W=ot(C.oldContent,C.newContent,it());W&&(R(),d({kind:"diff",added:W.added,removed:W.removed,lines:W.lines,hidden:W.hidden}))}else if(C.type==="tool_result"){C.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(C.output)&&(ho.current=!0);let W=lo.current.get(C.id);if(W){lo.current.delete(C.id),R();let M=jr(C.output,4,C.isError?void 0:W.name,W.input);d({kind:"tool-result",lines:M.lines,hidden:M.hidden,isError:C.isError}),C.isError||Qa(W.name,W.input,C.output)}}else if(C.type==="result"){R(!0),zt(M=>M+C.outputTokens),Kt(M=>M+C.costUsd);let W=C.inputTokens+C.cacheReadTokens+C.cacheCreationTokens;if(d({kind:"done",seconds:Math.round((Date.now()-bt.current)/1e3),tokens:C.outputTokens,costUsd:C.costUsd,ok:C.ok,...W>0?{inTokens:W,cachedPct:Math.round(C.cacheReadTokens/W*100)}:{}}),!p&&!G&&!P.trim()&&!$n.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),C.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(P))try{let M=ep(e);if(mn(M)){let H=qr(M,"utf8").trim();H&&(is(H),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(kn.current=C.ok&&/\?[\s*_"')\]]*$/.test(P.trimEnd()),C.ok&&w.cueSeen)Oa(!0),Be([]);else{let M=C.ok?Dd(P,an.map(H=>H.name)):[];if(M.length>0)Z(M[0]);else if(C.ok&&P.trim()&&!kn.current){let H=At(!1);H.kind==="recommend"&&(H.rec.lead||H.rec.picker)||Vw(c,P,e).then(J=>{J&&ro.current===i&&xe(J)}).catch(()=>{})}}if(f.uuid&&(Ra(f.uuid),!f.titleFired)){f.titleFired=!0;let M=f.uuid,H=f.firstPrompt;H&&Gd(H,e).then(J=>{J&&(Uw(M,J),$t(J))}).catch(()=>{})}}else C.type==="error"&&(R(!0),p=!0,C.kind==="auth"&&(ho.current=!0),d({kind:"note",text:`agent error: ${C.message}`,tone:"error"}))}finally{E(!1),A(),q(C=>C+1),Qe.current.uuid&&Rd(e,Qe.current.uuid,Ft.current),ho.current?(ho.current=!1,xn.current=l?.display??c,xe("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):xn.current=null,$n.current&&($n.current=!1,Tt.current.length>0&&(d({kind:"note",tone:"info",text:`(${Tt.current.length} queued message(s) discarded)`}),Tt.current=[],es([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Qa,it,xe,Z,He,At]),jt=X(async c=>{let l=Gr(e,"standard");bt.current=Date.now(),Lt(0),E(!0);let i=new AbortController;we.current=i;let f=async(P,G)=>{let p=Pa(P);se({verb:"Publishing",total:p.length,done:0,active:[],rows:eo(p),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:G?`Resolving cross-links in ${P.length} article${P.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${P.length} article${P.length===1?"":"s"} across ${p.length} partition${p.length===1?"":"s"} (\u2264${Bn} agents at once) on ${l.model}\u2026 (esc to stop)`});let y=!1;for await(let w of Vr({cwd:e,partitions:p,promptFor:m=>Hn(m.paths),concurrency:Bn,profileName:s,allowProdWrites:Wt.current,model:l.model,signal:i.signal}))if(w.type==="partition_status")w.status==="running"?se(m=>m&&{...m,active:[...m.active,w.label],rows:Ue(m.rows,w.label,"active"),lastAt:Date.now()}):se(m=>m&&{...m,active:m.active.filter(D=>D!==w.label),done:m.done+1,rows:Ue(m.rows,w.label,w.status==="done"?"done":"failed"),lastAt:Date.now()});else if(w.type==="partition_event")se(m=>{if(!m)return m;let D={...m,lastAt:Date.now()};return w.event.type==="tool"?D.tools=m.tools+1:w.event.type==="text"&&(D.chars=m.chars+w.event.delta.length),D});else if(w.type==="run_done"){y=w.aborted,Kt(R=>R+w.totalCostUsd),zt(R=>R+w.results.reduce((C,W)=>C+W.outputTokens,0));let m=w.aborted?"Stopped. ":"",D=t.kind==="api"?"api":"subscription";d({kind:"note",tone:w.aborted?"warn":w.ok?"ok":"warn",text:m+zs(w.results,p,D).join(`
397
+ `)});let A=Ys(e,s);if(A&&d({kind:"note",tone:"info",text:A}),!w.aborted){try{let R=await np({cwd:e,profileName:s}),C=op(R);C?d({kind:"note",tone:"info",text:C}):R.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${R.skipped}`})}catch(R){d({kind:"note",tone:"warn",text:`Order sync failed: ${R.message}`})}try{let R=sp(await rp({cwd:e,profileName:s}));R&&d({kind:"note",tone:"info",text:R})}catch(R){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${R.message}`})}}}return y};try{if(!await f(c,!1)){let G=await Ks(e,s,c);G.length>0&&await f(G,!0)}}catch(P){d({kind:"note",tone:"error",text:`Publish run failed: ${P.message}`})}finally{we.current=null,se(null),E(!1),q(P=>P+1)}},[e,s,d,t]),us=X(async c=>{await oe(Vs(c),{display:`/publish ${c}`,quietUser:!0});try{let l=await ur(e,s,c.replace(/\\/g,"/"));l.length>0&&(bn(`Related articles not yet published (${l.length}):`),Be([`/publish --related ${c}`,...l.map(i=>`/publish ${i}`)]))}catch{}},[e,s,oe]),vo=X(c=>{if(c)try{for(let l of Array.isArray(c)?c:[c]){let i=aa(e,l);if(!i)continue;Tr(e,i.title).ok&&d({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${i.title}`});return}}catch{}},[e,d]),Ja=X(async(c,l)=>{let f=ek(c,3),P=Gr(e,"standard"),G=new Map;for(let w of c){let m=Os(e,w,nr(e,w));m&&G.set(w,m)}bt.current=Date.now(),Lt(0),E(!0);let p=new AbortController;we.current=p,se({verb:"Authoring",unit:"spec",total:f.length,done:0,active:[],rows:eo(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${c.length} screenshot spec${c.length===1?"":"s"} across ${f.length} partition${f.length===1?"":"s"} (\u22646 agents at once) on ${P.model}${P.forced?" (forced)":""}\u2026 (esc to stop)`});let y=!1;try{for await(let w of Vr({cwd:e,partitions:f,promptFor:m=>Sc(m,G),concurrency:6,profileName:s,allowProdWrites:Wt.current,model:P.model,signal:p.signal}))if(w.type==="partition_status")w.status==="running"?se(m=>m&&{...m,active:[...m.active,w.label],rows:Ue(m.rows,w.label,"active"),lastAt:Date.now()}):se(m=>m&&{...m,active:m.active.filter(D=>D!==w.label),done:m.done+1,rows:Ue(m.rows,w.label,w.status==="done"?"done":"failed"),lastAt:Date.now()});else if(w.type==="partition_event")se(m=>{if(!m)return m;let D={...m,lastAt:Date.now()};return w.event.type==="tool"?D.tools=m.tools+1:w.event.type==="text"&&(D.chars=m.chars+w.event.delta.length),D});else if(w.type==="run_done"){Kt(R=>R+w.totalCostUsd),zt(R=>R+w.results.reduce((C,W)=>C+W.outputTokens,0));let m=w.results.filter(R=>R.ok).length,D=w.aborted?"Stopped. ":"";y=!w.aborted&&l.setup;let A=w.aborted?"":y?" Refreshing the capture-setup checklist\u2026":" Next: /screenshot capture --all (or /screenshot checklist first for the staging checklist).";d({kind:"note",tone:w.aborted?"warn":w.ok?"ok":"warn",text:`${D}Authored specs \u2014 ${m}/${w.results.length} batches ok.${A}`}),!w.aborted&&w.ok&&vo(l.runLine)}}catch(w){d({kind:"note",tone:"error",text:`Spec authoring failed: ${w.message}`})}finally{we.current=null,se(null),E(!1),q(w=>w+1)}if(y){let w=await pn();w.kind==="forward-to-agent"&&w.prompt&&await oe(w.prompt,{display:w.display,quietUser:!0});let m=Hi(e);m&&d({kind:"note",tone:"info",text:m.join(`
398
+ `)})}},[e,s,d,oe,vo]),Za=X(async c=>{let l=Os(e,c,nr(e,c))??void 0,i=await sr([c],void 0,{lastFailure:l});i.kind==="forward-to-agent"&&i.prompt&&await oe(i.prompt,{display:i.display,quietUser:!0}),yc(e,c)&&ve(`Spec ready \u2014 /screenshot capture ${c} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${c}`,reason:""})},[e,oe,ve]),Co=X(async(c,l)=>{if(!br(e)){await oe(Wi(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!ju(e)){d({kind:"note",tone:"info",text:"No saved login for screenshot capture yet \u2014 opening a browser window. Sign in to your app (MFA included); I'll continue automatically once the session saves. (esc cancels)"}),E(!0),po("Waiting for you to finish logging in (browser window)\u2026");let R=new AbortController;we.current=R;let C;try{C=await Nu({cwd:e,signal:R.signal})}catch(W){d({kind:"note",tone:"error",text:`Could not launch the login: ${W.message}`});return}finally{we.current=null,po(null),E(!1)}if(C.exitCode!==0){Fi(C.exitCode,C.output)?d({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."}):/unknown option/i.test(C.output)?d({kind:"note",tone:"warn",text:"Your d360-capture is older than this writer. Update it: npm i -g document360-capture \u2014 then /screenshot capture again."}):d({kind:"note",tone:R.signal.aborted?"warn":"error",text:R.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
399
+ ${Mi(C.output)}`});return}d({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let i=new Map(c.map(R=>[R,kc(e,R)]));if(c.length>1){let R=c.filter(C=>i.get(C).mutates);if(R.length>0&&(c=c.filter(C=>!i.get(C).mutates),d({kind:"note",tone:"warn",text:`\u26A0 ${R.length} spec${R.length===1?"":"s"} perform${R.length===1?"s":""} a REAL write in your app and ${R.length===1?"is":"are"} excluded from bulk capture. Run each deliberately, on its own:
400
400
  `+R.map(C=>`/screenshot capture ${C}${i.get(C).what?` (${i.get(C).what})`:""}`).join(`
401
- `)}),c.length===0))return}else if(c.length===1&&i.get(c[0]).mutates){let R=i.get(c[0]);d({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${R.what?`: ${R.what}`:R.declared?"":" (detected from the spec: form fill + commit click / file upload)"}. Running because you named it explicitly \u2014 check the result and clean up what it created. Tip: point the capture scope (.d360-writer/capture.json) at a demo/non-production context for shots like this.`})}E(!0);let f=new AbortController;we.current=f;let P=c.map(R=>({label:R,items:1,status:"pending"}));se({verb:"Capturing",unit:"screenshot",total:c.length,done:0,active:[],rows:P,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Capturing ${c.length} screenshot${c.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`});let G=Date.now(),p=[];try{for(let R of c){if(f.signal.aborted)break;se(J=>J&&{...J,active:[R],rows:Ue(J.rows,R,"active"),lastAt:Date.now()});let{exitCode:C,output:W}=await Li({cwd:e,id:R,signal:f.signal,stdio:"pipe"});if(Mi(C,W)){d({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."});return}let M=f.signal.aborted&&C!==0?"failed":_i(e,R,C,G),H=M==="captured"?void 0:M==="skipped"?Du(W)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Au(W);p.push({id:R,outcome:M,detail:H}),se(J=>J&&{...J,active:[],done:J.done+1,rows:Ue(J.rows,R,M==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(R){d({kind:"note",tone:"error",text:`Capture run failed: ${R.message}`})}finally{we.current=null,se(null),E(!1),q(R=>R+1)}if(p.length===0)return;let y=p.filter(R=>R.outcome==="captured"),w=p.filter(R=>R.outcome==="skipped"),m=p.filter(R=>R.outcome==="failed"),D=c.length-p.length;d({kind:"note",tone:m.length?"warn":y.length?"ok":"info",text:`\u2713 ${y.length} captured`+(w.length?` \xB7 \u2298 ${w.length} skipped`:"")+(m.length?` \xB7 \u2717 ${m.length} failed`:"")+(D?` \xB7 ${D} not run (stopped)`:"")});for(let R of w)d({kind:"note",tone:"info",text:`\u2298 ${R.id} \u2014 ${R.detail}`});for(let R of m)R.detail&&d({kind:"note",tone:"error",text:`\u2717 ${R.id}
402
- ${R.detail}`});lc(e,p.map(R=>({id:R.id,outcome:R.outcome,reason:R.detail,specSource:tr(e,R.id)})),new Date().toISOString());let A=Nu({results:p,ids:c,articles:Iu(e,y.map(R=>R.id))});A&&ve(A.note,{kind:"cmd",cmd:A.cmd,reason:""},A.tone),p.length===c.length&&m.length===0&&w.length===0&&xo(l?.runLine)},[e,d,ve,oe,xo]),us=X(c=>{let l=_t(c);if(!l||wt(l)&&!l.refreshToken)return null;let i={...mn(l.idToken)??{},...mn(l.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),ds=X((c,l)=>{if(l){let i=ie(e);i&&(i.defaultProfile=c,Vd(i,e))}a(c),Ae(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${l?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),us(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),Z("/login")),q(i=>i+1)},[e,d,Ae,us,Z]),Co=X((c,l,i)=>{jo(e,c,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Ae(),Gd(e,c)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:on(nn(e)).join(`
403
- `)}),Kt(jt()),Cn.current=Le(e).status==="current",Xt.current=nt(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,Ae,Kt]),Ro=X(async c=>{let l;try{l=await An(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Z("/workspace");return}if(l.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=l.workspaces.filter(P=>(P.workspace_type??"").toLowerCase()!=="apidocumentation"),f=i.length>0?i:l.workspaces;if(f.length===1){let P=f[0],G=l.workspaces.length-f.length;d({kind:"note",tone:"ok",text:`Selected the "${P.name??P.id}" workspace${G>0?" (skipped the API-documentation workspace)":""}.`}),Co(l.profile,l.projectId,P);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${f.length} available).`}),Z("/workspace")},[e,d,Co,Z]),So=X((c,l)=>{No(e,c,l.id,l.name),d({kind:"note",tone:"ok",text:`Project set to "${l.name??l.id}" (agent restarted).`}),Ae(),Ro(c)},[e,d,Ae,Ro]),Ja=X(async c=>{let l;try{l=je(e,c)}catch{return}if(!l.project.workspaceId){if(l.project.projectId){if(!l.project.projectName)try{let{projects:i}=await ct(e,l.name),f=i.find(P=>P.id===l.project.projectId);f?.name&&ak(e,l.name,{projectName:f.name})}catch{}await Ro(l.name);return}try{let{projects:i}=await ct(e,l.name);if(i.length===1){let f=i[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${f.name??f.id}".`}),So(l.name,{id:f.id,name:f.name});return}if(i.length>1){let f=i.map(P=>({id:P.id,name:P.name??P.id,sub:P.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),vt({cursor:0,current:-1,rows:f,profile:l.name,environment:l.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Z("/project")}},[e,d,Ro,So,Z]),Qt=X(()=>{let c=pe.current[0];if(!c)return;He();let{plan:l,mode:i}=c;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let P of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${P}`});l.overwritesLocalChanges&&i==="pull"&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let f=ot(l.oldContent,l.newContent,it());d(f?{kind:"diff",added:f.added,removed:f.removed,lines:f.lines,hidden:f.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),i==="conflict"?(d({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),d({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,it,He]),ps=X(()=>{if(pe.current.length>0){Qt();return}let c=Wt.current;Wt.current=[],c.length>0?(d({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),Et(c)):Z("/pull")},[Qt,d,Et,Z]),Za=X(c=>{if(pe.current.length===0)return!1;let l=c.trim().toLowerCase(),i=pe.current[0];if(i.mode==="conflict"){if(l==="l"||l==="local")pe.current.shift(),Wt.current.push(i.plan.path),d({kind:"note",tone:"info",text:`Keeping local ${i.plan.path} \u2014 will publish over the portal.`});else if(l==="p"||l==="portal"){pe.current.shift();try{Yd({cwd:e,profileName:s},i.plan),d({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(f){d({kind:"note",tone:"error",text:`Take-portal failed: ${f.message}`})}}else if(l==="s"||l==="skip"||l==="n")pe.current.shift(),d({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let f=pe.current.length;return pe.current=[],Wt.current=[],d({kind:"note",tone:"info",text:`Resolve cancelled (${f} conflict${f===1?"":"s"} left untouched).`}),!0}return ps(),!0}if(l==="y"||l==="yes"){let f=pe.current.shift().plan;try{Yd({cwd:e,profileName:s},f),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${f.path} (sync base advanced).`})}catch(P){d({kind:"note",tone:"error",text:`Pull failed: ${P.message}`})}}else if(l==="n"||l==="no"){let f=pe.current.shift().plan;d({kind:"note",tone:"info",text:`Skipped ${f.path}.`})}else{let f=pe.current.length;return pe.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${f} article(s) left untouched).`}),!0}return ps(),!0},[e,s,ps,d]),hs=X(async c=>{d({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let l=await Ca({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),f=l.entries.filter(G=>G.status==="conflict"&&G.path).map(G=>G.path);if(i){if(!f.includes(i)){d({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}f=[i]}if(f.length===0){d({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let P=[];for(let G of f)try{P.push({plan:await Kd({cwd:e,profileName:s,relPath:G}),mode:"conflict"})}catch(p){d({kind:"note",tone:"error",text:`Could not load ${G} from Document360: ${p.message}`})}if(P.length===0)return;d({kind:"note",tone:"info",text:`Resolving ${P.length} conflict${P.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),pe.current=P,Wt.current=[],Qt()}catch(l){d({kind:"note",tone:"error",text:`Could not compute sync status: ${l.message}`})}},[e,s,d,Qt]),el=X(c=>{let l=lo.current;if(!l)return!1;if(lo.current=null,He(),c.trim()!==l.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:f}=Ji(e,l.targets);d({kind:"note",tone:f.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`});for(let P of f)d({kind:"note",tone:"error",text:` \u2717 ${P.path}: ${P.error}`});return l.hadDevhints&&(d({kind:"note",tone:"warn",text:qo().join(`
404
- `)}),Kt(xs())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
405
- ${rp}`}),Z("/init"),ro(!1),!0},[e,d,Kt,He,Z]),Sn=X(async c=>{let l=c.slice(1).trim().split(/\s+/),i=(l[0]??"").toLowerCase(),f=l.slice(1);if(ro(!0),hr(f)&&["write","check","review","reorder"].includes(i)){let p=Hn(e,s);if(p.length===0){d({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let y=w=>i==="write"?`/write ${zc(f,w).join(" ")}`.trim():`/${i} ${[w,...f.filter(m=>m!=="--scope")].join(" ")}`.trim();if(p.length===1){Sn(y(p[0].token));return}Rt({cursor:0,rows:p,run:w=>{Sn(y(w))}});return}if(gt(i,f)){let p=Hn(e,s);if(p.length>1){let y=f.filter(A=>A.startsWith("--")).join(" "),w=A=>`/${i}${A?` ${i==="write"?`--scope ${A}`:A}`:""}${y?` ${y}`:""} ${A?"":"--all"}`.replace(/\s+/g," ").trim(),m=p.reduce((A,R)=>A+R.count,0),D={token:"",label:i==="review"?`Everything \u2014 all ${m} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${p.length} categories`:`Everything \u2014 rewrite all ${m} planned articles`,count:m};Rt({cursor:0,rows:[D,...p],run:A=>{Sn(w(A))}});return}}let P=async p=>{let y=ji(p);if(!kr(e)){await oe(Ui(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(y.mode==="single"){await vo([y.id],{runLine:[`/screenshot capture ${y.id}`,`/capture ${y.id}`]});return}if(y.mode==="failed"){let m=Ni(e,wr(e).rows);if(m.length===0){d({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),Z("/screenshot list");return}await vo(m);return}if(y.mode==="all"||y.mode==="scope"){let m=y.mode==="scope"?y.scope:void 0,{ready:D,captured:A,blocked:R,rows:C}=wr(e,m),W=[...D,...A,...y.retryBlocked?R:[]];if(W.length===0&&R.length>0&&!y.retryBlocked){let H=m?`/screenshot capture ${m} --retry-blocked`:"/screenshot capture --all --retry-blocked";ve(`All ${R.length} shot${R.length===1?"":"s"} in scope ${R.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${H}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(W.length===0){d({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Z("/screenshot");return}if(!y.retryBlocked){let H=m?`/screenshot capture ${m} --retry-blocked`:"/screenshot capture --all --retry-blocked",J=Ii(C.filter(le=>le.state==="blocked"),H);J&&d({kind:"note",tone:"info",text:J})}let M=y.mode==="scope"?[`/screenshot capture ${y.scope}`,`/capture ${y.scope}`]:["/screenshot capture --all","/capture --all"];await vo(W,{runLine:M});return}let w=Tu(Ye(e));if(w.length===0){d({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Z("/screenshot");return}Ct({cursor:0,rows:w,title:"Capture screenshots \u2014 pick what to shoot:"})},G=async()=>{let p=await un();p.kind==="forward-to-agent"&&p.prompt&&await oe(p.prompt,{display:p.display,quietUser:!0});let y=Wi(e);y&&d({kind:"note",tone:"info",text:y.join(`
406
- `)})};switch(i){case"help":xn({tab:0});return;case"exit":case"quit":Ie.current?.close(),r();return;case"clear":Ae(),Ut.current=[],ro(!1),He(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let p;try{p=je(e,s)}catch(y){d({kind:"note",tone:"error",text:y.message});return}d({kind:"note",tone:"info",text:`Profile "${p.name}" \u2192 ${p.connection.name} (${p.connection.apiUrl})${p.production?" \u26A0 PRODUCTION":""}`}),L(!0);try{let y=await Dw(p.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},m=>d({kind:"note",tone:"info",text:m})),w=Aw(p.name,y);if(Ew(w),await ys(w,p.name,m=>d({kind:"note",tone:"info",text:m})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${p.name}" as ${Oo(w)}`}),await Ja(s),$n.current){let m=$n.current;$n.current=null;let D=Me(e,s);D.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${m}.`}),Z(m)):(d({kind:"note",tone:"warn",text:`${D.reason} (then ${m}.)`}),Z("/login"),$n.current=m)}else bn.current&&(xe(bn.current,"\u21E5 tab to re-send your last prompt\u2026"),bn.current=null)}catch(y){d({kind:"note",tone:"error",text:`Login failed: ${y.message}`})}finally{L(!1),q(y=>y+1)}return}case"allow-prod":{let p=!1;try{p=je(e,s).production}catch{}if(!p){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Ft.current=!0,Ae(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let p=Si(f.join(" ")),y=Qe.current.uuid;if(!y){if(!p){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Jr.current=p,bt(p),pn(`${Mr} ${p}`),d({kind:"note",tone:"ok",text:`Session will be named "${p}" once it starts.`});return}if(!p){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Qe.current.firstPrompt??"";qd(w,e).then(m=>{m?(xe(`/rename ${m}`),d({kind:"note",tone:"info",text:`Suggestion: "${m}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Bw(y,p),bt(p),pn(`${Mr} ${p}`),d({kind:"note",tone:"ok",text:`Session renamed to "${p}".`});return}case"profile":{let p=f[0],y=ie(e);if(!p){let w=Object.entries(y?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let m=w.map(([R,C])=>({name:R,env:C.connection?.environment??"custom",prod:C.production===!0,who:us(R)})),D=s??y?.defaultProfile,A=Math.max(0,m.findIndex(R=>R.name===D));Bt({cursor:A,current:A,rows:m});return}if(p==="add"){let w=Pi(e,f[1],f[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${f[1]}" created (environment: ${f[2]??f[1]}).`}),ds(f[1],!1);return}if(!y?.profiles?.[p]){d({kind:"note",tone:"error",text:`Unknown profile "${p}". Create it: /profile add ${p} <environment>`});return}ds(p,!0);return}case"doctor":await Vn(f,{cwd:e,version:o});return;case"genre":{await Rr(f,{cwd:e});try{Yr.current=!(ie(e)?.appType??Vw(e))}catch{}q(p=>p+1);return}case"roadmap":{if(f[0]?.toLowerCase()==="done"){let p=Pr(e,f.slice(1).join(" ").trim());d({kind:"note",tone:p.ok?"ok":"warn",text:p.line}),q(y=>y+1);return}d({kind:"note",tone:"info",text:ra(e).join(`
407
- `)});return}case"mcp":await Yo(f);return;case"init":{if(ie(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let p=Xw().map(y=>({name:y,apiUrl:Qw(y).apiUrl}));Ht({cursor:0,rows:p});return}case"resume":{let p=f.join(" ").trim(),y=Ww(e).filter(D=>D.uuid!==Qe.current.uuid);if(!p){if(!y.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Tt({query:"",cursor:0,sessions:y});return}let w=Fw(e,p);if(!w){d({kind:"note",tone:"error",text:`No session matches "${p}".`});return}Ae(w.uuid),Qe.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},bt(w.name),va(w.uuid),Ut.current=[];let m=wa(e,w.uuid);for(let D of m)d(D);d({kind:"note",tone:"ok",text:m.length?`Resumed "${w.name}" \u2014 restored ${m.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let p=f.join(" ").trim(),y;try{y=await An(e,s)}catch(m){d({kind:"note",tone:"error",text:`Could not list workspaces: ${m.message}`});return}if(!p){let m=y.workspaces.map(A=>({id:A.id,name:A.name??A.id,type:A.workspace_type}));if(m.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let D=Math.max(0,m.findIndex(A=>A.id===y.current));qt({cursor:D,current:D,rows:m,profile:y.profile,projectId:y.projectId,projectName:y.projectName,environment:y.environment});return}let w=ms(y.workspaces,p);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${p}".`});return}Co(y.profile,y.projectId,w);return}case"project":{let p=f.join(" ").trim(),y;try{y=await ct(e,s)}catch(m){d({kind:"note",tone:"error",text:`Could not list projects: ${m.message} (signed in? try /login)`});return}if(!p){let m=y.projects.map(A=>({id:A.id,name:A.name??A.id,sub:A.sub_domain}));if(m.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let D=m.findIndex(A=>A.id===y.current);vt({cursor:Math.max(0,D),current:D,rows:m,profile:y.profile,environment:y.environment});return}let w=gs(y.projects,p);if(!w){d({kind:"note",tone:"error",text:`No project matches "${p}". Available: ${y.projects.map(m=>m.name??m.id).join(", ")}`});return}So(y.profile,w);return}case"logout":{let p;try{p=je(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let y=_w(p);Ow(e,p),Ae(),q(w=>w+1),d({kind:"note",tone:y?"ok":"info",text:y?`\u2713 Signed out of "${p}" and cleared its project/workspace selection.`:`Profile "${p}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Z("/login");return}case"publish":{if(!mo(c.trim()))return;if(f.includes("--screenshots")||f.includes("--shots")){let m=nr(Ye(e));if(m.length===0){d({kind:"note",tone:"info",text:"No captured screenshots yet \u2014 /screenshot capture first."});return}d({kind:"note",tone:"info",text:`Re-saving ${m.length} article${m.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await Et(m);return}if(f[0]==="--related"&&f[1]){let m=await cr(e,s,f[1].replace(/\\/g,"/"));if(m.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Et(m);return}let p=f.filter(m=>!m.startsWith("--"));if(p[0]){await cs(p[0]);return}let y=f.includes("--all"),w=f.includes("--force");d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Ca({cwd:e,profileName:s}),{clean:D,conflicts:A}=ir(m.entries),R=y&&w&&A.length>0,C=lr(m.entries);if(C>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${C} article${C===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.`}),A.length>0&&!R&&d({kind:"note",tone:"warn",text:ar(A.length)}),D.length===0&&!R){if(A.length>0){Z("/resolve");return}d({kind:"note",tone:"ok",text:C>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let W=m.counts["unknown-base"]??0;W>0&&d({kind:"note",tone:"info",text:`(${W} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),uo("Reconciling structure on Document360 (order + related articles)\u2026");try{let M=await ep({cwd:e,profileName:s}),H=op(await np({cwd:e,profileName:s})),J=tp(M);J?d({kind:"note",tone:"info",text:J}):M.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${M.skipped}`}),H&&d({kind:"note",tone:"info",text:H}),d({kind:"note",tone:"ok",text:J||H?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(J||H)&&Z("/structure")}catch(M){d({kind:"note",tone:"warn",text:`Structure sync failed: ${M.message}`})}finally{uo(null)}return}if(y){let W=(R?[...D,...A]:D).map(M=>M.path);await Et(W),A.length>0&&!R&&Z("/resolve");return}Vt({cursor:0,rows:Ac(D,A)})}catch(m){d({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!mo(c.trim()))return;await hs(f.find(p=>!p.startsWith("--")));return}case"preview":{let p=f.join(" ").trim();if(!p){let w=[];try{w=Object.keys(Gd(e,je(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}St({query:"",cursor:0,paths:w});return}let y=Pw(p)?p:xa(e,p);if(hn(y)){try{d({kind:"preview",name:eo(y),text:ip(Hr(y,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${y}: ${w.message}`})}return}if(yk.test(p)){try{let w=je(e,s),m={profile:w.name,connection:w.connection},D=w.project.projectId??Nw(m),A=await Iw(m,D,p);d({kind:"preview",name:A.title??p,text:A.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${p}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let p=f[0]?.trim();if(!p){let D=mr(Da(e));xt({cursor:D,current:D});return}let{lines:y,changed:w,effective:m}=qn(e,p);for(let D of y)d({kind:"note",tone:D.startsWith("\u26A0")?"warn":D.startsWith("\u2713")?"ok":"info",text:D});w&&(qa(D=>D+1),Ie.current?.setModel(m));return}case"convert":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:p,run:y}=oi(f),w=ek(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let m=ri(w,p);if(m.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${p}". (${w.length} are tracked overall.)`});return}let D=Ra(m),A=3,R=`/convert${p?` --scope ${p}`:""} --run`,C=Vr(e,"light");if(!y){let M=Xd({files:si(e,m),op:"convert",model:C.model}),H=p?`Scope: ${p} (${m.length} of ${w.length} tracked)
401
+ `)}),c.length===0))return}else if(c.length===1&&i.get(c[0]).mutates){let R=i.get(c[0]),C=Iu(e);d({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${R.what?`: ${R.what}`:R.declared?"":" (detected from the spec: form fill + commit click / file upload)"}. Running because you named it explicitly \u2014 check the result and clean up what it created. `+(C.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${C.url?` (${C.url})`:""}. If the spec cleans up after itself, confirm it did.`:"Tip: point the capture scope (.d360-writer/capture.json) at a demo/non-production context for shots like this.")})}E(!0);let f=new AbortController;we.current=f;let P=c.map(R=>({label:R,items:1,status:"pending"}));se({verb:"Capturing",unit:"screenshot",total:c.length,done:0,active:[],rows:P,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Capturing ${c.length} screenshot${c.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`});let G=Date.now(),p=[];try{for(let R of c){if(f.signal.aborted)break;se(J=>J&&{...J,active:[R],rows:Ue(J.rows,R,"active"),lastAt:Date.now()});let{exitCode:C,output:W}=await Ui({cwd:e,id:R,signal:f.signal,stdio:"pipe"});if(Fi(C,W)){d({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."});return}let M=f.signal.aborted&&C!==0?"failed":Li(e,R,C,G),H=M==="captured"?void 0:M==="skipped"?Au(W)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Eu(W);p.push({id:R,outcome:M,detail:H}),se(J=>J&&{...J,active:[],done:J.done+1,rows:Ue(J.rows,R,M==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(R){d({kind:"note",tone:"error",text:`Capture run failed: ${R.message}`})}finally{we.current=null,se(null),E(!1),q(R=>R+1)}if(p.length===0)return;let y=p.filter(R=>R.outcome==="captured"),w=p.filter(R=>R.outcome==="skipped"),m=p.filter(R=>R.outcome==="failed"),D=c.length-p.length;d({kind:"note",tone:m.length?"warn":y.length?"ok":"info",text:`\u2713 ${y.length} captured`+(w.length?` \xB7 \u2298 ${w.length} skipped`:"")+(m.length?` \xB7 \u2717 ${m.length} failed`:"")+(D?` \xB7 ${D} not run (stopped)`:"")});for(let R of w)d({kind:"note",tone:"info",text:`\u2298 ${R.id} \u2014 ${R.detail}`});for(let R of m)R.detail&&d({kind:"note",tone:"error",text:`\u2717 ${R.id}
402
+ ${R.detail}`});uc(e,p.map(R=>({id:R.id,outcome:R.outcome,reason:R.detail,specSource:nr(e,R.id)})),new Date().toISOString());let A=_u({results:p,ids:c,articles:Ou(e,y.map(R=>R.id))});A&&ve(A.note,{kind:"cmd",cmd:A.cmd,reason:""},A.tone),p.length===c.length&&m.length===0&&w.length===0&&vo(l?.runLine)},[e,d,ve,oe,vo]),ds=X(c=>{let l=Ot(c);if(!l||kt(l)&&!l.refreshToken)return null;let i={...yn(l.idToken)??{},...yn(l.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),ps=X((c,l)=>{if(l){let i=ie(e);i&&(i.defaultProfile=c,Yd(i,e))}a(c),Ae(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${l?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),ds(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),Z("/login")),q(i=>i+1)},[e,d,Ae,ds,Z]),Ro=X((c,l,i)=>{No(e,c,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Ae(),zd(e,c)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:rn(on(e)).join(`
403
+ `)}),Xt(Nt()),Sn.current=Le(e).status==="current",Qt.current=nt(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,Ae,Xt]),So=X(async c=>{let l;try{l=await jn(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Z("/workspace");return}if(l.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=l.workspaces.filter(P=>(P.workspace_type??"").toLowerCase()!=="apidocumentation"),f=i.length>0?i:l.workspaces;if(f.length===1){let P=f[0],G=l.workspaces.length-f.length;d({kind:"note",tone:"ok",text:`Selected the "${P.name??P.id}" workspace${G>0?" (skipped the API-documentation workspace)":""}.`}),Ro(l.profile,l.projectId,P);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${f.length} available).`}),Z("/workspace")},[e,d,Ro,Z]),Po=X((c,l)=>{Io(e,c,l.id,l.name),d({kind:"note",tone:"ok",text:`Project set to "${l.name??l.id}" (agent restarted).`}),Ae(),So(c)},[e,d,Ae,So]),el=X(async c=>{let l;try{l=je(e,c)}catch{return}if(!l.project.workspaceId){if(l.project.projectId){if(!l.project.projectName)try{let{projects:i}=await ct(e,l.name),f=i.find(P=>P.id===l.project.projectId);f?.name&&ck(e,l.name,{projectName:f.name})}catch{}await So(l.name);return}try{let{projects:i}=await ct(e,l.name);if(i.length===1){let f=i[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${f.name??f.id}".`}),Po(l.name,{id:f.id,name:f.name});return}if(i.length>1){let f=i.map(P=>({id:P.id,name:P.name??P.id,sub:P.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),Ct({cursor:0,current:-1,rows:f,profile:l.name,environment:l.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Z("/project")}},[e,d,So,Po,Z]),Jt=X(()=>{let c=pe.current[0];if(!c)return;He();let{plan:l,mode:i}=c;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let P of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${P}`});l.overwritesLocalChanges&&i==="pull"&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let f=ot(l.oldContent,l.newContent,it());d(f?{kind:"diff",added:f.added,removed:f.removed,lines:f.lines,hidden:f.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),i==="conflict"?(d({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),d({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,it,He]),hs=X(()=>{if(pe.current.length>0){Jt();return}let c=Bt.current;Bt.current=[],c.length>0?(d({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),jt(c)):Z("/pull")},[Jt,d,jt,Z]),tl=X(c=>{if(pe.current.length===0)return!1;let l=c.trim().toLowerCase(),i=pe.current[0];if(i.mode==="conflict"){if(l==="l"||l==="local")pe.current.shift(),Bt.current.push(i.plan.path),d({kind:"note",tone:"info",text:`Keeping local ${i.plan.path} \u2014 will publish over the portal.`});else if(l==="p"||l==="portal"){pe.current.shift();try{Kd({cwd:e,profileName:s},i.plan),d({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(f){d({kind:"note",tone:"error",text:`Take-portal failed: ${f.message}`})}}else if(l==="s"||l==="skip"||l==="n")pe.current.shift(),d({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let f=pe.current.length;return pe.current=[],Bt.current=[],d({kind:"note",tone:"info",text:`Resolve cancelled (${f} conflict${f===1?"":"s"} left untouched).`}),!0}return hs(),!0}if(l==="y"||l==="yes"){let f=pe.current.shift().plan;try{Kd({cwd:e,profileName:s},f),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${f.path} (sync base advanced).`})}catch(P){d({kind:"note",tone:"error",text:`Pull failed: ${P.message}`})}}else if(l==="n"||l==="no"){let f=pe.current.shift().plan;d({kind:"note",tone:"info",text:`Skipped ${f.path}.`})}else{let f=pe.current.length;return pe.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${f} article(s) left untouched).`}),!0}return hs(),!0},[e,s,hs,d]),fs=X(async c=>{d({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let l=await Sa({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),f=l.entries.filter(G=>G.status==="conflict"&&G.path).map(G=>G.path);if(i){if(!f.includes(i)){d({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}f=[i]}if(f.length===0){d({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let P=[];for(let G of f)try{P.push({plan:await Qd({cwd:e,profileName:s,relPath:G}),mode:"conflict"})}catch(p){d({kind:"note",tone:"error",text:`Could not load ${G} from Document360: ${p.message}`})}if(P.length===0)return;d({kind:"note",tone:"info",text:`Resolving ${P.length} conflict${P.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),pe.current=P,Bt.current=[],Jt()}catch(l){d({kind:"note",tone:"error",text:`Could not compute sync status: ${l.message}`})}},[e,s,d,Jt]),nl=X(c=>{let l=co.current;if(!l)return!1;if(co.current=null,He(),c.trim()!==l.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:f}=ea(e,l.targets);d({kind:"note",tone:f.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`});for(let P of f)d({kind:"note",tone:"error",text:` \u2717 ${P.path}: ${P.error}`});return l.hadDevhints&&(d({kind:"note",tone:"warn",text:Vo().join(`
404
+ `)}),Xt(vs())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
405
+ ${ip}`}),Z("/init"),so(!1),!0},[e,d,Xt,He,Z]),Tn=X(async c=>{let l=c.slice(1).trim().split(/\s+/),i=(l[0]??"").toLowerCase(),f=l.slice(1);if(so(!0),fr(f)&&["write","check","review","reorder"].includes(i)){let p=Vn(e,s);if(p.length===0){d({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let y=w=>i==="write"?`/write ${Xc(f,w).join(" ")}`.trim():`/${i} ${[w,...f.filter(m=>m!=="--scope")].join(" ")}`.trim();if(p.length===1){Tn(y(p[0].token));return}St({cursor:0,rows:p,run:w=>{Tn(y(w))}});return}if(yt(i,f)){let p=Vn(e,s);if(p.length>1){let y=f.filter(A=>A.startsWith("--")).join(" "),w=A=>`/${i}${A?` ${i==="write"?`--scope ${A}`:A}`:""}${y?` ${y}`:""} ${A?"":"--all"}`.replace(/\s+/g," ").trim(),m=p.reduce((A,R)=>A+R.count,0),D={token:"",label:i==="review"?`Everything \u2014 all ${m} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${p.length} categories`:`Everything \u2014 rewrite all ${m} planned articles`,count:m};St({cursor:0,rows:[D,...p],run:A=>{Tn(w(A))}});return}}let P=async p=>{let y=Ii(p);if(!br(e)){await oe(Wi(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(y.mode==="single"){await Co([y.id],{runLine:[`/screenshot capture ${y.id}`,`/capture ${y.id}`]});return}if(y.mode==="failed"){let m=_i(e,kr(e).rows);if(m.length===0){d({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),Z("/screenshot list");return}await Co(m);return}if(y.mode==="all"||y.mode==="scope"){let m=y.mode==="scope"?y.scope:void 0,{ready:D,captured:A,blocked:R,rows:C}=kr(e,m),W=[...D,...A,...y.retryBlocked?R:[]];if(W.length===0&&R.length>0&&!y.retryBlocked){let H=m?`/screenshot capture ${m} --retry-blocked`:"/screenshot capture --all --retry-blocked";ve(`All ${R.length} shot${R.length===1?"":"s"} in scope ${R.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${H}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(W.length===0){d({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Z("/screenshot");return}if(!y.retryBlocked){let H=m?`/screenshot capture ${m} --retry-blocked`:"/screenshot capture --all --retry-blocked",J=Oi(C.filter(le=>le.state==="blocked"),H);J&&d({kind:"note",tone:"info",text:J})}let M=y.mode==="scope"?[`/screenshot capture ${y.scope}`,`/capture ${y.scope}`]:["/screenshot capture --all","/capture --all"];await Co(W,{runLine:M});return}let w=Du(Ye(e));if(w.length===0){d({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Z("/screenshot");return}Rt({cursor:0,rows:w,title:"Capture screenshots \u2014 pick what to shoot:"})},G=async()=>{let p=await pn();p.kind==="forward-to-agent"&&p.prompt&&await oe(p.prompt,{display:p.display,quietUser:!0});let y=Hi(e);y&&d({kind:"note",tone:"info",text:y.join(`
406
+ `)})};switch(i){case"help":Cn({tab:0});return;case"exit":case"quit":Ie.current?.close(),r();return;case"clear":Ae(),Ft.current=[],so(!1),He(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let p;try{p=je(e,s)}catch(y){d({kind:"note",tone:"error",text:y.message});return}d({kind:"note",tone:"info",text:`Profile "${p.name}" \u2192 ${p.connection.name} (${p.connection.apiUrl})${p.production?" \u26A0 PRODUCTION":""}`}),L(!0);try{let y=await Ew(p.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},m=>d({kind:"note",tone:"info",text:m})),w=jw(p.name,y);if(Nw(w),await ws(w,p.name,m=>d({kind:"note",tone:"info",text:m})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${p.name}" as ${Lo(w)}`}),await el(s),vn.current){let m=vn.current;vn.current=null;let D=Me(e,s);D.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${m}.`}),Z(m)):(d({kind:"note",tone:"warn",text:`${D.reason} (then ${m}.)`}),Z("/login"),vn.current=m)}else xn.current&&(xe(xn.current,"\u21E5 tab to re-send your last prompt\u2026"),xn.current=null)}catch(y){d({kind:"note",tone:"error",text:`Login failed: ${y.message}`})}finally{L(!1),q(y=>y+1)}return}case"allow-prod":{let p=!1;try{p=je(e,s).production}catch{}if(!p){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Wt.current=!0,Ae(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let p=Pi(f.join(" ")),y=Qe.current.uuid;if(!y){if(!p){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Zr.current=p,$t(p),fn(`${Ur} ${p}`),d({kind:"note",tone:"ok",text:`Session will be named "${p}" once it starts.`});return}if(!p){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Qe.current.firstPrompt??"";Gd(w,e).then(m=>{m?(xe(`/rename ${m}`),d({kind:"note",tone:"info",text:`Suggestion: "${m}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}qw(y,p),$t(p),fn(`${Ur} ${p}`),d({kind:"note",tone:"ok",text:`Session renamed to "${p}".`});return}case"profile":{let p=f[0],y=ie(e);if(!p){let w=Object.entries(y?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let m=w.map(([R,C])=>({name:R,env:C.connection?.environment??"custom",prod:C.production===!0,who:ds(R)})),D=s??y?.defaultProfile,A=Math.max(0,m.findIndex(R=>R.name===D));Ht({cursor:A,current:A,rows:m});return}if(p==="add"){let w=Ti(e,f[1],f[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${f[1]}" created (environment: ${f[2]??f[1]}).`}),ps(f[1],!1);return}if(!y?.profiles?.[p]){d({kind:"note",tone:"error",text:`Unknown profile "${p}". Create it: /profile add ${p} <environment>`});return}ps(p,!0);return}case"doctor":await Yn(f,{cwd:e,version:o});return;case"genre":{await Sr(f,{cwd:e});try{zr.current=!(ie(e)?.appType??Yw(e))}catch{}q(p=>p+1);return}case"roadmap":{if(f[0]?.toLowerCase()==="done"){let p=Tr(e,f.slice(1).join(" ").trim());d({kind:"note",tone:p.ok?"ok":"warn",text:p.line}),q(y=>y+1);return}d({kind:"note",tone:"info",text:ia(e).join(`
407
+ `)});return}case"mcp":await zo(f);return;case"init":{if(ie(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let p=Jw().map(y=>({name:y,apiUrl:Zw(y).apiUrl}));qt({cursor:0,rows:p});return}case"resume":{let p=f.join(" ").trim(),y=Hw(e).filter(D=>D.uuid!==Qe.current.uuid);if(!p){if(!y.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Dt({query:"",cursor:0,sessions:y});return}let w=Bw(e,p);if(!w){d({kind:"note",tone:"error",text:`No session matches "${p}".`});return}Ae(w.uuid),Qe.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},$t(w.name),Ra(w.uuid),Ft.current=[];let m=ba(e,w.uuid);for(let D of m)d(D);d({kind:"note",tone:"ok",text:m.length?`Resumed "${w.name}" \u2014 restored ${m.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let p=f.join(" ").trim(),y;try{y=await jn(e,s)}catch(m){d({kind:"note",tone:"error",text:`Could not list workspaces: ${m.message}`});return}if(!p){let m=y.workspaces.map(A=>({id:A.id,name:A.name??A.id,type:A.workspace_type}));if(m.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let D=Math.max(0,m.findIndex(A=>A.id===y.current));Vt({cursor:D,current:D,rows:m,profile:y.profile,projectId:y.projectId,projectName:y.projectName,environment:y.environment});return}let w=gs(y.workspaces,p);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${p}".`});return}Ro(y.profile,y.projectId,w);return}case"project":{let p=f.join(" ").trim(),y;try{y=await ct(e,s)}catch(m){d({kind:"note",tone:"error",text:`Could not list projects: ${m.message} (signed in? try /login)`});return}if(!p){let m=y.projects.map(A=>({id:A.id,name:A.name??A.id,sub:A.sub_domain}));if(m.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let D=m.findIndex(A=>A.id===y.current);Ct({cursor:Math.max(0,D),current:D,rows:m,profile:y.profile,environment:y.environment});return}let w=ys(y.projects,p);if(!w){d({kind:"note",tone:"error",text:`No project matches "${p}". Available: ${y.projects.map(m=>m.name??m.id).join(", ")}`});return}Po(y.profile,w);return}case"logout":{let p;try{p=je(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let y=Lw(p);Mw(e,p),Ae(),q(w=>w+1),d({kind:"note",tone:y?"ok":"info",text:y?`\u2713 Signed out of "${p}" and cleared its project/workspace selection.`:`Profile "${p}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Z("/login");return}case"publish":{if(!go(c.trim()))return;if(f.includes("--screenshots")||f.includes("--shots")){let m=or(Ye(e));if(m.length===0){d({kind:"note",tone:"info",text:"No captured screenshots yet \u2014 /screenshot capture first."});return}d({kind:"note",tone:"info",text:`Re-saving ${m.length} article${m.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await jt(m);return}if(f[0]==="--related"&&f[1]){let m=await ur(e,s,f[1].replace(/\\/g,"/"));if(m.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await jt(m);return}let p=f.filter(m=>!m.startsWith("--"));if(p[0]){await us(p[0]);return}let y=f.includes("--all"),w=f.includes("--force");d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Sa({cwd:e,profileName:s}),{clean:D,conflicts:A}=ar(m.entries),R=y&&w&&A.length>0,C=cr(m.entries);if(C>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${C} article${C===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.`}),A.length>0&&!R&&d({kind:"note",tone:"warn",text:lr(A.length)}),D.length===0&&!R){if(A.length>0){Z("/resolve");return}d({kind:"note",tone:"ok",text:C>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let W=m.counts["unknown-base"]??0;W>0&&d({kind:"note",tone:"info",text:`(${W} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),po("Reconciling structure on Document360 (order + related articles)\u2026");try{let M=await np({cwd:e,profileName:s}),H=sp(await rp({cwd:e,profileName:s})),J=op(M);J?d({kind:"note",tone:"info",text:J}):M.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${M.skipped}`}),H&&d({kind:"note",tone:"info",text:H}),d({kind:"note",tone:"ok",text:J||H?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(J||H)&&Z("/structure")}catch(M){d({kind:"note",tone:"warn",text:`Structure sync failed: ${M.message}`})}finally{po(null)}return}if(y){let W=(R?[...D,...A]:D).map(M=>M.path);await jt(W),A.length>0&&!R&&Z("/resolve");return}Gt({cursor:0,rows:jc(D,A)})}catch(m){d({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!go(c.trim()))return;await fs(f.find(p=>!p.startsWith("--")));return}case"preview":{let p=f.join(" ").trim();if(!p){let w=[];try{w=Object.keys(zd(e,je(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Pt({query:"",cursor:0,paths:w});return}let y=Dw(p)?p:Ca(e,p);if(mn(y)){try{d({kind:"preview",name:to(y),text:lp(qr(y,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${y}: ${w.message}`})}return}if(kk.test(p)){try{let w=je(e,s),m={profile:w.name,connection:w.connection},D=w.project.projectId??_w(m),A=await Ow(m,D,p);d({kind:"preview",name:A.title??p,text:A.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${p}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let p=f[0]?.trim();if(!p){let D=gr(Ea(e));vt({cursor:D,current:D});return}let{lines:y,changed:w,effective:m}=Gn(e,p);for(let D of y)d({kind:"note",tone:D.startsWith("\u26A0")?"warn":D.startsWith("\u2713")?"ok":"info",text:D});w&&(Ga(D=>D+1),Ie.current?.setModel(m));return}case"convert":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:p,run:y}=ri(f),w=nk(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let m=si(w,p);if(m.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${p}". (${w.length} are tracked overall.)`});return}let D=Pa(m),A=3,R=`/convert${p?` --scope ${p}`:""} --run`,C=Gr(e,"light");if(!y){let M=Jd({files:ii(e,m),op:"convert",model:C.model}),H=p?`Scope: ${p} (${m.length} of ${w.length} tracked)
408
408
  `:"",J=`
409
- Model: ${C.model}${C.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:H+ai(D,M,A).join(`
410
- `)+J}),Z(R);return}kt.current=Date.now(),Ot(0),E(!0);let W=new AbortController;we.current=W,se({verb:"Converting",total:D.length,done:0,active:[],rows:Zn(D),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${m.length} articles across ${D.length} partitions (\u2264${A} agents at once) on ${C.model}\u2026 (esc to stop)`});try{for await(let M of qr({cwd:e,partitions:D,promptFor:ii,concurrency:A,profileName:s,allowProdWrites:Ft.current,model:C.model,signal:W.signal}))if(M.type==="partition_status")M.status==="running"?se(H=>H&&{...H,active:[...H.active,M.label],rows:Ue(H.rows,M.label,"active"),lastAt:Date.now()}):se(H=>H&&{...H,active:H.active.filter(J=>J!==M.label),done:H.done+1,rows:Ue(H.rows,M.label,M.status==="done"?"done":"failed"),lastAt:Date.now()});else if(M.type==="partition_event")se(H=>{if(!H)return H;let J={...H,lastAt:Date.now()};return M.event.type==="tool"?J.tools=H.tools+1:M.event.type==="text"&&(J.chars=H.chars+M.event.delta.length),J});else if(M.type==="run_done"){zt(le=>le+M.totalCostUsd),Yt(le=>le+M.results.reduce((Do,Ao)=>Do+Ao.outputTokens,0));let H=M.aborted?"Stopped. ":"",J=t.kind==="api"?"api":"subscription";d({kind:"note",tone:M.aborted?"warn":M.ok?"ok":"warn",text:H+li(M.results,D,J).join(`
411
- `)})}}catch(M){d({kind:"note",tone:"error",text:`Convert run failed: ${M.message}`})}finally{we.current=null,se(null),E(!1),q(M=>M+1)}return}case"write":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=tk(e);if(p.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:y,path:w,preview:m,concurrency:D,rewrite:A}=di(f),{docsDir:R,targets:C,reason:W,rewriting:M}=wi(e,p,{scope:y,path:w,rewrite:A});if(C.length===0){d({kind:"note",tone:"warn",text:W??"Nothing to write."});return}M&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${C.length} already-written article${C.length===1?"":"s"} (overwrites them; git has your baseline).`});let H=Ra(C),J=ui(D),le=Vr(e,"standard"),Do=!!w;if(m&&!Do){let ee=Xd({files:hi(e,p,C),op:"write",model:le.model}),ce=y?`Scope: ${y} (${C.length} pending)
409
+ Model: ${C.model}${C.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:H+li(D,M,A).join(`
410
+ `)+J}),Z(R);return}bt.current=Date.now(),Lt(0),E(!0);let W=new AbortController;we.current=W,se({verb:"Converting",total:D.length,done:0,active:[],rows:eo(D),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${m.length} articles across ${D.length} partitions (\u2264${A} agents at once) on ${C.model}\u2026 (esc to stop)`});try{for await(let M of Vr({cwd:e,partitions:D,promptFor:ai,concurrency:A,profileName:s,allowProdWrites:Wt.current,model:C.model,signal:W.signal}))if(M.type==="partition_status")M.status==="running"?se(H=>H&&{...H,active:[...H.active,M.label],rows:Ue(H.rows,M.label,"active"),lastAt:Date.now()}):se(H=>H&&{...H,active:H.active.filter(J=>J!==M.label),done:H.done+1,rows:Ue(H.rows,M.label,M.status==="done"?"done":"failed"),lastAt:Date.now()});else if(M.type==="partition_event")se(H=>{if(!H)return H;let J={...H,lastAt:Date.now()};return M.event.type==="tool"?J.tools=H.tools+1:M.event.type==="text"&&(J.chars=H.chars+M.event.delta.length),J});else if(M.type==="run_done"){Kt(le=>le+M.totalCostUsd),zt(le=>le+M.results.reduce((Ao,Eo)=>Ao+Eo.outputTokens,0));let H=M.aborted?"Stopped. ":"",J=t.kind==="api"?"api":"subscription";d({kind:"note",tone:M.aborted?"warn":M.ok?"ok":"warn",text:H+ci(M.results,D,J).join(`
411
+ `)})}}catch(M){d({kind:"note",tone:"error",text:`Convert run failed: ${M.message}`})}finally{we.current=null,se(null),E(!1),q(M=>M+1)}return}case"write":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=ok(e);if(p.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:y,path:w,preview:m,concurrency:D,rewrite:A}=pi(f),{docsDir:R,targets:C,reason:W,rewriting:M}=ki(e,p,{scope:y,path:w,rewrite:A});if(C.length===0){d({kind:"note",tone:"warn",text:W??"Nothing to write."});return}M&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${C.length} already-written article${C.length===1?"":"s"} (overwrites them; git has your baseline).`});let H=Pa(C),J=di(D),le=Gr(e,"standard"),Ao=!!w;if(m&&!Ao){let ee=Jd({files:fi(e,p,C),op:"write",model:le.model}),ce=y?`Scope: ${y} (${C.length} pending)
412
412
  `:"",ke=`
413
- Model: ${le.model}${le.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:ce+mi(H,ee,J).join(`
414
- `)+ke}),Z(`/write${y?` --scope ${y}`:""}`);return}kt.current=Date.now(),Ot(0),E(!0);let Ao=new AbortController;we.current=Ao,se({verb:"Writing",total:H.length,done:0,active:[],rows:Zn(H),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${C.length} article${C.length===1?"":"s"} across ${H.length} partition${H.length===1?"":"s"} (\u2264${J} agents at once) on ${le.model}${le.forced?" (forced)":""}\u2026 (esc to stop)`});let Eo=new Set;try{for await(let ee of qr({cwd:e,partitions:H,promptFor:ce=>fi(ce,R,{rewrite:M||Do}),concurrency:J,profileName:s,allowProdWrites:Ft.current,model:le.model,signal:Ao.signal}))if(ee.type==="partition_status")ee.status==="running"?se(ce=>ce&&{...ce,active:[...ce.active,ee.label],rows:Ue(ce.rows,ee.label,"active"),lastAt:Date.now()}):se(ce=>ce&&{...ce,active:ce.active.filter(ke=>ke!==ee.label),done:ce.done+1,rows:Ue(ce.rows,ee.label,ee.status==="done"?"done":"failed"),lastAt:Date.now()});else if(ee.type==="partition_event"){let ce=null;if(ee.event.type==="tool"){let ke=Dd(ee.event.name,ee.event.input,H[ee.index]?.paths??[]);ke&&!Eo.has(ke)&&(Eo.add(ke),ce=ee.label)}se(ke=>{if(!ke)return ke;let Ge={...ke,lastAt:Date.now()};return ee.event.type==="tool"?Ge.tools=ke.tools+1:ee.event.type==="text"&&(Ge.chars=ke.chars+ee.event.delta.length),ce&&(Ge.rows=Td(Ge.rows,ce)),Ge})}else if(ee.type==="run_done"){zt(at=>at+ee.totalCostUsd),Yt(at=>at+ee.results.reduce((tt,Cp)=>tt+Cp.outputTokens,0));let ce=ee.aborted?"Stopped. ":"",ke=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:ee.aborted?"warn":ee.ok?"ok":"warn",text:ce+gi(ee.results,H,ke).join(`
415
- `)}),!ee.aborted&&ee.ok)try{let at=(Eo.size>0?[...Eo]:C).map(tt=>`${R}/${tt}`);Sa(e,at,{writtenCap:Pa})}catch{}let Ge=ee.aborted?null:yi(e,R,C);if(Ge&&d({kind:"note",tone:"warn",text:Ge}),!ee.aborted&&ee.ok){let at=y??w??"",tt=at?` ${at}`:"";ve(Ge?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${tt} --fix, then /review${tt} --fix for editorial quality, then /publish --all (add /screenshot author --all first if you want images).`:`Written. I\u2019d run /review${tt} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot author --all first if you want images).`,{kind:"cmd",cmd:Ge?`/check${tt} --fix`:`/review${tt} --fix`,reason:""})}}}catch(ee){d({kind:"note",tone:"error",text:`Write run failed: ${ee.message}`})}finally{we.current=null,se(null),E(!1),q(ee=>ee+1)}return}case"draft":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:p,looseDocs:y}=ki(e);if(p.length===0&&y===0){d({kind:"note",tone:"info",text:$i});return}let w=f.join(" ").trim();if(!w&&p.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
413
+ Model: ${le.model}${le.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:ce+gi(H,ee,J).join(`
414
+ `)+ke}),Z(`/write${y?` --scope ${y}`:""}`);return}bt.current=Date.now(),Lt(0),E(!0);let Eo=new AbortController;we.current=Eo,se({verb:"Writing",total:H.length,done:0,active:[],rows:eo(H),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${C.length} article${C.length===1?"":"s"} across ${H.length} partition${H.length===1?"":"s"} (\u2264${J} agents at once) on ${le.model}${le.forced?" (forced)":""}\u2026 (esc to stop)`});let jo=new Set;try{for await(let ee of Vr({cwd:e,partitions:H,promptFor:ce=>mi(ce,R,{rewrite:M||Ao}),concurrency:J,profileName:s,allowProdWrites:Wt.current,model:le.model,signal:Eo.signal}))if(ee.type==="partition_status")ee.status==="running"?se(ce=>ce&&{...ce,active:[...ce.active,ee.label],rows:Ue(ce.rows,ee.label,"active"),lastAt:Date.now()}):se(ce=>ce&&{...ce,active:ce.active.filter(ke=>ke!==ee.label),done:ce.done+1,rows:Ue(ce.rows,ee.label,ee.status==="done"?"done":"failed"),lastAt:Date.now()});else if(ee.type==="partition_event"){let ce=null;if(ee.event.type==="tool"){let ke=Ed(ee.event.name,ee.event.input,H[ee.index]?.paths??[]);ke&&!jo.has(ke)&&(jo.add(ke),ce=ee.label)}se(ke=>{if(!ke)return ke;let Ge={...ke,lastAt:Date.now()};return ee.event.type==="tool"?Ge.tools=ke.tools+1:ee.event.type==="text"&&(Ge.chars=ke.chars+ee.event.delta.length),ce&&(Ge.rows=Ad(Ge.rows,ce)),Ge})}else if(ee.type==="run_done"){Kt(at=>at+ee.totalCostUsd),zt(at=>at+ee.results.reduce((tt,Sp)=>tt+Sp.outputTokens,0));let ce=ee.aborted?"Stopped. ":"",ke=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:ee.aborted?"warn":ee.ok?"ok":"warn",text:ce+yi(ee.results,H,ke).join(`
415
+ `)}),!ee.aborted&&ee.ok)try{let at=(jo.size>0?[...jo]:C).map(tt=>`${R}/${tt}`);Ta(e,at,{writtenCap:Da})}catch{}let Ge=ee.aborted?null:wi(e,R,C);if(Ge&&d({kind:"note",tone:"warn",text:Ge}),!ee.aborted&&ee.ok){let at=y??w??"",tt=at?` ${at}`:"";ve(Ge?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${tt} --fix, then /review${tt} --fix for editorial quality, then /publish --all (add /screenshot author --all first if you want images).`:`Written. I\u2019d run /review${tt} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot author --all first if you want images).`,{kind:"cmd",cmd:Ge?`/check${tt} --fix`:`/review${tt} --fix`,reason:""})}}}catch(ee){d({kind:"note",tone:"error",text:`Write run failed: ${ee.message}`})}finally{we.current=null,se(null),E(!1),q(ee=>ee+1)}return}case"draft":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:p,looseDocs:y}=bi(e);if(p.length===0&&y===0){d({kind:"note",tone:"info",text:xi});return}let w=f.join(" ").trim();if(!w&&p.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
416
416
  ${p.map(A=>` \u2022 ${A.name} (${A.docCount} doc${A.docCount===1?"":"s"})`).join(`
417
- `)}`}),Be(p.map(A=>`/draft ${A.name}`));return}let m="",D;if(w){let A=bi(p,w);A?m=A:D=w}else m=p[0]?.name??"";await oe(fr(m,D),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!mo(c.trim()))return;let p=f.find(y=>y.startsWith("--"));try{if(p==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let m=Date.now(),D=await Ca({cwd:e,profileName:s});d({kind:"note",tone:"info",text:dr(D,Date.now()-m).join(`
418
- `)});return}if(p==="--baseline"){let m=f.find(C=>!C.startsWith("--")),D=m?m.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:D?`Setting the sync baseline for ${D}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let A=await Yw({cwd:e,profileName:s,relPaths:D?[D]:void 0}),R=D?{rebaselined:[],skipped:[]}:await zw({cwd:e,profileName:s});if(A.baselined.length===0&&A.skipped.length===0&&R.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}A.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${A.baselined.length} article${A.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),R.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${R.rebaselined.length} article${R.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),A.skipped.length>0&&d({kind:"note",tone:"warn",text:`${A.skipped.length} skipped:
417
+ `)}`}),Be(p.map(A=>`/draft ${A.name}`));return}let m="",D;if(w){let A=$i(p,w);A?m=A:D=w}else m=p[0]?.name??"";await oe(mr(m,D),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!go(c.trim()))return;let p=f.find(y=>y.startsWith("--"));try{if(p==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let m=Date.now(),D=await Sa({cwd:e,profileName:s});d({kind:"note",tone:"info",text:pr(D,Date.now()-m).join(`
418
+ `)});return}if(p==="--baseline"){let m=f.find(C=>!C.startsWith("--")),D=m?m.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:D?`Setting the sync baseline for ${D}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let A=await Kw({cwd:e,profileName:s,relPaths:D?[D]:void 0}),R=D?{rebaselined:[],skipped:[]}:await Xw({cwd:e,profileName:s});if(A.baselined.length===0&&A.skipped.length===0&&R.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}A.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${A.baselined.length} article${A.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),R.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${R.rebaselined.length} article${R.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),A.skipped.length>0&&d({kind:"note",tone:"warn",text:`${A.skipped.length} skipped:
419
419
  ${A.skipped.map(C=>` - ${C.path} (${C.reason})`).join(`
420
- `)}`}),q(C=>C+1);return}if(p==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let m=await Gw({cwd:e,profileName:s}),D=m.onlyInLegacy.length===0&&m.onlyInManifest.length===0&&m.mappedMissingFromManifest.length===0,A=[`Legacy listing: ${m.legacyCount} \xB7 Manifest: ${m.manifestCount} \xB7 in both: ${m.inBoth}`];D?A.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(m.mappedMissingFromManifest.length&&A.push(`\u2717 ${m.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${m.mappedMissingFromManifest.slice(0,5).join(", ")}`),m.onlyInLegacy.length&&A.push(`\u26A0 ${m.onlyInLegacy.length} only in the legacy listing: ${m.onlyInLegacy.slice(0,5).join(", ")}`),m.onlyInManifest.length&&A.push(`\u26A0 ${m.onlyInManifest.length} only in the manifest: ${m.onlyInManifest.slice(0,5).join(", ")}`),A.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:D?"ok":"warn",text:A.join(`
421
- `)});return}if(p){d({kind:"note",tone:"error",text:`Unknown option: ${p} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=f[0];if(y){let m=await Kd({cwd:e,profileName:s,relPath:y.replace(/\\/g,"/")});pe.current=[{plan:m,mode:m.overwritesLocalChanges?"conflict":"pull"}],Wt.current=[],Qt();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let w=await ei({cwd:e,profileName:s});for(let m of ti(w))d({kind:"note",tone:m.tone,text:m.text});q(m=>m+1)}catch(y){d({kind:"note",tone:"error",text:`Pull failed: ${y.message}`})}return}case"scope":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=Kw(e);if(p.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Gt({cursor:0,rows:p.map(y=>({...y,checked:y.recommended}))});return}case"audit":{if(f[0]==="--auto"){let y=ie(e);if(!y){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=f[1]!=="off";Vd({...y,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let p=await Bn();p.kind==="forward-to-agent"&&p.prompt&&await oe(p.prompt,{display:p.display,quietUser:!0});return}case"check":{let p=f.find(m=>!m.startsWith("--")),y=p?` ${p}`:"",w=zd({cwd:e,scope:p});if(f.includes("--fix")){if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}d({kind:"note",tone:"info",text:`Fixing ${w.length} doc issue${w.length===1?"":"s"}\u2026`});let m=Zd(e,p);await oe(ea(w),{display:`/check${y} --fix`,quietUser:!0});try{Sa(e,m,{reviewedCap:Pa})}catch{}let D=zd({cwd:e,scope:p});d({kind:"note",tone:D.length===0?"ok":"warn",text:D.length===0?"\u2713 Doc-checker: all issues resolved.":Cr(D).join(`
422
- `)}),ve(D.length===0?`Deterministic issues fixed. Next: /review${y} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${y} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${y} --fix`,reason:""});return}d({kind:"note",tone:w.length===0?"ok":"warn",text:Cr(w).join(`
423
- `)}),w.length>0&&ve(`Found ${w.length} doc issue${w.length===1?"":"s"} above. /check${y} --fix has the agent fix them in place (or /review${y} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${y} --fix`,reason:""});return}case"structure":{let p=Kn(e,s);if(p.length===0){d({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}d({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...p].join(`
424
- `)});return}case"reorder":{let p=na(e,f);if(!p){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await oe(p.prompt,{display:p.display,quietUser:!0}),ve("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let p=ta(e,f);if(!p){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=f.includes("--fix"),w=f.find(D=>!D.startsWith("--")),m=y?Zd(e,w):[];if(await oe(p.prompt,{display:p.display,quietUser:!0}),y)try{Sa(e,m,{reviewedCap:Pa})}catch{}if(y)ve("\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let D=f.filter(A=>A!=="--fix").join(" ");ve(`The review listed issues above. /review${D?` ${D}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${D?` ${D}`:""} --fix`,reason:""})}return}case"capture-setup":{await G();return}case"devhints":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:on(nn(e)).join(`
425
- `)}),Kt(jt()),Cn.current=Le(e).status==="current",Xt.current=nt(e);return}case"discover":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await oe(Ks(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Bi(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await oe(Hi(),{display:"/inbox",quietUser:!0});return}case"feedback":{let p=Jd(e),y="";try{y=hn(p)?Hr(p,"utf8"):""}catch{y=""}if(!/^## /m.test(y)){d({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let w=await ga(y.trim());d({kind:"note",tone:w?"ok":"warn",text:w?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${p} and copy it manually.`}),w&&ss(null);return}case"document":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:p,what:y}=vi(f);if(!y&&xi(e)===0){d({kind:"note",tone:"info",text:Ri});return}let w=`/document${y?` ${y}`:""}${p?" --publish":""}`;await oe(Ci(y,p),{display:w,quietUser:!0});return}case"catch-up":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!mo(c.trim()))return;let{publish:p}=Vi(f);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let y=await Yi({cwd:e,profileName:s});for(let m of zi(y))d({kind:"note",tone:m.startsWith("\u2713")?"ok":m.startsWith("\u2139")?"info":"warn",text:m});let w=zn(Yn(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await oe(Gi({publish:p}),{display:`/catch-up${p?" --publish":""}`,quietUser:!0});return}case"update":{os.current=!0,d({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),so(!0);let p=await xr().finally(()=>so(!1));p.ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated ${p.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),Z("/exit"),_a("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${$r}`});return}case"screenshot":{let p=Un(f);if(p.mode==="capture"){await P(p.rest);return}if(p.mode==="checklist"){await G();return}if(p.mode==="list"){if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=ie(e)?.docsDir??Aa,D=Bs(e,p.scope),A=Ye(e,D);if(p.picker){if(A.length===0){d({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let W=vc(A);if(W.length===0){d({kind:"note",tone:"info",text:or(A,{docsDir:m}).join(`
426
- `)}),ve(`\u2713 All ${A.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}Ct({cursor:0,rows:W,title:"Screenshots \u2014 pick what to author or capture:"});return}d({kind:"note",tone:"info",text:or(A,{scope:D,detail:p.detail,docsDir:m}).join(`
427
- `)});let R=A.filter(W=>W.state==="placeholder").length,C=A.filter(W=>W.state==="spec").length;if(R>0){let W=D?`/screenshot author ${D}`:"/screenshot author --all";ve(`${R} of ${A.length} still need${R===1?"s":""} a spec \u2014 /screenshot author <id> authors one, ${W} authors them all in parallel.`,{kind:"cmd",cmd:W,reason:""})}else if(C>0){let W=D?`/screenshot capture ${D}`:"/screenshot capture";ve(`${C} spec${C===1?"":"s"} ready to capture \u2014 ${W} takes ${C===1?"it":"them"} (a real browser drives your app).`,{kind:"cmd",cmd:W,reason:""})}return}if(p.mode==="single"){await Qa(p.id);return}if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=p.mode==="scope"?p.scope:void 0,w=Zw(e,{scope:y}).map(m=>m.id);if(w.length===0){d({kind:"note",tone:"info",text:y?`No screenshot placeholders under ${y}.`:"No screenshot placeholders found in the docs."});return}await Xa(w,{setup:p.setup,runLine:p.mode==="scope"?[`/screenshot author ${p.scope}`,`/screenshot ${p.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await P(f);return}case"reset":{let p=Qi(e);if(p.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}lo.current={repoName:eo(e),targets:p,hadDevhints:hn(Qd(e))},d({kind:"note",tone:"warn",text:Zi(e,p).join(`
428
- `)}),xe(eo(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Qt,hs,d,Ae,oe,Et,cs,Ja]),Po=X(c=>{let l=(c??x).trim();if($(""),io(null),Lt(0),l.startsWith("/")&&(no.current=!1,yn.current=!1,He(),wn(null),Be(f=>jd(f,l))),!l||(Ia(!1),el(l))||Za(l))return;Qr.current.push(l);let i=Od(l,Oa.current);if(l.startsWith("/"))d({kind:"user",text:l}),We(!0),Sn(i).finally(()=>We(!1));else if(ck(i)){d({kind:"user",text:l});let f=uk(i);if(!f)oe(i,{display:l,quietUser:!0});else{try{dk(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}oe(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${f}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${f}" and the article path(s) you wrote.`,{display:l,quietUser:!0})}}else{let f=nd(e,i);oe(f??i,{display:l})}},[x,el,Za,Sn,oe]),tl=X(c=>{if(c.length>1){if(c.includes("\x1B"))return;let l=Nd(c);if(Id(l)){let i=_d(++wp.current,l);Oa.current.set(i,l),j(i)}else j(l);return}j(c)},[j]),Jt=Math.max(10,qe-6),nl=$a(()=>Wr(k.text,Jt),[k.text,Jt]),fs=X(c=>b(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+c))})),[]),To=X(c=>b(l=>({...l,pos:Md(Wr(l.text,Jt),l.pos,c)})),[Jt]),Pn=X(c=>b(l=>({...l,pos:Ud(Wr(l.text,Jt),l.pos,c)})),[Jt]),xp=["\x1B[H","\x1B[1~","\x1BOH"],vp=["\x1B[F","\x1B[4~","\x1BOF"],ol=X((c,l)=>l.leftArrow?(fs(-1),!0):l.rightArrow?(fs(1),!0):c&&xp.includes(c)?(Pn("start"),!0):c&&vp.includes(c)?(Pn("end"),!0):l.ctrl&&c==="a"?(Pn("start"),!0):l.ctrl&&c==="e"?(Pn("end"),!0):!1,[fs,Pn]);return Cw((c,l)=>{if(l.ctrl&&c==="c"){Ie.current?.close(),r();return}if(!U){if(T){if(l.escape){if(we.current){if(!we.current.signal.aborted){let i=(co?.verb??"work").toLowerCase(),f=co?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${f}s)\u2026`}),we.current.abort()}return}kn.current||(kn.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Ie.current?.interrupt());return}if(l.return){let i=x.trim();if(!i)return;Pt.current.push(i),Zr([...Pt.current]),$("");return}if(ol(c,l))return;if(l.upArrow){To(-1);return}if(l.downArrow){To(1);return}if(l.backspace||l.delete){v();return}c&&!l.ctrl&&!l.meta&&tl(c);return}if($t){if(l.upArrow){xt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){xt(i=>i&&{...i,cursor:Math.min(ze.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ze.length){xt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=ze[$t.cursor];xt(null);let{lines:f,changed:P,effective:G}=qn(e,i.value??"default");for(let p of f)d({kind:"note",tone:p.startsWith("\u26A0")?"warn":p.startsWith("\u2713")?"ok":"info",text:p});P&&(qa(p=>p+1),Ie.current?.setModel(G));return}if(c==="s"){let i=ze[$t.cursor];xt(null),Ie.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(l.escape){xt(null);return}return}if(Je){if(l.upArrow){Bt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Bt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Je.rows.length){Bt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return||c==="s"){let i=Je.rows[Je.cursor];Bt(null),ds(i.name,l.return===!0);return}if(l.escape){Bt(null);return}return}if(ho){if(l.escape){xn(null);return}if(l.leftArrow||l.tab&&l.shift){xn(i=>i&&{tab:(i.tab-1+Oe.length)%Oe.length});return}if(l.rightArrow||l.tab){xn(i=>i&&{tab:(i.tab+1)%Oe.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Oe.length){xn({tab:Number(c)-1});return}return}if(Ze){if(l.upArrow){Ht(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ht(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ze.rows.length){Ht(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ze.rows[Ze.cursor].name;if(Ht(null),!vs(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let P=!1;try{let G=_t(i);P=!!G&&!(wt(G)&&!G.refreshToken)}catch{P=!1}d({kind:"note",tone:"info",text:P?`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.`}),Z("/login"),q(G=>G+1);return}if(l.escape){Ht(null);return}return}if($e){if(l.upArrow){qt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){qt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=$e.rows.length){qt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=$e.rows[$e.cursor],{profile:f,projectId:P}=$e;qt(null),Co(f,P,i);return}if(l.escape){qt(null);return}return}if(Pe){if(l.upArrow){vt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){vt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Pe.rows.length){vt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Pe.rows[Pe.cursor],{profile:f}=Pe;vt(null),So(f,i);return}if(l.escape){vt(null);return}return}if(Ce){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===" "){Gt(i=>i&&{...i,rows:i.rows.map((f,P)=>P===i.cursor?{...f,checked:!f.checked}:f)});return}if(l.return){let i=Ce.rows.filter(f=>f.checked).map(f=>f.path);if(Gt(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Xs(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of i)d({kind:"note",tone:"info",text:` ${f}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){Gt(null);return}return}if(et){if(l.upArrow){Rt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Rt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=et.rows.length){Rt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=et.rows[et.cursor],f=et.run;Rt(null),f(i.token);return}if(l.escape){Rt(null);return}return}if(rt){if(l.upArrow){Vt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Vt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=rt.rows.length){Vt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=rt.rows[rt.cursor];Vt(null),i.conflict?hs(i.paths[0]):i.kind==="article"?cs(i.paths[0]):Et(i.paths);return}if(l.escape){Vt(null);return}return}if(st){if(l.upArrow){Ct(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ct(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=st.rows.length){Ct(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=st.rows[st.cursor];Ct(null),i.action==="capture"?vo(i.ids,{runLine:i.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):i.kind==="shot"?Qa(i.ids[0]):Xa(i.ids,{setup:!0,runLine:i.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(l.escape){Ct(null);return}return}if(Te){if(l.escape){St(null);return}if(l.upArrow){St(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){St(i=>i&&{...i,cursor:Math.min(Math.max(0,bo.length-1),i.cursor+1)});return}if(l.return){let i=bo[Te.cursor];if(i){St(null);try{d({kind:"preview",name:eo(i),text:ip(Hr(xa(e,i),"utf8"))})}catch(f){d({kind:"note",tone:"error",text:`Could not read ${i}: ${f.message}`})}}return}if(l.backspace||l.delete){St(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){St(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(De){if(l.escape){Tt(null);return}if(l.upArrow){Tt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Tt(i=>i&&{...i,cursor:Math.min(Math.max(0,$o.length-1),i.cursor+1)});return}if(l.return){let i=$o[De.cursor];if(i){Tt(null),Ae(i.uuid),Qe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},bt(i.name),va(i.uuid),Ut.current=[];let f=wa(e,i.uuid);for(let P of f)d(P);d({kind:"note",tone:"ok",text:f.length?`Resumed "${i.name}" \u2014 restored ${f.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(l.backspace||l.delete){Tt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){Tt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(l.tab&&!x&&fe){$(fe),He();return}if(!x&&be.length>0&&!zr&&c&&/^[1-9]$/.test(c)){let i=be[Number(c)-1];if(i){$(It(i));return}}if(!x&&(go||vn)&&c==="c"&&!l.ctrl&&!l.meta&&!l.return&&!l.tab){let i=go!=null;ga(go??vn).then(P=>{d({kind:"note",tone:P?"ok":"warn",text:P?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."}),P&&i&&ss(null),P&&!i&&Ga(!0)});return}if(!ol(c,l)){if(za){if(l.upArrow){Lt(i=>Math.max(0,i-1));return}if(l.downArrow){Lt(i=>Math.min(Ve.length-1,i+1));return}if(l.tab){$("/"+(Ve[Xr]?.name??"")+" "),Lt(0);return}if(l.return){let i=Ve[Xr];if(i){let f=x.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Kl(i.usage)&&!f){$("/"+i.name+" "),Lt(0);return}Po("/"+i.name+(f?" "+f:""));return}}}else{if(l.upArrow){if(x!==""&&Mt===null){To(-1);return}let i=Qr.current;if(!i.length)return;let f=Mt===null?i.length-1:Math.max(0,Mt-1);io(f),$(i[f]??"");return}if(l.downArrow){if(x!==""&&Mt===null){To(1);return}let i=Qr.current;if(Mt===null)return;let f=Mt+1;f>=i.length?(io(null),$("")):(io(f),$(i[f]??""));return}}if(l.return){Po();return}if(l.backspace||l.delete){v();return}if(l.escape){$(""),Lt(0),He(),Be([]),wn(null),no.current=!0;return}c&&!l.ctrl&&!l.meta&&tl(c)}}}),Ne(()=>{if(T||U)return;let c=Pt.current.shift();c!==void 0&&(Zr([...Pt.current]),Po(c))},[T,U,Po]),Q(ae,{flexDirection:"column",width:qe,children:[ls!==null&&Q(ae,{marginTop:1,flexDirection:"column",children:[ls.truncated&&I(N,{dimColor:!0,children:"\u2026"}),I(N,{children:ls.text})]}),T&&(co?I($k,{p:co}):I(wk,{startTime:kt.current,chars:yp})),!T&&Wa?I(kk,{text:Wa}):null,I(ae,{borderStyle:"round",borderColor:Ya.prod?"yellow":K,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:x?nl.map((c,l)=>{let i=k.text.slice(c.start,c.end),f=l===Br(nl,k.pos),P=Math.min(k.pos,c.end)-c.start;return Q(N,{children:[I(N,{color:K,children:l===0?"> ":" "}),f?Q(to,{children:[i.slice(0,P),I(fn,{ch:i[P]??" "}),i.slice(P+1)]}):i||" "]},`${l}-${c.start}`)}):Q(N,{children:[I(N,{color:K,children:"> "}),es?I(fn,{ch:" "}):fe&&!T&&me?Q(to,{children:[I(fn,{ch:me[0],dim:!0}),I(N,{color:"gray",children:me.slice(1)})]}):fe&&!T?Q(to,{children:[I(fn,{ch:fe[0],dim:!0}),I(N,{color:"gray",children:fe.slice(1)}),I(N,{dimColor:!0,children:" (tab)"})]}):(is.isSetup||!mp)&&!T?Q(to,{children:[I(fn,{ch:is.text[0],dim:!0}),I(N,{color:"gray",children:is.text.slice(1)})]}):I(fn,{ch:" "})]})}),Fa.length>0&&I(ae,{flexDirection:"column",paddingX:1,children:Fa.map((c,l)=>I(N,{color:"gray",children:`\u29D7 queued: ${c}`},`${l}-${c.slice(0,24)}`))}),ho?I(Sd,{tab:ho.tab,width:qe,version:o,engineVersion:ap}):$t?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Select model"}),I(N,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),ze.map((c,l)=>Q(N,{color:l===$t.cursor?K:void 0,children:[l===$t.cursor?"\u276F ":" ",`${l+1}. ${c.label}${l===$t.current?" \u2714":""}`.padEnd(16),I(N,{color:"gray",children:c.desc})]},c.label)),I(N,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Je?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Switch connection profile"}),Je.rows.map((c,l)=>Q(N,{color:l===Je.cursor?K:void 0,children:[l===Je.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Je.current?" \u2714":""}`.padEnd(20),I(N,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?I(N,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),I(N,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ze?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Pick your Document360 environment"}),Ze.rows.map((c,l)=>Q(N,{color:l===Ze.cursor?K:void 0,children:[l===Ze.cursor?"\u276F ":" ",`${l+1}. ${c.name}`.padEnd(16),I(N,{color:"gray",children:c.apiUrl})]},c.name)),I(N,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):$e?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Switch workspace"}),I(N,{dimColor:!0,children:`environment ${$e.environment} \xB7 project ${$e.projectName??`${$e.projectId.slice(0,8)}\u2026`}`}),$e.rows.map((c,l)=>Q(N,{color:l===$e.cursor?K:void 0,children:[l===$e.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===$e.current?" \u2714":""}`.padEnd(30),I(N,{color:"gray",children:c.type??""})]},c.id)),I(N,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):Pe?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Choose project"}),I(N,{dimColor:!0,children:`environment ${Pe.environment}`}),Pe.rows.map((c,l)=>Q(N,{color:l===Pe.cursor?K:void 0,children:[l===Pe.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Pe.current?" \u2714":""}`.padEnd(30),I(N,{color:"gray",children:c.sub??""})]},c.id)),I(N,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Ce?(()=>{let l=Math.min(Math.max(0,Ce.cursor-Math.floor(7)),Math.max(0,Ce.rows.length-14)),i=Ce.rows.slice(l,l+14),f=Ce.rows.filter(P=>P.checked).length;return Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:`Which folders back the user docs? (${f} selected of ${Ce.rows.length})`}),l>0?I(N,{dimColor:!0,children:` \u2191 ${l} more`}):null,i.map((P,G)=>{let p=l+G;return Q(N,{color:p===Ce.cursor?K:void 0,children:[p===Ce.cursor?"\u276F ":" ",P.checked?"\u25C9 ":"\u25CB ",P.path.padEnd(Math.min(48,qe-34)),I(N,{color:"gray",children:ur(P)})]},P.path)}),l+14<Ce.rows.length?I(N,{dimColor:!0,children:` \u2193 ${Ce.rows.length-l-14} more`}):null,I(N,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():et?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Which category? (pick one to scope to)"}),et.rows.map((c,l)=>{let i=l===et.cursor,f=`${l+1}.`.padEnd(3);return Q(N,{color:i?K:void 0,children:[i?"\u276F ":" ",`${f} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,qe-24))),I(N,{color:"gray",children:` ${c.token}`})]},c.token)}),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):rt?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),rt.rows.map((c,l)=>{let i=l===rt.cursor,f=c.indent?" ":" ",P=`${l+1}.`.padEnd(3);return Q(N,{color:i?K:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${f}${P} ${c.label}`.padEnd(Math.min(56,qe-24)),c.note?I(N,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):st?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:st.title}),(()=>{let{rows:l,cursor:i}=st,f=Math.max(0,Math.min(i-Math.floor(12/2),l.length-12)),P=l.slice(f,f+12),G=`${l.length}.`.length+1;return Q(to,{children:[f>0?I(N,{color:"gray",children:` \u2026 ${f} more above`}):null,P.map((p,y)=>{let w=f+y,m=w===i;return Q(N,{color:m?K:void 0,bold:(p.kind==="all"||p.kind==="category")&&!m,children:[m?"\u276F ":" ",`${w+1}.`.padEnd(G)," ".repeat(p.depth),p.label,p.note?I(N,{color:"gray",children:p.note}):null]},`${p.action}:${p.kind}:${p.ids.join(",")}`)}),f+12<l.length?I(N,{color:"gray",children:` \u2026 ${l.length-f-12} more below`}):null]})})(),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):Te?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:`Preview article${Te.query?` \u2014 filter: ${Te.query}`:" (type to filter)"}`}),bo.length===0?I(N,{color:"gray",children:"no articles match"}):bo.map((c,l)=>Q(N,{color:l===Te.cursor?K:void 0,children:[l===Te.cursor?"\u276F ":" ",c]},c)),I(N,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):De?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:`Resume session${De.query?` \u2014 filter: ${De.query}`:" (type to filter)"}`}),$o.length===0?I(N,{color:"gray",children:"no sessions match"}):$o.map((c,l)=>Q(N,{color:l===De.cursor?K:void 0,children:[l===De.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),I(N,{color:l===De.cursor?K:"gray",children:c.firstPrompt.slice(0,Math.max(10,qe-40))})]},c.uuid)),I(N,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):za?Q(ae,{flexDirection:"column",children:[At>0?I(N,{dimColor:!0,children:` \u22EF ${At} more above`}):null,as.map((c,l)=>{let i=At+l;return Q(N,{color:i===ko?K:void 0,children:[i===ko?"\u276F ":" ",c.usage.padEnd(22)," ",I(N,{color:i===ko?K:"gray",children:c.name==="model"&&ts?`${c.desc} (currently ${ts})`:c.desc})]},c.name)}),At+as.length<Ve.length?I(N,{dimColor:!0,children:` \u22EF ${Ve.length-At-as.length} more below`}):null,I(N,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!T&&!x&&be.length>0?Q(ae,{flexDirection:"column",paddingX:1,children:[Ua?I(N,{color:K,children:Ua}):null,be.map((c,l)=>{let i=It(c),f=i.slice(0,Math.max(20,qe-5)),P=qe-f.length-7,G=P>=12?(Ed(c)??Yl(i)).slice(0,P):"";return Q(N,{children:[I(N,{color:K,children:l+1})," ",f,G?I(N,{dimColor:!0,children:` \u2014 ${G}`}):null]},i)}),I(N,{dimColor:!0,children:`press 1-${be.length} to fill \xB7 esc cancel`})]}):I(ae,{paddingX:1,children:Q(N,{color:"gray",children:[Ya.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ts??"model n/a"}${t.kind==="api"?Ha>0?` \xB7 ${Se(Ha)}`:"":Ba>0?` \xB7 ${ht(Ba)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}Y();import{jsx as Rk}from"react/jsx-runtime";async function cp(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Ck(t);r.kind==="none"&&(console.error(""),console.error(S("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${F("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${F("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=vk(Rk(lp,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
429
- `),process.exit(0)}Y();import{writeCrashLog as up,isBenignTransportError as Sk}from"document360-engine";var dp=!1;function Ea(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function pp(e){if(dp)return;dp=!0;let t=(n,o)=>{if(Sk(o)){up({kind:n,level:"transport",message:Ea(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=up({kind:n,level:"fatal",message:Ea(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
430
- `+S(`\u2717 d360-writer crashed: ${Ea(o)}`)+`
420
+ `)}`}),q(C=>C+1);return}if(p==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let m=await zw({cwd:e,profileName:s}),D=m.onlyInLegacy.length===0&&m.onlyInManifest.length===0&&m.mappedMissingFromManifest.length===0,A=[`Legacy listing: ${m.legacyCount} \xB7 Manifest: ${m.manifestCount} \xB7 in both: ${m.inBoth}`];D?A.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(m.mappedMissingFromManifest.length&&A.push(`\u2717 ${m.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${m.mappedMissingFromManifest.slice(0,5).join(", ")}`),m.onlyInLegacy.length&&A.push(`\u26A0 ${m.onlyInLegacy.length} only in the legacy listing: ${m.onlyInLegacy.slice(0,5).join(", ")}`),m.onlyInManifest.length&&A.push(`\u26A0 ${m.onlyInManifest.length} only in the manifest: ${m.onlyInManifest.slice(0,5).join(", ")}`),A.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:D?"ok":"warn",text:A.join(`
421
+ `)});return}if(p){d({kind:"note",tone:"error",text:`Unknown option: ${p} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=f[0];if(y){let m=await Qd({cwd:e,profileName:s,relPath:y.replace(/\\/g,"/")});pe.current=[{plan:m,mode:m.overwritesLocalChanges?"conflict":"pull"}],Bt.current=[],Jt();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let w=await ti({cwd:e,profileName:s});for(let m of ni(w))d({kind:"note",tone:m.tone,text:m.text});q(m=>m+1)}catch(y){d({kind:"note",tone:"error",text:`Pull failed: ${y.message}`})}return}case"scope":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=Qw(e);if(p.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Yt({cursor:0,rows:p.map(y=>({...y,checked:y.recommended}))});return}case"audit":{if(f[0]==="--auto"){let y=ie(e);if(!y){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=f[1]!=="off";Yd({...y,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let p=await qn();p.kind==="forward-to-agent"&&p.prompt&&await oe(p.prompt,{display:p.display,quietUser:!0});return}case"check":{let p=f.find(m=>!m.startsWith("--")),y=p?` ${p}`:"",w=Xd({cwd:e,scope:p});if(f.includes("--fix")){if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}d({kind:"note",tone:"info",text:`Fixing ${w.length} doc issue${w.length===1?"":"s"}\u2026`});let m=tp(e,p);await oe(na(w),{display:`/check${y} --fix`,quietUser:!0});try{Ta(e,m,{reviewedCap:Da})}catch{}let D=Xd({cwd:e,scope:p});d({kind:"note",tone:D.length===0?"ok":"warn",text:D.length===0?"\u2713 Doc-checker: all issues resolved.":Rr(D).join(`
422
+ `)}),ve(D.length===0?`Deterministic issues fixed. Next: /review${y} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${y} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${y} --fix`,reason:""});return}d({kind:"note",tone:w.length===0?"ok":"warn",text:Rr(w).join(`
423
+ `)}),w.length>0&&ve(`Found ${w.length} doc issue${w.length===1?"":"s"} above. /check${y} --fix has the agent fix them in place (or /review${y} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${y} --fix`,reason:""});return}case"structure":{let p=Xn(e,s);if(p.length===0){d({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}d({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...p].join(`
424
+ `)});return}case"reorder":{let p=ra(e,f);if(!p){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await oe(p.prompt,{display:p.display,quietUser:!0}),ve("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let p=oa(e,f);if(!p){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=f.includes("--fix"),w=f.find(D=>!D.startsWith("--")),m=y?tp(e,w):[];if(await oe(p.prompt,{display:p.display,quietUser:!0}),y)try{Ta(e,m,{reviewedCap:Da})}catch{}if(y)ve("\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let D=f.filter(A=>A!=="--fix").join(" ");ve(`The review listed issues above. /review${D?` ${D}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${D?` ${D}`:""} --fix`,reason:""})}return}case"capture-setup":{await G();return}case"devhints":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:rn(on(e)).join(`
425
+ `)}),Xt(Nt()),Sn.current=Le(e).status==="current",Qt.current=nt(e);return}case"discover":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await oe(Xs(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(qi(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await oe(Vi(),{display:"/inbox",quietUser:!0});return}case"feedback":{let p=ep(e),y="";try{y=mn(p)?qr(p,"utf8"):""}catch{y=""}if(!/^## /m.test(y)){d({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let w=await wa(y.trim());d({kind:"note",tone:w?"ok":"warn",text:w?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${p} and copy it manually.`}),w&&is(null);return}case"document":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:p,what:y}=Ci(f);if(!y&&vi(e)===0){d({kind:"note",tone:"info",text:Si});return}let w=`/document${y?` ${y}`:""}${p?" --publish":""}`;await oe(Ri(y,p),{display:w,quietUser:!0});return}case"catch-up":{if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!go(c.trim()))return;let{publish:p}=Yi(f);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let y=await Ki({cwd:e,profileName:s});for(let m of Xi(y))d({kind:"note",tone:m.startsWith("\u2713")?"ok":m.startsWith("\u2139")?"info":"warn",text:m});let w=Kn(zn(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await oe(zi({publish:p}),{display:`/catch-up${p?" --publish":""}`,quietUser:!0});return}case"update":{rs.current=!0,d({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),io(!0);let p=await vr().finally(()=>io(!1));p.ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated ${p.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),Z("/exit"),La("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${xr}`});return}case"screenshot":{let p=Wn(f);if(p.mode==="capture"){await P(p.rest);return}if(p.mode==="checklist"){await G();return}if(p.mode==="list"){if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=ie(e)?.docsDir??ja,D=Hs(e,p.scope),A=Ye(e,D);if(p.picker){if(A.length===0){d({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let W=Rc(A);if(W.length===0){d({kind:"note",tone:"info",text:rr(A,{docsDir:m}).join(`
426
+ `)}),ve(`\u2713 All ${A.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}Rt({cursor:0,rows:W,title:"Screenshots \u2014 pick what to author or capture:"});return}d({kind:"note",tone:"info",text:rr(A,{scope:D,detail:p.detail,docsDir:m}).join(`
427
+ `)});let R=A.filter(W=>W.state==="placeholder").length,C=A.filter(W=>W.state==="spec").length;if(R>0){let W=D?`/screenshot author ${D}`:"/screenshot author --all";ve(`${R} of ${A.length} still need${R===1?"s":""} a spec \u2014 /screenshot author <id> authors one, ${W} authors them all in parallel.`,{kind:"cmd",cmd:W,reason:""})}else if(C>0){let W=D?`/screenshot capture ${D}`:"/screenshot capture";ve(`${C} spec${C===1?"":"s"} ready to capture \u2014 ${W} takes ${C===1?"it":"them"} (a real browser drives your app).`,{kind:"cmd",cmd:W,reason:""})}return}if(p.mode==="single"){await Za(p.id);return}if(!ie(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=p.mode==="scope"?p.scope:void 0,w=tk(e,{scope:y}).map(m=>m.id);if(w.length===0){d({kind:"note",tone:"info",text:y?`No screenshot placeholders under ${y}.`:"No screenshot placeholders found in the docs."});return}await Ja(w,{setup:p.setup,runLine:p.mode==="scope"?[`/screenshot author ${p.scope}`,`/screenshot ${p.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await P(f);return}case"reset":{let p=Zi(e);if(p.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}co.current={repoName:to(e),targets:p,hadDevhints:mn(Zd(e))},d({kind:"note",tone:"warn",text:ta(e,p).join(`
428
+ `)}),xe(to(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Jt,fs,d,Ae,oe,jt,us,el]),To=X(c=>{let l=(c??x).trim();if($(""),ao(null),Mt(0),l.startsWith("/")&&(oo.current=!1,kn.current=!1,He(),bn(null),Be(f=>Id(f,l))),!l||(Oa(!1),nl(l))||tl(l))return;Jr.current.push(l);let i=Md(l,Ma.current);if(l.startsWith("/"))d({kind:"user",text:l}),We(!0),Tn(i).finally(()=>We(!1));else if(dk(i)){d({kind:"user",text:l});let f=pk(i);if(!f)oe(i,{display:l,quietUser:!0});else{try{hk(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}oe(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${f}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${f}" and the article path(s) you wrote.`,{display:l,quietUser:!0})}}else{let f=rd(e,i);oe(f??i,{display:l})}},[x,nl,tl,Tn,oe]),ol=X(c=>{if(c.length>1){if(c.includes("\x1B"))return;let l=_d(c);if(Od(l)){let i=Ld(++bp.current,l);Ma.current.set(i,l),j(i)}else j(l);return}j(c)},[j]),Zt=Math.max(10,qe-6),rl=va(()=>Br(k.text,Zt),[k.text,Zt]),ms=X(c=>b(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+c))})),[]),Do=X(c=>b(l=>({...l,pos:Fd(Br(l.text,Zt),l.pos,c)})),[Zt]),Dn=X(c=>b(l=>({...l,pos:Wd(Br(l.text,Zt),l.pos,c)})),[Zt]),Cp=["\x1B[H","\x1B[1~","\x1BOH"],Rp=["\x1B[F","\x1B[4~","\x1BOF"],sl=X((c,l)=>l.leftArrow?(ms(-1),!0):l.rightArrow?(ms(1),!0):c&&Cp.includes(c)?(Dn("start"),!0):c&&Rp.includes(c)?(Dn("end"),!0):l.ctrl&&c==="a"?(Dn("start"),!0):l.ctrl&&c==="e"?(Dn("end"),!0):!1,[ms,Dn]);return Sw((c,l)=>{if(l.ctrl&&c==="c"){Ie.current?.close(),r();return}if(!U){if(T){if(l.escape){if(we.current){if(!we.current.signal.aborted){let i=(uo?.verb??"work").toLowerCase(),f=uo?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${f}s)\u2026`}),we.current.abort()}return}$n.current||($n.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Ie.current?.interrupt());return}if(l.return){let i=x.trim();if(!i)return;Tt.current.push(i),es([...Tt.current]),$("");return}if(sl(c,l))return;if(l.upArrow){Do(-1);return}if(l.downArrow){Do(1);return}if(l.backspace||l.delete){v();return}c&&!l.ctrl&&!l.meta&&ol(c);return}if(xt){if(l.upArrow){vt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){vt(i=>i&&{...i,cursor:Math.min(ze.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ze.length){vt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=ze[xt.cursor];vt(null);let{lines:f,changed:P,effective:G}=Gn(e,i.value??"default");for(let p of f)d({kind:"note",tone:p.startsWith("\u26A0")?"warn":p.startsWith("\u2713")?"ok":"info",text:p});P&&(Ga(p=>p+1),Ie.current?.setModel(G));return}if(c==="s"){let i=ze[xt.cursor];vt(null),Ie.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(l.escape){vt(null);return}return}if(Je){if(l.upArrow){Ht(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ht(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Je.rows.length){Ht(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return||c==="s"){let i=Je.rows[Je.cursor];Ht(null),ps(i.name,l.return===!0);return}if(l.escape){Ht(null);return}return}if(fo){if(l.escape){Cn(null);return}if(l.leftArrow||l.tab&&l.shift){Cn(i=>i&&{tab:(i.tab-1+Oe.length)%Oe.length});return}if(l.rightArrow||l.tab){Cn(i=>i&&{tab:(i.tab+1)%Oe.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Oe.length){Cn({tab:Number(c)-1});return}return}if(Ze){if(l.upArrow){qt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){qt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ze.rows.length){qt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ze.rows[Ze.cursor].name;if(qt(null),!Cs(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let P=!1;try{let G=Ot(i);P=!!G&&!(kt(G)&&!G.refreshToken)}catch{P=!1}d({kind:"note",tone:"info",text:P?`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.`}),Z("/login"),q(G=>G+1);return}if(l.escape){qt(null);return}return}if($e){if(l.upArrow){Vt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Vt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=$e.rows.length){Vt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=$e.rows[$e.cursor],{profile:f,projectId:P}=$e;Vt(null),Ro(f,P,i);return}if(l.escape){Vt(null);return}return}if(Pe){if(l.upArrow){Ct(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ct(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Pe.rows.length){Ct(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Pe.rows[Pe.cursor],{profile:f}=Pe;Ct(null),Po(f,i);return}if(l.escape){Ct(null);return}return}if(Ce){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===" "){Yt(i=>i&&{...i,rows:i.rows.map((f,P)=>P===i.cursor?{...f,checked:!f.checked}:f)});return}if(l.return){let i=Ce.rows.filter(f=>f.checked).map(f=>f.path);if(Yt(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Qs(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of i)d({kind:"note",tone:"info",text:` ${f}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){Yt(null);return}return}if(et){if(l.upArrow){St(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){St(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=et.rows.length){St(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=et.rows[et.cursor],f=et.run;St(null),f(i.token);return}if(l.escape){St(null);return}return}if(rt){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)<=rt.rows.length){Gt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=rt.rows[rt.cursor];Gt(null),i.conflict?fs(i.paths[0]):i.kind==="article"?us(i.paths[0]):jt(i.paths);return}if(l.escape){Gt(null);return}return}if(st){if(l.upArrow){Rt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Rt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=st.rows.length){Rt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=st.rows[st.cursor];Rt(null),i.action==="capture"?Co(i.ids,{runLine:i.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):i.kind==="shot"?Za(i.ids[0]):Ja(i.ids,{setup:!0,runLine:i.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(l.escape){Rt(null);return}return}if(Te){if(l.escape){Pt(null);return}if(l.upArrow){Pt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Pt(i=>i&&{...i,cursor:Math.min(Math.max(0,$o.length-1),i.cursor+1)});return}if(l.return){let i=$o[Te.cursor];if(i){Pt(null);try{d({kind:"preview",name:to(i),text:lp(qr(Ca(e,i),"utf8"))})}catch(f){d({kind:"note",tone:"error",text:`Could not read ${i}: ${f.message}`})}}return}if(l.backspace||l.delete){Pt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){Pt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(De){if(l.escape){Dt(null);return}if(l.upArrow){Dt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Dt(i=>i&&{...i,cursor:Math.min(Math.max(0,xo.length-1),i.cursor+1)});return}if(l.return){let i=xo[De.cursor];if(i){Dt(null),Ae(i.uuid),Qe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},$t(i.name),Ra(i.uuid),Ft.current=[];let f=ba(e,i.uuid);for(let P of f)d(P);d({kind:"note",tone:"ok",text:f.length?`Resumed "${i.name}" \u2014 restored ${f.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(l.backspace||l.delete){Dt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){Dt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(l.tab&&!x&&fe){$(fe),He();return}if(!x&&be.length>0&&!Kr&&c&&/^[1-9]$/.test(c)){let i=be[Number(c)-1];if(i){$(_t(i));return}}if(!x&&(yo||Rn)&&c==="c"&&!l.ctrl&&!l.meta&&!l.return&&!l.tab){let i=yo!=null;wa(yo??Rn).then(P=>{d({kind:"note",tone:P?"ok":"warn",text:P?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."}),P&&i&&is(null),P&&!i&&za(!0)});return}if(!sl(c,l)){if(Xa){if(l.upArrow){Mt(i=>Math.max(0,i-1));return}if(l.downArrow){Mt(i=>Math.min(Ve.length-1,i+1));return}if(l.tab){$("/"+(Ve[Qr]?.name??"")+" "),Mt(0);return}if(l.return){let i=Ve[Qr];if(i){let f=x.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Ql(i.usage)&&!f){$("/"+i.name+" "),Mt(0);return}To("/"+i.name+(f?" "+f:""));return}}}else{if(l.upArrow){if(x!==""&&Ut===null){Do(-1);return}let i=Jr.current;if(!i.length)return;let f=Ut===null?i.length-1:Math.max(0,Ut-1);ao(f),$(i[f]??"");return}if(l.downArrow){if(x!==""&&Ut===null){Do(1);return}let i=Jr.current;if(Ut===null)return;let f=Ut+1;f>=i.length?(ao(null),$("")):(ao(f),$(i[f]??""));return}}if(l.return){To();return}if(l.backspace||l.delete){v();return}if(l.escape){$(""),Mt(0),He(),Be([]),bn(null),oo.current=!0;return}c&&!l.ctrl&&!l.meta&&ol(c)}}}),Ne(()=>{if(T||U)return;let c=Tt.current.shift();c!==void 0&&(es([...Tt.current]),To(c))},[T,U,To]),Q(ae,{flexDirection:"column",width:qe,children:[cs!==null&&Q(ae,{marginTop:1,flexDirection:"column",children:[cs.truncated&&I(N,{dimColor:!0,children:"\u2026"}),I(N,{children:cs.text})]}),T&&(uo?I(vk,{p:uo}):I(bk,{startTime:bt.current,chars:kp})),!T&&Ha?I($k,{text:Ha}):null,I(ae,{borderStyle:"round",borderColor:Ka.prod?"yellow":K,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:x?rl.map((c,l)=>{let i=k.text.slice(c.start,c.end),f=l===Hr(rl,k.pos),P=Math.min(k.pos,c.end)-c.start;return Q(N,{children:[I(N,{color:K,children:l===0?"> ":" "}),f?Q(no,{children:[i.slice(0,P),I(gn,{ch:i[P]??" "}),i.slice(P+1)]}):i||" "]},`${l}-${c.start}`)}):Q(N,{children:[I(N,{color:K,children:"> "}),ts?I(gn,{ch:" "}):fe&&!T&&me?Q(no,{children:[I(gn,{ch:me[0],dim:!0}),I(N,{color:"gray",children:me.slice(1)})]}):fe&&!T?Q(no,{children:[I(gn,{ch:fe[0],dim:!0}),I(N,{color:"gray",children:fe.slice(1)}),I(N,{dimColor:!0,children:" (tab)"})]}):(as.isSetup||!yp)&&!T?Q(no,{children:[I(gn,{ch:as.text[0],dim:!0}),I(N,{color:"gray",children:as.text.slice(1)})]}):I(gn,{ch:" "})]})}),Ba.length>0&&I(ae,{flexDirection:"column",paddingX:1,children:Ba.map((c,l)=>I(N,{color:"gray",children:`\u29D7 queued: ${c}`},`${l}-${c.slice(0,24)}`))}),fo?I(Td,{tab:fo.tab,width:qe,version:o,engineVersion:cp}):xt?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Select model"}),I(N,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),ze.map((c,l)=>Q(N,{color:l===xt.cursor?K:void 0,children:[l===xt.cursor?"\u276F ":" ",`${l+1}. ${c.label}${l===xt.current?" \u2714":""}`.padEnd(16),I(N,{color:"gray",children:c.desc})]},c.label)),I(N,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Je?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Switch connection profile"}),Je.rows.map((c,l)=>Q(N,{color:l===Je.cursor?K:void 0,children:[l===Je.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Je.current?" \u2714":""}`.padEnd(20),I(N,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?I(N,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),I(N,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ze?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Pick your Document360 environment"}),Ze.rows.map((c,l)=>Q(N,{color:l===Ze.cursor?K:void 0,children:[l===Ze.cursor?"\u276F ":" ",`${l+1}. ${c.name}`.padEnd(16),I(N,{color:"gray",children:c.apiUrl})]},c.name)),I(N,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):$e?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Switch workspace"}),I(N,{dimColor:!0,children:`environment ${$e.environment} \xB7 project ${$e.projectName??`${$e.projectId.slice(0,8)}\u2026`}`}),$e.rows.map((c,l)=>Q(N,{color:l===$e.cursor?K:void 0,children:[l===$e.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===$e.current?" \u2714":""}`.padEnd(30),I(N,{color:"gray",children:c.type??""})]},c.id)),I(N,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):Pe?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Choose project"}),I(N,{dimColor:!0,children:`environment ${Pe.environment}`}),Pe.rows.map((c,l)=>Q(N,{color:l===Pe.cursor?K:void 0,children:[l===Pe.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Pe.current?" \u2714":""}`.padEnd(30),I(N,{color:"gray",children:c.sub??""})]},c.id)),I(N,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Ce?(()=>{let l=Math.min(Math.max(0,Ce.cursor-Math.floor(7)),Math.max(0,Ce.rows.length-14)),i=Ce.rows.slice(l,l+14),f=Ce.rows.filter(P=>P.checked).length;return Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:`Which folders back the user docs? (${f} selected of ${Ce.rows.length})`}),l>0?I(N,{dimColor:!0,children:` \u2191 ${l} more`}):null,i.map((P,G)=>{let p=l+G;return Q(N,{color:p===Ce.cursor?K:void 0,children:[p===Ce.cursor?"\u276F ":" ",P.checked?"\u25C9 ":"\u25CB ",P.path.padEnd(Math.min(48,qe-34)),I(N,{color:"gray",children:dr(P)})]},P.path)}),l+14<Ce.rows.length?I(N,{dimColor:!0,children:` \u2193 ${Ce.rows.length-l-14} more`}):null,I(N,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():et?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Which category? (pick one to scope to)"}),et.rows.map((c,l)=>{let i=l===et.cursor,f=`${l+1}.`.padEnd(3);return Q(N,{color:i?K:void 0,children:[i?"\u276F ":" ",`${f} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,qe-24))),I(N,{color:"gray",children:` ${c.token}`})]},c.token)}),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):rt?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),rt.rows.map((c,l)=>{let i=l===rt.cursor,f=c.indent?" ":" ",P=`${l+1}.`.padEnd(3);return Q(N,{color:i?K:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${f}${P} ${c.label}`.padEnd(Math.min(56,qe-24)),c.note?I(N,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):st?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:st.title}),(()=>{let{rows:l,cursor:i}=st,f=Math.max(0,Math.min(i-Math.floor(12/2),l.length-12)),P=l.slice(f,f+12),G=`${l.length}.`.length+1;return Q(no,{children:[f>0?I(N,{color:"gray",children:` \u2026 ${f} more above`}):null,P.map((p,y)=>{let w=f+y,m=w===i;return Q(N,{color:m?K:void 0,bold:(p.kind==="all"||p.kind==="category")&&!m,children:[m?"\u276F ":" ",`${w+1}.`.padEnd(G)," ".repeat(p.depth),p.label,p.note?I(N,{color:"gray",children:p.note}):null]},`${p.action}:${p.kind}:${p.ids.join(",")}`)}),f+12<l.length?I(N,{color:"gray",children:` \u2026 ${l.length-f-12} more below`}):null]})})(),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):Te?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:`Preview article${Te.query?` \u2014 filter: ${Te.query}`:" (type to filter)"}`}),$o.length===0?I(N,{color:"gray",children:"no articles match"}):$o.map((c,l)=>Q(N,{color:l===Te.cursor?K:void 0,children:[l===Te.cursor?"\u276F ":" ",c]},c)),I(N,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):De?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:`Resume session${De.query?` \u2014 filter: ${De.query}`:" (type to filter)"}`}),xo.length===0?I(N,{color:"gray",children:"no sessions match"}):xo.map((c,l)=>Q(N,{color:l===De.cursor?K:void 0,children:[l===De.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),I(N,{color:l===De.cursor?K:"gray",children:c.firstPrompt.slice(0,Math.max(10,qe-40))})]},c.uuid)),I(N,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Xa?Q(ae,{flexDirection:"column",children:[Et>0?I(N,{dimColor:!0,children:` \u22EF ${Et} more above`}):null,ls.map((c,l)=>{let i=Et+l;return Q(N,{color:i===bo?K:void 0,children:[i===bo?"\u276F ":" ",c.usage.padEnd(22)," ",I(N,{color:i===bo?K:"gray",children:c.name==="model"&&ns?`${c.desc} (currently ${ns})`:c.desc})]},c.name)}),Et+ls.length<Ve.length?I(N,{dimColor:!0,children:` \u22EF ${Ve.length-Et-ls.length} more below`}):null,I(N,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!T&&!x&&be.length>0?Q(ae,{flexDirection:"column",paddingX:1,children:[Wa?I(N,{color:K,children:Wa}):null,be.map((c,l)=>{let i=_t(c),f=i.slice(0,Math.max(20,qe-5)),P=qe-f.length-7,G=P>=12?(Nd(c)??Kl(i)).slice(0,P):"";return Q(N,{children:[I(N,{color:K,children:l+1})," ",f,G?I(N,{dimColor:!0,children:` \u2014 ${G}`}):null]},i)}),I(N,{dimColor:!0,children:`press 1-${be.length} to fill \xB7 esc cancel`})]}):I(ae,{paddingX:1,children:Q(N,{color:"gray",children:[Ka.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ns??"model n/a"}${t.kind==="api"?Va>0?` \xB7 ${Se(Va)}`:"":qa>0?` \xB7 ${ht(qa)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}Y();import{jsx as Pk}from"react/jsx-runtime";async function dp(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Sk(t);r.kind==="none"&&(console.error(""),console.error(S("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${F("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${F("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Rk(Pk(up,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
429
+ `),process.exit(0)}Y();import{writeCrashLog as pp,isBenignTransportError as Tk}from"document360-engine";var hp=!1;function Na(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function fp(e){if(hp)return;hp=!0;let t=(n,o)=>{if(Tk(o)){pp({kind:n,level:"transport",message:Na(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=pp({kind:n,level:"fatal",message:Na(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
430
+ `+S(`\u2717 d360-writer crashed: ${Na(o)}`)+`
431
431
  `),r&&process.stderr.write(g(` Crash details: ${r}`)+`
432
432
  `+g(" Run: d360-writer logs")+`
433
- `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Ak=Tk(import.meta.url),Gr=Ak("../package.json");pp("d360-writer");var Fe=new Pk;function ja(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Fe.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=>{ja(e),await Lo({profile:e.profile,manual:e.manual})});Fe.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{ja(e),await ml({profile:e.profile})});Fe.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{ja(e),await fl({profile:e.profile})});var Na=Fe.command("profile").description("Manage connection profiles for the current repo");Na.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Mo(process.cwd()));Na.command("use <name>").description("Set the default profile for this repo").action(e=>Uo(process.cwd(),e));Na.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Fo(process.cwd(),e));var hp=Fe.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");hp.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Zt(process.cwd(),e.profile));hp.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await al(process.cwd(),e,t.profile)});var fp=Fe.command("project").description("Choose the Document360 project for this repo (active profile's identity)");fp.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Io(process.cwd(),e.profile));fp.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await cl(process.cwd(),e,t.profile)});Fe.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Go(),ql));await e()});Fe.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>kl());Fe.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(()=>(yr(),bu)),n=await t(process.cwd(),Gr.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Fe.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Gr.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(Dk.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 bl(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 wd(e.cwd,e.auth,e.profile,Gr.version):await cp(e.cwd,e.auth,e.profile,Gr.version)});Fe.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
433
+ `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var jk=Ak(import.meta.url),Yr=jk("../package.json");fp("d360-writer");var Fe=new Dk;function Ia(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Fe.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=>{Ia(e),await Mo({profile:e.profile,manual:e.manual})});Fe.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ia(e),await yl({profile:e.profile})});Fe.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ia(e),await gl({profile:e.profile})});var _a=Fe.command("profile").description("Manage connection profiles for the current repo");_a.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Uo(process.cwd()));_a.command("use <name>").description("Set the default profile for this repo").action(e=>Fo(process.cwd(),e));_a.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Wo(process.cwd(),e));var mp=Fe.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");mp.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>en(process.cwd(),e.profile));mp.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await cl(process.cwd(),e,t.profile)});var gp=Fe.command("project").description("Choose the Document360 project for this repo (active profile's identity)");gp.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>_o(process.cwd(),e.profile));gp.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await dl(process.cwd(),e,t.profile)});Fe.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Yo(),Gl));await e()});Fe.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>$l());Fe.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(()=>(wr(),xu)),n=await t(process.cwd(),Yr.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Fe.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Yr.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(Ek.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 xl(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 bd(e.cwd,e.auth,e.profile,Yr.version):await dp(e.cwd,e.auth,e.profile,Yr.version)});Fe.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});