document360-writer 0.5.185 → 0.5.187

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 +127 -127
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- var mh=Object.defineProperty;var qn=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Pc=(e,t)=>{for(var n in t)mh(e,n,{get:t[n],enumerable:!0})};import mt from"picocolors";var Z,gh,yh,wh,Tc,Vn,y,A,B,M,W,fe,Te,K=qn(()=>{"use strict";Z="#7f56d9",[gh,yh,wh]=[127,86,217],Tc=e=>mt.isColorSupported?`\x1B[38;2;${gh};${yh};${wh}m${e}\x1B[39m`:e,Vn=e=>mt.bold(Tc(e)),y=e=>mt.dim(e),A=e=>mt.red(e),B=e=>mt.yellow(e),M=e=>mt.green(e),W=Tc,fe=e=>mt.gray(e),Te=e=>mt.bold(e)});import{existsSync as fn,writeFileSync as yt,readFileSync as of,readdirSync as rf}from"node:fs";import{join as Yc}from"node:path";import{devHintsGuidePath as rr,hintsDir as zc,hooksDir as Kc,architectureDir as el,messagesDir as Us,creatorNotesPath as Xc,devhintsStatePath as tl,directivesPath as Qc,DIRECTIVES_HEADER as sf,roadmapPath as Jc,ROADMAP_HEADER as af,ensureDir as zn,writeMessage as cf,listOpenForDev as lf}from"document360-engine";function nl(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var yh=Object.defineProperty;var qn=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Ec=(e,t)=>{for(var n in t)yh(e,n,{get:t[n],enumerable:!0})};import mt from"picocolors";var Z,wh,kh,bh,Dc,Vn,g,D,H,M,W,me,Ee,K=qn(()=>{"use strict";Z="#7f56d9",[wh,kh,bh]=[127,86,217],Dc=e=>mt.isColorSupported?`\x1B[38;2;${wh};${kh};${bh}m${e}\x1B[39m`:e,Vn=e=>mt.bold(Dc(e)),g=e=>mt.dim(e),D=e=>mt.red(e),H=e=>mt.yellow(e),M=e=>mt.green(e),W=Dc,me=e=>mt.gray(e),Ee=e=>mt.bold(e)});import{existsSync as fn,writeFileSync as yt,readFileSync as sf,readdirSync as af}from"node:fs";import{join as Kc}from"node:path";import{devHintsGuidePath as rr,hintsDir as Xc,hooksDir as Qc,architectureDir as nl,messagesDir as Us,creatorNotesPath as Jc,devhintsStatePath as ol,directivesPath as Zc,DIRECTIVES_HEADER as cf,roadmapPath as el,ROADMAP_HEADER as lf,ensureDir as zn,writeMessage as df,listOpenForDev as uf}from"document360-engine";function rl(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
3
3
 
4
- <!-- devhints script v${me} \xB7 maintained by document360-writer (/devhints). -->
4
+ <!-- devhints script v${ge} \xB7 maintained by document360-writer (/devhints). -->
5
5
 
6
6
  This repo's user documentation is written by **document360-writer** ("the docs agent"), a separate agent.
7
7
  It can read your code, but code alone can't tell it the *intent* \u2014 WHY a feature exists, which of a
@@ -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 uf(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
221
+ `}function hf(){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 gn(e){zn(zc(e)),zn(el(e)),zn(Us(e));for(let n of[zc(e),Us(e)]){let o=Yc(n,".gitkeep");fn(o)||yt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
236
- `)}fn(Xc(e))||yt(Xc(e),uf()),fn(Qc(e))||yt(Qc(e),sf),fn(Jc(e))||yt(Jc(e),af),yt(rr(e),nl()),zn(Kc(e)),yt(Yc(Kc(e),"open-questions.mjs"),df);let t=qe(e);return rl(e,new Date().toISOString()),t}async function ol(e,t){for(let n of yn(gn(t.cwd)))console.log(n);return{kind:"continue"}}function Bt(){return[`This is document360-writer's dev hand-off setup (v${me}).`,'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": ${me},`,' "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 Fs(e){try{let t=of(tl(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function rl(e,t){let o={...Fs(e)??{},emittedVersion:me,emittedAt:t};yt(tl(e),`${JSON.stringify(o,null,2)}
238
- `)}function it(e){try{return rf(el(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function qe(e){let n=Fs(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<me?"stale":"current",completedVersion:n}}function sr(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:me};try{if(!fn(rr(e)))return n;let o=Fs(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;me>r&&(zn(Us(e)),yt(rr(e),nl()),rl(e,t),n.guideRefreshed=!0),me>s&&(lf(e).some(c=>c.kind==="request"&&c.subject.startsWith(Zc))||(cf(e,{id:`onb${me}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Zc}${me})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${me}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",Bt()].join(`
239
- `)}),n.notifiedBuilder=!0))}catch{}return n}function ir(e){if(!fn(rr(e)))return[];let t=qe(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${me}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,mn,Bt(),mn,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Ws(){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 ar(){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):",mn,Ws(),mn]}function yn(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${me}.`," 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):",mn,Bt(),mn,"","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 mn,me,df,Zc,wt=qn(()=>{"use strict";mn="-".repeat(64),me=10,df=`#!/usr/bin/env node
235
+ `}function gn(e){zn(Xc(e)),zn(nl(e)),zn(Us(e));for(let n of[Xc(e),Us(e)]){let o=Kc(n,".gitkeep");fn(o)||yt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
236
+ `)}fn(Jc(e))||yt(Jc(e),hf()),fn(Zc(e))||yt(Zc(e),cf),fn(el(e))||yt(el(e),lf),yt(rr(e),rl()),zn(Qc(e)),yt(Kc(Qc(e),"open-questions.mjs"),pf);let t=qe(e);return il(e,new Date().toISOString()),t}async function sl(e,t){for(let n of yn(gn(t.cwd)))console.log(n);return{kind:"continue"}}function Bt(){return[`This is document360-writer's dev hand-off setup (v${ge}).`,'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": ${ge},`,' "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 Fs(e){try{let t=sf(ol(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function il(e,t){let o={...Fs(e)??{},emittedVersion:ge,emittedAt:t};yt(ol(e),`${JSON.stringify(o,null,2)}
238
+ `)}function it(e){try{return af(nl(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function qe(e){let n=Fs(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ge?"stale":"current",completedVersion:n}}function sr(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ge};try{if(!fn(rr(e)))return n;let o=Fs(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;ge>r&&(zn(Us(e)),yt(rr(e),rl()),il(e,t),n.guideRefreshed=!0),ge>s&&(uf(e).some(c=>c.kind==="request"&&c.subject.startsWith(tl))||(df(e,{id:`onb${ge}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${tl}${ge})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${ge}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",Bt()].join(`
239
+ `)}),n.notifiedBuilder=!0))}catch{}return n}function ir(e){if(!fn(rr(e)))return[];let t=qe(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${ge}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,mn,Bt(),mn,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Ws(){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 ar(){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):",mn,Ws(),mn]}function yn(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${ge}.`," 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):",mn,Bt(),mn,"","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 mn,ge,pf,tl,wt=qn(()=>{"use strict";mn="-".repeat(64),ge=10,pf=`#!/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,69 +275,69 @@ try {
275
275
  } catch {
276
276
  /* a session-start nudge must never break the session */
277
277
  }
278
- `;Zc="Re-run dev\u2194docs onboarding (protocol v"});var fl={};Pc(fl,{initCommand:()=>Hs,scaffoldInit:()=>Bs});import{input as Kn,confirm as pf}from"@inquirer/prompts";import{basename as sl,join as cr}from"node:path";import{existsSync as wn,readFileSync as hf,readdirSync as ff,writeFileSync as mf}from"node:fs";import{writeProjectConfig as il,readProjectConfig as gf,projectConfigPath as al,writerDir as yf,DEFAULT_DOCS_DIR as cl,DEFAULT_CAPTURE_DIR as ll,DEFAULT_OUTPUT_DIR as dl}from"document360-engine";function Bs(e,t="berlin"){let n=al(e);if(wn(n))return{created:!1,path:n,profileName:""};let o={projectId:pl(e)??sl(e),docsDir:cl,captureDir:ll,outputDir:dl,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:hl(e)};return il(o,e),ul(e),{created:!0,path:n,profileName:t}}function ul(e){let t=cr(yf(e),".gitignore");wn(t)||mf(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
279
- `),"utf8")}async function Hs(){let e=process.cwd(),t=al(e);if(wn(t)&&!await pf({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(y("init cancelled.")),{kind:"continue"};let n=pl(e)??sl(e),o=await Kn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Kn({message:"Capture directory (where document360-capture .spec.ts files live):",default:ll}),s=await Kn({message:"Screenshot output directory:",default:dl}),i=await Kn({message:"Default connection profile name:",default:"berlin"}),c=await Kn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),p={projectId:o,docsDir:cl,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:c},production:!1}},defaultProfile:i,authoritativeSourceFiles:hl(e)},h=gf(e);h?.terminologyGlossary&&(p.terminologyGlossary=h.terminologyGlossary),il(p,e),ul(e);let b=gn(e);console.log(""),console.log(M(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${W(`d360-writer login --profile ${i}`)} ${y("(sign in; project & workspace auto-selected)")}`),console.log("");for(let $ of yn(b))console.log($);return console.log(""),console.log(`${y("Then ask:")} ${W('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function pl(e){let t=cr(e,"package.json");if(!wn(t))return null;try{return JSON.parse(hf(t,"utf8")).name??null}catch{return null}}function hl(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])wn(cr(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=cr(e,n);wn(o)&&!wf(o)&&t.push(n)}return t}function wf(e){try{return ff(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var lr=qn(()=>{"use strict";K();wt()});import{createRequire as Ff}from"node:module";import{existsSync as Wf,readFileSync as Bf}from"node:fs";import{dirname as Ol,join as Ll}from"node:path";function $n(){let e;try{e=Hf.resolve("document360-capture/helpers")}catch{return null}let t=Ol(e);for(let n=0;n<5&&!Wf(Ll(t,"package.json"));n++)t=Ol(t);try{let n=JSON.parse(Bf(Ll(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var Hf,hr=qn(()=>{"use strict";Hf=Ff(import.meta.url)});var iu={};Pc(iu,{doctorCommand:()=>ao,renderDoctorChecks:()=>su,runDoctorChecks:()=>ru});import{existsSync as ey}from"node:fs";import{d360GetAll as ty,getAccessToken as ny,isExpired as Qi,loadProfileMap as oy,loadTokens as ry,packageSkillsDir as nu,ENGINE_VERSION as sy,projectConfigPath as iy,readProjectConfig as ay,DEFAULT_DOCS_DIR as cy,fetchManifestSummary as ly,resolveActiveProfile as dy,classifyClaudeAuth as uy,CLAUDE_CODE_SETUP_HINT as ou,resolveModelSetting as py,probeModel as hy,detectAppType as fy,playbookSkillName as my,D360AuthError as gy}from"document360-engine";async function ru(e,t){let n=[],o=$n();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${sy}${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=uy();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. ${ou}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ou});let i=py(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),s.state==="ready"){let x=await hy(e,i.model??void 0);x.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(x.latencyMs/1e3).toFixed(1)}s`}):x.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 ${x.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 c=ay(e);if(!c)return n.push({level:"fail",label:`No ${iy(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${c.projectId}`});let p=(c.docsDir??cy).replace(/\/+$/,"");n.push(c.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let h=c.authoritativeSourceFiles??[];n.push(h.length>0?{level:"ok",label:`Sources: docs grounded in ${h.length} path(s) (${h.slice(0,3).join(", ")}${h.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=c.appType??fy(e);if(b){let x=c.appType?"from config":"auto-detected",T=b==="web"||b==="cli";n.push({level:"ok",label:`Genre: ${b} (${x})${T?` \u2192 ${my(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 $;try{$=dy(e),n.push({level:"ok",label:`Profile: ${$.name} (${$.connection.name})${$.production?" \u26A0 PRODUCTION":""}`})}catch(x){return n.push({level:"fail",label:`Profile config: ${x.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let v=ry($.name);v?Qi(v)&&!v.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Qi(v)?n.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(v.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${$.name})`}),n.push($.project.workspaceId?{level:"ok",label:`Workspace: ${$.project.workspaceName??$.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let E=oy(e,$.name);E?E.projectId&&$.project.projectId&&E.projectId!==$.project.projectId?n.push({level:"fail",label:`Category map projectId (${E.projectId}) \u2260 profile projectId (${$.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(E.articles).length} articles, ${Object.keys(E.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${$.name}" (created on first /publish)`}),n.push(ey(nu())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${nu()}`,fix:"Reinstall document360-writer (broken install)"});let R=qe(e);if(R.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${me})`}):R.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${R.completedVersion}, current is v${me}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),v&&(!Qi(v)||v.refreshToken)){let x={profile:$.name,connection:$.connection};try{await ny(x);let F=await ty(x,"/v3/projects");n.push({level:"ok",label:`API reachable (${$.connection.apiUrl}) \u2014 ${F.length} project(s) visible`})}catch(F){n.push({level:"fail",label:`API call failed: ${F.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let T=E?.projectId??$.project.projectId;if(T&&$.project.workspaceId)try{let F=await ly(x,T,$.project.workspaceId);if(F){let G=(F.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${$.connection.name} (${F.languages?.length??0} language${(F.languages?.length??0)===1?"":"s"}) \xB7 hash ${G||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${$.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(F){F instanceof gy||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(F.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${$.project.projectName??T})`,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 (${F.message.slice(0,80)})`})}}return n}function su(e){let t=[""];for(let r of e){let s=r.level==="ok"?M("\u2713"):r.level==="warn"?B("\u26A0"):A("\u2717");t.push(` ${s} ${r.label}${r.detail?y(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${y("fix:")} ${W(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?M(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):A(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function ao(e,t){console.log(y("Running checks\u2026"));for(let n of su(await ru(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var _r=qn(()=>{"use strict";wt();K();hr()});import{Command as zb}from"commander";import{createRequire as Kb}from"node:module";import{AUTH_MODES as Xb}from"document360-engine";import{input as jh}from"@inquirer/prompts";import{loginPkce as Nh,refreshTokens as Ih,toStoredTokens as Ic,clearTokens as Oh,decodeJwtClaims as Nc,isExpired as Lh,loadTokens as _h,saveTokens as Oc,resolveActiveProfile as Qo,setProfileProject as Mh,readProjectConfig as Uh}from"document360-engine";K();import{select as kh}from"@inquirer/prompts";import{resolveActiveProfile as bh,setProfileProject as $h,resolveProjectId as vh,listWorkspaces as xh}from"document360-engine";async function Gn(e,t){let n=bh(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??vh(o);return{workspaces:await xh(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Ec=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function js(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 zo(e,t,n,o,r){$h(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Ac(e,t,n){let o;try{o=await Gn(e,n)}catch(s){return console.log(A(`Could not list workspaces: ${s.message}`)),1}let r=js(o.workspaces,t);return r?(zo(e,o.profile,o.projectId,r.id,r.name),console.log(M(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(A(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function hn(e,t){let n;try{n=await Gn(e,t)}catch(h){console.log(A(`Could not list workspaces: ${h.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(y("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===i?W("\u25CF"):" "} ${Ec(h)} ${y(h.id)}`);console.log(y("Run: d360-writer workspace use <name>"));return}let c=await kh({message:"Select the Document360 workspace for this repo:",choices:o.map(h=>({name:`${Ec(h)}${h.id===i?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===c);zo(e,s,r,c,p?.name),console.log(M(`\u2713 Workspace set to "${p?.name??c}" for profile "${s}".`))}K();import{select as Ch}from"@inquirer/prompts";import{resolveActiveProfile as Rh,setProfileProject as Sh,listProjects as Ph}from"document360-engine";async function gt(e,t){let n=Rh(e,t),o={profile:n.name,connection:n.connection};return{projects:await Ph(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Dc=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Ns(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function Ko(e,t,n,o){Sh(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function jc(e,t,n){let o;try{o=await gt(e,n)}catch(s){return console.log(A(`Could not list projects: ${s.message}`)),1}let r=Ns(o.projects,t);return r?(Ko(e,o.profile,r.id,r.name),console.log(M(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(A(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Xo(e,t){let n;try{n=await gt(e,t)}catch(p){console.log(A(`Could not list projects: ${p.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(y("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let p of o)console.log(` ${p.id===s?W("\u25CF"):" "} ${Dc(p)} ${y(p.id)}`);console.log(y("Run: d360-writer project use <name>"));return}let i=await Ch({message:"Select the Document360 project for this repo:",choices:o.map(p=>({name:`${Dc(p)}${p.id===s?" (current)":""}`,value:p.id}))}),c=o.find(p=>p.id===i);Ko(e,r,i,c?.name),console.log(M(`\u2713 Project set to "${c?.name??i}" for profile "${r}". Next: pick a workspace.`))}K();import Th from"picocolors";function Eh(e=process.env){return e.FORCE_HYPERLINK==="0"||!Th.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 Ah(e,t=e,n){return Eh(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Dh=/https?:\/\/[^\s\x1b]+/g;function Yn(e,t){return e.replace(Dh,n=>Ah(n,n,t))}function Lc(e){return{...Nc(e.idToken)??{},...Nc(e.accessToken)??{}}}function Jo(e){let t=Lc(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 Zo(e){let t=Qo(process.cwd(),e.profile),n=t.connection;console.log(y(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Nh(n,{manual:e.manual,promptForRedirect:s=>jh({message:s})},s=>console.log(Yn(s))),r=Ic(t.name,o);if(Oc(r),await Is(r,t.name,s=>console.log(y(s))),console.log(""),console.log(M(`\u2713 Logged in to "${t.name}" as ${Jo(r)}`)),console.log(y(` access token expires: ${r.expiresAt}`)),console.log(y(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Uh(process.cwd())?.profiles?.[t.name]&&(console.log(""),await hn(process.cwd(),t.name))}catch{}}async function Is(e,t,n){let r=Lc(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Qo(process.cwd(),t).project.projectId)return;let i;try{let{projects:c}=await gt(process.cwd(),t);i=c.find(p=>p.id===r)?.name}catch{}Mh(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function _c(e){let t=Qo(process.cwd(),e.profile),n=t.connection,o=_h(t.name);if(!o){console.log(A(`Not logged in to Document360 (profile "${t.name}").`)),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${W(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Jo(o)}`),Lh(o))if(o.refreshToken)try{let r=Ic(t.name,await Ih(n,o.refreshToken));Oc(r),console.log(M(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(B(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(B("Session expired (no refresh token).")),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(y(` expires: ${o.expiresAt}`))}async function Mc(e){let t=Qo(process.cwd(),e.profile);Oh(t.name)?console.log(M(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(y(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}K();import{readProjectConfig as Uc,writeProjectConfig as Fh,resolveActiveProfile as Wh,loadTokens as Bh,isExpired as Hh}from"document360-engine";function er(e){let t=Uc(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(A("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?W("\u25CF "):" ",s=o.production?B(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",c=Bh(n),p=c?Hh(c)&&!c.refreshToken?B("expired"):y("logged in"):y("not logged in");console.log(`${r}${W(n)} \u2192 ${i}${s} [${p}]`)}console.log(""),console.log(y("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function tr(e,t){let n=Uc(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(A(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Fh(n,e);let o=n.profiles[t].production?B(" \u26A0 PRODUCTION"):"";console.log(M(`\u2713 Default profile is now "${t}"${o}`))}function nr(e,t){try{let n=Wh(e,t);console.log(""),console.log(`Profile ${W(n.name)}${n.production?B(" \u26A0 PRODUCTION"):""}`),console.log(y(` api: ${n.connection.apiUrl}`)),console.log(y(` identity: ${n.connection.authorizationUrl}`)),console.log(y(` clientId: ${n.connection.clientId}`)),console.log(y(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(y(` project: ${n.project.projectId??"(set at login)"}`)),console.log(y(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(A(n.message)),process.exitCode=1}}K();import{existsSync as qh,readdirSync as Vh,statSync as Fc}from"node:fs";import{join as Wc}from"node:path";import{apiLogDir as Gh}from"document360-engine";function Bc(){let e=Gh();if(console.log(""),console.log(`Document360 API logs: ${W(e)}`),!qh(e)){console.log(y(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Vh(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(y(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Fc(Wc(e,r)).size/1024).toFixed(1);console.log(` ${r} ${y(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${y("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Fc(Wc(e,r)).size/1024).toFixed(1);console.log(` ${A(r)} ${y(`${s} KB`)}`)}}console.log(""),console.log(y("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(y("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}K();import{createSession as Yh,resolveAuth as zh,findByName as Kh,slugify as Xh,touchSession as Qh,upsertSession as Jh,resolveActiveProfile as Zh}from"document360-engine";async function Hc(e,t,n,o,r,s){let i=zh(n);i.kind==="none"&&(console.error(""),console.error(A("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(y("Using your Claude subscription (no API key set)."));let c=null;try{c=Zh(e,r)}catch(v){console.error(A(`Document360 profile error: ${v.message}`)),process.exit(2)}c.production&&(console.error(B(`\u26A0 Profile "${c.name}" is PRODUCTION.`)),s||(console.error(A("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(y(" --yes given \u2014 proceeding against production.")));let p;if(o){let v=Kh(e,o);v||(console.error(A(`No saved session matches "${o}" in this repo.`)),console.error(y("List sessions inside the REPL with /resume.")),process.exit(2)),p=v.uuid,console.error(y(`Resuming "${v.name}"`))}let h=Yh({cwd:e,resume:p,profileName:r,allowProdWrites:s===!0}),b=p??null,$=1;for await(let v of h.send(t))switch(v.type){case"session":if(!b){b=v.sessionId;let E=new Date().toISOString();Jh({uuid:b,name:Xh(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:E,updatedAt:E})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(fe(` \u2699 ${v.name}`));break;case"result":$=v.ok?0:1,console.error(y(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(A("agent finished with an error result"));break;case"error":console.error(""),console.error(A(`agent error: ${v.message}`)),process.exit(1)}b&&Qh(b),process.stdout.write(`
280
- `),process.exit($)}import{createInterface as nk}from"node:readline/promises";import{createSession as La,resolveAuth as ok,getSession as rk,setTitle as sk,slugify as ik,touchSession as ap,upsertSession as ak,generateTitle as ck,resolveActiveProfile as cp,resolveModelSetting as lk,readProjectConfig as dk,resolveAndPersistAppType as uk,decodeJwtClaims as ip,isExpired as pk,loadTokens as hk,isDirectiveMention as fk,stripDirectiveMention as mk,appendDirective as gk,reconcileUpgradeActions as yk,stampArticles as wk,listArticleFiles as kk,CONTENT_CAP_VERSION as bk}from"document360-engine";import{ENGINE_VERSION as tf}from"document360-engine";function Wt(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 or(e){if(e.length===0)return[];let t=(s,i)=>`${s}${"\u2500".repeat(78)}${i}`,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,i)=>{i>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let c of Wt(`${i+1}. ${s.feature}`,76))o.push(n(c));o.push(n());for(let c of Wt(s.why,73))o.push(n(` ${c}`));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}var He=[{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:"Each new shot is then checked automatically: D360-Writer looks at the picture and marks it \u2714 verified, or flags what is wrong and fixes the spec for you."},{t:"step",n:5,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 that did not work \u2014 a failed run, or one that failed verification."},{t:"cmd",name:"/screenshot capture --blocked",s:"Re-run the shots waiting on app data, once you have staged it (a bulk run leaves them out by default)."},{t:"cmd",name:"/screenshot verify",s:"Look at the captured pictures and mark them verified (<id> for one). Runs automatically after a capture \u2014 run it yourself for shots taken before this existed, or after an interrupted run. No browser needed."},{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 (\u2714 verified \xB7 \u25CF to verify \xB7 \u25D0 ready \xB7 \u2691 rejected \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:"What done means"},{t:"text",s:"\u2714 verified is the finish line, not \u25CF captured. A captured shot only means a file exists; it counts as done once the picture has been looked at and judged fit for the article."},{t:"gap"},{t:"sub",s:"When a shot does not produce a usable 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:"text",s:"\u2691 rejected means the shot ran but the picture is wrong \u2014 an empty placeholder where content should be, a callout on the wrong element, the subject unreadable. The spec is usually fixed for you; /screenshot capture --failed re-shoots. /screenshot list --detail shows each reason."},{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."}]}],qc=24;function Os(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?qc:Math.min(qc,Math.max(...t))}function Ls(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=Wt(t,s);return e.length>n?{nameCell:e,descLines:i,indent:r,nameOwnLine:!0}:{nameCell:e.padEnd(n),descLines:i,indent:r,nameOwnLine:!1}}function ef(e,t,n){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":{let o=Ls(e.name,e.s,t,n),r=o.descLines.slice(o.nameOwnLine?0:1).map(i=>`${o.indent}${i}`);return[o.nameOwnLine?` ${o.nameCell}`:` ${o.nameCell} ${o.descLines[0]??""}`,...r].join(`
281
- `)}case"gap":return""}}function Vc(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 He){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=Os(o.rows);for(let s of o.rows)n.push(ef(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function _s(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:tf}:void 0;for(let o of Vc(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"}}K();import{getSession as nf}from"document360-engine";async function Gc(e,t){let n=t.currentUuid(),o=n?nf(n):void 0;return console.log(o?y(`
278
+ `;tl="Re-run dev\u2194docs onboarding (protocol v"});var gl={};Ec(gl,{initCommand:()=>Hs,scaffoldInit:()=>Bs});import{input as Kn,confirm as ff}from"@inquirer/prompts";import{basename as al,join as cr}from"node:path";import{existsSync as wn,readFileSync as mf,readdirSync as gf,writeFileSync as yf}from"node:fs";import{writeProjectConfig as cl,readProjectConfig as wf,projectConfigPath as ll,writerDir as kf,DEFAULT_DOCS_DIR as dl,DEFAULT_CAPTURE_DIR as ul,DEFAULT_OUTPUT_DIR as pl}from"document360-engine";function Bs(e,t="berlin"){let n=ll(e);if(wn(n))return{created:!1,path:n,profileName:""};let o={projectId:fl(e)??al(e),docsDir:dl,captureDir:ul,outputDir:pl,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:ml(e)};return cl(o,e),hl(e),{created:!0,path:n,profileName:t}}function hl(e){let t=cr(kf(e),".gitignore");wn(t)||yf(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
279
+ `),"utf8")}async function Hs(){let e=process.cwd(),t=ll(e);if(wn(t)&&!await ff({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(g("init cancelled.")),{kind:"continue"};let n=fl(e)??al(e),o=await Kn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Kn({message:"Capture directory (where document360-capture .spec.ts files live):",default:ul}),s=await Kn({message:"Screenshot output directory:",default:pl}),i=await Kn({message:"Default connection profile name:",default:"berlin"}),c=await Kn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),p={projectId:o,docsDir:dl,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:c},production:!1}},defaultProfile:i,authoritativeSourceFiles:ml(e)},h=wf(e);h?.terminologyGlossary&&(p.terminologyGlossary=h.terminologyGlossary),cl(p,e),hl(e);let b=gn(e);console.log(""),console.log(M(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${W(`d360-writer login --profile ${i}`)} ${g("(sign in; project & workspace auto-selected)")}`),console.log("");for(let $ of yn(b))console.log($);return console.log(""),console.log(`${g("Then ask:")} ${W('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function fl(e){let t=cr(e,"package.json");if(!wn(t))return null;try{return JSON.parse(mf(t,"utf8")).name??null}catch{return null}}function ml(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])wn(cr(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=cr(e,n);wn(o)&&!bf(o)&&t.push(n)}return t}function bf(e){try{return gf(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var lr=qn(()=>{"use strict";K();wt()});import{createRequire as Bf}from"node:module";import{existsSync as Hf,readFileSync as qf}from"node:fs";import{dirname as _l,join as Ml}from"node:path";function $n(){let e;try{e=Vf.resolve("document360-capture/helpers")}catch{return null}let t=_l(e);for(let n=0;n<5&&!Hf(Ml(t,"package.json"));n++)t=_l(t);try{let n=JSON.parse(qf(Ml(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var Vf,hr=qn(()=>{"use strict";Vf=Bf(import.meta.url)});var cu={};Ec(cu,{doctorCommand:()=>ao,renderDoctorChecks:()=>au,runDoctorChecks:()=>iu});import{existsSync as ny}from"node:fs";import{d360GetAll as oy,getAccessToken as ry,isExpired as Qi,loadProfileMap as sy,loadTokens as iy,packageSkillsDir as ru,ENGINE_VERSION as ay,projectConfigPath as cy,readProjectConfig as ly,DEFAULT_DOCS_DIR as dy,fetchManifestSummary as uy,resolveActiveProfile as py,classifyClaudeAuth as hy,CLAUDE_CODE_SETUP_HINT as su,resolveModelSetting as fy,probeModel as my,detectAppType as gy,playbookSkillName as yy,D360AuthError as wy,applyStructureOrder as ky}from"document360-engine";async function iu(e,t){let n=[],o=$n();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${ay}${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=hy();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. ${su}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:su});let i=fy(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),s.state==="ready"){let C=await my(e,i.model??void 0);C.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(C.latencyMs/1e3).toFixed(1)}s`}):C.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${C.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let c=ly(e);if(!c)return n.push({level:"fail",label:`No ${cy(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${c.projectId}`});let p=(c.docsDir??dy).replace(/\/+$/,"");n.push(c.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let h=c.authoritativeSourceFiles??[];n.push(h.length>0?{level:"ok",label:`Sources: docs grounded in ${h.length} path(s) (${h.slice(0,3).join(", ")}${h.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=c.appType??gy(e);if(b){let C=c.appType?"from config":"auto-detected",P=b==="web"||b==="cli";n.push({level:"ok",label:`Genre: ${b} (${C})${P?` \u2192 ${yy(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 $;try{$=py(e),n.push({level:"ok",label:`Profile: ${$.name} (${$.connection.name})${$.production?" \u26A0 PRODUCTION":""}`})}catch(C){return n.push({level:"fail",label:`Profile config: ${C.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let v=iy($.name);v?Qi(v)&&!v.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Qi(v)?n.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(v.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${$.name})`}),n.push($.project.workspaceId?{level:"ok",label:`Workspace: ${$.project.workspaceName??$.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let E=sy(e,$.name);E?E.projectId&&$.project.projectId&&E.projectId!==$.project.projectId?n.push({level:"fail",label:`Category map projectId (${E.projectId}) \u2260 profile projectId (${$.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(E.articles).length} articles, ${Object.keys(E.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${$.name}" (created on first /publish)`}),n.push(ny(ru())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ru()}`,fix:"Reinstall document360-writer (broken install)"});let R=qe(e);if(R.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ge})`}):R.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${R.completedVersion}, current is v${ge}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),v&&(!Qi(v)||v.refreshToken)){let C={profile:$.name,connection:$.connection};try{await ry(C);let I=await oy(C,"/v3/projects");n.push({level:"ok",label:`API reachable (${$.connection.apiUrl}) \u2014 ${I.length} project(s) visible`})}catch(I){n.push({level:"fail",label:`API call failed: ${I.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let P=E?.projectId??$.project.projectId;if(P&&$.project.workspaceId){try{let I=await uy(C,P,$.project.workspaceId);if(I){let G=(I.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${$.connection.name} (${I.languages?.length??0} language${(I.languages?.length??0)===1?"":"s"}) \xB7 hash ${G||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${$.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(I){I instanceof wy||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(I.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${$.project.projectName??P})`,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 (${I.message.slice(0,80)})`})}try{let I=await ky({cwd:e,profileName:$.name,dryRun:!0}),G=I.categoriesReordered+I.articlesReordered;if(I.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${I.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /publish syncs it once this resolves"});else if(I.unverified)n.push({level:"warn",label:`Reading order: ${I.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not published (the listing returns published articles). Publish them, then /publish re-syncs the order"});else if(G>0){let q=[I.categoriesReordered>0?`${I.categoriesReordered} categor${I.categoriesReordered===1?"y":"ies"}`:"",I.articlesReordered>0?`${I.articlesReordered} article${I.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${q.join(" + ")} out of order on Document360`,fix:"Run /publish \u2014 it re-syncs the order from your NN- folder/file prefixes"})}else n.push({level:"ok",label:"Reading order: Document360 matches your structure"})}catch(I){n.push({level:"warn",label:`Reading order: check failed (${I.message.slice(0,80)})`})}}}return n}function au(e){let t=[""];for(let r of e){let s=r.level==="ok"?M("\u2713"):r.level==="warn"?H("\u26A0"):D("\u2717");t.push(` ${s} ${r.label}${r.detail?g(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${g("fix:")} ${W(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?M(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):D(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function ao(e,t){console.log(g("Running checks\u2026"));for(let n of au(await iu(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var _r=qn(()=>{"use strict";wt();K();hr()});import{Command as Qb}from"commander";import{createRequire as Jb}from"node:module";import{AUTH_MODES as Zb}from"document360-engine";import{input as Ih}from"@inquirer/prompts";import{loginPkce as Oh,refreshTokens as Lh,toStoredTokens as Lc,clearTokens as _h,decodeJwtClaims as Oc,isExpired as Mh,loadTokens as Uh,saveTokens as _c,resolveActiveProfile as Qo,setProfileProject as Fh,readProjectConfig as Wh}from"document360-engine";K();import{select as $h}from"@inquirer/prompts";import{resolveActiveProfile as vh,setProfileProject as xh,resolveProjectId as Ch,listWorkspaces as Rh}from"document360-engine";async function Gn(e,t){let n=vh(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Ch(o);return{workspaces:await Rh(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Ac=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function js(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 zo(e,t,n,o,r){xh(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function jc(e,t,n){let o;try{o=await Gn(e,n)}catch(s){return console.log(D(`Could not list workspaces: ${s.message}`)),1}let r=js(o.workspaces,t);return r?(zo(e,o.profile,o.projectId,r.id,r.name),console.log(M(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(D(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function hn(e,t){let n;try{n=await Gn(e,t)}catch(h){console.log(D(`Could not list workspaces: ${h.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(g("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===i?W("\u25CF"):" "} ${Ac(h)} ${g(h.id)}`);console.log(g("Run: d360-writer workspace use <name>"));return}let c=await $h({message:"Select the Document360 workspace for this repo:",choices:o.map(h=>({name:`${Ac(h)}${h.id===i?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===c);zo(e,s,r,c,p?.name),console.log(M(`\u2713 Workspace set to "${p?.name??c}" for profile "${s}".`))}K();import{select as Sh}from"@inquirer/prompts";import{resolveActiveProfile as Ph,setProfileProject as Th,listProjects as Eh}from"document360-engine";async function gt(e,t){let n=Ph(e,t),o={profile:n.name,connection:n.connection};return{projects:await Eh(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Nc=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Ns(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function Ko(e,t,n,o){Th(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Ic(e,t,n){let o;try{o=await gt(e,n)}catch(s){return console.log(D(`Could not list projects: ${s.message}`)),1}let r=Ns(o.projects,t);return r?(Ko(e,o.profile,r.id,r.name),console.log(M(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(D(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Xo(e,t){let n;try{n=await gt(e,t)}catch(p){console.log(D(`Could not list projects: ${p.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 p of o)console.log(` ${p.id===s?W("\u25CF"):" "} ${Nc(p)} ${g(p.id)}`);console.log(g("Run: d360-writer project use <name>"));return}let i=await Sh({message:"Select the Document360 project for this repo:",choices:o.map(p=>({name:`${Nc(p)}${p.id===s?" (current)":""}`,value:p.id}))}),c=o.find(p=>p.id===i);Ko(e,r,i,c?.name),console.log(M(`\u2713 Project set to "${c?.name??i}" for profile "${r}". Next: pick a workspace.`))}K();import Dh from"picocolors";function Ah(e=process.env){return e.FORCE_HYPERLINK==="0"||!Dh.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 jh(e,t=e,n){return Ah(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Nh=/https?:\/\/[^\s\x1b]+/g;function Yn(e,t){return e.replace(Nh,n=>jh(n,n,t))}function Mc(e){return{...Oc(e.idToken)??{},...Oc(e.accessToken)??{}}}function Jo(e){let t=Mc(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 Zo(e){let t=Qo(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 Oh(n,{manual:e.manual,promptForRedirect:s=>Ih({message:s})},s=>console.log(Yn(s))),r=Lc(t.name,o);if(_c(r),await Is(r,t.name,s=>console.log(g(s))),console.log(""),console.log(M(`\u2713 Logged in to "${t.name}" as ${Jo(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{Wh(process.cwd())?.profiles?.[t.name]&&(console.log(""),await hn(process.cwd(),t.name))}catch{}}async function Is(e,t,n){let r=Mc(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Qo(process.cwd(),t).project.projectId)return;let i;try{let{projects:c}=await gt(process.cwd(),t);i=c.find(p=>p.id===r)?.name}catch{}Fh(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function Uc(e){let t=Qo(process.cwd(),e.profile),n=t.connection,o=Uh(t.name);if(!o){console.log(D(`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 ${W(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Jo(o)}`),Mh(o))if(o.refreshToken)try{let r=Lc(t.name,await Lh(n,o.refreshToken));_c(r),console.log(M(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(H(`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(H("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 Fc(e){let t=Qo(process.cwd(),e.profile);_h(t.name)?console.log(M(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(g(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}K();import{readProjectConfig as Wc,writeProjectConfig as Bh,resolveActiveProfile as Hh,loadTokens as qh,isExpired as Vh}from"document360-engine";function er(e){let t=Wc(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(D("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?W("\u25CF "):" ",s=o.production?H(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",c=qh(n),p=c?Vh(c)&&!c.refreshToken?H("expired"):g("logged in"):g("not logged in");console.log(`${r}${W(n)} \u2192 ${i}${s} [${p}]`)}console.log(""),console.log(g("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function tr(e,t){let n=Wc(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(D(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Bh(n,e);let o=n.profiles[t].production?H(" \u26A0 PRODUCTION"):"";console.log(M(`\u2713 Default profile is now "${t}"${o}`))}function nr(e,t){try{let n=Hh(e,t);console.log(""),console.log(`Profile ${W(n.name)}${n.production?H(" \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(D(n.message)),process.exitCode=1}}K();import{existsSync as Gh,readdirSync as Yh,statSync as Bc}from"node:fs";import{join as Hc}from"node:path";import{apiLogDir as zh}from"document360-engine";function qc(){let e=zh();if(console.log(""),console.log(`Document360 API logs: ${W(e)}`),!Gh(e)){console.log(g(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Yh(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=(Bc(Hc(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=(Bc(Hc(e,r)).size/1024).toFixed(1);console.log(` ${D(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("")}K();import{createSession as Kh,resolveAuth as Xh,findByName as Qh,slugify as Jh,touchSession as Zh,upsertSession as ef,resolveActiveProfile as tf}from"document360-engine";async function Vc(e,t,n,o,r,s){let i=Xh(n);i.kind==="none"&&(console.error(""),console.error(D("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(g("Using your Claude subscription (no API key set)."));let c=null;try{c=tf(e,r)}catch(v){console.error(D(`Document360 profile error: ${v.message}`)),process.exit(2)}c.production&&(console.error(H(`\u26A0 Profile "${c.name}" is PRODUCTION.`)),s||(console.error(D("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(g(" --yes given \u2014 proceeding against production.")));let p;if(o){let v=Qh(e,o);v||(console.error(D(`No saved session matches "${o}" in this repo.`)),console.error(g("List sessions inside the REPL with /resume.")),process.exit(2)),p=v.uuid,console.error(g(`Resuming "${v.name}"`))}let h=Kh({cwd:e,resume:p,profileName:r,allowProdWrites:s===!0}),b=p??null,$=1;for await(let v of h.send(t))switch(v.type){case"session":if(!b){b=v.sessionId;let E=new Date().toISOString();ef({uuid:b,name:Jh(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:E,updatedAt:E})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(me(` \u2699 ${v.name}`));break;case"result":$=v.ok?0:1,console.error(g(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(D("agent finished with an error result"));break;case"error":console.error(""),console.error(D(`agent error: ${v.message}`)),process.exit(1)}b&&Zh(b),process.stdout.write(`
280
+ `),process.exit($)}import{createInterface as sk}from"node:readline/promises";import{createSession as La,resolveAuth as ik,getSession as ak,setTitle as ck,slugify as lk,touchSession as lp,upsertSession as dk,generateTitle as uk,resolveActiveProfile as dp,resolveModelSetting as pk,readProjectConfig as hk,resolveAndPersistAppType as fk,decodeJwtClaims as cp,isExpired as mk,loadTokens as gk,isDirectiveMention as yk,stripDirectiveMention as wk,appendDirective as kk,reconcileUpgradeActions as bk,stampArticles as $k,listArticleFiles as vk,CONTENT_CAP_VERSION as xk,applyStructureOrder as Ck,orderSyncLine as Rk}from"document360-engine";import{ENGINE_VERSION as of}from"document360-engine";function Wt(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 or(e){if(e.length===0)return[];let t=(s,i)=>`${s}${"\u2500".repeat(78)}${i}`,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,i)=>{i>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let c of Wt(`${i+1}. ${s.feature}`,76))o.push(n(c));o.push(n());for(let c of Wt(s.why,73))o.push(n(` ${c}`));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}var He=[{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:"Each new shot is then checked automatically: D360-Writer looks at the picture and marks it \u2714 verified, or flags what is wrong and fixes the spec for you."},{t:"step",n:5,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 that did not work \u2014 a failed run, or one that failed verification."},{t:"cmd",name:"/screenshot capture --blocked",s:"Re-run the shots waiting on app data, once you have staged it (a bulk run leaves them out by default)."},{t:"cmd",name:"/screenshot verify",s:"Look at the captured pictures and mark them verified (<id> for one). Runs automatically after a capture \u2014 run it yourself for shots taken before this existed, or after an interrupted run. No browser needed."},{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 (\u2714 verified \xB7 \u25CF to verify \xB7 \u25D0 ready \xB7 \u2691 rejected \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:"What done means"},{t:"text",s:"\u2714 verified is the finish line, not \u25CF captured. A captured shot only means a file exists; it counts as done once the picture has been looked at and judged fit for the article."},{t:"gap"},{t:"sub",s:"When a shot does not produce a usable 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:"text",s:"\u2691 rejected means the shot ran but the picture is wrong \u2014 an empty placeholder where content should be, a callout on the wrong element, the subject unreadable. The spec is usually fixed for you; /screenshot capture --failed re-shoots. /screenshot list --detail shows each reason."},{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."}]}],Gc=24;function Os(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?Gc:Math.min(Gc,Math.max(...t))}function Ls(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=Wt(t,s);return e.length>n?{nameCell:e,descLines:i,indent:r,nameOwnLine:!0}:{nameCell:e.padEnd(n),descLines:i,indent:r,nameOwnLine:!1}}function nf(e,t,n){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":{let o=Ls(e.name,e.s,t,n),r=o.descLines.slice(o.nameOwnLine?0:1).map(i=>`${o.indent}${i}`);return[o.nameOwnLine?` ${o.nameCell}`:` ${o.nameCell} ${o.descLines[0]??""}`,...r].join(`
281
+ `)}case"gap":return""}}function Yc(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 He){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=Os(o.rows);for(let s of o.rows)n.push(nf(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function _s(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:of}:void 0;for(let o of Yc(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"}}K();import{getSession as rf}from"document360-engine";async function zc(e,t){let n=t.currentUuid(),o=n?rf(n):void 0;return console.log(o?g(`
282
282
  (conversation reset \u2014 "${o.name}" is still available via /resume)
283
- `):y(`
283
+ `):g(`
284
284
  (conversation reset \u2014 agent will start fresh on the next prompt)
285
- `)),{kind:"clear"}}async function Ms(){return{kind:"exit"}}lr();K();import{readMcpConfig as qs,writeMcpConfig as ml}from"document360-engine";async function dr(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(kf(),{kind:"continue"}):t==="add"?(bf(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?($f(e.slice(1)),{kind:"continue"}):(console.log(A(`Unknown /mcp subcommand: ${t}`)),console.log(y("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function kf(){let e=qs(),t=Object.keys(e.servers);if(t.length===0){console.log(y(`
285
+ `)),{kind:"clear"}}async function Ms(){return{kind:"exit"}}lr();K();import{readMcpConfig as qs,writeMcpConfig as yl}from"document360-engine";async function dr(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?($f(),{kind:"continue"}):t==="add"?(vf(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(xf(e.slice(1)),{kind:"continue"}):(console.log(D(`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 $f(){let e=qs(),t=Object.keys(e.servers);if(t.length===0){console.log(g(`
286
286
  No MCP servers registered. Add one with /mcp add <name> <type> <ref>
287
- `));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(` ${W(n)} ${y("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?y(` [headers: ${r.join(", ")}]`):"";console.log(` ${W(n)} ${y(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function bf(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(A("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(A(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=qs(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let i={};for(let c=1;c<o.length;c++)if(o[c]==="-H"||o[c]==="--header"){let p=o[++c],h=p?.match(/^([^:=]+)[:=](.+)$/);if(!h){console.log(A(`-H expects key:value (no spaces). Got: ${p??"(nothing)"}`));return}i[h[1].trim()]=h[2].trim()}else{console.log(A(`Unexpected argument: ${o[c]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(i).length>0?i:void 0}}r.servers[t]=s,ml(r),console.log(""),console.log(M(`\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(y(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function $f(e){let t=e[0];if(!t){console.log(A("Usage: /mcp remove <name>"));return}let n=qs();if(!n.servers[t]){console.log(A(`No server named "${t}".`));return}delete n.servers[t],ml(n),console.log(M(`\u2713 Removed "${t}".`)),console.log(y(" Run /clear to drop it from the current session immediately."))}K();import{readFileSync as Tm}from"node:fs";import{join as Em}from"node:path";import{select as Am}from"@inquirer/prompts";import{computeSyncStatus as Sr,planPartitions as Dm,relatedArticlePaths as jm,resolveModelForOperation as Nm,runPartitioned as Im,loadProfileMap as Om,resolveActiveProfile as Lm,resolveCrossLinks as _m,applyStructureOrder as fd,orderSyncLine as md,applyRelatedArticles as gd,relatedSyncLine as yd}from"document360-engine";import se from"picocolors";import Sl from"wrap-ansi";import Xs from"string-width";K();import kt from"picocolors";import Vs from"wrap-ansi";import Gs from"string-width";var kn=[{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|verify|checklist|list] [id|path|--all|--failed|--blocked]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots (--all re-shoots everything; --failed re-runs the ones that did not work; --blocked re-runs the ones waiting on app data); verify: judge the captured pictures and mark them verified (runs automatically after a capture); 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 (builder hints + requests + Document360 portal drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live). For code changes, that's /audit",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=kn.find(r=>r.name===t);return o?o.desc:""}function wl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return kn.filter(n=>n.name.startsWith(t))}function kl(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var vf=new RegExp(`^\\s*/(?:${kn.map(e=>e.name).join("|")})(?:\\s|$)`),bl=e=>vf.test(e),$l=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),vl=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),xl=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function xf(e){let t=e.replace(/\r/g,"").split(`
288
- `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let c=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)c.push(t[o++]);o++,n.push({kind:"code",lines:c});continue}if($l(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&vl(t[o+1])){let c=xl(r);o+=2;let p=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)p.push(xl(t[o++]));n.push({kind:"table",header:c,rows:p});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 c=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let p=t[o++];c.push({ordered:/^\s*\d+\.\s+/.test(p),text:p.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:c});continue}if(r.trim()===""){o++;continue}if(bl(r)){n.push({kind:"para",text:r.trim()}),o++;continue}let i=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!bl(t[o])&&!$l(t[o])&&!(t[o].includes("|")&&o+1<t.length&&vl(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function Ys(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?kt.bold(t.slice(2,-2)):t.startsWith("`")?W(t.slice(1,-1)):kt.italic(t.slice(1,-1)))}var Cf=(e,t)=>e+" ".repeat(Math.max(0,t-Gs(e)));function Rf(e,t,n){let o=e.length,r=e.map((R,x)=>Math.max(Gs(R),...t.map(T=>Gs(T[x]??"")))),s=Math.max(24,n),i=3*o+1,c=[...r],p=()=>c.reduce((R,x)=>R+x,0)+i,h=0;for(;p()>s&&h++<1e4;){let R=-1,x=6;for(let T=0;T<o;T++)c[T]>x&&(x=c[T],R=T);if(R===-1)break;c[R]-=1}let b=(R,x,T)=>kt.gray(R+c.map(F=>"\u2500".repeat(F+2)).join(x)+T),$=kt.gray("\u2502"),v=(R,x)=>{let T=c.map((q,Y)=>{let pe=R[Y]??"",J=x?kt.bold(pe):Ys(pe);return Vs(J,q,{hard:!0}).split(`
289
- `)}),F=Math.max(...T.map(q=>q.length)),G=[];for(let q=0;q<F;q++)G.push(c.map((Y,pe)=>`${$} ${Cf(T[pe][q]??"",Y)} `).join("")+$);return G.join(`
290
- `)},E=[b("\u250C","\u252C","\u2510"),v(e,!0)];return E.push(t.length===0?b("\u2514","\u2534","\u2518"):b("\u251C","\u253C","\u2524")),t.forEach((R,x)=>{E.push(v(R,!1)),E.push(x===t.length-1?b("\u2514","\u2534","\u2518"):b("\u251C","\u253C","\u2524"))}),E.join(`
291
- `)}function Sf(e,t){switch(e.kind){case"heading":return kt.bold(e.text);case"hr":return kt.gray("\u2500".repeat(t));case"para":return Vs(Ys(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),[i="",...c]=Vs(Ys(o.text),Math.max(10,t-s.length)).split(`
287
+ `));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(` ${W(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(` ${W(n)} ${g(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function vf(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(D("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(D(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=qs(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let i={};for(let c=1;c<o.length;c++)if(o[c]==="-H"||o[c]==="--header"){let p=o[++c],h=p?.match(/^([^:=]+)[:=](.+)$/);if(!h){console.log(D(`-H expects key:value (no spaces). Got: ${p??"(nothing)"}`));return}i[h[1].trim()]=h[2].trim()}else{console.log(D(`Unexpected argument: ${o[c]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(i).length>0?i:void 0}}r.servers[t]=s,yl(r),console.log(""),console.log(M(`\u2713 Registered "${t}" (${n})`)),console.log(H(" 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 xf(e){let t=e[0];if(!t){console.log(D("Usage: /mcp remove <name>"));return}let n=qs();if(!n.servers[t]){console.log(D(`No server named "${t}".`));return}delete n.servers[t],yl(n),console.log(M(`\u2713 Removed "${t}".`)),console.log(g(" Run /clear to drop it from the current session immediately."))}K();import{readFileSync as Dm}from"node:fs";import{join as Am}from"node:path";import{select as jm}from"@inquirer/prompts";import{computeSyncStatus as Sr,planPartitions as Nm,relatedArticlePaths as Im,resolveModelForOperation as Om,runPartitioned as Lm,loadProfileMap as _m,resolveActiveProfile as Mm,resolveCrossLinks as Um,applyStructureOrder as gd,orderSyncLine as yd,applyRelatedArticles as wd,relatedSyncLine as kd}from"document360-engine";import se from"picocolors";import Tl from"wrap-ansi";import Xs from"string-width";K();import kt from"picocolors";import Vs from"wrap-ansi";import Gs from"string-width";var kn=[{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|verify|checklist|list] [id|path|--all|--failed|--blocked]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots (--all re-shoots everything; --failed re-runs the ones that did not work; --blocked re-runs the ones waiting on app data); verify: judge the captured pictures and mark them verified (runs automatically after a capture); 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 (builder hints + requests + Document360 portal drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live). For code changes, that's /audit",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"}],wl={"/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(wl[n])return wl[n];let o=kn.find(r=>r.name===t);return o?o.desc:""}function bl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return kn.filter(n=>n.name.startsWith(t))}function $l(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Cf=new RegExp(`^\\s*/(?:${kn.map(e=>e.name).join("|")})(?:\\s|$)`),vl=e=>Cf.test(e),xl=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Cl=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Rl=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Rf(e){let t=e.replace(/\r/g,"").split(`
288
+ `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let c=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)c.push(t[o++]);o++,n.push({kind:"code",lines:c});continue}if(xl(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Cl(t[o+1])){let c=Rl(r);o+=2;let p=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)p.push(Rl(t[o++]));n.push({kind:"table",header:c,rows:p});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 c=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let p=t[o++];c.push({ordered:/^\s*\d+\.\s+/.test(p),text:p.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:c});continue}if(r.trim()===""){o++;continue}if(vl(r)){n.push({kind:"para",text:r.trim()}),o++;continue}let i=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!vl(t[o])&&!xl(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Cl(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function Ys(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?kt.bold(t.slice(2,-2)):t.startsWith("`")?W(t.slice(1,-1)):kt.italic(t.slice(1,-1)))}var Sf=(e,t)=>e+" ".repeat(Math.max(0,t-Gs(e)));function Pf(e,t,n){let o=e.length,r=e.map((R,C)=>Math.max(Gs(R),...t.map(P=>Gs(P[C]??"")))),s=Math.max(24,n),i=3*o+1,c=[...r],p=()=>c.reduce((R,C)=>R+C,0)+i,h=0;for(;p()>s&&h++<1e4;){let R=-1,C=6;for(let P=0;P<o;P++)c[P]>C&&(C=c[P],R=P);if(R===-1)break;c[R]-=1}let b=(R,C,P)=>kt.gray(R+c.map(I=>"\u2500".repeat(I+2)).join(C)+P),$=kt.gray("\u2502"),v=(R,C)=>{let P=c.map((q,Y)=>{let he=R[Y]??"",J=C?kt.bold(he):Ys(he);return Vs(J,q,{hard:!0}).split(`
289
+ `)}),I=Math.max(...P.map(q=>q.length)),G=[];for(let q=0;q<I;q++)G.push(c.map((Y,he)=>`${$} ${Sf(P[he][q]??"",Y)} `).join("")+$);return G.join(`
290
+ `)},E=[b("\u250C","\u252C","\u2510"),v(e,!0)];return E.push(t.length===0?b("\u2514","\u2534","\u2518"):b("\u251C","\u253C","\u2524")),t.forEach((R,C)=>{E.push(v(R,!1)),E.push(C===t.length-1?b("\u2514","\u2534","\u2518"):b("\u251C","\u253C","\u2524"))}),E.join(`
291
+ `)}function Tf(e,t){switch(e.kind){case"heading":return kt.bold(e.text);case"hr":return kt.gray("\u2500".repeat(t));case"para":return Vs(Ys(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),[i="",...c]=Vs(Ys(o.text),Math.max(10,t-s.length)).split(`
292
292
  `);return` ${r} ${i}`+c.map(p=>`
293
293
  ${s}${p}`).join("")}).join(`
294
294
  `)}case"code":return e.lines.map(n=>kt.gray(" "+n)).join(`
295
- `);case"table":return Rf(e.header,e.rows,t)}}function zs(e,t){let n=Math.max(20,t);return xf(e).map(o=>Sf(o,n)).join(`
295
+ `);case"table":return Pf(e.header,e.rows,t)}}function zs(e,t){let n=Math.max(20,t);return Rf(e).map(o=>Tf(o,n)).join(`
296
296
 
297
- `)}K();import Pf from"picocolors";var Tf=[127,86,217],Ef=[22,38,43],Cl={T:Tf,E:Ef},Xn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Ks=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Af=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Rl(){if(!Pf.isColorSupported)return[];let e=Xn[0].length,t=[];for(let n=0;n<Xn.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Cl[Xn[n][r]],i=n+1<Xn.length?Cl[Xn[n+1][r]]:void 0;s&&i?o+=`${Ks(s)}${Af(i)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Ks(s)}\u2580\x1B[39m`:i?o+=`${Ks(i)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Qn(e){let t=n=>n.toFixed(1).endsWith(".0")?n.toFixed(0):n.toFixed(1);return e<1e3?String(e):e<1e6?`${t(e/1e3)}k`:`${t(e/1e6)}M`}function Jn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Ee(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function bt(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var bn=(e,t)=>` ${e.padEnd(13)}${t}`;function Df(e,t){let n=[Vn("\u270E document360-writer")+se.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),se.gray(" Reads your code, writes your docs."),"",bn("Claude:",`${e.claude}${se.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),bn("Document360:",e.configured?e.loggedOut?se.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?se.gray(` (${e.sessionHint})`):""}`:se.yellow("not set up \u2014 run /init")),bn("Profile:",e.configured?`${e.profile}${se.gray(` (${e.apiUrl})`)}${e.prod?se.bold(se.yellow(" \u26A0 PRODUCTION")):""}`:se.gray("\u2014 (run /init)")),bn("Project:",e.project),bn("Mode:",se.gray(e.mode)),bn("cwd:",se.gray(e.cwd))],o=Rl();if(o.length===0)return n.join(`
297
+ `)}K();import Ef from"picocolors";var Df=[127,86,217],Af=[22,38,43],Sl={T:Df,E:Af},Xn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Ks=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,jf=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Pl(){if(!Ef.isColorSupported)return[];let e=Xn[0].length,t=[];for(let n=0;n<Xn.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Sl[Xn[n][r]],i=n+1<Xn.length?Sl[Xn[n+1][r]]:void 0;s&&i?o+=`${Ks(s)}${jf(i)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Ks(s)}\u2580\x1B[39m`:i?o+=`${Ks(i)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Qn(e){let t=n=>n.toFixed(1).endsWith(".0")?n.toFixed(0):n.toFixed(1);return e<1e3?String(e):e<1e6?`${t(e/1e3)}k`:`${t(e/1e6)}M`}function Jn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function De(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function bt(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var bn=(e,t)=>` ${e.padEnd(13)}${t}`;function Nf(e,t){let n=[Vn("\u270E document360-writer")+se.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),se.gray(" Reads your code, writes your docs."),"",bn("Claude:",`${e.claude}${se.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),bn("Document360:",e.configured?e.loggedOut?se.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?se.gray(` (${e.sessionHint})`):""}`:se.yellow("not set up \u2014 run /init")),bn("Profile:",e.configured?`${e.profile}${se.gray(` (${e.apiUrl})`)}${e.prod?se.bold(se.yellow(" \u26A0 PRODUCTION")):""}`:se.gray("\u2014 (run /init)")),bn("Project:",e.project),bn("Mode:",se.gray(e.mode)),bn("cwd:",se.gray(e.cwd))],o=Pl();if(o.length===0)return n.join(`
298
298
  `);let r=2,s=3,i=Xs(o[0]);if(!(t>=r+i+s+Math.max(...n.map(b=>Xs(b)))))return[...o.map(b=>" "+b),...n].join(`
299
299
  `);let p=Math.max(0,Math.floor((n.length-o.length)/2)),h=[];for(let b=0;b<Math.max(o.length+p,n.length);b++){let $=o[b-p]??" ".repeat(i);h.push((" ".repeat(r)+$+" ".repeat(s)+(n[b]??"")).trimEnd())}return h.join(`
300
- `)}var jf={error:se.red,warn:se.yellow,ok:se.green,info:se.gray};function Qs(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1$2 ")}function Js(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Df(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),i=50,c=e.text.split(`
301
- `).flatMap(h=>Sl(h,s,{hard:!0}).split(`
300
+ `)}var If={error:se.red,warn:se.yellow,ok:se.green,info:se.gray};function Qs(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1$2 ")}function Js(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Nf(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),i=50,c=e.text.split(`
301
+ `).flatMap(h=>Tl(h,s,{hard:!0}).split(`
302
302
  `)),p=Math.max(0,c.length-i);return p>0&&(c=[...c.slice(0,i),se.dim(`\u2026 +${p} more lines`)]),`
303
303
  `+c.map((h,b)=>o+(b===0?W(" \u276F "):" ")+h+" ".repeat(Math.max(0,s-Xs(h))+1)+r).join(`
304
304
  `)}case"assistant":return`
305
305
  `+zs(e.text,n);case"tool":{let o=e.arg!==null?se.gray(`${e.sep}(${e.arg})`):"";return`
306
- `+Sl(se.green("\u25CF ")+se.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?se.red:se.gray,r=e.lines.map((s,i)=>o((i===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(se.dim(` \u2026 +${e.hidden} lines`)),r.join(`
306
+ `+Tl(se.green("\u25CF ")+se.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?se.red:se.gray,r=e.lines.map((s,i)=>o((i===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(se.dim(` \u2026 +${e.hidden} lines`)),r.join(`
307
307
  `)}case"diff":{let o=i=>i===1?"":"s",s=[se.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(se.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
308
308
  `)}case"link":return e.lines.map(o=>W(Yn(` \u2B95 ${o}`))).join(`
309
309
  `);case"preview":return`
310
310
  `+Vn(`\u25A3 Preview \u2014 ${e.name}`)+`
311
311
 
312
312
  `+zs(e.text,n);case"note":return`
313
- `+jf[e.tone](Yn(Qs(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${Qn(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
314
- `+(e.ok?se.magenta("\u2736 "):se.red("\u2736 "))+se.gray(`Cooked for ${Jn(e.seconds)} \xB7 ${Qn(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${Ee(e.costUsd)}`:""))}}}function Pl(e,t){return e.map(n=>Js(n,t)).join(`
315
- `)}import{resolveActiveProfile as Nf,loadTokens as If,isExpired as Of,decodeJwtClaims as Tl}from"document360-engine";function Lf(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ve(e,t){try{let n=Nf(e,t),o=If(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Of(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let i={...Tl(o.idToken)??{},...Tl(o.accessToken)??{}}.doc360_project_id;if(typeof i=="string"&&i&&i!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${Lf(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}import{existsSync as oi,readFileSync as ai}from"node:fs";import{isAbsolute as yr,join as wr,resolve as kr}from"node:path";import D from"picocolors";import fr from"string-width";import{readProjectConfig as vt,screenshotPlaceholderIds as Xl,DEFAULT_CAPTURE_DIR as br,DEFAULT_OUTPUT_DIR as ci,DEFAULT_DOCS_DIR as li,existingAnnotatedShotPath as sm,resolveOutputDir as Ql,migrateShotLayout as im,reviewIsCurrent as am,shotImageMtimeMs as cm,RAW_SUBDIR as lm,ANNOTATED_SUBDIR as dm}from"document360-engine";import{createHash as Al}from"node:crypto";import{readFileSync as Dl,writeFileSync as _f}from"node:fs";import{join as Mf}from"node:path";import{captureStatePath as jl}from"document360-engine";var El={version:1,shots:{}};function Nl(e){return Al("sha1").update(e).digest("hex").slice(0,12)}function ur(e){try{let t=JSON.parse(Dl(Mf(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]);if(!o)return null;let r=t.profiles?.[o],s=r?.scope??{},i=Object.keys(s).sort().map(c=>`${c}=${s[c]}`).join("&");return Al("sha1").update(`${o}|${r?.connection?.startUrl??""}|${i}`).digest("hex").slice(0,12)}catch{return null}}function at(e){try{let t=JSON.parse(Dl(jl(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...El,shots:{}}:{version:1,shots:t.shots}}catch{return{...El,shots:{}}}}function Uf(e,t){_f(jl(e),`${JSON.stringify(t,null,2)}
316
- `,"utf8")}function Zs(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function pr(e,t,n){if(t.length===0)return;let o=at(e),r=ur(e);for(let s of t){let i=s.specSource?Nl(s.specSource):void 0;o.shots[s.id]={outcome:s.outcome,at:n,...s.reason?{reason:s.reason}:{},...s.outcome==="skipped"?{blockedBy:Zs(s.reason)}:{},...i?{specHash:i}:{},...r?{envHash:r}:{}}}Uf(e,o)}function ei(e,t,n,o){let r=e.shots[t];return!r||n===null||!r.specHash||r.specHash!==Nl(n)||o&&r.envHash&&r.envHash!==o?null:r}function Il(e){let t=at(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function ti(e,t,n){let o=ei(at(e),t,n,ur(e));return!o||o.outcome==="captured"||!o.reason?null:{outcome:o.outcome,reason:o.reason}}hr();import{existsSync as qf,readFileSync as Ml,readdirSync as Ul,writeFileSync as Vf}from"node:fs";import{isAbsolute as Gf,join as Fl,resolve as Yf}from"node:path";import{readProjectConfig as zf,DEFAULT_CAPTURE_DIR as Kf}from"document360-engine";var _l="0.2.25";function Xf(e,t){if(!e)return!1;let n=s=>s.split("-")[0].split(".").map(i=>Number.parseInt(i,10)||0),o=n(e),r=n(t);for(let s=0;s<Math.max(o.length,r.length);s++){let i=(o[s]??0)-(r[s]??0);if(i!==0)return i>0}return!0}var Qf=/^([ \t]*)await\s+([^\n;]+?)\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo\s*(?:,\s*fullPage:\s*(?:true|false)\s*)?,?\s*\}\)\s*;?[ \t]*$/m,Jf=/^[ \t]*await\s+dumpAnnotations\(\s*page\s*,\s*PLACEHOLDER\s*\)\s*;?[ \t]*\r?\n?/m,Wl="(?:'([^']+)'|\"([^\"]+)\"|`([^`]+)`)",Zf=new RegExp(`^page\\s*\\.\\s*locator\\(\\s*${Wl}\\s*\\)$`),Bl=e=>e[1]??e[2]??e[3]??null,em=/^[A-Za-z_$][\w$]*$/;function tm(e,t){let o=new RegExp(`\\bconst\\s+${t}\\s*=\\s*page\\s*\\.\\s*locator\\(\\s*${Wl}\\s*\\)\\s*;`).exec(e);return o?Bl(o):null}function nm(e,t){let n=t.trim();if(n==="page")return null;let o=Zf.exec(n);if(o){let r=Bl(o);return r?{selector:r}:{unresolved:!0}}if(em.test(n)){let r=tm(e,n);return r?{selector:r}:{unresolved:!0}}return{unresolved:!0}}function Hl(e){if(/\bcaptureShot\s*\(/.test(e))return null;let t=(e.match(/\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo/g)??[]).length;if(t>1)return{unresolved:`${t} conditional capture calls`};let n=Qf.exec(e);if(!n)return null;let[o,r="",s=""]=n,i=nm(e,s);if(i===null)return null;if("unresolved"in i)return{unresolved:s.trim()};let c=/^([ \t]*)saveTo:\s*.+,[ \t]*$/m.exec(e);if(!c)return null;let p=i.selector.includes("'")?'"':"'",h=e.replace(c[0],`${c[0]}
317
- ${c[1]??" "}clipTo: ${p}${i.selector}${p},`);return h=h.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),h=h.replace(Jf,""),h=h.replace(/\bdumpAnnotations\b(?=[^\n]*from 'document360-capture\/helpers')/,"captureShot"),/from 'document360-capture\/helpers'/.test(h)&&!/\bcaptureShot\b[^\n]*from 'document360-capture\/helpers'/.test(h)&&(h=h.replace(/import \{([^}]*)\} from 'document360-capture\/helpers'/,(b,$)=>`import {${$.replace(/\s*$/,"")}, captureShot } from 'document360-capture/helpers'`)),{next:h,selector:i.selector}}function om(e){try{return Ul(e).filter(t=>t.endsWith(".spec.ts")).some(t=>{try{let n=Hl(Ml(Fl(e,t),"utf8"));return n!==null&&!("unresolved"in n)}catch{return!1}})}catch{return!1}}function rm(e){let t=zf(e)?.captureDir??Kf;return Gf(t)?t:Yf(e,t)}function ql(e,t){let n={migrated:[],skipped:[]},o=rm(e);if(!qf(o))return n;let r=t?.captureVersion===void 0?$n():t.captureVersion;if(!Xf(r,_l))return om(o)?{...n,heldBackForCapture:{installed:r,required:_l}}:n;let s;try{s=Ul(o).filter(i=>i.endsWith(".spec.ts"))}catch{return n}for(let i of s.sort()){let c=i.slice(0,-8),p=Fl(o,i);try{let h=Ml(p,"utf8"),b=Hl(h);if(b===null)continue;if("unresolved"in b){n.skipped.push({id:c,receiver:b.unresolved});continue}Vf(p,b.next,"utf8"),n.migrated.push(c)}catch{}}return n}function Vl(e){if(e.heldBackForCapture){let{installed:n,required:o}=e.heldBackForCapture;return`\u26A0 Some capture specs need a fix that requires d360-capture ${o}+ (${n?`you have ${n}`:"not found on this machine"}). Until then their callouts may sit in the wrong place on cropped screenshots.
313
+ `+If[e.tone](Yn(Qs(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${Qn(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
314
+ `+(e.ok?se.magenta("\u2736 "):se.red("\u2736 "))+se.gray(`Cooked for ${Jn(e.seconds)} \xB7 ${Qn(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${De(e.costUsd)}`:""))}}}function El(e,t){return e.map(n=>Js(n,t)).join(`
315
+ `)}import{resolveActiveProfile as Of,loadTokens as Lf,isExpired as _f,decodeJwtClaims as Dl}from"document360-engine";function Mf(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ve(e,t){try{let n=Of(e,t),o=Lf(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(_f(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let i={...Dl(o.idToken)??{},...Dl(o.accessToken)??{}}.doc360_project_id;if(typeof i=="string"&&i&&i!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${Mf(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}import{existsSync as oi,readFileSync as ai}from"node:fs";import{isAbsolute as yr,join as wr,resolve as kr}from"node:path";import A from"picocolors";import fr from"string-width";import{readProjectConfig as vt,screenshotPlaceholderIds as Jl,DEFAULT_CAPTURE_DIR as br,DEFAULT_OUTPUT_DIR as ci,DEFAULT_DOCS_DIR as li,existingAnnotatedShotPath as am,resolveOutputDir as Zl,migrateShotLayout as cm,reviewIsCurrent as lm,shotImageMtimeMs as dm,RAW_SUBDIR as um,ANNOTATED_SUBDIR as pm}from"document360-engine";import{createHash as jl}from"node:crypto";import{readFileSync as Nl,writeFileSync as Uf}from"node:fs";import{join as Ff}from"node:path";import{captureStatePath as Il}from"document360-engine";var Al={version:1,shots:{}};function Ol(e){return jl("sha1").update(e).digest("hex").slice(0,12)}function ur(e){try{let t=JSON.parse(Nl(Ff(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]);if(!o)return null;let r=t.profiles?.[o],s=r?.scope??{},i=Object.keys(s).sort().map(c=>`${c}=${s[c]}`).join("&");return jl("sha1").update(`${o}|${r?.connection?.startUrl??""}|${i}`).digest("hex").slice(0,12)}catch{return null}}function at(e){try{let t=JSON.parse(Nl(Il(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...Al,shots:{}}:{version:1,shots:t.shots}}catch{return{...Al,shots:{}}}}function Wf(e,t){Uf(Il(e),`${JSON.stringify(t,null,2)}
316
+ `,"utf8")}function Zs(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function pr(e,t,n){if(t.length===0)return;let o=at(e),r=ur(e);for(let s of t){let i=s.specSource?Ol(s.specSource):void 0;o.shots[s.id]={outcome:s.outcome,at:n,...s.reason?{reason:s.reason}:{},...s.outcome==="skipped"?{blockedBy:Zs(s.reason)}:{},...i?{specHash:i}:{},...r?{envHash:r}:{}}}Wf(e,o)}function ei(e,t,n,o){let r=e.shots[t];return!r||n===null||!r.specHash||r.specHash!==Ol(n)||o&&r.envHash&&r.envHash!==o?null:r}function Ll(e){let t=at(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function ti(e,t,n){let o=ei(at(e),t,n,ur(e));return!o||o.outcome==="captured"||!o.reason?null:{outcome:o.outcome,reason:o.reason}}hr();import{existsSync as Gf,readFileSync as Fl,readdirSync as Wl,writeFileSync as Yf}from"node:fs";import{isAbsolute as zf,join as Bl,resolve as Kf}from"node:path";import{readProjectConfig as Xf,DEFAULT_CAPTURE_DIR as Qf}from"document360-engine";var Ul="0.2.25";function Jf(e,t){if(!e)return!1;let n=s=>s.split("-")[0].split(".").map(i=>Number.parseInt(i,10)||0),o=n(e),r=n(t);for(let s=0;s<Math.max(o.length,r.length);s++){let i=(o[s]??0)-(r[s]??0);if(i!==0)return i>0}return!0}var Zf=/^([ \t]*)await\s+([^\n;]+?)\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo\s*(?:,\s*fullPage:\s*(?:true|false)\s*)?,?\s*\}\)\s*;?[ \t]*$/m,em=/^[ \t]*await\s+dumpAnnotations\(\s*page\s*,\s*PLACEHOLDER\s*\)\s*;?[ \t]*\r?\n?/m,Hl="(?:'([^']+)'|\"([^\"]+)\"|`([^`]+)`)",tm=new RegExp(`^page\\s*\\.\\s*locator\\(\\s*${Hl}\\s*\\)$`),ql=e=>e[1]??e[2]??e[3]??null,nm=/^[A-Za-z_$][\w$]*$/;function om(e,t){let o=new RegExp(`\\bconst\\s+${t}\\s*=\\s*page\\s*\\.\\s*locator\\(\\s*${Hl}\\s*\\)\\s*;`).exec(e);return o?ql(o):null}function rm(e,t){let n=t.trim();if(n==="page")return null;let o=tm.exec(n);if(o){let r=ql(o);return r?{selector:r}:{unresolved:!0}}if(nm.test(n)){let r=om(e,n);return r?{selector:r}:{unresolved:!0}}return{unresolved:!0}}function Vl(e){if(/\bcaptureShot\s*\(/.test(e))return null;let t=(e.match(/\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo/g)??[]).length;if(t>1)return{unresolved:`${t} conditional capture calls`};let n=Zf.exec(e);if(!n)return null;let[o,r="",s=""]=n,i=rm(e,s);if(i===null)return null;if("unresolved"in i)return{unresolved:s.trim()};let c=/^([ \t]*)saveTo:\s*.+,[ \t]*$/m.exec(e);if(!c)return null;let p=i.selector.includes("'")?'"':"'",h=e.replace(c[0],`${c[0]}
317
+ ${c[1]??" "}clipTo: ${p}${i.selector}${p},`);return h=h.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),h=h.replace(em,""),h=h.replace(/\bdumpAnnotations\b(?=[^\n]*from 'document360-capture\/helpers')/,"captureShot"),/from 'document360-capture\/helpers'/.test(h)&&!/\bcaptureShot\b[^\n]*from 'document360-capture\/helpers'/.test(h)&&(h=h.replace(/import \{([^}]*)\} from 'document360-capture\/helpers'/,(b,$)=>`import {${$.replace(/\s*$/,"")}, captureShot } from 'document360-capture/helpers'`)),{next:h,selector:i.selector}}function sm(e){try{return Wl(e).filter(t=>t.endsWith(".spec.ts")).some(t=>{try{let n=Vl(Fl(Bl(e,t),"utf8"));return n!==null&&!("unresolved"in n)}catch{return!1}})}catch{return!1}}function im(e){let t=Xf(e)?.captureDir??Qf;return zf(t)?t:Kf(e,t)}function Gl(e,t){let n={migrated:[],skipped:[]},o=im(e);if(!Gf(o))return n;let r=t?.captureVersion===void 0?$n():t.captureVersion;if(!Jf(r,Ul))return sm(o)?{...n,heldBackForCapture:{installed:r,required:Ul}}:n;let s;try{s=Wl(o).filter(i=>i.endsWith(".spec.ts"))}catch{return n}for(let i of s.sort()){let c=i.slice(0,-8),p=Bl(o,i);try{let h=Fl(p,"utf8"),b=Vl(h);if(b===null)continue;if("unresolved"in b){n.skipped.push({id:c,receiver:b.unresolved});continue}Yf(p,b.next,"utf8"),n.migrated.push(c)}catch{}}return n}function Yl(e){if(e.heldBackForCapture){let{installed:n,required:o}=e.heldBackForCapture;return`\u26A0 Some capture specs need a fix that requires d360-capture ${o}+ (${n?`you have ${n}`:"not found on this machine"}). Until then their callouts may sit in the wrong place on cropped screenshots.
318
318
  Run /update to bring the whole toolchain up, then /screenshot again.`}if(e.migrated.length===0&&e.skipped.length===0)return null;let t=[];return e.migrated.length>0&&t.push(`\u2195 Fixed ${e.migrated.length} capture spec${e.migrated.length===1?"":"s"} that cropped the screenshot without telling the annotator \u2014 their callouts were landing outside the image. Re-capture to pick up the fix.`),e.skipped.length>0&&t.push(`\u26A0 ${e.skipped.length} spec${e.skipped.length===1?"":"s"} crop${e.skipped.length===1?"s":""} to something that needs a human eye (${e.skipped.slice(0,3).map(n=>n.id).join(", ")}${e.skipped.length>3?"\u2026":""}) \u2014 /screenshot verify flags them if their callouts are off.`),t.join(`
319
- `)}var Jl=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Gl(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?Jl(n):void 0,...t?{detail:!0}:{}}}function Zn(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="verify"||t==="review")return{mode:"verify",rest:e.slice(1)};if(t==="checklist"||t==="setup")return{mode:"checklist"};if(t==="list")return Gl(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 Gl(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:Jl(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function $e(e,t){let n=vt(e),o=n?.captureDir??br,r=n?.outputDir??ci,s=(p,h)=>yr(p)?wr(p,h):kr(e,p,h),i=at(e),c=ur(e);return Xl(e,{scope:t}).map(({id:p,file:h})=>{let b=s(o,`${p}.spec.ts`),$=null;if(oi(b))try{$=ai(b,"utf8")}catch{}let v=Ql(e,r),E=oi(sm(v,p)),R=$===null?null:ei(i,p,$,c),x=i.shots[p]?.review,T=E&&am(x,cm(v,p))?x:void 0,F=$!==null&&hm($),G=E&&T?.verdict==="ok"?"verified":E&&T?.verdict==="rejected"?"rejected":E?"captured":$===null?"placeholder":F||R?.outcome==="skipped"?"blocked":R?.outcome==="failed"?"broken":"spec",q=$===null?void 0:ed($),Y=F?fm($):R?.reason,pe=F?"testid":R?.outcome==="skipped"?Zs(R.reason):void 0;return{id:p,file:h,state:G,...q?{mutates:q.mutates,...q.declared?{}:{undeclared:!0}}:{},...$!==null&&zl($).length>0?{unguardedWaits:zl($)}:{},...$!==null&&Yl($).length>0?{unverifiedForce:Yl($)}:{},...G==="blocked"||G==="broken"?{...Y?{reason:Y}:{},...pe?{blockedBy:pe}:{}}:{},...G==="rejected"?{...T?.reason?{reason:T.reason}:{},...T?.repaired?{repaired:!0}:{}}:{}}})}function um(e){let t=vt(e)?.outputDir??ci;return im(Ql(e,t))}function eo(e){let t=um(e),n=vt(e)?.outputDir??ci,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${lm},${dm}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=Vl(ql(e));return r&&o.push(r),o.length>0?o.join(`
320
- `):null}function vn(e,t){let n=vt(e)?.captureDir??br,o=yr(n)?wr(n,`${t}.spec.ts`):kr(e,n,`${t}.spec.ts`);try{return ai(o,"utf8")}catch{return null}}function Zl(e,t){let n=vt(e)?.captureDir??br;return oi(yr(n)?wr(n,`${t}.spec.ts`):kr(e,n,`${t}.spec.ts`))}function pm(e,t,n){let o=[n.trim()];for(let r=t+1;r<e.length;r++){let s=/^\s*\/\/\s?(.*)$/.exec(e[r]);if(!s)break;let i=s[1].trim();if(!i||/^(CAPTURE-[A-Z]+:|TODO\b|NOTE\b|Grounding\b|\d+\.\s)/.test(i)||(o.push(i),o.join(" ").length>400))break}return o.join(" ")}function ed(e){let t=e.split(/\r?\n/),n=t.findIndex(c=>/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b/i.test(c)),o=n>=0?/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/i.exec(t[n]):null;if(o){let c=pm(t,n,o[2]??"");return{mutates:o[1].toLowerCase()==="mutates",declared:!0,what:c||void 0}}let r=/setInputFiles/.test(e),s=/\{\s*name:\s*['"][^'"]*\b(create|import|save|apply|confirm|delete|submit|send|mint)\b[^'"]*['"][^}]*\}\s*\)\s*\.click\(/i.test(e),i=/\.fill\(/.test(e);return{mutates:r||i&&s,declared:!1}}function hm(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function fm(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 td(e){return e.split(/\r?\n/).map(t=>{if(/^\s*\*/.test(t))return"";let n=/(?<!:)\/\//.exec(t);return n?t.slice(0,n.index):t})}function Yl(e,t=10){let n=td(e),o=[];for(let[r,s]of n.entries())/\.click\s*\([^)]*force\s*:\s*true/.test(s)&&(/test\.skip\s*\(/.test(n.slice(r+1,r+1+t).join(`
321
- `))||o.push(r+1));return o}function zl(e){let t=[],n=td(e);for(let[o,r]of n.entries()){if(!/\.waitFor\s*\(/.test(r))continue;let s=r;for(let i=o+1;i<n.length&&!/;\s*$/.test(s.trim())&&i<o+4;i++)s+=n[i];/\.catch\s*\(/.test(s)||t.push(o+1)}return t}function nd(e){return(e??"").trim().replace(/[.\s]+$/,"")}function od(e,t){let n=vt(e)?.captureDir??br,o=yr(n)?wr(n,`${t}.spec.ts`):kr(e,n,`${t}.spec.ts`);try{return ed(ai(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var mm=["captured","verified","rejected"],gm=e=>mm.includes(e);function $r(e){return[...new Set(e.filter(t=>gm(t.state)).map(t=>t.file))].sort()}function vr(e){let t=e.filter(o=>o.state==="rejected");if(t.length===0)return null;let n=Math.max(...t.map(o=>o.id.length));return[`${ye("\u26A0",D.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${D.magenta(o.id.padEnd(n))} ${D.gray(xn(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${D.bold("/screenshot capture --failed")}`].join(`
322
- `)}var ym={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",verified:"\u2714",rejected:"\u2691"},wm={placeholder:D.gray,spec:D.yellow,blocked:D.cyan,broken:D.red,captured:D.blue,verified:D.green,rejected:D.magenta},rd=` ${D.green("\u2714 verified")} ${D.blue("\u25CF to verify")} ${D.yellow("\u25D0 ready")} ${D.magenta("\u2691 rejected")} ${D.cyan("\u2298 blocked")} ${D.red("\u2717 broken")} ${D.gray("\u25CB to spec")}`;function ye(e,t=n=>n){return`${t(e)} `}function xn(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function xr(e){let t=xn(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function to(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=xr(o),i=`${r} ${s.toLowerCase()}`,c=t.get(i)??{reason:s,blockedBy:r,ids:[]};t.has(i)||t.set(i,c),c.ids.push(n.id)}return[...t.values()].sort((n,o)=>o.ids.length-n.ids.length||n.reason.localeCompare(o.reason))}function sd(e){let t=to(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((c,p)=>c+p.ids.length,0);r.push(` ${D.bold("Stage this data")} ${D.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let i=8;for(let c of n.slice(0,i)){let p=Wt(c.reason,86);r.push(` ${D.cyan($t(`${c.ids.length}\xD7`,4))} ${p[0]??""}`);for(let b of p.slice(1))r.push(` ${b}`);let h=c.ids.slice(0,4).join(" \xB7 ");r.push(D.gray(` ${h}${c.ids.length>4?` \xB7 +${c.ids.length-4} more`:""}`))}n.length>i&&r.push(D.gray(` \u2026 ${n.length-i} more staging action${n.length-i===1?"":"s"} \u2014 /screenshot list --detail`))}if(o.length>0){let s=o.reduce((i,c)=>i+c.ids.length,0);r.push(` ${ye("\u2298",D.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${D.bold("/screenshot checklist")} builds the hand-off.`)}return r}function id(e,t){let n=e.filter(i=>(i.unguardedWaits?.length??0)>0),o=e.filter(i=>i.undeclared);if(n.length===0&&o.length===0)return[];let r=["",` ${ye("\u26A0",D.yellow)}Some specs were written before later reliability fixes:`],s=(i,c)=>` ${i.slice(0,8).map(c).join(" \xB7 ")}${i.length>8?` \xB7 +${i.length-8} more`:""}`;if(n.length>0){let i=n.length;r.push(D.gray(` ${i} crash${i===1?"es":""} instead of telling you what to stage when the data ${i===1?"it needs":"they need"} is missing`)),t&&r.push(D.gray(s(n,c=>`${c.id}:${c.unguardedWaits.join(",")}`)))}if(o.length>0){let i=o.length,c=o.filter(p=>p.mutates).length;r.push(D.gray(` ${i} do${i===1?"es":""} not say whether ${i===1?"it changes":"they change"} data in your app`+(c>0?`, so ${c===1?"one is":`${c} are`} left out of bulk runs to be safe`:""))),t&&r.push(D.gray(s(o,p=>p.id)))}return r.push(D.gray(` Re-write them all with the current rules: ${D.bold("/screenshot author --all")}`)),r}function ad(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${ye("\u26A0",D.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+D.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),D.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),D.gray(` Re-author to check what the click did: ${D.bold("/screenshot author <id>")}`)]}var mr=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),$t=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function cd(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 km=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),bm=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function $m(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return bm.has(r)?r.toUpperCase():o>0&&km.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function ri(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:$m(t?t[2]:e)}}function vm(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function Kl(e,t,n){let o=t>0?Math.round(e/t*n):0;return D.green("\u2588".repeat(o))+D.gray("\u2591".repeat(Math.max(0,n-o)))}function xm(e,t){let n=t>0?Math.round(e/t*100):0,o=$t(`${n}%`,4);return n===100?D.green(o):n>0?D.yellow(o):D.gray(o)}function ld(e,t){let n=new Map;for(let o of e){let r=cd(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 Cm(e,t){let n=(J,re)=>J.filter(le=>le.state===re).length,o=e.length,r=n(e,"verified"),s=n(e,"captured"),i=n(e,"rejected"),c=n(e,"spec"),p=n(e,"blocked"),h=n(e,"broken"),b=n(e,"placeholder"),$=new Set(e.map(J=>J.file)).size,v=ld(e,t),E=[];E.push(` ${D.bold("Screenshots")} ${D.green(`${r}/${o} verified`)} ${D.gray("\xB7")} ${s>0?D.blue(`${s} to verify`):D.gray("0 to verify")}`+(i>0?` ${D.gray("\xB7")} ${D.magenta(`${i} rejected`)}`:"")+` ${D.gray("\xB7")} ${c>0?D.yellow(`${c} ready`):D.gray("0 ready")}`+(p>0?` ${D.gray("\xB7")} ${D.cyan(`${p} blocked`)}`:"")+(h>0?` ${D.gray("\xB7")} ${D.red(`${h} broken`)}`:"")+` ${D.gray("\xB7")} ${b>0?D.red(`${b} to spec`):D.gray("0 to spec")} `+D.gray(`across ${$} article${$===1?"":"s"}`));let R=o>0?Math.round(r/o*100):0;E.push(` [${Kl(r,o,32)}] ${D.bold(`${R}%`)}`),E.push("");let x=v.map(([J])=>ri(J)),T=Math.min(32,Math.max(7,...x.map(J=>J.name.length))),F=J=>J.length>T?`${J.slice(0,T-1)}\u2026`:mr(J,T),G=[...s>0?[{head:"To verify",w:9,state:"captured",color:D.blue}]:[],...i>0?[{head:"Rejected",w:8,state:"rejected",color:D.magenta}]:[],{head:"Ready",w:5,state:"spec",color:D.yellow},...p>0?[{head:"Blocked",w:7,state:"blocked",color:D.cyan}]:[],...h>0?[{head:"Broken",w:6,state:"broken",color:D.red}]:[],{head:"To spec",w:7,state:"placeholder",color:D.red}];E.push(D.gray(` ${mr("#",2)} ${mr("Chapter",T)} ${$t("Verified",8)} ${G.map(J=>$t(J.head,J.w)).join(" ")} Progress`));for(let[J,[,re]]of v.entries()){let le=n(re,"verified"),ae=re.length,{num:Ze,name:Ue}=x[J],ze=le===ae,lt=F(Ue),Pt=G.map(dt=>{let Yt=n(re,dt.state);return Yt>0?dt.color($t(String(Yt),dt.w)):D.gray($t("\u2014",dt.w))}).join(" ");E.push(` ${D.cyan(mr(Ze,2))} ${ze?D.green(lt):le>0?lt:D.gray(lt)} ${ze?D.green($t(`${le}/${ae}`,8)):$t(`${le}/${ae}`,8)} ${Pt} ${Kl(le,ae,10)} ${xm(le,ae)}`)}E.push("");let q=h>0?` ${D.gray("\xB7")} ${h} spec${h===1?"":"s"} broken \u2014 ${D.bold(`/screenshot ${e.find(J=>J.state==="broken").id}`)} re-authors ${h===1?"it":"the first"}`:"",Y=e.filter(J=>J.state==="spec"&&J.mutates).length,pe=c>Y;if(b>0)E.push(` ${ye("\u2192",D.yellow)}${b} placeholder${b===1?"":"s"} still need a spec \u2014 run ${D.bold("/screenshot author --all")}${q}`);else if(c>0&&(pe||s===0)){let J=Y>0?D.gray(` \u2014 ${c-Y} in one go; ${Y} write${Y===1?"s":""} real data and run${Y===1?"s":""} one at a time`):"";E.push(` ${ye("\u2192",D.yellow)}${c} spec${c===1?"":"s"} ready to capture \u2014 run ${D.bold("/screenshot capture")}${J}${q}`)}else if(s>0&&c>0)E.push(` ${ye("\u2192",D.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${D.bold("/screenshot verify")}`+D.gray(" \u2014 no browser needed")+D.gray(` \xB7 ${c} ready spec${c===1?"":"s"} write real data, so ${c===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+q);else if(p>0)E.push(` ${ye("\u2192",D.cyan)}${p} shot${p===1?"":"s"} blocked \u2014 stage the data below, then ${D.bold("/screenshot capture --blocked")}${q}`);else if(h>0)E.push(` ${ye("\u2192",D.red)}${h} spec${h===1?"":"s"} broken \u2014 ${D.bold(`/screenshot ${e.find(J=>J.state==="broken").id}`)} re-authors ${h===1?"it":"the first"} (re-capturing fails the same way)`);else if(s>0)E.push(` ${ye("\u2192",D.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${D.bold("/screenshot verify")}`+D.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(i>0){let J=e.filter(re=>re.state==="rejected"&&re.repaired).length;E.push(` ${ye("\u2691",D.magenta)}${i} shot${i===1?"":"s"} failed review \u2014 `+(J>0?`${J} spec${J===1?"":"s"} already repaired; re-capture with ${D.bold("/screenshot capture --failed")}`:`see the reasons below, then ${D.bold("/screenshot capture --failed")}`))}else E.push(` ${ye("\u2713",D.green)}all ${o} verified \u2014 ${D.bold("/publish")} embeds them in the articles`);if(r>0&&r<o){let J=v.filter(([,re])=>re.every(le=>le.state!=="verified")).map(([re])=>{let{num:le,name:ae}=ri(re);return le?`${le} ${ae}`:ae});J.length>0&&E.push(D.gray(` Furthest behind: ${J.slice(0,5).join(" \xB7 ")}${J.length>5?" \u2026":""} (0% verified)`))}return E.push(...sd(e),...ad(e),...id(e,!1)),E.push(""),E.push(rd),E.push(D.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),E}function Rm(e,t,n){let o=new Set(e.map(c=>c.file)),r=e.filter(c=>c.state==="verified").length,s=e.filter(c=>c.state==="captured").length,i=[` ${D.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${D.green(`${r} verified`)}${s>0?D.blue(` \xB7 ${s} to verify`):""}${n?D.gray(` \xB7 scope ${n}`):""}`,""];for(let[c,p]of ld(e,t)){let h=p.filter(R=>R.state==="verified").length,{num:b,name:$}=ri(c),v=b?`${b} \xB7 ${$}`:$;i.push(` ${D.bold(v)} ${D.gray(`(${h}/${p.length})`)}`);let E=new Map;for(let R of p){let x=vm(R.file),T=E.get(x)??[];E.has(x)||E.set(x,T),T.push(R)}for(let R of[...E.keys()].sort()){i.push(D.gray(` ${R}`));for(let x of E.get(R)){let T=wm[x.state];if(i.push(` ${ye(ym[x.state],T)}${T(x.id)}`),(x.state==="blocked"||x.state==="broken"||x.state==="rejected")&&x.reason){for(let F of Wt(xn(x.reason),84))i.push(D.gray(` ${F}`));x.state==="rejected"&&i.push(D.gray(` ${x.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return i.push(...sd(e),...ad(e),...id(e,!0)),i.push("",rd),i}function Cr(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??li;return t?.detail||n?Rm(e,o,n):Cm(e,o)}function di(e,t){if(!t||!/^\d+$/.test(t))return t;let n=vt(e)?.docsDir??li,o=String(Number(t));for(let{file:r}of Xl(e)){let s=cd(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function dd(e,t){let r=e.map(c=>" ".repeat(c.depth)+c.label),s=Math.max(0,...e.map((c,p)=>c.note?fr(r[p]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((c,p)=>{let h=r[p];if(!c.note)return{head:h,note:""};let b=Math.max(2,i+2-fr(h)),$=c.note.trim(),v=t-fr(h)-b;return{head:h+" ".repeat(b),note:v>1&&fr($)>v?`${$.slice(0,v-1)}\u2026`:$}})}function Sm(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function gr(e,t,n){let o=new Map;for(let s of t){let{category:i,article:c}=Sm(s.file),p=o.get(i)??new Map;o.set(i,p);let h=p.get(c)??[];p.set(c,h),h.push(s)}let r=s=>n==="author"||!s.mutates;for(let s of[...o.keys()].sort()){let i=o.get(s),c=[...i.values()].flat().filter(r).map(h=>h.id),p=c.length>0;p&&e.push({kind:"category",action:n,label:`${s} (${c.length})`,ids:c,depth:1});for(let h of[...i.keys()].sort()){let b=i.get(h),$=b.filter(r).map(R=>R.id),v=$.length>0;v&&e.push({kind:"article",action:n,label:`${h} (${$.length})`,ids:$,depth:p?2:1});let E=(p?1:0)+(v?1:0)+1;for(let R of b){let x=n==="capture"&&R.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:R.id,ids:[R.id],depth:E,...x?{note:x}:{}})}}}}function ni(e){return e?xn(e):""}function ui(e,t,n,o=[]){let r=t.filter(i=>!i.mutates);r.length>1&&e.push({kind:"all",action:"capture",label:`Retry ${r.length} blocked shots (Prerequisites not met \u2014 Stage the data first)`,ids:r.map(i=>i.id),depth:0});for(let i of[...t].sort((c,p)=>c.id.localeCompare(p.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${ni(i.reason)}`});n.length>1&&e.push({kind:"all",action:"author",label:`Re-author ${n.length} broken specs`,ids:n.map(i=>i.id),depth:0});for(let i of[...n].sort((c,p)=>c.id.localeCompare(p.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${ni(i.reason)}`});let s=o.filter(i=>!i.mutates);s.length>1&&e.push({kind:"all",action:"capture",label:`Re-capture ${s.length} shots that failed review`,ids:s.map(i=>i.id),depth:0});for(let i of[...o].sort((c,p)=>c.id.localeCompare(p.id))){let c=i.repaired?"re-captures":"re-captures (spec not yet repaired)";e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2691 ${c} \u2014 ${ni(i.reason)}`})}}function ud(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}),gr(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}),gr(o,n,"capture"),ui(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected")),o}var si=["MANDATORY \u2014 a missing prerequisite must SKIP, never time out. Two rules, applied to EVERY locator","in the spec, not just the first one or the one shown in the skill's example:","1. A bare `await x.waitFor(...)` is itself the bug: on a missing element it THROWS and the run"," reports a hard failure with a stack trace instead of a staging instruction. Every wait must be",' `await x.waitFor({ state: "visible", timeout: 10_000 }).catch(() => {});` followed by',' `if ((await x.count()) === 0) test.skip(true, "Prerequisite not met: \u2026")`. That applies to each'," element you wait on or click IN TURN \u2014 tabs, toggles, rows, buttons reached after the first"," guard \u2014 because any of them can be absent for the same reason the data is."," And guard on the SAME predicate the action needs: `.click()` requires visible AND ENABLED, so a",' DISABLED button passes both waitFor({state:"visible"}) and count()>0 and then times out at 15s'," (measured). Add `|| !(await x.isEnabled().catch(() => false))` to the condition, and put the"," control's own title/aria-disabled text in the skip reason \u2014 a disabled control is the product"," telling you the prerequisite is unmet, usually with the reason attached.",' And when a wait DOES time out, diagnose before you guard: a skip asserts "your app lacks this',' data", so if the real cause is a locator matching a node you did not intend (a rollup row, a'," sibling with the same testid), that assertion is a lie and sends the user to stage what they"," already have. Narrow the selector first, THEN guard."," Two corollaries, both of which have cost a wasted repair round:"," (a) An element that is not RENDERED is not absent. A collapsed tree node, an unopened accordion,"," an inactive tab, a virtualised list or page 2 of a table keeps its children out of the DOM."," EXPAND/scroll/switch to reach the target \u2014 that is a step to script, not data to stage."," (b) When you narrow past a decoy, count the UNNARROWED set too and put the number in the reason:",' "Found 6 folder roll-ups but no endpoint-level score \u2014 if one exists it may not be rendered".',' A bare "prerequisite not met" cannot tell absent data from an over-narrow selector. Put that'," evidence in a LATER sentence, never the first: grouping keys on the first sentence, so an",' interpolated count there makes every run its own "action" and the dedup stops working.'," (c) `click({ force: true })` is the ONE pattern that turns a failure into a silent WRONG"," SCREENSHOT rather than a crash or skip: it skips the actionability checks, so a click that"," lands on nothing photographs the unchanged screen and that image ships in the docs. It is"," sometimes right (a button nested inside a button reads as intercepted by its own ancestor)."," Never force blind: ground it in source, scrollIntoViewIfNeeded() first, and ASSERT THE"," CONSEQUENCE immediately after with a guarded wait + test.skip, so a no-op force skips."," Know its limit: force skips the CHECK but still hit-tests real screen coordinates, so the"," element that RECEIVES the event may not be the one your locator names (measured: a forced"," click on a pill nested in its section-header button never ran the pill's own handler).",' For a genuinely nested interactive node use `locator.dispatchEvent("click")`, which goes'," straight to that node with no hit-test \u2014 and still assert the consequence."," (d) Never bind a locator to an attribute your own interaction CHANGES. A locator is re-evaluated",' on every use, so `button[title="Multi-select scenarios"]` matches nothing once the click',' flips it to `title="Exit select mode"` \u2014 a 15s "not found" timeout on an element that is'," right there (measured). Toggling labels are normal (Play/Pause, Expand/Collapse, Select"," all/Deselect all): if the attribute is a ternary on state it is not an identity. Match both"," values in one locator, or use a testid."," (e) Cleanup after the screenshot is BEST-EFFORT and must never throw or test.skip. Anything"," after page.screenshot()/dumpAnnotations() runs with the image already on disk, so a throw"," there turns a successful capture into a reported failure and the shot is thrown away"," (measured: a valid .raw.png plus annotations, reported broken). Guard with isVisible()/"," isEnabled() and click best-effort \u2014 by then there is nothing left to skip.","2. Never reason about whether a role/text locator is unique; you cannot verify that by reading"," source, and Playwright fails the whole spec on 2+ matches. Every `getByRole`/`getByText`/"," `:has-text` without a unique data-testid gets `.first()` or a container scope"," (`page.locator('[data-testid=\"\u2026\"]').getByRole(\u2026)`). If you catch yourself writing a comment"," ARGUING a selector is unique, scope it instead \u2014 that argument is what fails.","3. Every skip reason opens with the SHARED staging action, worded identically across every shot",' that needs the same thing, naming where in the product to do it ("Create an API key in Settings',' \u2192 API Keys."); shot-specific detail (counts, which record, which state) goes in LATER sentences.'," The dashboard groups blocked shots by that first sentence, so a near-duplicate wording splits one"," chore into two. Grep sibling specs and reuse their exact opening sentence.","Before you finish, re-read each spec you wrote and check all three rules line by line."].join(`
323
- `);function Pm(e){return e.outcome==="failed"?["REPAIR \u2014 the existing spec FAILED its last capture with:",e.reason,'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."]:["REPAIR \u2014 the existing spec SKIPPED its last capture with:",e.reason,"You are being asked to re-author a shot that SKIPPED, and that is itself the signal: the normal","response to a blocked shot is to STAGE the data, not to rewrite the spec. So treat that reason as","SUSPECT \u2014 assume it is a FALSE skip until you have proved otherwise. Two things make a guard report",'"not staged" when the data exists:',"1. THE TARGET IS NOT RENDERED. Trace the path from the entry point to the element you finally need"," and confirm every intermediate container is OPENED. A collapsed tree node, an unopened accordion,"," an inactive tab, a virtualised list or page 2 of a table keeps its children out of the DOM, so the"," count is zero and the skip fires \u2014 for data sitting one click away. Expanding is a step to SCRIPT.","2. THE SELECTOR IS TOO NARROW. If you filtered past a decoy, count the UNNARROWED set and put the",' number in the reason ("Found 6 folder roll-ups but no endpoint-level score"), so the next reader'," can tell absent data from an over-narrow selector without opening the app.","A spec that satisfies every rule in this skill and still cannot reach its target is NOT correct.",'"No changes needed" is earned by tracing reachability end to end \u2014 not by checking conformance.']}var ii="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 pd(e,t){let n=e.paths,o=n.filter(i=>t?.get(i)?.outcome==="failed"),r=n.filter(i=>t?.get(i)?.outcome==="skipped"),s=i=>`- ${i}: ${t.get(i).reason.replace(/\s+/g," ").trim()}`;return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(i=>`- ${i}`).join(`
319
+ `)}var ed=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function zl(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?ed(n):void 0,...t?{detail:!0}:{}}}function Zn(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="verify"||t==="review")return{mode:"verify",rest:e.slice(1)};if(t==="checklist"||t==="setup")return{mode:"checklist"};if(t==="list")return zl(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 zl(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:ed(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function ve(e,t){let n=vt(e),o=n?.captureDir??br,r=n?.outputDir??ci,s=(p,h)=>yr(p)?wr(p,h):kr(e,p,h),i=at(e),c=ur(e);return Jl(e,{scope:t}).map(({id:p,file:h})=>{let b=s(o,`${p}.spec.ts`),$=null;if(oi(b))try{$=ai(b,"utf8")}catch{}let v=Zl(e,r),E=oi(am(v,p)),R=$===null?null:ei(i,p,$,c),C=i.shots[p]?.review,P=E&&lm(C,dm(v,p))?C:void 0,I=$!==null&&mm($),G=E&&P?.verdict==="ok"?"verified":E&&P?.verdict==="rejected"?"rejected":E?"captured":$===null?"placeholder":I||R?.outcome==="skipped"?"blocked":R?.outcome==="failed"?"broken":"spec",q=$===null?void 0:nd($),Y=I?gm($):R?.reason,he=I?"testid":R?.outcome==="skipped"?Zs(R.reason):void 0;return{id:p,file:h,state:G,...q?{mutates:q.mutates,...q.declared?{}:{undeclared:!0}}:{},...$!==null&&Xl($).length>0?{unguardedWaits:Xl($)}:{},...$!==null&&Kl($).length>0?{unverifiedForce:Kl($)}:{},...G==="blocked"||G==="broken"?{...Y?{reason:Y}:{},...he?{blockedBy:he}:{}}:{},...G==="rejected"?{...P?.reason?{reason:P.reason}:{},...P?.repaired?{repaired:!0}:{}}:{}}})}function hm(e){let t=vt(e)?.outputDir??ci;return cm(Zl(e,t))}function eo(e){let t=hm(e),n=vt(e)?.outputDir??ci,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${um},${pm}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=Yl(Gl(e));return r&&o.push(r),o.length>0?o.join(`
320
+ `):null}function vn(e,t){let n=vt(e)?.captureDir??br,o=yr(n)?wr(n,`${t}.spec.ts`):kr(e,n,`${t}.spec.ts`);try{return ai(o,"utf8")}catch{return null}}function td(e,t){let n=vt(e)?.captureDir??br;return oi(yr(n)?wr(n,`${t}.spec.ts`):kr(e,n,`${t}.spec.ts`))}function fm(e,t,n){let o=[n.trim()];for(let r=t+1;r<e.length;r++){let s=/^\s*\/\/\s?(.*)$/.exec(e[r]);if(!s)break;let i=s[1].trim();if(!i||/^(CAPTURE-[A-Z]+:|TODO\b|NOTE\b|Grounding\b|\d+\.\s)/.test(i)||(o.push(i),o.join(" ").length>400))break}return o.join(" ")}function nd(e){let t=e.split(/\r?\n/),n=t.findIndex(c=>/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b/i.test(c)),o=n>=0?/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/i.exec(t[n]):null;if(o){let c=fm(t,n,o[2]??"");return{mutates:o[1].toLowerCase()==="mutates",declared:!0,what:c||void 0}}let r=/setInputFiles/.test(e),s=/\{\s*name:\s*['"][^'"]*\b(create|import|save|apply|confirm|delete|submit|send|mint)\b[^'"]*['"][^}]*\}\s*\)\s*\.click\(/i.test(e),i=/\.fill\(/.test(e);return{mutates:r||i&&s,declared:!1}}function mm(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function gm(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 od(e){return e.split(/\r?\n/).map(t=>{if(/^\s*\*/.test(t))return"";let n=/(?<!:)\/\//.exec(t);return n?t.slice(0,n.index):t})}function Kl(e,t=10){let n=od(e),o=[];for(let[r,s]of n.entries())/\.click\s*\([^)]*force\s*:\s*true/.test(s)&&(/test\.skip\s*\(/.test(n.slice(r+1,r+1+t).join(`
321
+ `))||o.push(r+1));return o}function Xl(e){let t=[],n=od(e);for(let[o,r]of n.entries()){if(!/\.waitFor\s*\(/.test(r))continue;let s=r;for(let i=o+1;i<n.length&&!/;\s*$/.test(s.trim())&&i<o+4;i++)s+=n[i];/\.catch\s*\(/.test(s)||t.push(o+1)}return t}function rd(e){return(e??"").trim().replace(/[.\s]+$/,"")}function sd(e,t){let n=vt(e)?.captureDir??br,o=yr(n)?wr(n,`${t}.spec.ts`):kr(e,n,`${t}.spec.ts`);try{return nd(ai(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var ym=["captured","verified","rejected"],wm=e=>ym.includes(e);function $r(e){return[...new Set(e.filter(t=>wm(t.state)).map(t=>t.file))].sort()}function vr(e){let t=e.filter(o=>o.state==="rejected");if(t.length===0)return null;let n=Math.max(...t.map(o=>o.id.length));return[`${we("\u26A0",A.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${A.magenta(o.id.padEnd(n))} ${A.gray(xn(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${A.bold("/screenshot capture --failed")}`].join(`
322
+ `)}var km={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",verified:"\u2714",rejected:"\u2691"},bm={placeholder:A.gray,spec:A.yellow,blocked:A.cyan,broken:A.red,captured:A.blue,verified:A.green,rejected:A.magenta},id=` ${A.green("\u2714 verified")} ${A.blue("\u25CF to verify")} ${A.yellow("\u25D0 ready")} ${A.magenta("\u2691 rejected")} ${A.cyan("\u2298 blocked")} ${A.red("\u2717 broken")} ${A.gray("\u25CB to spec")}`;function we(e,t=n=>n){return`${t(e)} `}function xn(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function xr(e){let t=xn(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function to(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=xr(o),i=`${r} ${s.toLowerCase()}`,c=t.get(i)??{reason:s,blockedBy:r,ids:[]};t.has(i)||t.set(i,c),c.ids.push(n.id)}return[...t.values()].sort((n,o)=>o.ids.length-n.ids.length||n.reason.localeCompare(o.reason))}function ad(e){let t=to(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((c,p)=>c+p.ids.length,0);r.push(` ${A.bold("Stage this data")} ${A.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let i=8;for(let c of n.slice(0,i)){let p=Wt(c.reason,86);r.push(` ${A.cyan($t(`${c.ids.length}\xD7`,4))} ${p[0]??""}`);for(let b of p.slice(1))r.push(` ${b}`);let h=c.ids.slice(0,4).join(" \xB7 ");r.push(A.gray(` ${h}${c.ids.length>4?` \xB7 +${c.ids.length-4} more`:""}`))}n.length>i&&r.push(A.gray(` \u2026 ${n.length-i} more staging action${n.length-i===1?"":"s"} \u2014 /screenshot list --detail`))}if(o.length>0){let s=o.reduce((i,c)=>i+c.ids.length,0);r.push(` ${we("\u2298",A.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${A.bold("/screenshot checklist")} builds the hand-off.`)}return r}function cd(e,t){let n=e.filter(i=>(i.unguardedWaits?.length??0)>0),o=e.filter(i=>i.undeclared);if(n.length===0&&o.length===0)return[];let r=["",` ${we("\u26A0",A.yellow)}Some specs were written before later reliability fixes:`],s=(i,c)=>` ${i.slice(0,8).map(c).join(" \xB7 ")}${i.length>8?` \xB7 +${i.length-8} more`:""}`;if(n.length>0){let i=n.length;r.push(A.gray(` ${i} crash${i===1?"es":""} instead of telling you what to stage when the data ${i===1?"it needs":"they need"} is missing`)),t&&r.push(A.gray(s(n,c=>`${c.id}:${c.unguardedWaits.join(",")}`)))}if(o.length>0){let i=o.length,c=o.filter(p=>p.mutates).length;r.push(A.gray(` ${i} do${i===1?"es":""} not say whether ${i===1?"it changes":"they change"} data in your app`+(c>0?`, so ${c===1?"one is":`${c} are`} left out of bulk runs to be safe`:""))),t&&r.push(A.gray(s(o,p=>p.id)))}return r.push(A.gray(` Re-write them all with the current rules: ${A.bold("/screenshot author --all")}`)),r}function ld(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${we("\u26A0",A.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+A.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),A.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),A.gray(` Re-author to check what the click did: ${A.bold("/screenshot author <id>")}`)]}var mr=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),$t=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function dd(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 $m=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),vm=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function xm(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return vm.has(r)?r.toUpperCase():o>0&&$m.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function ri(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:xm(t?t[2]:e)}}function Cm(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function Ql(e,t,n){let o=t>0?Math.round(e/t*n):0;return A.green("\u2588".repeat(o))+A.gray("\u2591".repeat(Math.max(0,n-o)))}function Rm(e,t){let n=t>0?Math.round(e/t*100):0,o=$t(`${n}%`,4);return n===100?A.green(o):n>0?A.yellow(o):A.gray(o)}function ud(e,t){let n=new Map;for(let o of e){let r=dd(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 Sm(e,t){let n=(J,re)=>J.filter(le=>le.state===re).length,o=e.length,r=n(e,"verified"),s=n(e,"captured"),i=n(e,"rejected"),c=n(e,"spec"),p=n(e,"blocked"),h=n(e,"broken"),b=n(e,"placeholder"),$=new Set(e.map(J=>J.file)).size,v=ud(e,t),E=[];E.push(` ${A.bold("Screenshots")} ${A.green(`${r}/${o} verified`)} ${A.gray("\xB7")} ${s>0?A.blue(`${s} to verify`):A.gray("0 to verify")}`+(i>0?` ${A.gray("\xB7")} ${A.magenta(`${i} rejected`)}`:"")+` ${A.gray("\xB7")} ${c>0?A.yellow(`${c} ready`):A.gray("0 ready")}`+(p>0?` ${A.gray("\xB7")} ${A.cyan(`${p} blocked`)}`:"")+(h>0?` ${A.gray("\xB7")} ${A.red(`${h} broken`)}`:"")+` ${A.gray("\xB7")} ${b>0?A.red(`${b} to spec`):A.gray("0 to spec")} `+A.gray(`across ${$} article${$===1?"":"s"}`));let R=o>0?Math.round(r/o*100):0;E.push(` [${Ql(r,o,32)}] ${A.bold(`${R}%`)}`),E.push("");let C=v.map(([J])=>ri(J)),P=Math.min(32,Math.max(7,...C.map(J=>J.name.length))),I=J=>J.length>P?`${J.slice(0,P-1)}\u2026`:mr(J,P),G=[...s>0?[{head:"To verify",w:9,state:"captured",color:A.blue}]:[],...i>0?[{head:"Rejected",w:8,state:"rejected",color:A.magenta}]:[],{head:"Ready",w:5,state:"spec",color:A.yellow},...p>0?[{head:"Blocked",w:7,state:"blocked",color:A.cyan}]:[],...h>0?[{head:"Broken",w:6,state:"broken",color:A.red}]:[],{head:"To spec",w:7,state:"placeholder",color:A.red}];E.push(A.gray(` ${mr("#",2)} ${mr("Chapter",P)} ${$t("Verified",8)} ${G.map(J=>$t(J.head,J.w)).join(" ")} Progress`));for(let[J,[,re]]of v.entries()){let le=n(re,"verified"),ae=re.length,{num:Ze,name:Fe}=C[J],ze=le===ae,lt=I(Fe),Pt=G.map(dt=>{let Yt=n(re,dt.state);return Yt>0?dt.color($t(String(Yt),dt.w)):A.gray($t("\u2014",dt.w))}).join(" ");E.push(` ${A.cyan(mr(Ze,2))} ${ze?A.green(lt):le>0?lt:A.gray(lt)} ${ze?A.green($t(`${le}/${ae}`,8)):$t(`${le}/${ae}`,8)} ${Pt} ${Ql(le,ae,10)} ${Rm(le,ae)}`)}E.push("");let q=h>0?` ${A.gray("\xB7")} ${h} spec${h===1?"":"s"} broken \u2014 ${A.bold(`/screenshot ${e.find(J=>J.state==="broken").id}`)} re-authors ${h===1?"it":"the first"}`:"",Y=e.filter(J=>J.state==="spec"&&J.mutates).length,he=c>Y;if(b>0)E.push(` ${we("\u2192",A.yellow)}${b} placeholder${b===1?"":"s"} still need a spec \u2014 run ${A.bold("/screenshot author --all")}${q}`);else if(c>0&&(he||s===0)){let J=Y>0?A.gray(` \u2014 ${c-Y} in one go; ${Y} write${Y===1?"s":""} real data and run${Y===1?"s":""} one at a time`):"";E.push(` ${we("\u2192",A.yellow)}${c} spec${c===1?"":"s"} ready to capture \u2014 run ${A.bold("/screenshot capture")}${J}${q}`)}else if(s>0&&c>0)E.push(` ${we("\u2192",A.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${A.bold("/screenshot verify")}`+A.gray(" \u2014 no browser needed")+A.gray(` \xB7 ${c} ready spec${c===1?"":"s"} write real data, so ${c===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+q);else if(p>0)E.push(` ${we("\u2192",A.cyan)}${p} shot${p===1?"":"s"} blocked \u2014 stage the data below, then ${A.bold("/screenshot capture --blocked")}${q}`);else if(h>0)E.push(` ${we("\u2192",A.red)}${h} spec${h===1?"":"s"} broken \u2014 ${A.bold(`/screenshot ${e.find(J=>J.state==="broken").id}`)} re-authors ${h===1?"it":"the first"} (re-capturing fails the same way)`);else if(s>0)E.push(` ${we("\u2192",A.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${A.bold("/screenshot verify")}`+A.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(i>0){let J=e.filter(re=>re.state==="rejected"&&re.repaired).length;E.push(` ${we("\u2691",A.magenta)}${i} shot${i===1?"":"s"} failed review \u2014 `+(J>0?`${J} spec${J===1?"":"s"} already repaired; re-capture with ${A.bold("/screenshot capture --failed")}`:`see the reasons below, then ${A.bold("/screenshot capture --failed")}`))}else E.push(` ${we("\u2713",A.green)}all ${o} verified \u2014 ${A.bold("/publish")} embeds them in the articles`);if(r>0&&r<o){let J=v.filter(([,re])=>re.every(le=>le.state!=="verified")).map(([re])=>{let{num:le,name:ae}=ri(re);return le?`${le} ${ae}`:ae});J.length>0&&E.push(A.gray(` Furthest behind: ${J.slice(0,5).join(" \xB7 ")}${J.length>5?" \u2026":""} (0% verified)`))}return E.push(...ad(e),...ld(e),...cd(e,!1)),E.push(""),E.push(id),E.push(A.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),E}function Pm(e,t,n){let o=new Set(e.map(c=>c.file)),r=e.filter(c=>c.state==="verified").length,s=e.filter(c=>c.state==="captured").length,i=[` ${A.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${A.green(`${r} verified`)}${s>0?A.blue(` \xB7 ${s} to verify`):""}${n?A.gray(` \xB7 scope ${n}`):""}`,""];for(let[c,p]of ud(e,t)){let h=p.filter(R=>R.state==="verified").length,{num:b,name:$}=ri(c),v=b?`${b} \xB7 ${$}`:$;i.push(` ${A.bold(v)} ${A.gray(`(${h}/${p.length})`)}`);let E=new Map;for(let R of p){let C=Cm(R.file),P=E.get(C)??[];E.has(C)||E.set(C,P),P.push(R)}for(let R of[...E.keys()].sort()){i.push(A.gray(` ${R}`));for(let C of E.get(R)){let P=bm[C.state];if(i.push(` ${we(km[C.state],P)}${P(C.id)}`),(C.state==="blocked"||C.state==="broken"||C.state==="rejected")&&C.reason){for(let I of Wt(xn(C.reason),84))i.push(A.gray(` ${I}`));C.state==="rejected"&&i.push(A.gray(` ${C.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return i.push(...ad(e),...ld(e),...cd(e,!0)),i.push("",id),i}function Cr(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??li;return t?.detail||n?Pm(e,o,n):Sm(e,o)}function di(e,t){if(!t||!/^\d+$/.test(t))return t;let n=vt(e)?.docsDir??li,o=String(Number(t));for(let{file:r}of Jl(e)){let s=dd(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function pd(e,t){let r=e.map(c=>" ".repeat(c.depth)+c.label),s=Math.max(0,...e.map((c,p)=>c.note?fr(r[p]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((c,p)=>{let h=r[p];if(!c.note)return{head:h,note:""};let b=Math.max(2,i+2-fr(h)),$=c.note.trim(),v=t-fr(h)-b;return{head:h+" ".repeat(b),note:v>1&&fr($)>v?`${$.slice(0,v-1)}\u2026`:$}})}function Tm(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function gr(e,t,n){let o=new Map;for(let s of t){let{category:i,article:c}=Tm(s.file),p=o.get(i)??new Map;o.set(i,p);let h=p.get(c)??[];p.set(c,h),h.push(s)}let r=s=>n==="author"||!s.mutates;for(let s of[...o.keys()].sort()){let i=o.get(s),c=[...i.values()].flat().filter(r).map(h=>h.id),p=c.length>0;p&&e.push({kind:"category",action:n,label:`${s} (${c.length})`,ids:c,depth:1});for(let h of[...i.keys()].sort()){let b=i.get(h),$=b.filter(r).map(R=>R.id),v=$.length>0;v&&e.push({kind:"article",action:n,label:`${h} (${$.length})`,ids:$,depth:p?2:1});let E=(p?1:0)+(v?1:0)+1;for(let R of b){let C=n==="capture"&&R.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:R.id,ids:[R.id],depth:E,...C?{note:C}:{}})}}}}function ni(e){return e?xn(e):""}function ui(e,t,n,o=[]){let r=t.filter(i=>!i.mutates);r.length>1&&e.push({kind:"all",action:"capture",label:`Retry ${r.length} blocked shots (Prerequisites not met \u2014 Stage the data first)`,ids:r.map(i=>i.id),depth:0});for(let i of[...t].sort((c,p)=>c.id.localeCompare(p.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${ni(i.reason)}`});n.length>1&&e.push({kind:"all",action:"author",label:`Re-author ${n.length} broken specs`,ids:n.map(i=>i.id),depth:0});for(let i of[...n].sort((c,p)=>c.id.localeCompare(p.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${ni(i.reason)}`});let s=o.filter(i=>!i.mutates);s.length>1&&e.push({kind:"all",action:"capture",label:`Re-capture ${s.length} shots that failed review`,ids:s.map(i=>i.id),depth:0});for(let i of[...o].sort((c,p)=>c.id.localeCompare(p.id))){let c=i.repaired?"re-captures":"re-captures (spec not yet repaired)";e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2691 ${c} \u2014 ${ni(i.reason)}`})}}function hd(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}),gr(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}),gr(o,n,"capture"),ui(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected")),o}var si=["MANDATORY \u2014 a missing prerequisite must SKIP, never time out. Two rules, applied to EVERY locator","in the spec, not just the first one or the one shown in the skill's example:","1. A bare `await x.waitFor(...)` is itself the bug: on a missing element it THROWS and the run"," reports a hard failure with a stack trace instead of a staging instruction. Every wait must be",' `await x.waitFor({ state: "visible", timeout: 10_000 }).catch(() => {});` followed by',' `if ((await x.count()) === 0) test.skip(true, "Prerequisite not met: \u2026")`. That applies to each'," element you wait on or click IN TURN \u2014 tabs, toggles, rows, buttons reached after the first"," guard \u2014 because any of them can be absent for the same reason the data is."," And guard on the SAME predicate the action needs: `.click()` requires visible AND ENABLED, so a",' DISABLED button passes both waitFor({state:"visible"}) and count()>0 and then times out at 15s'," (measured). Add `|| !(await x.isEnabled().catch(() => false))` to the condition, and put the"," control's own title/aria-disabled text in the skip reason \u2014 a disabled control is the product"," telling you the prerequisite is unmet, usually with the reason attached.",' And when a wait DOES time out, diagnose before you guard: a skip asserts "your app lacks this',' data", so if the real cause is a locator matching a node you did not intend (a rollup row, a'," sibling with the same testid), that assertion is a lie and sends the user to stage what they"," already have. Narrow the selector first, THEN guard."," Two corollaries, both of which have cost a wasted repair round:"," (a) An element that is not RENDERED is not absent. A collapsed tree node, an unopened accordion,"," an inactive tab, a virtualised list or page 2 of a table keeps its children out of the DOM."," EXPAND/scroll/switch to reach the target \u2014 that is a step to script, not data to stage."," (b) When you narrow past a decoy, count the UNNARROWED set too and put the number in the reason:",' "Found 6 folder roll-ups but no endpoint-level score \u2014 if one exists it may not be rendered".',' A bare "prerequisite not met" cannot tell absent data from an over-narrow selector. Put that'," evidence in a LATER sentence, never the first: grouping keys on the first sentence, so an",' interpolated count there makes every run its own "action" and the dedup stops working.'," (c) `click({ force: true })` is the ONE pattern that turns a failure into a silent WRONG"," SCREENSHOT rather than a crash or skip: it skips the actionability checks, so a click that"," lands on nothing photographs the unchanged screen and that image ships in the docs. It is"," sometimes right (a button nested inside a button reads as intercepted by its own ancestor)."," Never force blind: ground it in source, scrollIntoViewIfNeeded() first, and ASSERT THE"," CONSEQUENCE immediately after with a guarded wait + test.skip, so a no-op force skips."," Know its limit: force skips the CHECK but still hit-tests real screen coordinates, so the"," element that RECEIVES the event may not be the one your locator names (measured: a forced"," click on a pill nested in its section-header button never ran the pill's own handler).",' For a genuinely nested interactive node use `locator.dispatchEvent("click")`, which goes'," straight to that node with no hit-test \u2014 and still assert the consequence."," (d) Never bind a locator to an attribute your own interaction CHANGES. A locator is re-evaluated",' on every use, so `button[title="Multi-select scenarios"]` matches nothing once the click',' flips it to `title="Exit select mode"` \u2014 a 15s "not found" timeout on an element that is'," right there (measured). Toggling labels are normal (Play/Pause, Expand/Collapse, Select"," all/Deselect all): if the attribute is a ternary on state it is not an identity. Match both"," values in one locator, or use a testid."," (e) Cleanup after the screenshot is BEST-EFFORT and must never throw or test.skip. Anything"," after page.screenshot()/dumpAnnotations() runs with the image already on disk, so a throw"," there turns a successful capture into a reported failure and the shot is thrown away"," (measured: a valid .raw.png plus annotations, reported broken). Guard with isVisible()/"," isEnabled() and click best-effort \u2014 by then there is nothing left to skip.","2. Never reason about whether a role/text locator is unique; you cannot verify that by reading"," source, and Playwright fails the whole spec on 2+ matches. Every `getByRole`/`getByText`/"," `:has-text` without a unique data-testid gets `.first()` or a container scope"," (`page.locator('[data-testid=\"\u2026\"]').getByRole(\u2026)`). If you catch yourself writing a comment"," ARGUING a selector is unique, scope it instead \u2014 that argument is what fails.","3. Every skip reason opens with the SHARED staging action, worded identically across every shot",' that needs the same thing, naming where in the product to do it ("Create an API key in Settings',' \u2192 API Keys."); shot-specific detail (counts, which record, which state) goes in LATER sentences.'," The dashboard groups blocked shots by that first sentence, so a near-duplicate wording splits one"," chore into two. Grep sibling specs and reuse their exact opening sentence.","Before you finish, re-read each spec you wrote and check all three rules line by line."].join(`
323
+ `);function Em(e){return e.outcome==="failed"?["REPAIR \u2014 the existing spec FAILED its last capture with:",e.reason,'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."]:["REPAIR \u2014 the existing spec SKIPPED its last capture with:",e.reason,"You are being asked to re-author a shot that SKIPPED, and that is itself the signal: the normal","response to a blocked shot is to STAGE the data, not to rewrite the spec. So treat that reason as","SUSPECT \u2014 assume it is a FALSE skip until you have proved otherwise. Two things make a guard report",'"not staged" when the data exists:',"1. THE TARGET IS NOT RENDERED. Trace the path from the entry point to the element you finally need"," and confirm every intermediate container is OPENED. A collapsed tree node, an unopened accordion,"," an inactive tab, a virtualised list or page 2 of a table keeps its children out of the DOM, so the"," count is zero and the skip fires \u2014 for data sitting one click away. Expanding is a step to SCRIPT.","2. THE SELECTOR IS TOO NARROW. If you filtered past a decoy, count the UNNARROWED set and put the",' number in the reason ("Found 6 folder roll-ups but no endpoint-level score"), so the next reader'," can tell absent data from an over-narrow selector without opening the app.","A spec that satisfies every rule in this skill and still cannot reach its target is NOT correct.",'"No changes needed" is earned by tracing reachability end to end \u2014 not by checking conformance.']}var ii="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 fd(e,t){let n=e.paths,o=n.filter(i=>t?.get(i)?.outcome==="failed"),r=n.filter(i=>t?.get(i)?.outcome==="skipped"),s=i=>`- ${i}: ${t.get(i).reason.replace(/\s+/g," ").trim()}`;return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(i=>`- ${i}`).join(`
324
324
  `),"",...o.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).",...o.map(s),""]:[],...r.length>0?["REPAIR \u2014 these already have a spec and it SKIPPED. Treat each reason as SUSPECT, not as proof","the spec is right: a FALSE skip is indistinguishable from a true one from inside the spec, and","you are being asked to re-author rather than to stage. Check TWO things before concluding a","spec needs no change. (1) Is the target RENDERED? A collapsed tree node, unopened accordion,","inactive tab, virtualised list or page 2 of a table keeps children out of the DOM, so the count","is zero for data one click away \u2014 expanding is a step to SCRIPT. (2) Is the selector too narrow?","If you filtered past a decoy, count the unnarrowed set and put the number in the reason. A spec","that satisfies every rule and still cannot reach its target is NOT correct.",...r.map(s),""]:[],"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.",si,ii].join(`
325
- `)}async function Rr(e,t,n){let o=Zn(e),r=eo(t?.cwd??process.cwd());if(r&&console.log(D.gray(r)),o.mode==="list"){let p=t?.cwd??process.cwd(),h=di(p,o.scope),b=vt(p)?.docsDir??li,$=$e(p,h);for(let v of Cr($,{scope:h,detail:o.detail,docsDir:b}))console.log(v);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.",si,ii,...n?.prior?["",...Pm(n.prior)]:[]].join(`
325
+ `)}async function Rr(e,t,n){let o=Zn(e),r=eo(t?.cwd??process.cwd());if(r&&console.log(A.gray(r)),o.mode==="list"){let p=t?.cwd??process.cwd(),h=di(p,o.scope),b=vt(p)?.docsDir??li,$=ve(p,h);for(let v of Cr($,{scope:h,detail:o.detail,docsDir:b}))console.log(v);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.",si,ii,...n?.prior?["",...Em(n.prior)]:[]].join(`
326
326
  `),display:`/screenshot ${o.id}`};if(o.mode==="capture"||o.mode==="verify"||o.mode==="checklist")return{kind:"continue"};let i=[`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-CHECKLIST.md.":""} Report specs written, TODO data-testids, and data to stage.`,si,ii].join(`
327
327
  `),c=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:c}}var no=3;function pi(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(`
328
- `)}var hd={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function hi(e){return e.filter(t=>t.path!==null&&t.status in hd&&!t.link).map(t=>({path:t.path,label:hd[t.status]}))}function Pr(e){let t=hi(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 Tr(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 Er(e){return e.filter(t=>t.link).length}function fi(e,t){try{let n=Om(e,Lm(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=_m(Tm(Em(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 Mm(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 wd(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("/"),i=o.get(s);i?i.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((i,c)=>i.path.localeCompare(c.path));n.push({kind:"category",label:`${Mm(r)} (${s.length})`,paths:s.map(i=>i.path),indent:!1});for(let i of s){let c=i.path.replace(/\\/g,"/").split("/").pop()??i.path;n.push({kind:"article",label:c,paths:[i.path],indent:!0,note:i.label})}}for(let r of[...t].sort((s,i)=>s.path.localeCompare(i.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function oo(e){return[`Run the publish-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). Compute each publish form IN MEMORY and pass it straight to the tool \u2014 NEVER write it to disk (no *.publish.md siblings, no temp copies anywhere in the docs tree; the local .md files stay untouched). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures) and remind me drafts need review in the portal."].join(`
329
- `)}function mi(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),s=e.filter(v=>!v.ok),i=e.reduce((v,E)=>v+o(E),0),c=r.reduce((v,E)=>v+o(E),0),p=n==="api"?`${Ee(e.reduce((v,E)=>v+E.costUsd,0))} total`:bt(e.reduce((v,E)=>v+E.outputTokens,0)),h=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,b=v=>`${v} article${v===1?"":"s"}`,$=[];if(s.length===0)$.push(`Published ${b(i)} (${h}) successfully \xB7 ${p}.`),$.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{$.push(`Published ${c}/${b(i)} (${h}) \xB7 ${p}.`),$.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let v of s)$.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return $}async function xt(e,t){let{model:n}=Nm(e.cwd,"standard"),o=async(r,s)=>{let i=Dm(r);console.log(y(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 ${i.length} partition${i.length===1?"":"s"} (\u2264${no} agents at once) on ${n}\u2026`)),s||console.log(y(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let c=!1;for await(let p of Im({cwd:e.cwd,partitions:i,promptFor:h=>oo(h.paths),concurrency:no,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(p.type==="partition_status")p.status==="running"?console.log(y(` \u25B8 ${p.label} \u2014 publishing\u2026`)):p.status==="done"?console.log(M(` \u2713 ${p.label}`)):console.log(A(` \u2717 ${p.label}`));else if(p.type==="run_done"){c=p.aborted,console.log("");let h=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let $ of mi(p.results,i,h))console.log(p.ok?M($):B($));let b=fi(e.cwd,e.profileName);b&&console.log(y(b));try{let $=md(await fd({cwd:e.cwd,profileName:e.profileName}));$&&console.log(y($))}catch{}try{let $=yd(await gd({cwd:e.cwd,profileName:e.profileName}));$&&console.log(y($))}catch{}}return c};try{if(!await o(t,!1)){let s=await gi(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(A(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Ar(e,t,n){let o=jm(e,n);if(o.length===0)return[];let r=new Set(hi((await Sr({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function gi(e,t,n){try{let o=new Set(n),r=await Sr({cwd:e,profileName:t});return hi(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function kd(e,t){let n=Ve(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(A(n.reason)),{kind:"continue"};let o=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let r=t?.cwd??process.cwd(),s=$e(r),i=$r(s);if(i.length===0)return console.log(y("No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"};let c=vr(s);return c&&console.log(c),t?await xt(t,i):{kind:"forward-to-agent",prompt:oo(i),display:"/publish --screenshots"}}if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Ar(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(M("\u2713 All related articles are already published.")),{kind:"continue"}):await xt(t,r)}if(o==="--all"){console.log(y("Checking what needs publishing\u2026"));try{let r=await Sr({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:i}=Pr(r.entries),c=Er(r.entries),p=e.includes("--force")&&i.length>0;c>0&&console.log(B(`\u26A0 ${c} 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.`)),i.length>0&&!p&&console.log(B(Tr(i.length)));let h=p?[...s,...i]:s;if(h.length===0){if(i.length>0)return console.log(y("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(M(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let b=md(await fd({cwd:t.cwd,profileName:t.profileName}));b&&console.log(y(b));let $=yd(await gd({cwd:t.cwd,profileName:t.profileName}));$&&console.log(y($))}catch{}return{kind:"continue"}}return t?await xt(t,h.map(b=>b.path)):{kind:"forward-to-agent",prompt:oo(h.map(b=>b.path)),display:"/publish --all"}}catch(r){return console.log(A(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(y("Checking what needs publishing\u2026"));let r;try{let s=await Sr({cwd:t?.cwd??process.cwd()}),{clean:i,conflicts:c}=Pr(s.entries);r=i;let p=Er(s.entries);if(p>0&&console.log(B(`\u26A0 ${p} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),c.length>0&&console.log(B(Tr(c.length))),r.length===0&&c.length>0)return console.log(y("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(A(`Could not compute sync status: ${s.message}`)),console.log(y("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(M("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(y(" (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} ${y(`(${s.label})`)}`);return console.log(y("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>Am({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(y("Cancelled.")),{kind:"continue"}}if(o==="--all")return await xt(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:pi(o),display:`/publish ${o}`}}async function ro(){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 if any article is changed in both places, or changed on Document360 and not yet pulled down (the local copy cannot be trusted until that is resolved). Say which articles and what to do about them, in plain words \u2014 never the internal status word.","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(`
330
- `),display:"/audit"}}K();import{readProjectConfig as Um}from"document360-engine";function yi(){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(`
331
- `)}async function bd(e,t){let n=t?.cwd??process.cwd();return Um(n)?{kind:"forward-to-agent",prompt:yi(),display:"/discover"}:(console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"})}K();import{checkbox as Fm}from"@inquirer/prompts";import{inventoryRepo as Wm,readProjectConfig as $d,writeProjectConfig as Bm}from"document360-engine";function wi(e,t){let n=$d(e);n&&(n.authoritativeSourceFiles=t,Bm(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 vd(e,t){let n=t?.cwd??process.cwd();if(!$d(n))return console.log(A("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Wm(n);if(o.length===0)return console.log(y('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(W("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${y(Dr(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Fm({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(y("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(y("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};wi(n,r),console.log(M(`\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"}}K();import{confirm as Jm}from"@inquirer/prompts";import{applyPull as $i,computeSyncStatus as Dd,compareRemoteSources as Zm,planPull as jd,planImport as eg,applyImport as tg,establishBaselines as ng,rebaselineServerMeta as og,D360AuthError as rg}from"document360-engine";K();var xd=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:A,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:W,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:A,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:A,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:fe,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:y,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:y,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:fe,mark:"\xB7"}];function Hm(e){return e.path?e.path:`${e.title??"(untitled)"} ${fe(`[${e.articleId}]`)}`}function qm(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 jr(e,t){let n=[],o=e.entries.filter(b=>b.link);if(o.length>0){n.push(""),n.push(Te("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??"")} ${fe(`\u2192 "${b.link.title}"`)}`)}for(let b of xd){let $=e.entries.filter(v=>v.status===b.status&&!(b.status==="untracked-local"&&v.link));if($.length!==0){n.push(""),n.push(Te(b.header));for(let v of $)n.push(` ${b.paint(b.mark)} ${b.paint(Hm(v))}${v.detail?fe(` (${v.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let i={"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"},c=o.length,p=s===r?M("\u2713 everything up to date"):[r>0?M(`\u2713 ${r} up to date`):null,c>0?`${c} to link`:null,...xd.map(b=>{let $=(e.counts[b.status]??0)-(b.status==="untracked-local"?c:0);return $>0?`${$} ${i[b.status]}`:null})].filter(Boolean).join(fe(" \xB7 ")),h=t!==void 0?` \xB7 synced in ${qm(t)}`:"";return n.push(p+fe(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${h}`)),n}import{structuredPatch as Vm}from"diff";import Cd from"picocolors";var Rd=80,Gm="\x1B[48;2;74;28;28m",Ym="\x1B[48;2;24;66;24m",Sd="\x1B[49m",ki=e=>String(e).padStart(5);function Pd(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function Td(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 ct(e,t,n){let o=v=>{let E=v.replace(/\r\n/g,`
328
+ `)}var md={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function hi(e){return e.filter(t=>t.path!==null&&t.status in md&&!t.link).map(t=>({path:t.path,label:md[t.status]}))}function Pr(e){let t=hi(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 Tr(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 Er(e){return e.filter(t=>t.link).length}function fi(e,t){try{let n=_m(e,Mm(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Um(Dm(Am(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 Fm(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 bd(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("/"),i=o.get(s);i?i.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((i,c)=>i.path.localeCompare(c.path));n.push({kind:"category",label:`${Fm(r)} (${s.length})`,paths:s.map(i=>i.path),indent:!1});for(let i of s){let c=i.path.replace(/\\/g,"/").split("/").pop()??i.path;n.push({kind:"article",label:c,paths:[i.path],indent:!0,note:i.label})}}for(let r of[...t].sort((s,i)=>s.path.localeCompare(i.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function oo(e){return[`Run the publish-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). Compute each publish form IN MEMORY and pass it straight to the tool \u2014 NEVER write it to disk (no *.publish.md siblings, no temp copies anywhere in the docs tree; the local .md files stay untouched). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures) and remind me drafts need review in the portal."].join(`
329
+ `)}function mi(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),s=e.filter(v=>!v.ok),i=e.reduce((v,E)=>v+o(E),0),c=r.reduce((v,E)=>v+o(E),0),p=n==="api"?`${De(e.reduce((v,E)=>v+E.costUsd,0))} total`:bt(e.reduce((v,E)=>v+E.outputTokens,0)),h=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,b=v=>`${v} article${v===1?"":"s"}`,$=[];if(s.length===0)$.push(`Published ${b(i)} (${h}) successfully \xB7 ${p}.`),$.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{$.push(`Published ${c}/${b(i)} (${h}) \xB7 ${p}.`),$.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let v of s)$.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return $}async function xt(e,t){let{model:n}=Om(e.cwd,"standard"),o=async(r,s)=>{let i=Nm(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 ${i.length} partition${i.length===1?"":"s"} (\u2264${no} agents at once) on ${n}\u2026`)),s||console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let c=!1;for await(let p of Lm({cwd:e.cwd,partitions:i,promptFor:h=>oo(h.paths),concurrency:no,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(p.type==="partition_status")p.status==="running"?console.log(g(` \u25B8 ${p.label} \u2014 publishing\u2026`)):p.status==="done"?console.log(M(` \u2713 ${p.label}`)):console.log(D(` \u2717 ${p.label}`));else if(p.type==="run_done"){c=p.aborted,console.log("");let h=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let $ of mi(p.results,i,h))console.log(p.ok?M($):H($));let b=fi(e.cwd,e.profileName);b&&console.log(g(b));try{let $=yd(await gd({cwd:e.cwd,profileName:e.profileName}));$&&console.log(g($))}catch{}try{let $=kd(await wd({cwd:e.cwd,profileName:e.profileName}));$&&console.log(g($))}catch{}}return c};try{if(!await o(t,!1)){let s=await gi(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(D(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Dr(e,t,n){let o=Im(e,n);if(o.length===0)return[];let r=new Set(hi((await Sr({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function gi(e,t,n){try{let o=new Set(n),r=await Sr({cwd:e,profileName:t});return hi(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function $d(e,t){let n=Ve(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(D(n.reason)),{kind:"continue"};let o=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let r=t?.cwd??process.cwd(),s=ve(r),i=$r(s);if(i.length===0)return console.log(g("No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"};let c=vr(s);return c&&console.log(c),t?await xt(t,i):{kind:"forward-to-agent",prompt:oo(i),display:"/publish --screenshots"}}if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Dr(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(M("\u2713 All related articles are already published.")),{kind:"continue"}):await xt(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:i}=Pr(r.entries),c=Er(r.entries),p=e.includes("--force")&&i.length>0;c>0&&console.log(H(`\u26A0 ${c} 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.`)),i.length>0&&!p&&console.log(H(Tr(i.length)));let h=p?[...s,...i]:s;if(h.length===0){if(i.length>0)return console.log(g("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(M(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let b=yd(await gd({cwd:t.cwd,profileName:t.profileName}));b&&console.log(g(b));let $=kd(await wd({cwd:t.cwd,profileName:t.profileName}));$&&console.log(g($))}catch{}return{kind:"continue"}}return t?await xt(t,h.map(b=>b.path)):{kind:"forward-to-agent",prompt:oo(h.map(b=>b.path)),display:"/publish --all"}}catch(r){return console.log(D(`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:i,conflicts:c}=Pr(s.entries);r=i;let p=Er(s.entries);if(p>0&&console.log(H(`\u26A0 ${p} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),c.length>0&&console.log(H(Tr(c.length))),r.length===0&&c.length>0)return console.log(g("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(D(`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(M("\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(()=>jm({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 xt(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:pi(o),display:`/publish ${o}`}}async function ro(){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 if any article is changed in both places, or changed on Document360 and not yet pulled down (the local copy cannot be trusted until that is resolved). Say which articles and what to do about them, in plain words \u2014 never the internal status word.","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(`
330
+ `),display:"/audit"}}K();import{readProjectConfig as Wm}from"document360-engine";function yi(){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(`
331
+ `)}async function vd(e,t){let n=t?.cwd??process.cwd();return Wm(n)?{kind:"forward-to-agent",prompt:yi(),display:"/discover"}:(console.log(D("No d360-writer config here. Run /init first.")),{kind:"continue"})}K();import{checkbox as Bm}from"@inquirer/prompts";import{inventoryRepo as Hm,readProjectConfig as xd,writeProjectConfig as qm}from"document360-engine";function wi(e,t){let n=xd(e);n&&(n.authoritativeSourceFiles=t,qm(n,e))}function Ar(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 Cd(e,t){let n=t?.cwd??process.cwd();if(!xd(n))return console.log(D("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Hm(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(W("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${g(Ar(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Bm({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Ar(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"};wi(n,r),console.log(M(`\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"}}K();import{confirm as eg}from"@inquirer/prompts";import{applyPull as $i,computeSyncStatus as Nd,compareRemoteSources as tg,planPull as Id,planImport as ng,applyImport as og,establishBaselines as rg,rebaselineServerMeta as sg,D360AuthError as ig}from"document360-engine";K();var Rd=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:D,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:H,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:W,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:D,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:D,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:me,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:me,mark:"\xB7"}];function Vm(e){return e.path?e.path:`${e.title??"(untitled)"} ${me(`[${e.articleId}]`)}`}function Gm(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 jr(e,t){let n=[],o=e.entries.filter(b=>b.link);if(o.length>0){n.push(""),n.push(Ee("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let b of o)n.push(` ${H("~")} ${H(b.path??"")} ${me(`\u2192 "${b.link.title}"`)}`)}for(let b of Rd){let $=e.entries.filter(v=>v.status===b.status&&!(b.status==="untracked-local"&&v.link));if($.length!==0){n.push(""),n.push(Ee(b.header));for(let v of $)n.push(` ${b.paint(b.mark)} ${b.paint(Vm(v))}${v.detail?me(` (${v.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let i={"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"},c=o.length,p=s===r?M("\u2713 everything up to date"):[r>0?M(`\u2713 ${r} up to date`):null,c>0?`${c} to link`:null,...Rd.map(b=>{let $=(e.counts[b.status]??0)-(b.status==="untracked-local"?c:0);return $>0?`${$} ${i[b.status]}`:null})].filter(Boolean).join(me(" \xB7 ")),h=t!==void 0?` \xB7 synced in ${Gm(t)}`:"";return n.push(p+me(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${h}`)),n}import{structuredPatch as Ym}from"diff";import Sd from"picocolors";var Pd=80,zm="\x1B[48;2;74;28;28m",Km="\x1B[48;2;24;66;24m",Td="\x1B[49m",ki=e=>String(e).padStart(5);function Ed(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function Dd(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 ct(e,t,n){let o=v=>{let E=v.replace(/\r\n/g,`
332
332
  `);return E.endsWith(`
333
333
  `)||E===""?E:E+`
334
- `},r=o(e),s=o(t);if(r===s)return null;let i=Math.max(20,n-10),c=Vm("a","b",r,s,"","",{context:3}),p=0,h=0,b=[];c.hunks.forEach((v,E)=>{E>0&&b.push(Cd.gray(" \u2026"));let R=v.oldStart,x=v.newStart,T=[],F=[],G=()=>{for(let q=0;q<T.length;q++){let Y=q<F.length?Pd(T[q],F[q]):void 0;h++,b.push(`${Gm}${ki(R++)} - ${Td(T[q],i,Y)}${Sd}`)}for(let q=0;q<F.length;q++){let Y=q<T.length?Pd(T[q],F[q]):void 0;p++,b.push(`${Ym}${ki(x++)} + ${Td(F[q],i,Y)}${Sd}`)}T=[],F=[]};for(let q of v.lines){let Y=q[0],pe=q.slice(1);Y==="-"?T.push(pe):Y==="+"?F.push(pe):(G(),b.push(Cd.gray(ki(x))+" "+pe.slice(0,i)),R++,x++)}G()});let $=b.slice(0,Rd);return{added:p,removed:h,lines:$,hidden:Math.max(0,b.length-Rd)}}K();import{select as zm}from"@inquirer/prompts";import{applyPull as Km,computeSyncStatus as Xm,planPull as Qm}from"document360-engine";var Ed=e=>e===1?"":"s";async function bi(e,t){console.log(""),console.log(`${W("\u25CF")} ${Te(t.title)} ${fe(`(${t.path})`)}`);for(let r of t.notes)console.log(B(` \u26A0 ${r}`));let n=ct(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(fe(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${Ed(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(y(` \u2026 +${n.hidden} more diff lines`))}else console.log(y(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>zm({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"?(Km({cwd:e.cwd,profileName:e.profileName},t),console.log(M(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(y(" Skipped \u2014 still a conflict.")),"skipped")}async function Ad(e,t){let n=Ve(t.cwd,t.profileName);if(!n.ok)return console.log(A(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Xm({cwd:t.cwd,profileName:t.profileName})).entries.filter(c=>c.status==="conflict"&&c.path).map(c=>c.path);if(o){if(!s.includes(o))return console.log(M(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(M("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[];for(let c of s){let p=await Qm({cwd:t.cwd,profileName:t.profileName,relPath:c});await bi(t,p)==="keep-local"&&i.push(c)}if(i.length>0)return console.log(y(`Publishing ${i.length} kept-local article${Ed(i.length)} over the portal\u2026`)),await xt(t,i)}catch(r){console.log(A(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Nd(e,t){let n=Ve(t.cwd,t.profileName);if(!n.ok)return console.log(A(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await sg(t),{kind:"continue"};if(o==="--baseline")return await ig(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await ag(t),{kind:"continue"};if(o)return console.log(A(`Unknown option: ${o}`)),console.log(y("Usage: /pull pull portal edits + import new portal articles")),console.log(y(" /pull <path> pull one article (or resolve a conflict)")),console.log(y(" /pull --status drift report only (no writes)")),console.log(y(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await cg(t,r),{kind:"continue"};console.log(y("Pulling changes from Document360\u2026"));let s=await vi({cwd:t.cwd,profileName:t.profileName});for(let i of xi(s))console.log(i.tone==="ok"?M(i.text):i.tone==="warn"?B(i.text):y(i.text));console.log("")}catch(r){r instanceof rg?console.log(A(r.message)):console.log(A(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function vi(e){let t=await Dd({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 jd({cwd:e.cwd,profileName:e.profileName,relPath:o.path});$i({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 eg({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});tg({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 Nr=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Ht=e=>e===1?"":"s";function xi(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Ht(e.pulled.length)} into local: ${Nr(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Ht(e.imported.length)}: ${Nr(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Ht(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Ht(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). (${Nr(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Ht(e.failed.length)} failed: ${Nr(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 sg(e){console.log(y("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Dd({cwd:e.cwd,profileName:e.profileName});for(let o of jr(n,Date.now()-t))console.log(o);console.log("")}async function ig(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(y(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await ng({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await og({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(M("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(M(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(M(`\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(y(` - ${s.path} (${s.reason})`))}}async function ag(e){console.log(y("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Zm({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Te(String(t.legacyCount))} \xB7 Manifest: ${Te(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(M("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(A(`\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(y(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function cg(e,t){let n=t.replace(/\\/g,"/"),o=await jd({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await bi(e,o)==="keep-local"&&(console.log(y(`Publishing ${o.path} over the portal\u2026`)),await xt(e,[o.path]));return}console.log(""),console.log(`${W("\u25CF")} ${Te(o.title)} ${fe(`(${o.path})`)}`);for(let i of o.notes)console.log(B(` \u26A0 ${i}`));let r=ct(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(y(" Local file already matches the remote content \u2014 advancing the sync base only.")),$i({cwd:e.cwd,profileName:e.profileName},o);return}console.log(fe(` \u23BF Added ${r.added} line${Ht(r.added)}, removed ${r.removed} line${Ht(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(y(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Jm({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(y(" Skipped."));return}$i({cwd:e.cwd,profileName:e.profileName},o),console.log(M(` \u2713 Pulled ${o.path} (sync base advanced).`))}K();import{statSync as lg}from"node:fs";import{resolve as dg}from"node:path";import{estimateBulkCost as ug,planPartitions as pg,readProjectConfig as hg,resolveModelForOperation as fg,runPartitioned as mg,trackedArticlePaths as gg}from"document360-engine";var Ci=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 Pi(e,t){return t.map(n=>{let o=0;try{o=lg(dg(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Ti(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:
334
+ `},r=o(e),s=o(t);if(r===s)return null;let i=Math.max(20,n-10),c=Ym("a","b",r,s,"","",{context:3}),p=0,h=0,b=[];c.hunks.forEach((v,E)=>{E>0&&b.push(Sd.gray(" \u2026"));let R=v.oldStart,C=v.newStart,P=[],I=[],G=()=>{for(let q=0;q<P.length;q++){let Y=q<I.length?Ed(P[q],I[q]):void 0;h++,b.push(`${zm}${ki(R++)} - ${Dd(P[q],i,Y)}${Td}`)}for(let q=0;q<I.length;q++){let Y=q<P.length?Ed(P[q],I[q]):void 0;p++,b.push(`${Km}${ki(C++)} + ${Dd(I[q],i,Y)}${Td}`)}P=[],I=[]};for(let q of v.lines){let Y=q[0],he=q.slice(1);Y==="-"?P.push(he):Y==="+"?I.push(he):(G(),b.push(Sd.gray(ki(C))+" "+he.slice(0,i)),R++,C++)}G()});let $=b.slice(0,Pd);return{added:p,removed:h,lines:$,hidden:Math.max(0,b.length-Pd)}}K();import{select as Xm}from"@inquirer/prompts";import{applyPull as Qm,computeSyncStatus as Jm,planPull as Zm}from"document360-engine";var Ad=e=>e===1?"":"s";async function bi(e,t){console.log(""),console.log(`${W("\u25CF")} ${Ee(t.title)} ${me(`(${t.path})`)}`);for(let r of t.notes)console.log(H(` \u26A0 ${r}`));let n=ct(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(me(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${Ad(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(()=>Xm({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"?(Qm({cwd:e.cwd,profileName:e.profileName},t),console.log(M(" \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 jd(e,t){let n=Ve(t.cwd,t.profileName);if(!n.ok)return console.log(D(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Jm({cwd:t.cwd,profileName:t.profileName})).entries.filter(c=>c.status==="conflict"&&c.path).map(c=>c.path);if(o){if(!s.includes(o))return console.log(M(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(M("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[];for(let c of s){let p=await Zm({cwd:t.cwd,profileName:t.profileName,relPath:c});await bi(t,p)==="keep-local"&&i.push(c)}if(i.length>0)return console.log(g(`Publishing ${i.length} kept-local article${Ad(i.length)} over the portal\u2026`)),await xt(t,i)}catch(r){console.log(D(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Od(e,t){let n=Ve(t.cwd,t.profileName);if(!n.ok)return console.log(D(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await ag(t),{kind:"continue"};if(o==="--baseline")return await cg(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await lg(t),{kind:"continue"};if(o)return console.log(D(`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 dg(t,r),{kind:"continue"};console.log(g("Pulling changes from Document360\u2026"));let s=await vi({cwd:t.cwd,profileName:t.profileName});for(let i of xi(s))console.log(i.tone==="ok"?M(i.text):i.tone==="warn"?H(i.text):g(i.text));console.log("")}catch(r){r instanceof ig?console.log(D(r.message)):console.log(D(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function vi(e){let t=await Nd({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 Id({cwd:e.cwd,profileName:e.profileName,relPath:o.path});$i({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 ng({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});og({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 Nr=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Ht=e=>e===1?"":"s";function xi(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Ht(e.pulled.length)} into local: ${Nr(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Ht(e.imported.length)}: ${Nr(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Ht(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Ht(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). (${Nr(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Ht(e.failed.length)} failed: ${Nr(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 ag(e){console.log(g("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Nd({cwd:e.cwd,profileName:e.profileName});for(let o of jr(n,Date.now()-t))console.log(o);console.log("")}async function cg(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 rg({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await sg({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(M("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(M(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(M(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(H(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(g(` - ${s.path} (${s.reason})`))}}async function lg(e){console.log(g("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await tg({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Ee(String(t.legacyCount))} \xB7 Manifest: ${Ee(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(M("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(D(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(H(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(H(` ${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 dg(e,t){let n=t.replace(/\\/g,"/"),o=await Id({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await bi(e,o)==="keep-local"&&(console.log(g(`Publishing ${o.path} over the portal\u2026`)),await xt(e,[o.path]));return}console.log(""),console.log(`${W("\u25CF")} ${Ee(o.title)} ${me(`(${o.path})`)}`);for(let i of o.notes)console.log(H(` \u26A0 ${i}`));let r=ct(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.")),$i({cwd:e.cwd,profileName:e.profileName},o);return}console.log(me(` \u23BF Added ${r.added} line${Ht(r.added)}, removed ${r.removed} line${Ht(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(g(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>eg({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(g(" Skipped."));return}$i({cwd:e.cwd,profileName:e.profileName},o),console.log(M(` \u2713 Pulled ${o.path} (sync base advanced).`))}K();import{statSync as ug}from"node:fs";import{resolve as pg}from"node:path";import{estimateBulkCost as hg,planPartitions as fg,readProjectConfig as mg,resolveModelForOperation as gg,runPartitioned as yg,trackedArticlePaths as wg}from"document360-engine";var Ci=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 Pi(e,t){return t.map(n=>{let o=0;try{o=ug(pg(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Ti(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:
335
335
  - 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.
336
336
  - 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.
337
337
  - 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.
338
338
  - Work only on these files:
339
339
  `+e.paths.map(t=>`- ${t}`).join(`
340
- `)}function Ei(e,t,n){let o=e.reduce((c,p)=>c+p.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(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${Ee(r)}\u2013${Ee(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Ai(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),i=e.reduce((R,x)=>R+o(x),0),c=r.reduce((R,x)=>R+o(x),0),p=e.reduce((R,x)=>R+x.costUsd,0),h=e.reduce((R,x)=>R+x.outputTokens,0),b=n==="api"?`${Ee(p)} total`:bt(h),$=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=R=>`${R} article${R===1?"":"s"}`,E=[];if(s.length===0)E.push(`Converted ${v(i)} (${$}) successfully \xB7 ${b}.`);else{E.push(`Converted ${c}/${v(i)} (${$}) \xB7 ${b}.`),E.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let R of s)E.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return E}async function Id(e,t){if(!hg(t.cwd))return console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Ri(e),r=gg(t.cwd,t.profileName);if(r.length===0)return console.log(A("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(A(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let i=pg(s),c=`/convert${n?` --scope ${n}`:""} --run`,{model:p,forced:h}=fg(t.cwd,"light");if(!o){let b=ug({files:Pi(t.cwd,s),op:"convert",model:p});n&&console.log(y(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let $ of Ei(i,b,Ci))console.log($);return console.log(y(`Model: ${p}${h?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(y(`Run ${c} to start.`)),console.log(""),{kind:"continue"}}console.log(y(`Converting ${s.length} articles across ${i.length} partitions (\u2264${Ci} agents at once) on ${p}\u2026`)),console.log(y(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let b of mg({cwd:t.cwd,partitions:i,promptFor:Ti,concurrency:Ci,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:p}))if(b.type==="partition_status")b.status==="running"?console.log(y(` \u25B8 ${b.label} \u2014 converting\u2026`)):b.status==="done"?console.log(M(` \u2713 ${b.label}`)):console.log(A(` \u2717 ${b.label}`));else if(b.type==="run_done"){console.log("");let $=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let v of Ai(b.results,i,$))console.log(b.ok?M(v):B(v))}}catch(b){console.log(A(`Convert run failed: ${b.message}`))}return console.log(""),{kind:"continue"}}K();import{statSync as _d}from"node:fs";import{resolve as Md}from"node:path";import{estimateBulkCost as Rg,lintDocs as Sg,planPartitions as Pg,readDocsPlan as Tg,readProjectConfig as Ud,DEFAULT_DOCS_DIR as Eg,resolveModelForOperation as Ag,runPartitioned as Dg,stampArticles as jg,CONTENT_CAP_VERSION as Ng}from"document360-engine";import{readProjectConfig as yg,loadProfileMap as wg,resolveActiveProfile as kg,desiredCategoryOrder as bg,desiredArticleOrder as $g,DEFAULT_DOCS_DIR as vg}from"document360-engine";var Di=e=>e.replace(/\\/g,"/"),xg=e=>Di(e).split("/").pop()??e;function Cg(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function so(e,t){try{let n=yg(e);if(!n)return[];let o=kg(e,t),r=wg(e,o.name);if(!r)return[];let s=Di(n.docsDir??vg).replace(/\/+$/,""),i=new Map;for(let p of $g(r))i.set(p.categoryPath,(i.get(p.categoryPath)??0)+1);let c=[];for(let p of bg(r)){let h=Di(p.path),b=h.startsWith(`${s}/`)?h.slice(s.length+1):h===s?"":h;b&&c.push({token:b,label:Cg(xg(h)),count:i.get(p.path)??0})}return c}catch{return[]}}function Od(e,t){let n=so(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 Ct(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=so(e,o);if(r.length<=1)return[];let s=n.filter(h=>h.startsWith("--")).join(" "),i=s?` ${s}`:"",c=`/${t}${i} --all`.replace(/\s+/g," "),p=h=>t==="write"?`/write --scope ${h}${i}`:`/${t} ${h}${i}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((h,b)=>h+b.count,0)} articles). Pick a target:`,` ${c} (everything)`,...r.map(h=>` ${p(h.token)} (${h.label} \xB7 ${h.count} article${h.count===1?"":"s"})`)]}function Ir(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Ld(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 Ig=3,Og=8;function ji(e){return e===void 0||!Number.isFinite(e)?Ig:Math.max(1,Math.min(Math.floor(e),Og))}function Ni(e){let t,n,o=!1,r=!1,s,i=p=>{let h=Number(p);return p!==void 0&&Number.isFinite(h)?h:void 0};for(let p=0;p<e.length;p++){let h=e[p];if(h==="--preview"||h==="--dry-run")o=!0;else if(h==="--rewrite"||h==="--force")r=!0;else{if(h==="--run"||h==="--yes"||h==="--all")continue;h==="--scope"?t=e[++p]:h?.startsWith("--scope=")?t=h.slice(8):h==="--concurrency"?s=i(e[++p]):h?.startsWith("--concurrency=")?s=i(h.slice(14)):h&&!h.startsWith("--")&&(n=h)}}let c=p=>p?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:c(t),path:c(n),preview:o,concurrency:s,rewrite:r}}function Lg(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function _g(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Ii(e,t,n){return n.filter(o=>{try{return _d(Md(e,t,o)).size===0}catch{return!0}})}function Oi(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let i of o.get(r)?.sources??[])try{s+=_d(Md(e,i)).size}catch{}return{path:r,bytes:s}})}function Li(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.
340
+ `)}function Ei(e,t,n){let o=e.reduce((c,p)=>c+p.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(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${De(r)}\u2013${De(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Di(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),i=e.reduce((R,C)=>R+o(C),0),c=r.reduce((R,C)=>R+o(C),0),p=e.reduce((R,C)=>R+C.costUsd,0),h=e.reduce((R,C)=>R+C.outputTokens,0),b=n==="api"?`${De(p)} total`:bt(h),$=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=R=>`${R} article${R===1?"":"s"}`,E=[];if(s.length===0)E.push(`Converted ${v(i)} (${$}) successfully \xB7 ${b}.`);else{E.push(`Converted ${c}/${v(i)} (${$}) \xB7 ${b}.`),E.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let R of s)E.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return E}async function Ld(e,t){if(!mg(t.cwd))return console.log(D("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Ri(e),r=wg(t.cwd,t.profileName);if(r.length===0)return console.log(D("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(D(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let i=fg(s),c=`/convert${n?` --scope ${n}`:""} --run`,{model:p,forced:h}=gg(t.cwd,"light");if(!o){let b=hg({files:Pi(t.cwd,s),op:"convert",model:p});n&&console.log(g(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let $ of Ei(i,b,Ci))console.log($);return console.log(g(`Model: ${p}${h?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(g(`Run ${c} to start.`)),console.log(""),{kind:"continue"}}console.log(g(`Converting ${s.length} articles across ${i.length} partitions (\u2264${Ci} agents at once) on ${p}\u2026`)),console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let b of yg({cwd:t.cwd,partitions:i,promptFor:Ti,concurrency:Ci,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:p}))if(b.type==="partition_status")b.status==="running"?console.log(g(` \u25B8 ${b.label} \u2014 converting\u2026`)):b.status==="done"?console.log(M(` \u2713 ${b.label}`)):console.log(D(` \u2717 ${b.label}`));else if(b.type==="run_done"){console.log("");let $=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let v of Di(b.results,i,$))console.log(b.ok?M(v):H(v))}}catch(b){console.log(D(`Convert run failed: ${b.message}`))}return console.log(""),{kind:"continue"}}K();import{statSync as Ud}from"node:fs";import{resolve as Fd}from"node:path";import{estimateBulkCost as Pg,lintDocs as Tg,planPartitions as Eg,readDocsPlan as Dg,readProjectConfig as Wd,DEFAULT_DOCS_DIR as Ag,resolveModelForOperation as jg,runPartitioned as Ng,stampArticles as Ig,CONTENT_CAP_VERSION as Og}from"document360-engine";import{readProjectConfig as kg,loadProfileMap as bg,resolveActiveProfile as $g,desiredCategoryOrder as vg,desiredArticleOrder as xg,DEFAULT_DOCS_DIR as Cg}from"document360-engine";var Ai=e=>e.replace(/\\/g,"/"),Rg=e=>Ai(e).split("/").pop()??e;function Sg(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function so(e,t){try{let n=kg(e);if(!n)return[];let o=$g(e,t),r=bg(e,o.name);if(!r)return[];let s=Ai(n.docsDir??Cg).replace(/\/+$/,""),i=new Map;for(let p of xg(r))i.set(p.categoryPath,(i.get(p.categoryPath)??0)+1);let c=[];for(let p of vg(r)){let h=Ai(p.path),b=h.startsWith(`${s}/`)?h.slice(s.length+1):h===s?"":h;b&&c.push({token:b,label:Sg(Rg(h)),count:i.get(p.path)??0})}return c}catch{return[]}}function _d(e,t){let n=so(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 Ct(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=so(e,o);if(r.length<=1)return[];let s=n.filter(h=>h.startsWith("--")).join(" "),i=s?` ${s}`:"",c=`/${t}${i} --all`.replace(/\s+/g," "),p=h=>t==="write"?`/write --scope ${h}${i}`:`/${t} ${h}${i}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((h,b)=>h+b.count,0)} articles). Pick a target:`,` ${c} (everything)`,...r.map(h=>` ${p(h.token)} (${h.label} \xB7 ${h.count} article${h.count===1?"":"s"})`)]}function Ir(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Md(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 Lg=3,_g=8;function ji(e){return e===void 0||!Number.isFinite(e)?Lg:Math.max(1,Math.min(Math.floor(e),_g))}function Ni(e){let t,n,o=!1,r=!1,s,i=p=>{let h=Number(p);return p!==void 0&&Number.isFinite(h)?h:void 0};for(let p=0;p<e.length;p++){let h=e[p];if(h==="--preview"||h==="--dry-run")o=!0;else if(h==="--rewrite"||h==="--force")r=!0;else{if(h==="--run"||h==="--yes"||h==="--all")continue;h==="--scope"?t=e[++p]:h?.startsWith("--scope=")?t=h.slice(8):h==="--concurrency"?s=i(e[++p]):h?.startsWith("--concurrency=")?s=i(h.slice(14)):h&&!h.startsWith("--")&&(n=h)}}let c=p=>p?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:c(t),path:c(n),preview:o,concurrency:s,rewrite:r}}function Mg(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Ug(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Ii(e,t,n){return n.filter(o=>{try{return Ud(Fd(e,t,o)).size===0}catch{return!0}})}function Oi(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let i of o.get(r)?.sources??[])try{s+=Ud(Fd(e,i)).size}catch{}return{path:r,bytes:s}})}function Li(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.
341
341
  `:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
342
342
  - 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).
343
343
  - 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).
@@ -347,103 +347,103 @@ ${c[1]??" "}clipTo: ${p}${i.selector}${p},`);return h=h.replace(o,`${r}await ca
347
347
  - 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.
348
348
  Articles:
349
349
  `+e.paths.map(r=>`- ${r}`).join(`
350
- `)}function _i(e,t,n){let o=e.reduce((i,c)=>i+c.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(i=>` \u2022 ${i.label} \u2014 ${i.paths.length} article${i.paths.length===1?"":"s"}`),"",`Estimated cost: ${Ee(r)}\u2013${Ee(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Mi(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),i=e.reduce((R,x)=>R+o(x),0),c=r.reduce((R,x)=>R+o(x),0),p=e.reduce((R,x)=>R+x.costUsd,0),h=e.reduce((R,x)=>R+x.outputTokens,0),b=n==="api"?`${Ee(p)} total`:bt(h),$=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=R=>`${R} article${R===1?"":"s"}`,E=[];if(s.length===0)E.push(`Wrote ${v(i)} (${$}) successfully \xB7 ${b}.`),E.push("Next \u2014 push them to Document360:"),E.push("/publish --all"),E.push("Or add screenshots first with /screenshot author --all. Drafts are reviewable in the portal after publishing.");else{E.push(`Wrote ${c}/${v(i)} (${$}) \xB7 ${b}.`),E.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let R of s)E.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return E}function Ui(e,t,n){try{let o=Sg({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 Fi(e,t,n){let o=(Ud(e)?.docsDir??Eg).replace(/\/+$/,""),r=t.map(c=>c.path);if(n.path){let c=Lg(n.path,o);return r.includes(c)?{docsDir:o,targets:[c],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${c}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=_g(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 i=Ii(e,o,s);if(i.length===0){let c=n.scope?` under "${n.scope}"`:"",p=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${c} are already written. Use /write <path> to rewrite one, or /write${p} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}async function Fd(e,t){if(!Ud(t.cwd))return console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Ir(e)){for(let F of Od(t.cwd,t.profileName))console.log(y(F));return{kind:"continue"}}if(Ct("write",e)){let F=Cn(t.cwd,"write",e,t.profileName);if(F.length>0){for(let G of F)console.log(y(G));return{kind:"continue"}}}let n=Tg(t.cwd);if(n.length===0)return console.log(A("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:i,rewrite:c}=Ni(e),{docsDir:p,targets:h,reason:b,rewriting:$}=Fi(t.cwd,n,{scope:o,path:r,rewrite:c});if(h.length===0)return console.log(b?B(b):B("Nothing to write.")),{kind:"continue"};$&&console.log(B(`--rewrite: regenerating ${h.length} already-written article${h.length===1?"":"s"} (overwrites them; git has your baseline).`));let v=Pg(h),E=ji(i),{model:R,forced:x}=Ag(t.cwd,"standard"),T=!!r;if(s&&!T){let F=Rg({files:Oi(t.cwd,n,h),op:"write",model:R});o&&console.log(y(`Scope: ${o} (${h.length} pending).`));for(let G of _i(v,F,E))console.log(G);return console.log(y(`Model: ${R}${x?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(y(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(y(`Writing ${h.length} article${h.length===1?"":"s"} across ${v.length} partition${v.length===1?"":"s"} (\u2264${E} agents at once) on ${R}\u2026`)),console.log(y(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let F of Dg({cwd:t.cwd,partitions:v,promptFor:G=>Li(G,p,{rewrite:$||T}),concurrency:E,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:R}))if(F.type==="partition_status")F.status==="running"?console.log(y(` \u25B8 ${F.label} \u2014 writing\u2026`)):F.status==="done"?console.log(M(` \u2713 ${F.label}`)):console.log(A(` \u2717 ${F.label}`));else if(F.type==="run_done"){console.log("");let G=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let Y of Mi(F.results,v,G))console.log(F.ok?M(Y):B(Y));if(F.ok)try{jg(t.cwd,h.map(Y=>`${p}/${Y}`),{writtenCap:Ng})}catch{}let q=Ui(t.cwd,p,h);q&&console.log(B(q))}}catch(F){console.log(A(`Write run failed: ${F.message}`))}return console.log(""),{kind:"continue"}}K();import{existsSync as Mg,readdirSync as Wd,statSync as Bd}from"node:fs";import{join as Hd}from"node:path";import{inputDir as Ug,readProjectConfig as Fg}from"document360-engine";var qd=/\.(md|markdown|pdf|txt)$/i;function Wi(e){let t=Ug(e);if(!Mg(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Wd(t)){let s=Hd(t,r),i=!1;try{i=Bd(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let c=Wg(s);c>0&&n.push({name:r,docCount:c})}else qd.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Wg(e){let t=0;for(let n of Wd(e))try{Bd(Hd(e,n)).isFile()&&qd.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 Or(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(`
351
- `)}var Hi="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Vd(e,t){let n=t?.cwd??process.cwd();if(!Fg(n))return console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Wi(n);if(o.length===0&&r===0)return console.log(y(Hi)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(y("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let p of o)console.log(` ${p.name} ${y(`(${p.docCount} doc${p.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let c=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Or(c),display:c?`/draft ${c}`:"/draft"}}let i=Bi(o,s);return{kind:"forward-to-agent",prompt:Or(i??"",i?void 0:s),display:`/draft ${s}`}}K();import{listOpenForDocs as Bg,readProjectConfig as Hg}from"document360-engine";function qi(e){try{return Bg(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 Gi(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(`
352
- `)}var Yi="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 Gd(e,t){let n=t?.cwd??process.cwd();if(!Hg(n))return console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Vi(e);if(!r&&qi(n)===0)return console.log(y(Yi)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Gi(r,o),display:s}}K();import{search as qg}from"@inquirer/prompts";import{findByName as Vg,getSession as Gg,listSessions as Yg,relativeTime as zd}from"document360-engine";async function Kd(e,t){let n=Yg(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(y("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=Vg(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(A(`No session matches "${o}".`)),Yd(n),{kind:"continue"})}if(!process.stdin.isTTY)return Yd(n),console.log(y("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>qg({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let i=(s??"").toLowerCase();return n.filter(c=>!i||c.name.toLowerCase().includes(i)||c.firstPrompt.toLowerCase().includes(i)).map(c=>({name:`${c.name} ${zd(c.updatedAt)}`,value:c.uuid,description:c.firstPrompt.slice(0,100)}))}})),r=Gg(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Yd(e){console.log("");for(let t of e.slice(0,15))console.log(` ${W(t.name)} ${y(zd(t.updatedAt))}`),console.log(` ${y(t.firstPrompt.slice(0,80))}`);console.log("")}K();import{renameSession as zg}from"document360-engine";function zi(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 Xd(e,t){let n=zi(e.join(" "));if(!n)return console.log(A("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(zg(o,n)?console.log(M(`\u2713 Session renamed to "${n}"`)):console.log(A("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(M(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Qd,readProjectConfig as Kg,writeProjectConfig as Xg}from"document360-engine";K();function Ki(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Kg(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 Qd().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Xg(o,e),null):`Unknown environment "${r}". Known: ${Qd().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function Jd(e,t){let n=e[0];if(!n)return er(t.cwd),{kind:"continue"};if(n==="add"){let o=Ki(t.cwd,e[1],e[2]);return o?(console.log(A(o)),{kind:"continue"}):(console.log(M(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${W(`/profile ${e[1]}`)} then ${W("/login")}`),{kind:"continue"})}return tr(t.cwd,n),nr(t.cwd,n),console.log(y(" Restarting agent for the new profile\u2026")),{kind:"clear"}}K();import{select as Qg}from"@inquirer/prompts";import{readProjectConfig as Jg,readUserConfig as Zd,resolveModelSetting as Xi,writeUserConfig as eu}from"document360-engine";var Je=[{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 Lr(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Je.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Zg(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 io(e,t){let n=()=>Xi(e).model;if(t==="default"){let s=Zd();return s.defaultModel?(delete s.defaultModel,eu(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Xi(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}}eu({...Zd(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Jg(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 tu(e,t){let n=e[0]?.trim();if(!n){let i=Xi(t.cwd);if(!process.stdin.isTTY)return console.log(`${Te("Model:")} ${W(i.model)}${i.source==="auto"?y(" (auto)"):""}`),console.log(y(` source: ${Zg(i)}`)),console.log(y(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let c=Lr(i),p;try{p=await t.withPausedInput(()=>Qg({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:Je[c].value,choices:Je.map((v,E)=>({name:`${v.label}${E===c?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(y("Cancelled.")),{kind:"continue"}}let{lines:h,changed:b,effective:$}=io(t.cwd,p??"default");for(let v of h)console.log(v.startsWith("\u26A0")?B(v):v.startsWith("\u2713")?M(v):y(v));return b&&await t.setModel($),{kind:"continue"}}let{lines:o,changed:r,effective:s}=io(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?B(i):i.startsWith("\u2713")?M(i):y(i));return r&&await t.setModel(s),{kind:"continue"}}_r();async function au(e,t){return await t.withPausedInput(()=>hn(t.cwd)),{kind:"clear"}}async function cu(e,t){return await t.withPausedInput(()=>Xo(t.cwd,t.profileName)),{kind:"clear"}}K();import{resolveActiveProfile as yy}from"document360-engine";async function lu(e,t){let n=!1;try{n=yy(t.cwd).production}catch{}return n?(console.log(B("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(y("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}K();var du=async(e,t)=>{try{await t.withPausedInput(()=>Zo({}))}catch(n){console.log(A(`Login failed: ${n.message}`))}return{kind:"continue"}};K();import{resolveActiveProfile as wy,clearTokens as ky,clearProfileProject as by}from"document360-engine";async function uu(e,t){let n;try{n=wy(t.cwd,t.profileName).name}catch(r){return console.log(A(r.message)),{kind:"continue"}}let o=ky(n);return by(t.cwd,n),console.log(o?M(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):y(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(y("Run /login to sign in and pick a project.")),{kind:"continue"}}import{spawn as hu}from"node:child_process";import{existsSync as Zi,readFileSync as Ji,statSync as Ty}from"node:fs";import{homedir as Ey}from"node:os";import{basename as Ay,join as po}from"node:path";import{readProjectConfig as Dy,DEFAULT_OUTPUT_DIR as jy,existingAnnotatedShotPath as Ny,resolveOutputDir as Iy}from"document360-engine";import Ae from"picocolors";import{annotationsPath as $y,resolveOutputDir as vy,readProjectConfig as xy,DEFAULT_OUTPUT_DIR as Cy,existingAnnotatedShotPath as Ry}from"document360-engine";function Sy(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function co(e){return e.filter(t=>t.state==="captured").map(t=>t.id)}function qt(e,t){let n=vy(e,xy(e)?.outputDir??Cy),o=new Map($e(e).map(i=>[i.id,i])),r=i=>i.replace(`${e}\\`,"").replace(`${e}/`,"").replace(/\\/g,"/"),s=t.map(i=>{let c=o.get(i)?.file??"(unknown article)";return[`- ${i}`,` image: ${r(Ry(n,i))}`,` facts: ${r($y(n,i))}`,` article: ${c}`].join(`
350
+ `)}function _i(e,t,n){let o=e.reduce((i,c)=>i+c.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(i=>` \u2022 ${i.label} \u2014 ${i.paths.length} article${i.paths.length===1?"":"s"}`),"",`Estimated cost: ${De(r)}\u2013${De(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Mi(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),i=e.reduce((R,C)=>R+o(C),0),c=r.reduce((R,C)=>R+o(C),0),p=e.reduce((R,C)=>R+C.costUsd,0),h=e.reduce((R,C)=>R+C.outputTokens,0),b=n==="api"?`${De(p)} total`:bt(h),$=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=R=>`${R} article${R===1?"":"s"}`,E=[];if(s.length===0)E.push(`Wrote ${v(i)} (${$}) successfully \xB7 ${b}.`),E.push("Next \u2014 push them to Document360:"),E.push("/publish --all"),E.push("Or add screenshots first with /screenshot author --all. Drafts are reviewable in the portal after publishing.");else{E.push(`Wrote ${c}/${v(i)} (${$}) \xB7 ${b}.`),E.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let R of s)E.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return E}function Ui(e,t,n){try{let o=Tg({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 Fi(e,t,n){let o=(Wd(e)?.docsDir??Ag).replace(/\/+$/,""),r=t.map(c=>c.path);if(n.path){let c=Mg(n.path,o);return r.includes(c)?{docsDir:o,targets:[c],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${c}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=Ug(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 i=Ii(e,o,s);if(i.length===0){let c=n.scope?` under "${n.scope}"`:"",p=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${c} are already written. Use /write <path> to rewrite one, or /write${p} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}async function Bd(e,t){if(!Wd(t.cwd))return console.log(D("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Ir(e)){for(let I of _d(t.cwd,t.profileName))console.log(g(I));return{kind:"continue"}}if(Ct("write",e)){let I=Cn(t.cwd,"write",e,t.profileName);if(I.length>0){for(let G of I)console.log(g(G));return{kind:"continue"}}}let n=Dg(t.cwd);if(n.length===0)return console.log(D("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:i,rewrite:c}=Ni(e),{docsDir:p,targets:h,reason:b,rewriting:$}=Fi(t.cwd,n,{scope:o,path:r,rewrite:c});if(h.length===0)return console.log(b?H(b):H("Nothing to write.")),{kind:"continue"};$&&console.log(H(`--rewrite: regenerating ${h.length} already-written article${h.length===1?"":"s"} (overwrites them; git has your baseline).`));let v=Eg(h),E=ji(i),{model:R,forced:C}=jg(t.cwd,"standard"),P=!!r;if(s&&!P){let I=Pg({files:Oi(t.cwd,n,h),op:"write",model:R});o&&console.log(g(`Scope: ${o} (${h.length} pending).`));for(let G of _i(v,I,E))console.log(G);return console.log(g(`Model: ${R}${C?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(g(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(g(`Writing ${h.length} article${h.length===1?"":"s"} across ${v.length} partition${v.length===1?"":"s"} (\u2264${E} agents at once) on ${R}\u2026`)),console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let I of Ng({cwd:t.cwd,partitions:v,promptFor:G=>Li(G,p,{rewrite:$||P}),concurrency:E,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:R}))if(I.type==="partition_status")I.status==="running"?console.log(g(` \u25B8 ${I.label} \u2014 writing\u2026`)):I.status==="done"?console.log(M(` \u2713 ${I.label}`)):console.log(D(` \u2717 ${I.label}`));else if(I.type==="run_done"){console.log("");let G=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let Y of Mi(I.results,v,G))console.log(I.ok?M(Y):H(Y));if(I.ok)try{Ig(t.cwd,h.map(Y=>`${p}/${Y}`),{writtenCap:Og})}catch{}let q=Ui(t.cwd,p,h);q&&console.log(H(q))}}catch(I){console.log(D(`Write run failed: ${I.message}`))}return console.log(""),{kind:"continue"}}K();import{existsSync as Fg,readdirSync as Hd,statSync as qd}from"node:fs";import{join as Vd}from"node:path";import{inputDir as Wg,readProjectConfig as Bg}from"document360-engine";var Gd=/\.(md|markdown|pdf|txt)$/i;function Wi(e){let t=Wg(e);if(!Fg(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Hd(t)){let s=Vd(t,r),i=!1;try{i=qd(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let c=Hg(s);c>0&&n.push({name:r,docCount:c})}else Gd.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Hg(e){let t=0;for(let n of Hd(e))try{qd(Vd(e,n)).isFile()&&Gd.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 Or(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(`
351
+ `)}var Hi="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Yd(e,t){let n=t?.cwd??process.cwd();if(!Bg(n))return console.log(D("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Wi(n);if(o.length===0&&r===0)return console.log(g(Hi)),{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 p of o)console.log(` ${p.name} ${g(`(${p.docCount} doc${p.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let c=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Or(c),display:c?`/draft ${c}`:"/draft"}}let i=Bi(o,s);return{kind:"forward-to-agent",prompt:Or(i??"",i?void 0:s),display:`/draft ${s}`}}K();import{listOpenForDocs as qg,readProjectConfig as Vg}from"document360-engine";function qi(e){try{return qg(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 Gi(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(`
352
+ `)}var Yi="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 zd(e,t){let n=t?.cwd??process.cwd();if(!Vg(n))return console.log(D("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Vi(e);if(!r&&qi(n)===0)return console.log(g(Yi)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Gi(r,o),display:s}}K();import{search as Gg}from"@inquirer/prompts";import{findByName as Yg,getSession as zg,listSessions as Kg,relativeTime as Xd}from"document360-engine";async function Qd(e,t){let n=Kg(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=Yg(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(D(`No session matches "${o}".`)),Kd(n),{kind:"continue"})}if(!process.stdin.isTTY)return Kd(n),console.log(g("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Gg({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let i=(s??"").toLowerCase();return n.filter(c=>!i||c.name.toLowerCase().includes(i)||c.firstPrompt.toLowerCase().includes(i)).map(c=>({name:`${c.name} ${Xd(c.updatedAt)}`,value:c.uuid,description:c.firstPrompt.slice(0,100)}))}})),r=zg(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Kd(e){console.log("");for(let t of e.slice(0,15))console.log(` ${W(t.name)} ${g(Xd(t.updatedAt))}`),console.log(` ${g(t.firstPrompt.slice(0,80))}`);console.log("")}K();import{renameSession as Xg}from"document360-engine";function zi(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 Jd(e,t){let n=zi(e.join(" "));if(!n)return console.log(D("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Xg(o,n)?console.log(M(`\u2713 Session renamed to "${n}"`)):console.log(D("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(M(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Zd,readProjectConfig as Qg,writeProjectConfig as Jg}from"document360-engine";K();function Ki(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Qg(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 Zd().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Jg(o,e),null):`Unknown environment "${r}". Known: ${Zd().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function eu(e,t){let n=e[0];if(!n)return er(t.cwd),{kind:"continue"};if(n==="add"){let o=Ki(t.cwd,e[1],e[2]);return o?(console.log(D(o)),{kind:"continue"}):(console.log(M(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${W(`/profile ${e[1]}`)} then ${W("/login")}`),{kind:"continue"})}return tr(t.cwd,n),nr(t.cwd,n),console.log(g(" Restarting agent for the new profile\u2026")),{kind:"clear"}}K();import{select as Zg}from"@inquirer/prompts";import{readProjectConfig as ey,readUserConfig as tu,resolveModelSetting as Xi,writeUserConfig as nu}from"document360-engine";var Je=[{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 Lr(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Je.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function ty(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 io(e,t){let n=()=>Xi(e).model;if(t==="default"){let s=tu();return s.defaultModel?(delete s.defaultModel,nu(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Xi(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}}nu({...tu(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=ey(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 ou(e,t){let n=e[0]?.trim();if(!n){let i=Xi(t.cwd);if(!process.stdin.isTTY)return console.log(`${Ee("Model:")} ${W(i.model)}${i.source==="auto"?g(" (auto)"):""}`),console.log(g(` source: ${ty(i)}`)),console.log(g(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let c=Lr(i),p;try{p=await t.withPausedInput(()=>Zg({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:Je[c].value,choices:Je.map((v,E)=>({name:`${v.label}${E===c?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}let{lines:h,changed:b,effective:$}=io(t.cwd,p??"default");for(let v of h)console.log(v.startsWith("\u26A0")?H(v):v.startsWith("\u2713")?M(v):g(v));return b&&await t.setModel($),{kind:"continue"}}let{lines:o,changed:r,effective:s}=io(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?H(i):i.startsWith("\u2713")?M(i):g(i));return r&&await t.setModel(s),{kind:"continue"}}_r();async function lu(e,t){return await t.withPausedInput(()=>hn(t.cwd)),{kind:"clear"}}async function du(e,t){return await t.withPausedInput(()=>Xo(t.cwd,t.profileName)),{kind:"clear"}}K();import{resolveActiveProfile as by}from"document360-engine";async function uu(e,t){let n=!1;try{n=by(t.cwd).production}catch{}return n?(console.log(H("\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"})}K();var pu=async(e,t)=>{try{await t.withPausedInput(()=>Zo({}))}catch(n){console.log(D(`Login failed: ${n.message}`))}return{kind:"continue"}};K();import{resolveActiveProfile as $y,clearTokens as vy,clearProfileProject as xy}from"document360-engine";async function hu(e,t){let n;try{n=$y(t.cwd,t.profileName).name}catch(r){return console.log(D(r.message)),{kind:"continue"}}let o=vy(n);return xy(t.cwd,n),console.log(o?M(`\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 mu}from"node:child_process";import{existsSync as Zi,readFileSync as Ji,statSync as Ay}from"node:fs";import{homedir as jy}from"node:os";import{basename as Ny,join as po}from"node:path";import{readProjectConfig as Iy,DEFAULT_OUTPUT_DIR as Oy,existingAnnotatedShotPath as Ly,resolveOutputDir as _y}from"document360-engine";import Ae from"picocolors";import{annotationsPath as Cy,resolveOutputDir as Ry,readProjectConfig as Sy,DEFAULT_OUTPUT_DIR as Py,existingAnnotatedShotPath as Ty}from"document360-engine";function Ey(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function co(e){return e.filter(t=>t.state==="captured").map(t=>t.id)}function qt(e,t){let n=Ry(e,Sy(e)?.outputDir??Py),o=new Map(ve(e).map(i=>[i.id,i])),r=i=>i.replace(`${e}\\`,"").replace(`${e}/`,"").replace(/\\/g,"/"),s=t.map(i=>{let c=o.get(i)?.file??"(unknown article)";return[`- ${i}`,` image: ${r(Ty(n,i))}`,` facts: ${r(Cy(n,i))}`,` article: ${c}`].join(`
353
353
  `)}).join(`
354
354
  `);return[`Run the review-screenshots skill over ${t.length} newly captured screenshot${t.length===1?"":"s"}.`,"","For EACH shot below:","1. READ THE IMAGE FILE. Actually look at the picture \u2014 this judgment cannot be made from the spec"," source or the JSON alone.","2. Read its facts JSON (the `capture` block records what the capture observed: image dimensions,"," crop origin, whether the origin was inferred rather than declared, selectors that never resolved,"," and boxes that fell outside the frame).","3. Read the article to see what the placeholder promises the reader at that point.","4. Record a verdict with d360_verify_screenshot \u2014 every shot gets exactly one call.",' On "rejected": give a one-line plain-language reason, then FIX THE SPEC that produced it and pass'," repaired: true. Do not re-run the capture yourself; the user does that.","",s,"","Then report to the user briefly: ONE line per rejected shot naming the defect in plain words and what","you changed. Do NOT state counts, totals, or the re-capture command \u2014 an exact receipt is printed from","your recorded verdicts right after your report, so any number you state can only contradict it."].join(`
355
- `)}function lo(e){return`${ye("\u2192",Ae.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var Py=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function uo(e,t){if(t.length===0)return[];let n=at(e).shots,o=[],r=[],s=[];for(let c of t){let p=n[c]?.review;p?p.verdict==="ok"?o.push(c):r.push({id:c,reason:p.reason??"no reason recorded",repaired:!!p.repaired}):s.push(c)}let i=[""];if(i.push(`${ye("\u2714",Ae.green)}${Ae.green(`${o.length} verified`)}`+(r.length>0?` ${Ae.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${Ae.yellow(`? ${s.length} not verified`)}`:"")+Ae.gray(` ${t.length} shot${t.length===1?"":"s"} in this pass`)),r.length>0){let c=Math.max(...r.map(h=>h.id.length));for(let h of r)i.push(` ${Ae.magenta(h.id.padEnd(c))} ${Ae.gray(Py(h.reason))}`);let p=r.filter(h=>h.repaired).length;i.push(`${ye("\u2192",Ae.magenta)}Re-capture the ${r.length} flagged: ${Ae.bold("/screenshot capture --failed")}`+(p<r.length?Ae.gray(` (${r.length-p} still need${r.length-p===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${ye("\u26A0",Ae.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${Ae.bold("/screenshot verify")} again.`),i}async function pu(e,t){let n=t?.cwd??process.cwd(),o=eo(n);o&&console.log(o);let r=$e(n),s=Sy(e);if(s.mode==="single"){let c=r.find(p=>p.id===s.id);return c?["captured","verified","rejected"].includes(c.state)?{kind:"forward-to-agent",prompt:qt(n,[s.id]),display:`/screenshot verify ${s.id}`}:(console.log(`"${s.id}" has no captured image yet \u2014 /screenshot capture ${s.id} takes the shot first.`),{kind:"continue"}):(console.log(`No screenshot placeholder called "${s.id}". /screenshot list shows them all.`),{kind:"continue"})}let i=co(r);if(i.length===0){let c=r.filter(h=>h.state==="verified").length,p=r.filter(h=>h.state==="rejected").length;return console.log(p>0?`Nothing left to verify. ${p} shot${p===1?"":"s"} failed verification \u2014 re-capture with: /screenshot capture --failed`:c>0?`All ${c} captured shot${c===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."),{kind:"continue"}}return{kind:"forward-to-agent",prompt:qt(n,i),display:"/screenshot verify"}}var Oy=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function ea(e){let t=e.find(o=>!o.startsWith("--")),n=e.includes("--blocked")||e.includes("--retry-blocked");return e.includes("--failed")?{mode:"failed"}:e.includes("--all")?{mode:"all",retryBlocked:n}:!t&&n?{mode:"blocked"}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:Oy(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function ho(e,t){let n=$e(e,t),o=r=>n.filter(s=>s.state===r).map(s=>s.id);return{ready:o("spec"),captured:[...o("captured"),...o("verified"),...o("rejected")].sort(),blocked:o("blocked"),broken:o("broken"),rejected:o("rejected"),rows:n}}function fu(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"||s.state==="verified"),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}),gr(o,t,"capture"),ui(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected"));for(let s of[...n].sort((i,c)=>i.id.localeCompare(c.id))){let i=s.state==="verified"?" \u2714 verified \u2014 re-capture":" \u25CF to verify \u2014 re-capture";o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:i})}return o}function ta(e,t){let n=new Set(t.filter(r=>r.state!=="placeholder").map(r=>r.id)),o=t.filter(r=>r.state==="rejected").map(r=>r.id);return[...new Set([...Il(e).filter(r=>n.has(r)),...o])].sort()}function na(e,t){let n=e.length;if(n===0)return null;let o=to(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(`
356
- `)}function Ly(e,t){let n=Dy(e)?.outputDir??jy;return Ny(Iy(e,n),t)}function oa(e,t,n,o){let r=Ly(e,t);return Zi(r)&&Ty(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function mu(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}var _y=/element is not (?:enabled|visible|stable|editable)|intercepts pointer events|outside of the viewport|element is not attached/i;function gu(e){let t=e.split(/\r?\n/).map(s=>s.trim()).filter(Boolean),n=t.filter(s=>/\b\w*Error\b|Cannot navigate|Timeout \d+m?s (exceeded|waiting)|net::|browser has been closed/i.test(s)&&!/^Error Context:/i.test(s)),o=[...new Set(t.filter(s=>_y.test(s)).map(s=>s.replace(/^-\s*/,"")))].slice(0,2),r=t.find(s=>/locator resolved to/i.test(s))?.replace(/^-\s*/,"");return n.length>0||o.length>0?[...new Set([...n].slice(0,2)),...o,...r&&o.length>0?[r.length>120?`${r.slice(0,119)}\u2026`:r]:[]].join(`
355
+ `)}function lo(e){return`${we("\u2192",Ae.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var Dy=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function uo(e,t){if(t.length===0)return[];let n=at(e).shots,o=[],r=[],s=[];for(let c of t){let p=n[c]?.review;p?p.verdict==="ok"?o.push(c):r.push({id:c,reason:p.reason??"no reason recorded",repaired:!!p.repaired}):s.push(c)}let i=[""];if(i.push(`${we("\u2714",Ae.green)}${Ae.green(`${o.length} verified`)}`+(r.length>0?` ${Ae.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${Ae.yellow(`? ${s.length} not verified`)}`:"")+Ae.gray(` ${t.length} shot${t.length===1?"":"s"} in this pass`)),r.length>0){let c=Math.max(...r.map(h=>h.id.length));for(let h of r)i.push(` ${Ae.magenta(h.id.padEnd(c))} ${Ae.gray(Dy(h.reason))}`);let p=r.filter(h=>h.repaired).length;i.push(`${we("\u2192",Ae.magenta)}Re-capture the ${r.length} flagged: ${Ae.bold("/screenshot capture --failed")}`+(p<r.length?Ae.gray(` (${r.length-p} still need${r.length-p===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${we("\u26A0",Ae.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${Ae.bold("/screenshot verify")} again.`),i}async function fu(e,t){let n=t?.cwd??process.cwd(),o=eo(n);o&&console.log(o);let r=ve(n),s=Ey(e);if(s.mode==="single"){let c=r.find(p=>p.id===s.id);return c?["captured","verified","rejected"].includes(c.state)?{kind:"forward-to-agent",prompt:qt(n,[s.id]),display:`/screenshot verify ${s.id}`}:(console.log(`"${s.id}" has no captured image yet \u2014 /screenshot capture ${s.id} takes the shot first.`),{kind:"continue"}):(console.log(`No screenshot placeholder called "${s.id}". /screenshot list shows them all.`),{kind:"continue"})}let i=co(r);if(i.length===0){let c=r.filter(h=>h.state==="verified").length,p=r.filter(h=>h.state==="rejected").length;return console.log(p>0?`Nothing left to verify. ${p} shot${p===1?"":"s"} failed verification \u2014 re-capture with: /screenshot capture --failed`:c>0?`All ${c} captured shot${c===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."),{kind:"continue"}}return{kind:"forward-to-agent",prompt:qt(n,i),display:"/screenshot verify"}}var My=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function ea(e){let t=e.find(o=>!o.startsWith("--")),n=e.includes("--blocked")||e.includes("--retry-blocked");return e.includes("--failed")?{mode:"failed"}:e.includes("--all")?{mode:"all",retryBlocked:n}:!t&&n?{mode:"blocked"}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:My(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function ho(e,t){let n=ve(e,t),o=r=>n.filter(s=>s.state===r).map(s=>s.id);return{ready:o("spec"),captured:[...o("captured"),...o("verified"),...o("rejected")].sort(),blocked:o("blocked"),broken:o("broken"),rejected:o("rejected"),rows:n}}function gu(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"||s.state==="verified"),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}),gr(o,t,"capture"),ui(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected"));for(let s of[...n].sort((i,c)=>i.id.localeCompare(c.id))){let i=s.state==="verified"?" \u2714 verified \u2014 re-capture":" \u25CF to verify \u2014 re-capture";o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:i})}return o}function ta(e,t){let n=new Set(t.filter(r=>r.state!=="placeholder").map(r=>r.id)),o=t.filter(r=>r.state==="rejected").map(r=>r.id);return[...new Set([...Ll(e).filter(r=>n.has(r)),...o])].sort()}function na(e,t){let n=e.length;if(n===0)return null;let o=to(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(`
356
+ `)}function Uy(e,t){let n=Iy(e)?.outputDir??Oy;return Ly(_y(e,n),t)}function oa(e,t,n,o){let r=Uy(e,t);return Zi(r)&&Ay(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function yu(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}var Fy=/element is not (?:enabled|visible|stable|editable)|intercepts pointer events|outside of the viewport|element is not attached/i;function wu(e){let t=e.split(/\r?\n/).map(s=>s.trim()).filter(Boolean),n=t.filter(s=>/\b\w*Error\b|Cannot navigate|Timeout \d+m?s (exceeded|waiting)|net::|browser has been closed/i.test(s)&&!/^Error Context:/i.test(s)),o=[...new Set(t.filter(s=>Fy.test(s)).map(s=>s.replace(/^-\s*/,"")))].slice(0,2),r=t.find(s=>/locator resolved to/i.test(s))?.replace(/^-\s*/,"");return n.length>0||o.length>0?[...new Set([...n].slice(0,2)),...o,...r&&o.length>0?[r.length>120?`${r.slice(0,119)}\u2026`:r]:[]].join(`
357
357
  `):ra(e)}function ra(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(`
358
- `)}var My=/^[A-Za-z0-9._-]+$/;function sa(e){return new Promise((t,n)=>{if(!My.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=hu(`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",i=>{r+=i.toString()}),o.stderr?.on("data",i=>{r+=i.toString()}));let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",i=>{e.signal?.removeEventListener("abort",s),n(i)}),o.on("close",i=>{e.signal?.removeEventListener("abort",s),t({exitCode:i??1,output:r})})})}function yu(e,t=Ey()){try{let n=JSON.parse(Ji(po(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(Ji(po(e,"package.json"),"utf8")).name}catch{}o||=Ay(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?Zi(po(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function wu(e){return new Promise((t,n)=>{let o=hu("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",i=>{r+=i.toString()}),o.stderr?.on("data",i=>{r+=i.toString()});let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",i=>{e.signal?.removeEventListener("abort",s),n(i)}),o.on("close",i=>{e.signal?.removeEventListener("abort",s),t({exitCode:i??1,output:r})})})}function ia(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function ku(e){try{let t=JSON.parse(Ji(po(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 Ur(e){return Zi(po(e,".d360-writer","capture.json"))}function aa(){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(`
359
- `)}function bu(e,t){let n=e.filter(i=>i.state==="blocked"&&i.blockedBy!=="testid").length,o=e.filter(i=>i.state==="blocked"&&i.blockedBy==="testid").length,r=t+n+o;if(r===0)return null;let s=[];return t>0&&s.push(`${t} write${t===1?"s":""} real data`),n>0&&s.push(`${n} blocked on data`),o>0&&s.push(`${o} wait${o===1?"s":""} on a developer`),` ${r} held back \u2014 ${s.join(", ")}
360
- /screenshot list --detail shows what each one needs`}function $u(e,t){let n={newlyCaptured:[],newlyBlocked:[],stillBroken:[],newlyBroken:[],brokeDifferently:[],repairedNowBlocked:[],blockedAsBefore:[],blockedNewReason:[]};for(let o of t){let r=e.shots[o.id],s=r?.outcome;o.outcome==="captured"&&s!=="captured"?n.newlyCaptured.push(o.id):o.outcome==="failed"?s!=="failed"?n.newlyBroken.push(o.id):Mr(r?.reason)!==Mr(o.detail)?n.brokeDifferently.push(o.id):n.stillBroken.push(o.id):o.outcome==="skipped"&&(s==="failed"?n.repairedNowBlocked.push(o.id):s!=="skipped"?n.newlyBlocked.push(o.id):xr(r?.reason??"")!==xr(o.detail??"")?n.blockedNewReason.push(o.id):n.blockedAsBefore.push(o.id))}return n}function Mr(e,t=72){let o=((e??"no error text captured").split(/\r?\n/).map(r=>r.trim()).find(Boolean)??"").replace(/^(Error|TimeoutError):\s*/i,"").replace(/\s+/g," ");return o.length>t?`${o.slice(0,t-1)}\u2026`:o}function vu(e,t=3){if(e.length===0||e.length>t)return[];let n=Math.max(...e.map(o=>o.id.length));return e.map(o=>`\u2298 ${o.id.padEnd(n)} ${o.detail?xn(o.detail):"no reason recorded"}`)}function Rn(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function xu(e,t){if(!t)return[];let n=[],o=(i,c,p,h)=>{c>0&&n.push({glyph:i,label:`${c} ${p}`,tail:h})};if(o("\u2713",e.newlyCaptured.length,"newly captured",Rn(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",Rn(e.newlyBroken)),o("\u2192",e.repairedNowBlocked.length,"repaired",`no longer broken \u2014 only data stands in the way \xB7 ${Rn(e.repairedNowBlocked)}`),o("\u2298",e.newlyBlocked.length,"newly blocked",Rn(e.newlyBlocked)),o("\u2192",e.blockedNewReason.length,"blocked on something new",`an earlier step now passes \xB7 ${Rn(e.blockedNewReason)}`),o("\u2192",e.brokeDifferently.length,"broken differently",`the previous cause is fixed \xB7 ${Rn(e.brokeDifferently)}`),o("\u2717",e.stillBroken.length,"still broken","same error \u2014 these need re-authoring"),o("\xB7",e.blockedAsBefore.length,"blocked as before","nothing staged since last time"),n.length===0)return[];let r=Math.max(...n.map(i=>i.label.length));return[""," Since your last run",...n.map(i=>` ${i.glyph} ${i.label.padEnd(r)} ${i.tail}`)]}function Cu(e){let t=e.results.filter($=>$.outcome==="captured"),n=e.results.filter($=>$.outcome==="skipped"),o=e.results.filter($=>$.outcome==="failed"),r=$=>$===1?"":"s";if(t.length+n.length+o.length===0)return null;let s=e.articles.length===1?`/publish ${e.articles[0]}`:"/publish --screenshots",i=e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",c=o[0]?.id,p=[];o.length>0&&p.push({glyph:"\u2717",cmd:`/screenshot ${c}`,why:`re-author the ${o.length===1?"broken spec":`first of ${o.length} broken specs`} \u2014 re-running fails the same way`}),n.length>0&&p.push({glyph:"\u2298",cmd:"/screenshot list",why:`what to stage for the ${n.length} blocked shot${r(n.length)}`}),t.length>0&&p.push({glyph:"\u2713",cmd:s,why:`embed the ${t.length} new PNG${r(t.length)}`});let h=Math.max(...p.map($=>$.cmd.length));return{note:p.map($=>`${$.glyph} ${$.cmd.padEnd(h)} ${$.why}`).join(`
361
- `),cmd:o.length>0?`/screenshot ${c}`:t.length>0?s:i,tone:o.length>0?"warn":"info"}}function Ru(e,t){let n=new Map($e(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function ca(e,t){let n=t?.cwd??process.cwd(),o=ea(e);if(!Ur(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:i,rows:c}=ho(n,o.mode==="scope"?o.scope:void 0),p=ta(n,c),h=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,b=o.mode==="single"?[o.id]:o.mode==="failed"?p:o.mode==="blocked"?i:o.mode==="picker"?r:[...r,...s,...h?i:[]];if(b.length===0)return o.mode==="failed"?console.log("No broken specs to re-run \u2014 /screenshot list shows where things stand."):o.mode==="blocked"?console.log("No shots are waiting on app data \u2014 /screenshot list shows where things stand."):console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};if(!h&&o.mode!=="single"&&o.mode!=="failed"&&o.mode!=="blocked"){let x=na(c.filter(T=>T.state==="blocked"),"/screenshot capture --blocked");x&&console.log(x)}let $=Date.now(),v=[];for(let x of b){console.log(`\u25B6 ${x}`);try{let{exitCode:T}=await sa({cwd:n,id:x,stdio:"inherit"});v.push({id:x,outcome:oa(n,x,T,$)})}catch(T){if(T.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};v.push({id:x,outcome:"failed",detail:T.message})}}let E=x=>v.filter(T=>T.outcome===x).length;console.log(`\u2713 ${E("captured")} captured \xB7 \u2298 ${E("skipped")} skipped \xB7 \u2717 ${E("failed")} failed`);let R=v.filter(x=>x.outcome==="captured");return pr(n,v.map(x=>({id:x.id,outcome:x.outcome,reason:x.detail,specSource:vn(n,x.id)})),new Date().toISOString()),R.length>0?(console.log(lo(R.length)),{kind:"forward-to-agent",prompt:qt(n,R.map(x=>x.id)),display:"/screenshot verify"}):{kind:"continue"}}import{existsSync as Uy,readFileSync as Fy}from"node:fs";import{isAbsolute as Wy,join as By,resolve as Hy}from"node:path";import{readProjectConfig as qy,DEFAULT_CAPTURE_DIR as Vy}from"document360-engine";async function Sn(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-writer/capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-CHECKLIST.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
362
- `),display:"/screenshot checklist"}}var Su="-".repeat(64);function la(e){let t=Vy;try{let b=qy(e);b?.captureDir&&(t=b.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Wy(t)?By(t,"CAPTURE-TESTID-REQUESTS.json"):Hy(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Uy(n))return null;let o;try{let b=JSON.parse(Fy(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,i=`${s} data-testid attribute${s===1?"":"s"}`,c=`${r} source file${r===1?"":"s"}`,p=`${t}/CAPTURE-TESTID-REQUESTS.md`,h=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${i} requested across ${c}.`,"\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.","",Su,`Read ${p} and ${h}. They list ${i} 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.",Su]}wt();K();import{listOpenForDocs as Gy,readProjectConfig as Yy}from"document360-engine";function da(e){try{return Gy(e).length}catch{return 0}}function ua(){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(`
363
- `)}async function Pu(e,t){let n=t?.cwd??process.cwd();return Yy(n)?da(n)===0?(console.log(y("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:ua(),display:"/inbox"}:(console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"})}K();import{listOpenHints as zy,listOpenForDocs as Ky,listOpenDirectives as Xy,readProjectConfig as Qy,computeSyncStatus as Jy,planPull as Zy,applyPull as ew,planImport as tw,applyImport as nw}from"document360-engine";function fo(e){let t=0,n=0,o=0,r=0;try{t=zy(e).length}catch{}try{let s=Ky(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=Xy(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function mo(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 ha(e){return{publish:e.includes("--publish")}}function fa({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 (say plainly that you left a question for their engineers). Write the whole summary for a technical writer: no tool names, no internal file names, no raw status words, no hint ids \u2014 plain sentences about what changed and what is worth their attention."),t.join(`
364
- `)}var ow={status:Jy,plan:Zy,apply:ew,planImport:tw,applyImport:nw};async function ma(e,t=ow){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 pa=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Fr=e=>e===1?"":"s";function ga(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${Fr(e.pulled.length)} into local: ${pa(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Fr(e.imported.length)} into local drafts: ${pa(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Fr(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${pa(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${Fr(e.failed.length)} failed \u2014 left for /pull.`),t}async function Tu(e,t){let n=t?.cwd??process.cwd();if(!Qy(n))return console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ve(n,t?.profileName);if(!o.ok)return console.log(A(o.reason)),{kind:"continue"};let{publish:r}=ha(e);console.log(y("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await ma({cwd:n,profileName:t?.profileName});for(let c of ga(s))console.log(c.startsWith("\u2713")?M(c):c.startsWith("\u2139")?y(c):B(c));let i=mo(fo(n));return console.log(y(i?`Catching up on ${i}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:fa({publish:r}),display:`/catch-up${r?" --publish":""}`}}K();import{spawn as Eu}from"node:child_process";var Pn="document360-writer",Wr=`npm i -g ${Pn}@latest`,rw="document360-capture";function sw(){return new Promise(e=>{try{let t=Eu("d360-capture --version",{stdio:"ignore",shell:!0,windowsHide:!0});t.on("error",()=>e(!1)),t.on("close",n=>e(n===0))}catch{e(!1)}})}async function Br(){let e=process.platform==="win32",n=await sw()?[Pn,rw]:[Pn];return new Promise(o=>{try{let r=Eu(`npm i -g ${n.map(s=>`${s}@latest`).join(" ")}`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});r.on("error",s=>o({ok:!1,output:String(s),packages:n})),r.on("close",s=>o({ok:s===0,output:"",packages:n})),e||r.unref()}catch(r){o({ok:!1,output:String(r),packages:n})}})}async function Au(){console.log(y("Updating the d360-writer toolchain\u2026"));let e=await Br();return e.ok?console.log(M(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)):console.log(A(`Update failed \u2014 run manually: ${Wr}`)),{kind:"continue"}}K();wt();import{existsSync as ya,rmSync as iw}from"node:fs";import{basename as Du,resolve as wa}from"node:path";import{execFileSync as aw}from"node:child_process";import{input as cw}from"@inquirer/prompts";import{readProjectConfig as lw,devHintsGuidePath as dw}from"document360-engine";var uw=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],pw=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Hr=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),ju=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Nu(e){let t=Hr(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:ju(t)?!0:pw.has(t)}function ka(e){let t=null;try{t=lw(e)}catch{t=null}let n=new Set(uw);for(let o of[Hr(t?.docsDir),Hr(t?.captureDir),Hr(t?.outputDir)])o&&ju(o)&&n.add(o);return[...n].filter(o=>Nu(o)&&ya(wa(e,o)))}function ba(e,t){let n=[],o=[];for(let r of t){if(!Nu(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{iw(wa(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Iu(e,t){try{return aw("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
365
- `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function hw(e){return Iu(e,".d360-writer/hints")}function fw(e){return Iu(e,".d360-writer/messages")}function $a(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=hw(e),o=fw(e),r=ya(wa(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: ${Du(e)}`]}async function Ou(e,t){let n=ka(t.cwd);for(let p of $a(t.cwd,n))console.log(n.length===0?y(p):p);if(n.length===0)return{kind:"continue"};let o=Du(t.cwd);if((await t.withPausedInput(()=>cw({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(B("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=ya(dw(t.cwd)),{removed:i,failed:c}=ba(t.cwd,n);console.log(M(`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`));for(let p of c)console.log(A(` \u2717 ${p.path}: ${p.error}`));if(s){for(let p of ar())console.log(p);console.log(y("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(y("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}K();import{lintDocs as mw}from"document360-engine";function qr(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 va(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(`
358
+ `)}var Wy=/^[A-Za-z0-9._-]+$/;function sa(e){return new Promise((t,n)=>{if(!Wy.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=mu(`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",i=>{r+=i.toString()}),o.stderr?.on("data",i=>{r+=i.toString()}));let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",i=>{e.signal?.removeEventListener("abort",s),n(i)}),o.on("close",i=>{e.signal?.removeEventListener("abort",s),t({exitCode:i??1,output:r})})})}function ku(e,t=jy()){try{let n=JSON.parse(Ji(po(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(Ji(po(e,"package.json"),"utf8")).name}catch{}o||=Ny(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?Zi(po(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function bu(e){return new Promise((t,n)=>{let o=mu("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",i=>{r+=i.toString()}),o.stderr?.on("data",i=>{r+=i.toString()});let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",i=>{e.signal?.removeEventListener("abort",s),n(i)}),o.on("close",i=>{e.signal?.removeEventListener("abort",s),t({exitCode:i??1,output:r})})})}function ia(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function $u(e){try{let t=JSON.parse(Ji(po(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 Ur(e){return Zi(po(e,".d360-writer","capture.json"))}function aa(){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(`
359
+ `)}function vu(e,t){let n=e.filter(i=>i.state==="blocked"&&i.blockedBy!=="testid").length,o=e.filter(i=>i.state==="blocked"&&i.blockedBy==="testid").length,r=t+n+o;if(r===0)return null;let s=[];return t>0&&s.push(`${t} write${t===1?"s":""} real data`),n>0&&s.push(`${n} blocked on data`),o>0&&s.push(`${o} wait${o===1?"s":""} on a developer`),` ${r} held back \u2014 ${s.join(", ")}
360
+ /screenshot list --detail shows what each one needs`}function xu(e,t){let n={newlyCaptured:[],newlyBlocked:[],stillBroken:[],newlyBroken:[],brokeDifferently:[],repairedNowBlocked:[],blockedAsBefore:[],blockedNewReason:[]};for(let o of t){let r=e.shots[o.id],s=r?.outcome;o.outcome==="captured"&&s!=="captured"?n.newlyCaptured.push(o.id):o.outcome==="failed"?s!=="failed"?n.newlyBroken.push(o.id):Mr(r?.reason)!==Mr(o.detail)?n.brokeDifferently.push(o.id):n.stillBroken.push(o.id):o.outcome==="skipped"&&(s==="failed"?n.repairedNowBlocked.push(o.id):s!=="skipped"?n.newlyBlocked.push(o.id):xr(r?.reason??"")!==xr(o.detail??"")?n.blockedNewReason.push(o.id):n.blockedAsBefore.push(o.id))}return n}function Mr(e,t=72){let o=((e??"no error text captured").split(/\r?\n/).map(r=>r.trim()).find(Boolean)??"").replace(/^(Error|TimeoutError):\s*/i,"").replace(/\s+/g," ");return o.length>t?`${o.slice(0,t-1)}\u2026`:o}function Cu(e,t=3){if(e.length===0||e.length>t)return[];let n=Math.max(...e.map(o=>o.id.length));return e.map(o=>`\u2298 ${o.id.padEnd(n)} ${o.detail?xn(o.detail):"no reason recorded"}`)}function Rn(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function Ru(e,t){if(!t)return[];let n=[],o=(i,c,p,h)=>{c>0&&n.push({glyph:i,label:`${c} ${p}`,tail:h})};if(o("\u2713",e.newlyCaptured.length,"newly captured",Rn(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",Rn(e.newlyBroken)),o("\u2192",e.repairedNowBlocked.length,"repaired",`no longer broken \u2014 only data stands in the way \xB7 ${Rn(e.repairedNowBlocked)}`),o("\u2298",e.newlyBlocked.length,"newly blocked",Rn(e.newlyBlocked)),o("\u2192",e.blockedNewReason.length,"blocked on something new",`an earlier step now passes \xB7 ${Rn(e.blockedNewReason)}`),o("\u2192",e.brokeDifferently.length,"broken differently",`the previous cause is fixed \xB7 ${Rn(e.brokeDifferently)}`),o("\u2717",e.stillBroken.length,"still broken","same error \u2014 these need re-authoring"),o("\xB7",e.blockedAsBefore.length,"blocked as before","nothing staged since last time"),n.length===0)return[];let r=Math.max(...n.map(i=>i.label.length));return[""," Since your last run",...n.map(i=>` ${i.glyph} ${i.label.padEnd(r)} ${i.tail}`)]}function Su(e){let t=e.results.filter($=>$.outcome==="captured"),n=e.results.filter($=>$.outcome==="skipped"),o=e.results.filter($=>$.outcome==="failed"),r=$=>$===1?"":"s";if(t.length+n.length+o.length===0)return null;let s=e.articles.length===1?`/publish ${e.articles[0]}`:"/publish --screenshots",i=e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",c=o[0]?.id,p=[];o.length>0&&p.push({glyph:"\u2717",cmd:`/screenshot ${c}`,why:`re-author the ${o.length===1?"broken spec":`first of ${o.length} broken specs`} \u2014 re-running fails the same way`}),n.length>0&&p.push({glyph:"\u2298",cmd:"/screenshot list",why:`what to stage for the ${n.length} blocked shot${r(n.length)}`}),t.length>0&&p.push({glyph:"\u2713",cmd:s,why:`embed the ${t.length} new PNG${r(t.length)}`});let h=Math.max(...p.map($=>$.cmd.length));return{note:p.map($=>`${$.glyph} ${$.cmd.padEnd(h)} ${$.why}`).join(`
361
+ `),cmd:o.length>0?`/screenshot ${c}`:t.length>0?s:i,tone:o.length>0?"warn":"info"}}function Pu(e,t){let n=new Map(ve(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function ca(e,t){let n=t?.cwd??process.cwd(),o=ea(e);if(!Ur(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:i,rows:c}=ho(n,o.mode==="scope"?o.scope:void 0),p=ta(n,c),h=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,b=o.mode==="single"?[o.id]:o.mode==="failed"?p:o.mode==="blocked"?i:o.mode==="picker"?r:[...r,...s,...h?i:[]];if(b.length===0)return o.mode==="failed"?console.log("No broken specs to re-run \u2014 /screenshot list shows where things stand."):o.mode==="blocked"?console.log("No shots are waiting on app data \u2014 /screenshot list shows where things stand."):console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};if(!h&&o.mode!=="single"&&o.mode!=="failed"&&o.mode!=="blocked"){let C=na(c.filter(P=>P.state==="blocked"),"/screenshot capture --blocked");C&&console.log(C)}let $=Date.now(),v=[];for(let C of b){console.log(`\u25B6 ${C}`);try{let{exitCode:P}=await sa({cwd:n,id:C,stdio:"inherit"});v.push({id:C,outcome:oa(n,C,P,$)})}catch(P){if(P.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};v.push({id:C,outcome:"failed",detail:P.message})}}let E=C=>v.filter(P=>P.outcome===C).length;console.log(`\u2713 ${E("captured")} captured \xB7 \u2298 ${E("skipped")} skipped \xB7 \u2717 ${E("failed")} failed`);let R=v.filter(C=>C.outcome==="captured");return pr(n,v.map(C=>({id:C.id,outcome:C.outcome,reason:C.detail,specSource:vn(n,C.id)})),new Date().toISOString()),R.length>0?(console.log(lo(R.length)),{kind:"forward-to-agent",prompt:qt(n,R.map(C=>C.id)),display:"/screenshot verify"}):{kind:"continue"}}import{existsSync as By,readFileSync as Hy}from"node:fs";import{isAbsolute as qy,join as Vy,resolve as Gy}from"node:path";import{readProjectConfig as Yy,DEFAULT_CAPTURE_DIR as zy}from"document360-engine";async function Sn(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-writer/capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-CHECKLIST.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
362
+ `),display:"/screenshot checklist"}}var Tu="-".repeat(64);function la(e){let t=zy;try{let b=Yy(e);b?.captureDir&&(t=b.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=qy(t)?Vy(t,"CAPTURE-TESTID-REQUESTS.json"):Gy(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!By(n))return null;let o;try{let b=JSON.parse(Hy(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,i=`${s} data-testid attribute${s===1?"":"s"}`,c=`${r} source file${r===1?"":"s"}`,p=`${t}/CAPTURE-TESTID-REQUESTS.md`,h=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${i} requested across ${c}.`,"\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.","",Tu,`Read ${p} and ${h}. They list ${i} 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.",Tu]}wt();K();import{listOpenForDocs as Ky,readProjectConfig as Xy}from"document360-engine";function da(e){try{return Ky(e).length}catch{return 0}}function ua(){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(`
363
+ `)}async function Eu(e,t){let n=t?.cwd??process.cwd();return Xy(n)?da(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:ua(),display:"/inbox"}:(console.log(D("No d360-writer config here. Run /init first.")),{kind:"continue"})}K();import{listOpenHints as Qy,listOpenForDocs as Jy,listOpenDirectives as Zy,readProjectConfig as ew,computeSyncStatus as tw,planPull as nw,applyPull as ow,planImport as rw,applyImport as sw}from"document360-engine";function fo(e){let t=0,n=0,o=0,r=0;try{t=Qy(e).length}catch{}try{let s=Jy(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=Zy(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function mo(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 ha(e){return{publish:e.includes("--publish")}}function fa({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 (say plainly that you left a question for their engineers). Write the whole summary for a technical writer: no tool names, no internal file names, no raw status words, no hint ids \u2014 plain sentences about what changed and what is worth their attention."),t.join(`
364
+ `)}var iw={status:tw,plan:nw,apply:ow,planImport:rw,applyImport:sw};async function ma(e,t=iw){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 pa=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Fr=e=>e===1?"":"s";function ga(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${Fr(e.pulled.length)} into local: ${pa(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Fr(e.imported.length)} into local drafts: ${pa(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Fr(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${pa(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${Fr(e.failed.length)} failed \u2014 left for /pull.`),t}async function Du(e,t){let n=t?.cwd??process.cwd();if(!ew(n))return console.log(D("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ve(n,t?.profileName);if(!o.ok)return console.log(D(o.reason)),{kind:"continue"};let{publish:r}=ha(e);console.log(g("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await ma({cwd:n,profileName:t?.profileName});for(let c of ga(s))console.log(c.startsWith("\u2713")?M(c):c.startsWith("\u2139")?g(c):H(c));let i=mo(fo(n));return console.log(g(i?`Catching up on ${i}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:fa({publish:r}),display:`/catch-up${r?" --publish":""}`}}K();import{spawn as Au}from"node:child_process";var Pn="document360-writer",Wr=`npm i -g ${Pn}@latest`,aw="document360-capture";function cw(){return new Promise(e=>{try{let t=Au("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 Br(){let e=process.platform==="win32",n=await cw()?[Pn,aw]:[Pn];return new Promise(o=>{try{let r=Au(`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 ju(){console.log(g("Updating the d360-writer toolchain\u2026"));let e=await Br();return e.ok?console.log(M(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)):console.log(D(`Update failed \u2014 run manually: ${Wr}`)),{kind:"continue"}}K();wt();import{existsSync as ya,rmSync as lw}from"node:fs";import{basename as Nu,resolve as wa}from"node:path";import{execFileSync as dw}from"node:child_process";import{input as uw}from"@inquirer/prompts";import{readProjectConfig as pw,devHintsGuidePath as hw}from"document360-engine";var fw=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],mw=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Hr=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Iu=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Ou(e){let t=Hr(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Iu(t)?!0:mw.has(t)}function ka(e){let t=null;try{t=pw(e)}catch{t=null}let n=new Set(fw);for(let o of[Hr(t?.docsDir),Hr(t?.captureDir),Hr(t?.outputDir)])o&&Iu(o)&&n.add(o);return[...n].filter(o=>Ou(o)&&ya(wa(e,o)))}function ba(e,t){let n=[],o=[];for(let r of t){if(!Ou(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{lw(wa(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Lu(e,t){try{return dw("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
365
+ `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function gw(e){return Lu(e,".d360-writer/hints")}function yw(e){return Lu(e,".d360-writer/messages")}function $a(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=gw(e),o=yw(e),r=ya(wa(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(s=>` \u2022 ${s}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o>0?[`\u26A0 ${o} message(s) under .d360-writer/messages/ are not committed \u2014 commit them first or they're gone.`]:[],...r?["Note: a repo-root user-docs/ is NOT touched (only .d360-writer/ is removed)."]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${Nu(e)}`]}async function _u(e,t){let n=ka(t.cwd);for(let p of $a(t.cwd,n))console.log(n.length===0?g(p):p);if(n.length===0)return{kind:"continue"};let o=Nu(t.cwd);if((await t.withPausedInput(()=>uw({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(H("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=ya(hw(t.cwd)),{removed:i,failed:c}=ba(t.cwd,n);console.log(M(`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`));for(let p of c)console.log(D(` \u2717 ${p.path}: ${p.error}`));if(s){for(let p of ar())console.log(p);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"}}K();import{lintDocs as ww}from"document360-engine";function qr(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 va(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(`
366
366
  `)).join(`
367
367
  `)].join(`
368
- `)}async function Lu(e,t){let n=e.includes("--fix"),o=e.find(i=>!i.startsWith("--")),r=o?` ${o}`:"",s=mw({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(M("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(y(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:va(s),display:`/check${r} --fix`});console.log(y("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let i of qr(s))console.log(s.length===0?M(i):B(i));return s.length>0&&console.log(y("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}K();import{lintDocs as $w,loadStyleGuide as vw,buildReviewPrompt as xw,readProjectConfig as Cw,DEFAULT_DOCS_DIR as Rw}from"document360-engine";K();import{readProjectConfig as gw,loadProfileMap as yw,resolveActiveProfile as ww,desiredCategoryOrder as kw,desiredArticleOrder as bw}from"document360-engine";function _u(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Mu=e=>e.replace(/\\/g,"/").split("/").pop()??e;function go(e,t){try{if(!gw(e))return[];let n=ww(e,t),o=yw(e,n.name);if(!o)return[];let r=new Map;for(let i of bw(o)){let c=r.get(i.categoryPath);c?c.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of kw(o)){s.push(_u(Mu(i.path)));for(let c of(r.get(i.path)??[]).sort((p,h)=>p.order-h.order))s.push(` ${_u(Mu(c.path))}`)}return s}catch{return[]}}async function Uu(e,t){let n=go(t.cwd,t.profileName);if(n.length===0)return console.log(y("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(W("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function xa(e,t){let n=Cw(e);if(!n)return null;let o=(n.docsDir??Rw).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(b=>!b.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),i=$w({cwd:e}),c=s?i.filter(b=>b.path===`${o}/${s}`||b.path.startsWith(`${o}/${s}/`)):i,p=s?"":go(e).join(`
369
- `);return{prompt:xw({docsRoot:o,scope:s,styleGuide:vw(e),deterministicFindings:c,fix:r,structure:p||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function Fu(e,t){if(Ct("review",e)){let o=Cn(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(y(r));return{kind:"continue"}}}let n=xa(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"})}K();import{readProjectConfig as Sw}from"document360-engine";function Ca(e,t){if(!Sw(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(`
370
- `),display:`/reorder${n?` ${n}`:""}`}}async function Wu(e,t){if(Ct("reorder",e)){let o=Cn(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(y(r));return{kind:"continue"}}}let n=Ca(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"})}K();import{readProjectConfig as Pw,writeProjectConfig as Bu,isAppType as Tw,playbookSkillName as Ew,detectAppType as Hu}from"document360-engine";var qu=["web","cli","service","library"],Aw=new Set(["web","cli"]);function Ra(e){return Aw.has(e)?`${Ew(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Vr(e,t){let n=t.cwd,o=Pw(n);if(!o)return console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??Hu(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${W("Genre:")} ${s} (${i}) \u2014 ${Ra(s)}`)}else console.log(B("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(y(`Set it: /genre <${qu.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(y("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;Bu(i,n);let c=Hu(n);return console.log(M(`\u2713 Genre reset to auto-detect \u2014 now: ${c?`${c} (${Ra(c)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return Tw(r)?(Bu({...o,appType:r},n),console.log(M(`\u2713 Genre set to ${r} \u2014 ${Ra(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(A(`Unknown genre "${r}". Choose one of: ${qu.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}K();import{listRoadmap as Gr,roadmapProgress as Vu,stampRoadmapDone as Dw}from"document360-engine";function Sa(e){let t=Gr(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=Vu(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 Yr(e,t){let n=Gr(e).filter(h=>h.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=h=>h.trim().toLowerCase(),s=n.find(h=>r(h.title)===r(o)),i=o?s?[s]:n.filter(h=>r(h.title).includes(r(o))):[n[0]];if(i.length>1)return{ok:!1,line:`"${o}" matches ${i.length} open steps \u2014 add a distinguishing word:
368
+ `)}async function Mu(e,t){let n=e.includes("--fix"),o=e.find(i=>!i.startsWith("--")),r=o?` ${o}`:"",s=ww({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(M("\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:va(s),display:`/check${r} --fix`});console.log(g("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let i of qr(s))console.log(s.length===0?M(i):H(i));return s.length>0&&console.log(g("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}K();import{lintDocs as Cw,loadStyleGuide as Rw,buildReviewPrompt as Sw,readProjectConfig as Pw,DEFAULT_DOCS_DIR as Tw}from"document360-engine";K();import{readProjectConfig as kw,loadProfileMap as bw,resolveActiveProfile as $w,desiredCategoryOrder as vw,desiredArticleOrder as xw}from"document360-engine";function Uu(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Fu=e=>e.replace(/\\/g,"/").split("/").pop()??e;function go(e,t){try{if(!kw(e))return[];let n=$w(e,t),o=bw(e,n.name);if(!o)return[];let r=new Map;for(let i of xw(o)){let c=r.get(i.categoryPath);c?c.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of vw(o)){s.push(Uu(Fu(i.path)));for(let c of(r.get(i.path)??[]).sort((p,h)=>p.order-h.order))s.push(` ${Uu(Fu(c.path))}`)}return s}catch{return[]}}async function Wu(e,t){let n=go(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(W("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function xa(e,t){let n=Pw(e);if(!n)return null;let o=(n.docsDir??Tw).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(b=>!b.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),i=Cw({cwd:e}),c=s?i.filter(b=>b.path===`${o}/${s}`||b.path.startsWith(`${o}/${s}/`)):i,p=s?"":go(e).join(`
369
+ `);return{prompt:Sw({docsRoot:o,scope:s,styleGuide:Rw(e),deterministicFindings:c,fix:r,structure:p||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function Bu(e,t){if(Ct("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=xa(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(D("No d360-writer config here. Run /init first.")),{kind:"continue"})}K();import{readProjectConfig as Ew}from"document360-engine";function Ca(e,t){if(!Ew(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(`
370
+ `),display:`/reorder${n?` ${n}`:""}`}}async function Hu(e,t){if(Ct("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=Ca(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(D("No d360-writer config here. Run /init first.")),{kind:"continue"})}K();import{readProjectConfig as Dw,writeProjectConfig as qu,isAppType as Aw,playbookSkillName as jw,detectAppType as Vu}from"document360-engine";var Gu=["web","cli","service","library"],Nw=new Set(["web","cli"]);function Ra(e){return Nw.has(e)?`${jw(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Vr(e,t){let n=t.cwd,o=Dw(n);if(!o)return console.log(D("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??Vu(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${W("Genre:")} ${s} (${i}) \u2014 ${Ra(s)}`)}else console.log(H("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(g(`Set it: /genre <${Gu.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,...i}=o;qu(i,n);let c=Vu(n);return console.log(M(`\u2713 Genre reset to auto-detect \u2014 now: ${c?`${c} (${Ra(c)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return Aw(r)?(qu({...o,appType:r},n),console.log(M(`\u2713 Genre set to ${r} \u2014 ${Ra(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(D(`Unknown genre "${r}". Choose one of: ${Gu.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}K();import{listRoadmap as Gr,roadmapProgress as Yu,stampRoadmapDone as Iw}from"document360-engine";function Sa(e){let t=Gr(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=Yu(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 Yr(e,t){let n=Gr(e).filter(h=>h.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=h=>h.trim().toLowerCase(),s=n.find(h=>r(h.title)===r(o)),i=o?s?[s]:n.filter(h=>r(h.title).includes(r(o))):[n[0]];if(i.length>1)return{ok:!1,line:`"${o}" matches ${i.length} open steps \u2014 add a distinguishing word:
371
371
  ${i.map(h=>` \u25CB ${h.title}`).join(`
372
372
  `)}`};if(i.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
373
373
  ${n.map(h=>` \u25CB ${h.title}`).join(`
374
- `)}`};let c=i[0].title;Dw(e,c,{doneAt:new Date().toISOString()});let p=Vu(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${c}${p?` \u2014 next up: ${p.title}${p.run?` (${p.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function Pa(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?Gr(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function Gu(e,t){let n=Pa(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(`
375
- `):null}function Yu(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=Gr(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:
374
+ `)}`};let c=i[0].title;Iw(e,c,{doneAt:new Date().toISOString()});let p=Yu(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${c}${p?` \u2014 next up: ${p.title}${p.run?` (${p.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function Pa(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?Gr(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function zu(e,t){let n=Pa(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(`
375
+ `):null}function Ku(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=Gr(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:
376
376
  ${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(`
377
- `):null}async function zu(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Yr(n,e.slice(1).join(" ").trim());return console.log(r.ok?M(r.line):B(r.line)),{kind:"continue"}}let o=Sa(n);console.log(W(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?y(r):r);return{kind:"continue"}}var Ku={help:_s,"?":_s,clear:Gc,exit:Ms,quit:Ms,init:Hs,mcp:dr,publish:kd,audit:ro,discover:bd,scope:vd,pull:Nd,resolve:Ad,convert:Id,write:Fd,draft:Vd,document:Gd,resume:Kd,rename:Xd,profile:Jd,model:tu,doctor:ao,workspace:au,project:cu,"allow-prod":lu,login:du,logout:uu,screenshot:async(e,t)=>{let n=Zn(e);return n.mode==="capture"?ca(n.rest,t):n.mode==="verify"?pu(n.rest,t):n.mode==="checklist"?Sn():Rr(e,t)},capture:ca,"capture-setup":Sn,devhints:ol,inbox:Pu,"catch-up":Tu,update:Au,reset:Ou,check:Lu,review:Fu,reorder:Wu,structure:Uu,genre:Vr,roadmap:zu};function Xu(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}wt();var jw="Or just tell me what to write or update.",Nw='\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 ve(e){return e===1?"":"s"}function zr(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function yo(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var Iw={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 Ow(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:Iw,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${ve(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${ve(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
378
- \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${ve(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${ve(n)}.`})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${ve(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${ve(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ve(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${ve(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${ve(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${ve(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${ve(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${ve(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.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${ve(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function Qu(e){return e.find(t=>t.lead||t.picker)??null}function Ta(e,t){let n=Qu(t),o=[];n?.lead?o.push(yo(n.lead)):n?.picker&&o.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let c of t.filter(p=>p!==n).slice(0,2))c.follow&&o.push(c.follow);let r=o.join(" "),s=t.filter(c=>c.bullet).map(c=>{let p=c.lead?.kind==="cmd"?c.lead.cmd:null;return` \u2022 ${c.bullet}${p&&!r.includes(p)?` \u2014 ${p}`:""}`}),i=[[e,...s].join(`
379
- `)];return o.length&&i.push(o.join(" ")),i.push(jw),i.join(`
380
-
381
- `)}function wo(e){if(!e.ready)return{kind:"idle"};let t=Ow(e);if(!e.hasDocs){let s=Qu(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:Ta("\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:Nw,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${ve(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${ve(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"||n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${ve(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:Ta("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:Ta("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as Ea,readdirSync as Da}from"node:fs";import{spawnSync as Lw}from"node:child_process";import{join as Kr}from"node:path";import{readProjectConfig as Zu,resolveActiveProfile as ep,loadTokens as _w,isExpired as Mw,loadProfileMap as tp,localAheadPaths as Uw,loadKnownConflicts as Fw,readDocsPlan as Ww,devHintsGuidePath as Bw,DEFAULT_DOCS_DIR as Aa,roadmapProgress as Hw,listRoadmap as qw,readProductBriefState as Vw,reconcileCommitRequest as Gw}from"document360-engine";wt();function Ju(e){try{return Da(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ja(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Ju(Kr(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Ju(Kr(e,o)))}function Na(e,t){try{let n=Zu(e);if(!n)return!1;let o=ep(e,t),r=tp(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Kr(e,(n.docsDir??Aa).replace(/\/+$/,""));return!!(Ea(s)&&Da(s).length>0||Ea(Bw(e)))}catch{return!1}}function ko(e,t,n){try{let o=Zu(e);if(!o)return null;let r=ep(e,t),s=_w(r.name),i=!!s&&(!Mw(s)||!!s.refreshToken),c=Na(e,t)||!ja(e,o.authoritativeSourceFiles),p=tp(e,r.name),h=p?Object.keys(p.articles).length:0,b=Kr(e,(o.docsDir??Aa).replace(/\/+$/,"")),$=!1;try{$=Ea(b)&&Da(b).length>0}catch{}let v=0;if(p?.lastAnalyzedCommit)try{let ae=Lw("git",["rev-list","--count",`${p.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});ae.status===0&&(v=parseInt((ae.stdout||"").trim(),10)||0)}catch{}let E=0;try{let ae=Ww(e);if(ae.length>0){let Ze=(o.docsDir??Aa).replace(/\/+$/,"");E=Ii(e,Ze,ae.map(Ue=>Ue.path)).length}}catch{}let R=fo(e),x=mo({...R,directives:0}),T=Uw(e,t),F=new Set(Fw(e,r.name)),G=T.filter(ae=>F.has(ae)).length,q=T.length-G,Y=qe(e),pe=Hw(e),J=Gw(e,new Date().toISOString()),re=Vw(e),le=re?{status:re.status,openQuestions:re.openQuestions}:null;return!le&&$&&qw(e).some(Ze=>Ze.status==="open"&&(Ze.run??"").trim()==="/discover")&&(le={status:"pending",openQuestions:0}),{ready:i&&c&&!n.claudeMissing,hasDocs:$,tracked:h,pendingText:x,directives:R.directives,behind:v,pendingWrites:E,localAhead:q,conflicts:G,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:Y.status,devhintsCompletedVersion:Y.completedVersion,devhintsToVersion:me,builderStarted:it(e),genreUnknown:n.genreUnknown,roadmap:pe,discovery:le,uncommittedDocs:J.dirty.length}}catch{return null}}K();var Yw={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"},op=160,Oa=200,rp=40;function Le(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function np(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}: ${Le(typeof r=="string"?r:JSON.stringify(r),rp)}`);return t.length>4&&n.push("\u2026"),Le(n.join(", "),op)}var zw=new Set(["file_path","notebook_path"]);function Kw(e,t){if(!t)return e;let n=i=>i.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 Rt=e=>typeof e=="string"&&e?e:null,Ia=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Xw(e){let t=Rt(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 Qw(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Rt(t.title);if(!o)return null;let r=Xw(t.local_path);return n("Create article",`"${Le(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Rt(t.title),r=Ia(t.article_id);return n("Update article",o?`"${Le(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Ia(t.article_id)?`id ${Ia(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",Rt(t.name)?`"${Le(Rt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Rt(t.file_path);return n("Upload image",o?Le(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Xr(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...i]=e.split("__"),c=i.join("__");if(s==="document360"){let b=Qw(c,t);if(b)return b}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${p}`,sep:" ",arg:np(t)}}let o=Yw[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&zw.has(o)?Kw(r,n):r;return{title:e,sep:"",arg:Le(s,op)}}return{title:e,sep:"",arg:np(t)}}function Jw(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 Zw(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Jw).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Le(r,Oa))]}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}: ${Le(String(r),rp)}`);return n.length>0?[Le(n.join(" \xB7 "),Oa)]:null}return null}function ek(e){let t=Rt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function tk(e,t,n){switch(e){case"d360_create_article":{let o=ek(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=Rt(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 ${Le(o[0],120)}`:""}`]}default:return null}}function Qr(e,t=4,n,o){let r=e.replace(/\r\n/g,`
382
- `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let i=tk(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=Zw(r)??r.split(`
383
- `);return{lines:s.slice(0,t).map(i=>Le(i,Oa)),hidden:Math.max(0,s.length-t)}}function Jr(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Zr(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 sp(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 es(e){return sp(e,"url")}function ts(e){return sp(e,"preview_url")}var $k=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function vk(e,t,n,o){if($k.test(e))try{let r=cp(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=Zr(t,n),c=es(n);e.endsWith("publish_article")&&c&&console.log(W(` \u2B95 Live: ${c}`));let p=ts(n);p?console.log(W(` \u2B95 Preview: ${p}`)):i&&s&&console.log(W(` \u2B95 Preview: ${Jr(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function lp(e=process.cwd(),t="auto",n,o){let r=ok(t);r.kind==="none"&&(console.error(""),console.error(A("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${W("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${W('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),xk(e,n),r.kind==="subscription"&&(r.stored?console.log(y(" Using your Claude subscription (no API key set).")):console.log(y(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,i=La({cwd:e,profileName:n,allowProdWrites:s}),c={uuid:null,firstPrompt:null,titleFired:!1},p=nk({input:process.stdin,output:process.stdout}),h=[],b=null,$=!1;p.on("line",R=>{if(b){let x=b;b=null,x(R)}else h.push(R)}),p.on("close",()=>{if($=!0,b){let R=b;b=null,R(null)}});function v(){return h.length>0?Promise.resolve(h.shift()):$?Promise.resolve(null):(process.stdout.write(W("> ")),new Promise(R=>{b=R}))}let E={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{i.close(),i=La({cwd:e,profileName:n,allowProdWrites:s}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setPendingName:R=>{c.pendingName=R},setModel:async R=>i.setModel(R),withPausedInput:async R=>{p.pause();try{return await R()}finally{p.resume()}}};try{for(;;){let R=await v();if(R===null)break;let x=R.trim();if(x){if(x.startsWith("/")){let T=Xu(x);if(!T)continue;let F=Ku[T.name];if(!F){console.log(A(`Unknown command: /${T.name}`)),console.log(y("Type /help for the list."));continue}let G=await F(T.args,E);if(G.kind==="exit")break;if(G.kind==="clear"){E.restartAgent();continue}if(G.kind==="allow-prod"){s=!0,E.restartAgent(),console.log(M("\u2713 Production writes authorized for this session.")),console.log("");continue}if(G.kind==="resume"){i.close(),i=La({cwd:e,resume:G.uuid,profileName:n,allowProdWrites:s});let q=rk(G.uuid);c={uuid:G.uuid,firstPrompt:q?.firstPrompt??null,titleFired:!0},ap(G.uuid),console.log(M(`\u2713 Resumed "${G.name}"`)),console.log("");continue}if(G.kind==="forward-to-agent"){c.firstPrompt||(c.firstPrompt=G.display??G.prompt);let q=(G.display??"").trim().split(/\s+/),Y=(q[0]==="/check"||q[0]==="/review")&&q.includes("--fix"),pe=q.slice(1).find(ae=>!ae.startsWith("--")),J=Y?kk(e,pe):[],re=q[0]==="/screenshot"&&(q[1]==="verify"||q[1]==="review"),le=re?q[2]&&!q[2].startsWith("--")?[q[2]]:co($e(e)):[];if(await _a(i,G.prompt,r,c,e),Y)try{wk(e,J,{reviewedCap:bk})}catch{}if(re&&le.length>0)try{for(let ae of uo(e,le))console.log(ae)}catch{}}else Ck(e,n);continue}if(fk(x)){let T=mk(x);if(T){try{gk(e,{title:T,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}c.firstPrompt||(c.firstPrompt=x),await _a(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${T}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${T}" and the article path(s) you wrote.`,r,c,e);continue}}c.firstPrompt||(c.firstPrompt=x),await _a(i,x,r,c,e)}}}finally{i.close(),p.close()}}function xk(e,t){console.log(""),console.log(Vn("document360-writer")),console.log(y(` cwd: ${e}`));let n=lk(e);if(console.log(y(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Rk(e,t)),!dk(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(sr(e),!it(e))for(let r of ir(e))console.log(B(` ${r}`))}catch{}try{let r=uk(e);r.persisted&&r.appType?console.log(y(` \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=yk(e);for(let s of or(r.applied))console.log(B(` ${s}`))}catch{}try{let r=ko(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?wo(r):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?B:y;for(let c of Qs(s.rec.note).split(`
384
- `))console.log(i(` ${c}`));s.rec.picker&&console.log(W(` Pick one: ${s.rec.picker.options.map(c=>c.cmd).join(" \xB7 ")}`))}}catch{}}console.log(y(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Ck(e,t){try{let n=ko(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?wo(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(y(` Next: ${yo(o.rec.lead)}`))}catch{}}function Rk(e,t){try{let n=cp(e,t),o=n.production?B(" \u26A0 PRODUCTION"):"",r=hk(n.name);if(!r)return y(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...ip(r.idToken)??{},...ip(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return pk(r)&&!r.refreshToken?B(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):y(` Document360: ${i} \xB7 profile "${n.name}"${o}`)}catch(n){return y(` Document360: ${n.message.split(".")[0]}`)}}function Sk(){console.error(""),console.error(`Sign in with your Claude subscription: run ${W("claude")} once, then retry.`),console.error(` (No Claude Code? ${W("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${W("https://console.anthropic.com/settings/keys")}`)}function Pk(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;ak({uuid:t,name:r??ik(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Tk(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||ck(o,t).then(r=>{r&&sk(n,r)}).catch(()=>{})}async function _a(e,t,n,o,r){let s=new Map;for await(let i of e.send(t))Ek(i,o,r,n,s)}function Ek(e,t,n,o,r){switch(e.type){case"session":t.uuid||Pk(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Xr(e.name,e.input,process.cwd());s&&(process.stdout.write(`
385
-
386
- `),console.log(`${M("\u25CF")} ${Te(s.title)}${s.arg!==null?fe(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=ct(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let i=c=>c===1?"":"s";console.log(fe(` \u23BF Added ${s.added} line${i(s.added)}, removed ${s.removed} line${i(s.removed)}`));for(let c of s.lines)console.log(c);s.hidden>0&&console.log(y(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let i=Qr(e.output,4,e.isError?void 0:s.name,s.input),c=e.isError?A:fe;i.lines.forEach((p,h)=>console.log(c((h===0?" \u23BF ":" ")+p))),i.hidden>0&&console.log(y(` \u2026 +${i.hidden} lines`)),e.isError||vk(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
387
- `);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(y(` (${Qn(s)}\u2192${Qn(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(ap(t.uuid),t.titleFired||Tk(t,n));break}case"error":console.error(""),console.error(A(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Sk();break}}import{render as qb}from"ink";import{resolveAuth as Vb}from"document360-engine";import{useCallback as ee,useEffect as Me,useMemo as qa,useRef as oe,useState as X}from"react";import{Box as ue,Text as I,useApp as qk,useInput as Vk,useStdout as Gk}from"ink";import{existsSync as En,readFileSync as cs,readdirSync as Yk}from"node:fs";import{basename as vo,isAbsolute as zk,join as Va}from"node:path";import{createSession as Np,classifyClaudeAuth as Qa,CLAUDE_CODE_SETUP_HINT as Kk,loginPkce as Xk,toStoredTokens as Qk,saveTokens as Jk,getAccessToken as Zk,resolveActiveProfile as _e,resolveProjectId as eb,getArticle as tb,decodeJwtClaims as Dn,isExpired as St,loadTokens as Gt,clearTokens as nb,clearProfileProject as ob,setTitle as rb,slugify as sb,touchSession as Ga,upsertSession as ib,generateTitle as Ip,findByName as ab,listSessions as cb,renameSession as lb,suggestNextAction as db,readProjectConfig as de,writeProjectConfig as Op,resolveAndPersistAppType as ub,detectAppType as pb,resolveModelSetting as Ja,loadProfileMap as Lp,applyPull as _p,computeSyncStatus as Ya,lintDocs as Mp,compareRemoteSources as hb,planPull as Up,establishBaselines as fb,rebaselineServerMeta as mb,inventoryRepo as gb,knownEnvironments as yb,resolveEnvironment as wb,planPartitions as za,partitionEvenly as kb,screenshotPlaceholderIds as bb,trackedArticlePaths as $b,runPartitioned as ls,estimateBulkCost as Fp,resolveModelForOperation as ds,readDocsPlan as vb,checkForUpdate as xb,detectInstallKind as Cb,isSelfUpdatable as Rb,devHintsGuidePath as Wp,toolFeedbackPath as Bp,reconcileToolFeedback as Sb,reconcileUpgradeActions as Pb,stampArticles as Ka,listArticleFiles as Hp,CONTENT_CAP_VERSION as Xa,ENGINE_VERSION as Qp,DEFAULT_DOCS_DIR as Za,setProfileProject as Tb,writeCrashLog as Eb,applyStructureOrder as qp,orderSyncLine as Vp,applyRelatedArticles as Gp,relatedSyncLine as Yp}from"document360-engine";hr();wt();import{spawn as dp}from"node:child_process";function Ak(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Dk(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?dp([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):dp(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",i=>o(i===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 Ma(e){for(let[t,n]of Ak())if(await Dk(t,n,e))return!0;return!1}var jk=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Ua(e,t){if(t.closed)return e;let n=e.split(`
388
- `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){jk.test(s)&&(t.cueSeen=!0);continue}let i=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);i?(n[r]=`${i[1]}${++t.num}. ${i[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
389
- `)}import{existsSync as Nk,mkdirSync as Ik,readFileSync as Ok,writeFileSync as Lk}from"node:fs";import{join as up}from"node:path";import{writerDir as _k}from"document360-engine";function pp(e){return up(_k(e),".sessions")}function hp(e,t){return up(pp(e),`${t}.json`)}function fp(e,t,n){try{Ik(pp(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Lk(hp(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Fa(e,t){try{let n=hp(e,t);if(!Nk(n))return[];let o=JSON.parse(Ok(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Mk=e=>`\x1B]0;${e}\x07`,Uk=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function mp(e){process.stdout.isTTY&&process.stdout.write(e)}function Tn(e){mp(Mk(e))}function ns(e){mp(Uk(e))}var os=["\xB7 "," \xB7"],rs="\u{1F7E3}";_r();lr();K();import{Box as Wa,Text as we}from"ink";import{jsx as ke,jsxs as bo}from"react/jsx-runtime";function Fk({row:e,nameW:t,width:n}){switch(e.t){case"head":return ke(we,{color:Z,bold:!0,children:e.s});case"text":return ke(we,{children:e.s});case"dim":return ke(we,{dimColor:!0,children:e.s});case"sub":return ke(we,{bold:!0,dimColor:!0,children:e.s});case"good":return ke(we,{color:"green",children:e.s});case"step":return bo(we,{children:[ke(we,{color:Z,children:`${e.n}. `}),e.s]});case"cmd":{let o=Ls(e.name,e.s,t,n),r=o.descLines.slice(o.nameOwnLine?0:1);return bo(Wa,{flexDirection:"column",children:[bo(we,{children:[" ",ke(we,{color:Z,children:o.nameCell}),!o.nameOwnLine&&ke(we,{dimColor:!0,children:` ${o.descLines[0]??""}`})]}),r.map((s,i)=>ke(we,{dimColor:!0,children:`${o.indent}${s}`},i))]})}case"gap":return ke(we,{children:" "})}}function gp({tab:e,width:t,version:n,engineVersion:o}){let r=He[e]??He[0],s=6+He.reduce((c,p)=>c+p.label.length+4,0),i="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return bo(Wa,{flexDirection:"column",paddingX:1,children:[bo(we,{children:[ke(we,{color:Z,bold:!0,children:"Help "}),He.map((c,p)=>p===e?ke(we,{color:"white",backgroundColor:Z,bold:!0,children:` ${c.label} `},c.key):ke(we,{dimColor:!0,children:` ${c.label} `},c.key))]}),ke(we,{color:Z,children:i}),ke(Wa,{flexDirection:"column",marginTop:1,children:r.rows.map((c,p)=>ke(Fk,{row:c,nameW:Os(r.rows),width:t},p))}),ke(we,{dimColor:!0,children:`
390
- \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var Wk=/^(?:\d+[.)]|[-*•])\s+/;function yp(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
391
- `)){let i=s.trim().replace(Wk,""),c=i.match(/^`([^`]+)`$/);c&&(i=c[1].trim());let p=i.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!p||!o.has(p[1].toLowerCase()))continue;let h=`/${p[1].toLowerCase()}${p[2]?` ${p[2]}`:""}`;if(r.includes(h)||r.push(h),r.length>=n)break}return r}K();function $o(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Ge(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function wp(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Bk=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function kp(e,t,n){if(!Bk.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 i=s.replace(/\\/g,"/");return r===i||r.endsWith(`/${i}`)})??null}function Ba(e){return e.replace(/^[\w.-]+\//,"")}var ss=16,bp={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Vt(e){return typeof e=="string"?e:e.cmd}function $p(e){return typeof e=="string"?void 0:e.desc}function Ha(e){return e.trim().split(/\s+/).slice(1).join(" ")}function vp(e,t){let n=Ha(t);return e.some(r=>Vt(r).trim()===t.trim()||!!n&&Ha(Vt(r))===n)?e.filter(r=>Vt(r).trim()!==t.trim()&&!(n&&Ha(Vt(r))===n)):[]}import{isDirectiveMention as Ab,stripDirectiveMention as Db,appendDirective as jb}from"document360-engine";var Hk=/\[Pasted text #\d+ \+\d+ lines?\]/g;function xp(e){return e.replace(/\r\n?/g,`
392
- `)}function Cp(e){return e.includes(`
393
- `)||e.length>200}function Rp(e,t){let n=t.split(`
394
- `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Sp(e,t){return e.replace(Hk,n=>t.get(n)??n)}function Pp(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function is(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
395
- `)){if(s.length===0)o.push({start:r,end:r});else for(let i=0;i<s.length;i+=n)o.push({start:r+i,end:r+Math.min(i+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function as(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Tp(e,t,n){let o=as(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 Ep(e,t,n){let o=e[as(e,t)];return n==="start"?o.start:o.end}function Ap(e,t,n){let o=Math.max(1,n),r=e.split(`
377
+ `):null}async function Xu(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Yr(n,e.slice(1).join(" ").trim());return console.log(r.ok?M(r.line):H(r.line)),{kind:"continue"}}let o=Sa(n);console.log(W(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?g(r):r);return{kind:"continue"}}var Qu={help:_s,"?":_s,clear:zc,exit:Ms,quit:Ms,init:Hs,mcp:dr,publish:$d,audit:ro,discover:vd,scope:Cd,pull:Od,resolve:jd,convert:Ld,write:Bd,draft:Yd,document:zd,resume:Qd,rename:Jd,profile:eu,model:ou,doctor:ao,workspace:lu,project:du,"allow-prod":uu,login:pu,logout:hu,screenshot:async(e,t)=>{let n=Zn(e);return n.mode==="capture"?ca(n.rest,t):n.mode==="verify"?fu(n.rest,t):n.mode==="checklist"?Sn():Rr(e,t)},capture:ca,"capture-setup":Sn,devhints:sl,inbox:Eu,"catch-up":Du,update:ju,reset:_u,check:Mu,review:Bu,reorder:Hu,structure:Wu,genre:Vr,roadmap:Xu};function Ju(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}wt();var Ow="Or just tell me what to write or update.",Lw='\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 xe(e){return e===1?"":"s"}function zr(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function yo(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var _w={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 Mw(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:_w,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${xe(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${xe(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
378
+ \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${xe(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${xe(n)}.`})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${xe(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${xe(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${xe(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${xe(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${xe(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${xe(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${xe(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${xe(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.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${xe(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function Zu(e){return e.find(t=>t.lead||t.picker)??null}function Ta(e,t){let n=Zu(t),o=[];n?.lead?o.push(yo(n.lead)):n?.picker&&o.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let c of t.filter(p=>p!==n).slice(0,2))c.follow&&o.push(c.follow);let r=o.join(" "),s=t.filter(c=>c.bullet).map(c=>{let p=c.lead?.kind==="cmd"?c.lead.cmd:null;return` \u2022 ${c.bullet}${p&&!r.includes(p)?` \u2014 ${p}`:""}`}),i=[[e,...s].join(`
379
+ `)];return o.length&&i.push(o.join(" ")),i.push(Ow),i.join(`
380
+
381
+ `)}function wo(e){if(!e.ready)return{kind:"idle"};let t=Mw(e);if(!e.hasDocs){let s=Zu(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:Ta("\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:Lw,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${xe(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${xe(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"||n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${xe(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:Ta("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:Ta("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as Ea,readdirSync as Aa}from"node:fs";import{spawnSync as Uw}from"node:child_process";import{join as Kr}from"node:path";import{readProjectConfig as tp,resolveActiveProfile as np,loadTokens as Fw,isExpired as Ww,loadProfileMap as op,localAheadPaths as Bw,loadKnownConflicts as Hw,readDocsPlan as qw,devHintsGuidePath as Vw,DEFAULT_DOCS_DIR as Da,roadmapProgress as Gw,listRoadmap as Yw,readProductBriefState as zw,reconcileCommitRequest as Kw}from"document360-engine";wt();function ep(e){try{return Aa(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ja(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>ep(Kr(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&ep(Kr(e,o)))}function Na(e,t){try{let n=tp(e);if(!n)return!1;let o=np(e,t),r=op(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Kr(e,(n.docsDir??Da).replace(/\/+$/,""));return!!(Ea(s)&&Aa(s).length>0||Ea(Vw(e)))}catch{return!1}}function ko(e,t,n){try{let o=tp(e);if(!o)return null;let r=np(e,t),s=Fw(r.name),i=!!s&&(!Ww(s)||!!s.refreshToken),c=Na(e,t)||!ja(e,o.authoritativeSourceFiles),p=op(e,r.name),h=p?Object.keys(p.articles).length:0,b=Kr(e,(o.docsDir??Da).replace(/\/+$/,"")),$=!1;try{$=Ea(b)&&Aa(b).length>0}catch{}let v=0;if(p?.lastAnalyzedCommit)try{let ae=Uw("git",["rev-list","--count",`${p.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});ae.status===0&&(v=parseInt((ae.stdout||"").trim(),10)||0)}catch{}let E=0;try{let ae=qw(e);if(ae.length>0){let Ze=(o.docsDir??Da).replace(/\/+$/,"");E=Ii(e,Ze,ae.map(Fe=>Fe.path)).length}}catch{}let R=fo(e),C=mo({...R,directives:0}),P=Bw(e,t),I=new Set(Hw(e,r.name)),G=P.filter(ae=>I.has(ae)).length,q=P.length-G,Y=qe(e),he=Gw(e),J=Kw(e,new Date().toISOString()),re=zw(e),le=re?{status:re.status,openQuestions:re.openQuestions}:null;return!le&&$&&Yw(e).some(Ze=>Ze.status==="open"&&(Ze.run??"").trim()==="/discover")&&(le={status:"pending",openQuestions:0}),{ready:i&&c&&!n.claudeMissing,hasDocs:$,tracked:h,pendingText:C,directives:R.directives,behind:v,pendingWrites:E,localAhead:q,conflicts:G,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:Y.status,devhintsCompletedVersion:Y.completedVersion,devhintsToVersion:ge,builderStarted:it(e),genreUnknown:n.genreUnknown,roadmap:he,discovery:le,uncommittedDocs:J.dirty.length}}catch{return null}}K();var Xw={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"},sp=160,Oa=200,ip=40;function _e(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function rp(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}: ${_e(typeof r=="string"?r:JSON.stringify(r),ip)}`);return t.length>4&&n.push("\u2026"),_e(n.join(", "),sp)}var Qw=new Set(["file_path","notebook_path"]);function Jw(e,t){if(!t)return e;let n=i=>i.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 Rt=e=>typeof e=="string"&&e?e:null,Ia=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Zw(e){let t=Rt(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 ek(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Rt(t.title);if(!o)return null;let r=Zw(t.local_path);return n("Create article",`"${_e(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Rt(t.title),r=Ia(t.article_id);return n("Update article",o?`"${_e(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Ia(t.article_id)?`id ${Ia(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",Rt(t.name)?`"${_e(Rt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Rt(t.file_path);return n("Upload image",o?_e(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Xr(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...i]=e.split("__"),c=i.join("__");if(s==="document360"){let b=ek(c,t);if(b)return b}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${p}`,sep:" ",arg:rp(t)}}let o=Xw[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&Qw.has(o)?Jw(r,n):r;return{title:e,sep:"",arg:_e(s,sp)}}return{title:e,sep:"",arg:rp(t)}}function tk(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 nk(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(tk).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>_e(r,Oa))]}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}: ${_e(String(r),ip)}`);return n.length>0?[_e(n.join(" \xB7 "),Oa)]:null}return null}function ok(e){let t=Rt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function rk(e,t,n){switch(e){case"d360_create_article":{let o=ok(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=Rt(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 ${_e(o[0],120)}`:""}`]}default:return null}}function Qr(e,t=4,n,o){let r=e.replace(/\r\n/g,`
382
+ `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let i=rk(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=nk(r)??r.split(`
383
+ `);return{lines:s.slice(0,t).map(i=>_e(i,Oa)),hidden:Math.max(0,s.length-t)}}function Jr(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Zr(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 ap(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 es(e){return ap(e,"url")}function ts(e){return ap(e,"preview_url")}var up=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Sk(e,t,n,o){if(up.test(e))try{let r=dp(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=Zr(t,n),c=es(n);e.endsWith("publish_article")&&c&&console.log(W(` \u2B95 Live: ${c}`));let p=ts(n);p?console.log(W(` \u2B95 Preview: ${p}`)):i&&s&&console.log(W(` \u2B95 Preview: ${Jr(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function pp(e=process.cwd(),t="auto",n,o){let r=ik(t);r.kind==="none"&&(console.error(""),console.error(D("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${W("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${W('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Pk(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,i=La({cwd:e,profileName:n,allowProdWrites:s}),c={uuid:null,firstPrompt:null,titleFired:!1},p=sk({input:process.stdin,output:process.stdout}),h=[],b=null,$=!1;p.on("line",R=>{if(b){let C=b;b=null,C(R)}else h.push(R)}),p.on("close",()=>{if($=!0,b){let R=b;b=null,R(null)}});function v(){return h.length>0?Promise.resolve(h.shift()):$?Promise.resolve(null):(process.stdout.write(W("> ")),new Promise(R=>{b=R}))}let E={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{i.close(),i=La({cwd:e,profileName:n,allowProdWrites:s}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setPendingName:R=>{c.pendingName=R},setModel:async R=>i.setModel(R),withPausedInput:async R=>{p.pause();try{return await R()}finally{p.resume()}}};try{for(;;){let R=await v();if(R===null)break;let C=R.trim();if(C){if(C.startsWith("/")){let P=Ju(C);if(!P)continue;let I=Qu[P.name];if(!I){console.log(D(`Unknown command: /${P.name}`)),console.log(g("Type /help for the list."));continue}let G=await I(P.args,E);if(G.kind==="exit")break;if(G.kind==="clear"){E.restartAgent();continue}if(G.kind==="allow-prod"){s=!0,E.restartAgent(),console.log(M("\u2713 Production writes authorized for this session.")),console.log("");continue}if(G.kind==="resume"){i.close(),i=La({cwd:e,resume:G.uuid,profileName:n,allowProdWrites:s});let q=ak(G.uuid);c={uuid:G.uuid,firstPrompt:q?.firstPrompt??null,titleFired:!0},lp(G.uuid),console.log(M(`\u2713 Resumed "${G.name}"`)),console.log("");continue}if(G.kind==="forward-to-agent"){c.firstPrompt||(c.firstPrompt=G.display??G.prompt);let q=(G.display??"").trim().split(/\s+/),Y=(q[0]==="/check"||q[0]==="/review")&&q.includes("--fix"),he=q.slice(1).find(ae=>!ae.startsWith("--")),J=Y?vk(e,he):[],re=q[0]==="/screenshot"&&(q[1]==="verify"||q[1]==="review"),le=re?q[2]&&!q[2].startsWith("--")?[q[2]]:co(ve(e)):[];if(await _a(i,G.prompt,r,c,e,n),Y)try{$k(e,J,{reviewedCap:xk})}catch{}if(re&&le.length>0)try{for(let ae of uo(e,le))console.log(ae)}catch{}}else Tk(e,n);continue}if(yk(C)){let P=wk(C);if(P){try{kk(e,{title:P,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}c.firstPrompt||(c.firstPrompt=C),await _a(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${P}". 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 "${P}" and the article path(s) you wrote.`,r,c,e,n);continue}}c.firstPrompt||(c.firstPrompt=C),await _a(i,C,r,c,e,n)}}}finally{i.close(),p.close()}}function Pk(e,t){console.log(""),console.log(Vn("document360-writer")),console.log(g(` cwd: ${e}`));let n=pk(e);if(console.log(g(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Ek(e,t)),!hk(e))console.log(H(" 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(sr(e),!it(e))for(let r of ir(e))console.log(H(` ${r}`))}catch{}try{let r=fk(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=bk(e);for(let s of or(r.applied))console.log(H(` ${s}`))}catch{}try{let r=ko(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?wo(r):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?H:g;for(let c of Qs(s.rec.note).split(`
384
+ `))console.log(i(` ${c}`));s.rec.picker&&console.log(W(` Pick one: ${s.rec.picker.options.map(c=>c.cmd).join(" \xB7 ")}`))}}catch{}}console.log(g(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Tk(e,t){try{let n=ko(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?wo(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(g(` Next: ${yo(o.rec.lead)}`))}catch{}}function Ek(e,t){try{let n=dp(e,t),o=n.production?H(" \u26A0 PRODUCTION"):"",r=gk(n.name);if(!r)return g(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...cp(r.idToken)??{},...cp(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return mk(r)&&!r.refreshToken?H(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):g(` Document360: ${i} \xB7 profile "${n.name}"${o}`)}catch(n){return g(` Document360: ${n.message.split(".")[0]}`)}}function Dk(){console.error(""),console.error(`Sign in with your Claude subscription: run ${W("claude")} once, then retry.`),console.error(` (No Claude Code? ${W("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${W("https://console.anthropic.com/settings/keys")}`)}function Ak(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;dk({uuid:t,name:r??lk(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function jk(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||uk(o,t).then(r=>{r&&ck(n,r)}).catch(()=>{})}async function _a(e,t,n,o,r,s){let i=new Map,c=!1;for await(let p of e.send(t))p.type==="tool"&&up.test(p.name)&&(c=!0),Nk(p,o,r,n,i);if(c)try{let p=Rk(await Ck({cwd:r,profileName:s}));p&&console.log(p)}catch{}}function Nk(e,t,n,o,r){switch(e.type){case"session":t.uuid||Ak(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Xr(e.name,e.input,process.cwd());s&&(process.stdout.write(`
385
+
386
+ `),console.log(`${M("\u25CF")} ${Ee(s.title)}${s.arg!==null?me(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=ct(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let i=c=>c===1?"":"s";console.log(me(` \u23BF Added ${s.added} line${i(s.added)}, removed ${s.removed} line${i(s.removed)}`));for(let c of s.lines)console.log(c);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 i=Qr(e.output,4,e.isError?void 0:s.name,s.input),c=e.isError?D:me;i.lines.forEach((p,h)=>console.log(c((h===0?" \u23BF ":" ")+p))),i.hidden>0&&console.log(g(` \u2026 +${i.hidden} lines`)),e.isError||Sk(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
387
+ `);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(g(` (${Qn(s)}\u2192${Qn(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(lp(t.uuid),t.titleFired||jk(t,n));break}case"error":console.error(""),console.error(D(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Dk();break}}import{render as Yb}from"ink";import{resolveAuth as zb}from"document360-engine";import{useCallback as ee,useEffect as Ue,useMemo as qa,useRef as oe,useState as X}from"react";import{Box as ue,Text as O,useApp as zk,useInput as Kk,useStdout as Xk}from"ink";import{existsSync as En,readFileSync as cs,readdirSync as Qk}from"node:fs";import{basename as vo,isAbsolute as Jk,join as Va}from"node:path";import{createSession as Lp,classifyClaudeAuth as Za,CLAUDE_CODE_SETUP_HINT as Zk,loginPkce as eb,toStoredTokens as tb,saveTokens as nb,getAccessToken as ob,resolveActiveProfile as Me,resolveProjectId as rb,getArticle as sb,decodeJwtClaims as An,isExpired as St,loadTokens as Gt,clearTokens as ib,clearProfileProject as ab,setTitle as cb,slugify as lb,touchSession as Ga,upsertSession as db,generateTitle as _p,findByName as ub,listSessions as pb,renameSession as hb,suggestNextAction as fb,readProjectConfig as de,writeProjectConfig as Mp,resolveAndPersistAppType as mb,detectAppType as gb,resolveModelSetting as ec,loadProfileMap as Up,applyPull as Fp,computeSyncStatus as Ya,lintDocs as Wp,compareRemoteSources as yb,planPull as Bp,establishBaselines as wb,rebaselineServerMeta as kb,inventoryRepo as bb,knownEnvironments as $b,resolveEnvironment as vb,planPartitions as za,partitionEvenly as xb,screenshotPlaceholderIds as Cb,trackedArticlePaths as Rb,runPartitioned as ls,estimateBulkCost as Hp,resolveModelForOperation as ds,readDocsPlan as Sb,checkForUpdate as Pb,detectInstallKind as Tb,isSelfUpdatable as Eb,devHintsGuidePath as qp,toolFeedbackPath as Vp,reconcileToolFeedback as Db,reconcileUpgradeActions as Ab,stampArticles as Ka,listArticleFiles as Gp,CONTENT_CAP_VERSION as Xa,ENGINE_VERSION as Zp,DEFAULT_DOCS_DIR as tc,setProfileProject as jb,writeCrashLog as Nb,applyStructureOrder as Qa,orderSyncLine as Ja,applyRelatedArticles as Yp,relatedSyncLine as zp}from"document360-engine";hr();wt();import{spawn as hp}from"node:child_process";function Ik(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Ok(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?hp([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):hp(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",i=>o(i===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 Ma(e){for(let[t,n]of Ik())if(await Ok(t,n,e))return!0;return!1}var Lk=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Ua(e,t){if(t.closed)return e;let n=e.split(`
388
+ `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){Lk.test(s)&&(t.cueSeen=!0);continue}let i=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);i?(n[r]=`${i[1]}${++t.num}. ${i[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
389
+ `)}import{existsSync as _k,mkdirSync as Mk,readFileSync as Uk,writeFileSync as Fk}from"node:fs";import{join as fp}from"node:path";import{writerDir as Wk}from"document360-engine";function mp(e){return fp(Wk(e),".sessions")}function gp(e,t){return fp(mp(e),`${t}.json`)}function yp(e,t,n){try{Mk(mp(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Fk(gp(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Fa(e,t){try{let n=gp(e,t);if(!_k(n))return[];let o=JSON.parse(Uk(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Bk=e=>`\x1B]0;${e}\x07`,Hk=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function wp(e){process.stdout.isTTY&&process.stdout.write(e)}function Tn(e){wp(Bk(e))}function ns(e){wp(Hk(e))}var os=["\xB7 "," \xB7"],rs="\u{1F7E3}";_r();lr();K();import{Box as Wa,Text as ke}from"ink";import{jsx as be,jsxs as bo}from"react/jsx-runtime";function qk({row:e,nameW:t,width:n}){switch(e.t){case"head":return be(ke,{color:Z,bold:!0,children:e.s});case"text":return be(ke,{children:e.s});case"dim":return be(ke,{dimColor:!0,children:e.s});case"sub":return be(ke,{bold:!0,dimColor:!0,children:e.s});case"good":return be(ke,{color:"green",children:e.s});case"step":return bo(ke,{children:[be(ke,{color:Z,children:`${e.n}. `}),e.s]});case"cmd":{let o=Ls(e.name,e.s,t,n),r=o.descLines.slice(o.nameOwnLine?0:1);return bo(Wa,{flexDirection:"column",children:[bo(ke,{children:[" ",be(ke,{color:Z,children:o.nameCell}),!o.nameOwnLine&&be(ke,{dimColor:!0,children:` ${o.descLines[0]??""}`})]}),r.map((s,i)=>be(ke,{dimColor:!0,children:`${o.indent}${s}`},i))]})}case"gap":return be(ke,{children:" "})}}function kp({tab:e,width:t,version:n,engineVersion:o}){let r=He[e]??He[0],s=6+He.reduce((c,p)=>c+p.label.length+4,0),i="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return bo(Wa,{flexDirection:"column",paddingX:1,children:[bo(ke,{children:[be(ke,{color:Z,bold:!0,children:"Help "}),He.map((c,p)=>p===e?be(ke,{color:"white",backgroundColor:Z,bold:!0,children:` ${c.label} `},c.key):be(ke,{dimColor:!0,children:` ${c.label} `},c.key))]}),be(ke,{color:Z,children:i}),be(Wa,{flexDirection:"column",marginTop:1,children:r.rows.map((c,p)=>be(qk,{row:c,nameW:Os(r.rows),width:t},p))}),be(ke,{dimColor:!0,children:`
390
+ \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var Vk=/^(?:\d+[.)]|[-*•])\s+/;function bp(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
391
+ `)){let i=s.trim().replace(Vk,""),c=i.match(/^`([^`]+)`$/);c&&(i=c[1].trim());let p=i.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!p||!o.has(p[1].toLowerCase()))continue;let h=`/${p[1].toLowerCase()}${p[2]?` ${p[2]}`:""}`;if(r.includes(h)||r.push(h),r.length>=n)break}return r}K();function $o(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Ge(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function $p(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Gk=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function vp(e,t,n){if(!Gk.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 i=s.replace(/\\/g,"/");return r===i||r.endsWith(`/${i}`)})??null}function Ba(e){return e.replace(/^[\w.-]+\//,"")}var ss=16,xp={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Vt(e){return typeof e=="string"?e:e.cmd}function Cp(e){return typeof e=="string"?void 0:e.desc}function Ha(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Rp(e,t){let n=Ha(t);return e.some(r=>Vt(r).trim()===t.trim()||!!n&&Ha(Vt(r))===n)?e.filter(r=>Vt(r).trim()!==t.trim()&&!(n&&Ha(Vt(r))===n)):[]}import{isDirectiveMention as Ib,stripDirectiveMention as Ob,appendDirective as Lb}from"document360-engine";var Yk=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Sp(e){return e.replace(/\r\n?/g,`
392
+ `)}function Pp(e){return e.includes(`
393
+ `)||e.length>200}function Tp(e,t){let n=t.split(`
394
+ `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Ep(e,t){return e.replace(Yk,n=>t.get(n)??n)}function Dp(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function is(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
395
+ `)){if(s.length===0)o.push({start:r,end:r});else for(let i=0;i<s.length;i+=n)o.push({start:r+i,end:r+Math.min(i+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function as(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Ap(e,t,n){let o=as(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 jp(e,t,n){let o=e[as(e,t)];return n==="start"?o.start:o.end}function Np(e,t,n){let o=Math.max(1,n),r=e.split(`
396
396
  `),s=0;for(let i=r.length-1;i>=0;i--){let c=r[i];if(s+=Math.max(1,Math.ceil(c.length/o)),s>=t){let p=s-t;return{text:[p>0?c.slice(p*o):c,...r.slice(i+1)].join(`
397
- `),truncated:i>0||p>0}}}return{text:e,truncated:!1}}function Dp(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 jp(e){let t=!1,n=0,o=0;for(let r of e.split(`
398
- `)){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 xo,jsx as O,jsxs as te}from"react/jsx-runtime";var Nb={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},zp=` 1. /init \u2014 pick your Document360 environment & scaffold config
397
+ `),truncated:i>0||p>0}}}return{text:e,truncated:!1}}function Ip(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 Op(e){let t=!1,n=0,o=0;for(let r of e.split(`
398
+ `)){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 xo,jsx as _,jsxs as te}from"react/jsx-runtime";var _b={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},Kp=` 1. /init \u2014 pick your Document360 environment & scaffold config
399
399
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
400
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Ib(e,t,n,o){let r=Qa(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)",i=Ja(e),c=de(e),p=(c?.docsDir??Za).replace(/\/+$/,""),h=c?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${p}/ + config`,b={version:t,engineVersion:Qp,captureVersion:$n(),claude:s,model:i.model,modelSource:Nb[i.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:c!==null,mode:h};if(c===null)return b;try{let $=_e(e,o);b.profile=$.name,b.apiUrl=$.connection.apiUrl,b.prod=$.production,b.project=$.project.projectName??$.project.projectId??"(chosen at login)";let v=Gt($.name);if(v){let E={...Dn(v.idToken)??{},...Dn(v.accessToken)??{}},R=E.email??E.preferred_username??"signed in";St(v)?v.refreshToken&&(b.who=R,b.loggedOut=!1,b.sessionHint="session expired \u2014 refreshing\u2026"):(b.who=R,b.loggedOut=!1,b.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return b}function Ob(e,t){try{let n=_e(e,t),o=Gt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Dn(o.idToken)??{},...Dn(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return St(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 Kp=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],jn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Lb="Ask me to write or update an article\u2026";function An({ch:e,dim:t}){let[n,o]=X(!0);return Me(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),O(I,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var _b=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Xp(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Mb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ub({startTime:e,chars:t}){let[n,o]=X(0);Me(()=>{let p=setInterval(()=>o(h=>h+1),120);return()=>clearInterval(p)},[]);let r=jn[n%jn.length],s=Kp[Math.floor(n/16)%Kp.length],i=Math.floor((Date.now()-e)/1e3),c=Math.round(t/4);return te(ue,{children:[O(I,{color:Z,children:` ${r} ${s}\u2026 `}),O(I,{color:"gray",children:`(${Jn(i)} \xB7 ~${c} tokens \xB7 esc to interrupt)`})]})}function Fb({text:e}){let[t,n]=X(0);return Me(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),O(ue,{paddingX:1,children:O(I,{color:Z,children:`${jn[t%jn.length]} ${e}`})})}var Wb=12e4;function Bb({p:e}){let[t,n]=X(0);Me(()=>{let T=setInterval(()=>n(F=>F+1),150);return()=>clearInterval(T)},[]);let o=jn[t%jn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),i=Math.round(e.chars/4),c=Date.now()-e.lastAt>=Wb,p=e.verb??"Converting",h=e.unit??"article",b=e.rows.reduce((T,F)=>T+F.items,0),$=p.toLowerCase(),v=e.rows,E=0;if(v.length>ss){let T=v.findIndex(G=>G.status==="active"||G.status==="pending"),F=Math.max(0,Math.min(T-2,v.length-ss));E=v.slice(0,F).filter(G=>G.status==="done").length,v=v.slice(F,F+ss)}let R=Math.min(40,Math.max(...v.map(T=>Ba(T.label).length),0)),x=T=>T==="failed"?"red":T==="active"?Z:void 0;return te(ue,{flexDirection:"column",children:[te(ue,{children:[O(I,{color:Z,children:` ${o} ${p} ${b} ${h}${b===1?"":"s"} `}),O(I,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${i} tokens \xB7 ${Jn(r)} \xB7 esc to stop`})]}),E>0&&O(I,{dimColor:!0,children:` \u2714 +${E} done`}),v.map(T=>te(I,{color:x(T.status),dimColor:T.status==="done"||T.status==="pending",children:[` ${bp[T.status]} ${Ba(T.label).padEnd(R)}`,T.status==="active"&&T.itemsDone!==void 0?` (${T.itemsDone}/${T.items} ${h}${T.items===1?"":"s"})`:T.status!=="pending"?` (${T.items} ${h}${T.items===1?"":"s"})`:"",T.status==="active"?` \u2190 ${$}\u2026`:""]},T.label)),c&&O(I,{color:"yellow",children:` \u26A0 no activity for ${Jn(s)} \u2014 press esc to stop if it's wedged`})]})}var Hb=10800*1e3;function Jp({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=qk(),[s,i]=X(n),[c,p]=X(null),[h,b]=X({text:"",pos:0}),$=h.text,v=ee(d=>{b(l=>{let a=typeof d=="function"?d(l.text):d;return{text:a,pos:a.length}})},[]),E=ee(d=>{b(l=>({text:l.text.slice(0,l.pos)+d+l.text.slice(l.pos),pos:l.pos+d.length}))},[]),R=ee(()=>{b(d=>{if(d.pos===0)return d;let l=d.text.slice(0,d.pos),a=Pp(l)??l.slice(0,-1);return{text:a+d.text.slice(d.pos),pos:a.length}})},[]),[x,T]=X(!1),[F,G]=X(!1),[q,Y]=X(0),[pe,J]=X(!1),[re,le]=X(null),[ae,Ze]=X(null),[Ue,ze]=X([]),lt=oe(!1),Pt=oe(!1),dt=oe(!1),[Yt,oc]=X(!1),Co=oe(0),[sh,Ro]=X(!1),[ih,So]=X(!1),[ps,rc]=X(null),[ah,zt]=X(0),Tt=oe(0),[hs,Kt]=X(0),[Xt,Po]=X(null),sc=oe(new Map),ch=oe(0),Qt=oe([]),Fe=oe(null);Fe.current===null&&(Fe.current=Np({cwd:e,profileName:s,allowProdWrites:!1}));let et=oe({uuid:null,firstPrompt:null,titleFired:!1}),To=oe(new Map),ic=oe(null),Jt=oe(!1),fs=oe([]),ge=oe([]),Zt=oe([]),Eo=oe(null),[ac,Et]=X(null),ms=oe(null),[At,Dt]=X(null),[tt,en]=X(null),[nt,tn]=X(null),[Re,nn]=X(null),[De,jt]=X(null),[ut,on]=X(null),[pt,Nt]=X(null),[ot,It]=X(null),[cc,Nn]=X(null),[je,Ot]=X(null),[Pe,rn]=X(null),[lc,gs]=X([]),Lt=oe([]),In=oe(!1),xe=oe(null),[Ao,ce]=X(null),[dc,Do]=X(null),jo=oe(!1),On=oe(null),Ln=oe(null),[Ne,_t]=X(null),[No,_n]=X(null),ys=!!(nt||Re||De||ut||pt||ot||je||Pe||Ne||No),[uc,sn]=X(0),[pc,an]=X(0),[lh,hc]=X(0),ws=qa(()=>{try{let d=Ja(e);return d.source==="auto"?`${d.model} (auto)`:d.model}catch{return null}},[e,lh]),{stdout:We}=Gk(),[,dh]=X(0),fc=oe(`${We.columns??80}x${We.rows??24}`),ht=ee(()=>Math.max(20,(We.columns??80)-1),[We]),u=ee(d=>{Qt.current.push(d),console.log(Js(d,ht()))},[ht]),Se=ee((d,l)=>{Co.current++,le(d),Ze(l??null)},[]),Ke=ee(()=>{Co.current++,le(null),Ze(null)},[]),ne=ee(d=>Se(d,zr({kind:"cmd",cmd:d,reason:""})),[Se]),Io=ee((d,l)=>{!l?.silent&&d.note&&u({kind:"note",tone:d.tone,text:d.note}),d.picker&&(ze(d.picker.options.map(a=>({cmd:a.cmd,desc:a.desc}))),Nn(d.picker.title)),d.lead&&Se(d.lead.kind==="cmd"?d.lead.cmd:d.lead.text,zr(d.lead))},[u,Se]),be=ee((d,l,a="info")=>{d&&u({kind:"note",tone:a,text:d}),l&&Se(l.kind==="cmd"?l.cmd:l.text,zr(l))},[u,Se]),[Mn,ks]=X(null),[uh,mc]=X(!1),cn=ee(d=>{ks(d),mc(!1),u({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),bs=oe(!1),$s=ee(async()=>{try{if(bs.current||!Rb(Cb())||de(e)?.mode==="engineer")return;let d=await xb({pkg:Pn,currentVersion:o,force:!0});if(!d.updateAvailable||!d.latest)return;bs.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${Pn} ${d.current} \u2192 ${d.latest}\u2026 (wait for the \u2713 before you /exit)`}),So(!0),(await Br().finally(()=>So(!1))).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${d.latest} \u2014 run /exit, then relaunch to apply.`}),ne("/exit"),rc(d.latest)):u({kind:"note",tone:"warn",text:`Update available (v${d.latest}) but auto-update failed \u2014 run: ${Wr}`})}catch{}},[e,o,u,ne]),Oo=ee(d=>{let l=Ve(e,s);return l.ok?!0:(u({kind:"note",tone:"warn",text:l.reason}),Ln.current=d,ne("/login"),!1)},[e,s,u,ne]),[Lo,vs]=X(null),Mt=ee(d=>{let l=ko(e,s,{claudeMissing:Qa(t).state==="missing",allowAutoAudit:d,genreUnknown:dt.current});return l?wo(l):{kind:"idle"}},[e,s,t]),Un=oe(!0),ln=oe(!1),_o=oe(0),Fn=oe(0);Me(()=>{let d=setInterval(()=>{if(Un.current){_o.current=0,Fn.current=0;return}if(!x)try{if(!En(Wp(e)))return;if(qe(e).status==="current"){Un.current=!0,_o.current=0,Fn.current=0;let a=Mt(!1),m=a.kind==="recommend"?a.rec:null,j=ln.current?`\u2713 Your builder finished the protocol update (v${me}) \u2014 the dev\u2194docs hand-off is current again.`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs.";u({kind:"note",tone:"ok",text:`${j}${m?.lead?` ${yo(m.lead)}`:""}`}),ks(null),m&&(m.lead||m.picker)?Io(m,{silent:!0}):ln.current||Se("write the docs for this repo"),Y(V=>V+1);return}if(ln.current)return;_o.current+=1;let l=_o.current;if((l===4||l%15===0)&&Fn.current<3){Fn.current+=1;let a=Fn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";u({kind:"note",tone:"info",text:it(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${a}`:`\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.${a}`})}}catch{}},4e3);return()=>clearInterval(d)},[e,x,u,Mt,Io,Se]),Me(()=>{let d=ac??vo(e);if(!x){ns(0),Tn(`${rs} ${d}`);return}ns(3);let l=0;Tn(`${os[0]} ${d}`);let a=setInterval(()=>{l=(l+1)%os.length,Tn(`${os[l]} ${d}`)},400);return()=>clearInterval(a)},[x,e,ac]),Me(()=>()=>ns(0),[]),Me(()=>{let d=performance.now(),l=[],a=(w,k)=>{let g=performance.now();try{return k()}finally{let C=Math.round(performance.now()-g);C>=80&&l.push(`${w}: ${C}ms`)}};u({kind:"banner",info:a("banner",()=>Ib(e,o,t,s))});let m=Qa(t).state==="missing";if(m&&u({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
401
- ${Kk}
400
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Mb(e,t,n,o){let r=Za(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)",i=ec(e),c=de(e),p=(c?.docsDir??tc).replace(/\/+$/,""),h=c?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${p}/ + config`,b={version:t,engineVersion:Zp,captureVersion:$n(),claude:s,model:i.model,modelSource:_b[i.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:c!==null,mode:h};if(c===null)return b;try{let $=Me(e,o);b.profile=$.name,b.apiUrl=$.connection.apiUrl,b.prod=$.production,b.project=$.project.projectName??$.project.projectId??"(chosen at login)";let v=Gt($.name);if(v){let E={...An(v.idToken)??{},...An(v.accessToken)??{}},R=E.email??E.preferred_username??"signed in";St(v)?v.refreshToken&&(b.who=R,b.loggedOut=!1,b.sessionHint="session expired \u2014 refreshing\u2026"):(b.who=R,b.loggedOut=!1,b.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return b}function Ub(e,t){try{let n=Me(e,t),o=Gt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...An(o.idToken)??{},...An(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return St(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 Xp=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],jn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Fb="Ask me to write or update an article\u2026";function Dn({ch:e,dim:t}){let[n,o]=X(!0);return Ue(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),_(O,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Qp=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Jp(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Wb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Bb({startTime:e,chars:t}){let[n,o]=X(0);Ue(()=>{let p=setInterval(()=>o(h=>h+1),120);return()=>clearInterval(p)},[]);let r=jn[n%jn.length],s=Xp[Math.floor(n/16)%Xp.length],i=Math.floor((Date.now()-e)/1e3),c=Math.round(t/4);return te(ue,{children:[_(O,{color:Z,children:` ${r} ${s}\u2026 `}),_(O,{color:"gray",children:`(${Jn(i)} \xB7 ~${c} tokens \xB7 esc to interrupt)`})]})}function Hb({text:e}){let[t,n]=X(0);return Ue(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),_(ue,{paddingX:1,children:_(O,{color:Z,children:`${jn[t%jn.length]} ${e}`})})}var qb=12e4;function Vb({p:e}){let[t,n]=X(0);Ue(()=>{let P=setInterval(()=>n(I=>I+1),150);return()=>clearInterval(P)},[]);let o=jn[t%jn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),i=Math.round(e.chars/4),c=Date.now()-e.lastAt>=qb,p=e.verb??"Converting",h=e.unit??"article",b=e.rows.reduce((P,I)=>P+I.items,0),$=p.toLowerCase(),v=e.rows,E=0;if(v.length>ss){let P=v.findIndex(G=>G.status==="active"||G.status==="pending"),I=Math.max(0,Math.min(P-2,v.length-ss));E=v.slice(0,I).filter(G=>G.status==="done").length,v=v.slice(I,I+ss)}let R=Math.min(40,Math.max(...v.map(P=>Ba(P.label).length),0)),C=P=>P==="failed"?"red":P==="active"?Z:void 0;return te(ue,{flexDirection:"column",children:[te(ue,{children:[_(O,{color:Z,children:` ${o} ${p} ${b} ${h}${b===1?"":"s"} `}),_(O,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${i} tokens \xB7 ${Jn(r)} \xB7 esc to stop`})]}),E>0&&_(O,{dimColor:!0,children:` \u2714 +${E} done`}),v.map(P=>te(O,{color:C(P.status),dimColor:P.status==="done"||P.status==="pending",children:[` ${xp[P.status]} ${Ba(P.label).padEnd(R)}`,P.status==="active"&&P.itemsDone!==void 0?` (${P.itemsDone}/${P.items} ${h}${P.items===1?"":"s"})`:P.status!=="pending"?` (${P.items} ${h}${P.items===1?"":"s"})`:"",P.status==="active"?` \u2190 ${$}\u2026`:""]},P.label)),c&&_(O,{color:"yellow",children:` \u26A0 no activity for ${Jn(s)} \u2014 press esc to stop if it's wedged`})]})}var Gb=10800*1e3;function eh({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=zk(),[s,i]=X(n),[c,p]=X(null),[h,b]=X({text:"",pos:0}),$=h.text,v=ee(d=>{b(l=>{let a=typeof d=="function"?d(l.text):d;return{text:a,pos:a.length}})},[]),E=ee(d=>{b(l=>({text:l.text.slice(0,l.pos)+d+l.text.slice(l.pos),pos:l.pos+d.length}))},[]),R=ee(()=>{b(d=>{if(d.pos===0)return d;let l=d.text.slice(0,d.pos),a=Dp(l)??l.slice(0,-1);return{text:a+d.text.slice(d.pos),pos:a.length}})},[]),[C,P]=X(!1),[I,G]=X(!1),[q,Y]=X(0),[he,J]=X(!1),[re,le]=X(null),[ae,Ze]=X(null),[Fe,ze]=X([]),lt=oe(!1),Pt=oe(!1),dt=oe(!1),[Yt,sc]=X(!1),Co=oe(0),[ah,Ro]=X(!1),[ch,So]=X(!1),[ps,ic]=X(null),[lh,zt]=X(0),Tt=oe(0),[hs,Kt]=X(0),[Xt,Po]=X(null),ac=oe(new Map),dh=oe(0),Qt=oe([]),We=oe(null);We.current===null&&(We.current=Lp({cwd:e,profileName:s,allowProdWrites:!1}));let et=oe({uuid:null,firstPrompt:null,titleFired:!1}),To=oe(new Map),cc=oe(null),Jt=oe(!1),fs=oe([]),ye=oe([]),Zt=oe([]),Eo=oe(null),[lc,Et]=X(null),ms=oe(null),[Dt,At]=X(null),[tt,en]=X(null),[nt,tn]=X(null),[Se,nn]=X(null),[je,jt]=X(null),[ut,on]=X(null),[pt,Nt]=X(null),[ot,It]=X(null),[dc,Nn]=X(null),[Ne,Ot]=X(null),[Te,rn]=X(null),[uc,gs]=X([]),Lt=oe([]),In=oe(!1),Ce=oe(null),[Do,ce]=X(null),[pc,Ao]=X(null),jo=oe(!1),On=oe(null),Ln=oe(null),[Ie,_t]=X(null),[No,_n]=X(null),ys=!!(nt||Se||je||ut||pt||ot||Ne||Te||Ie||No),[hc,sn]=X(0),[fc,an]=X(0),[uh,mc]=X(0),ws=qa(()=>{try{let d=ec(e);return d.source==="auto"?`${d.model} (auto)`:d.model}catch{return null}},[e,uh]),{stdout:Be}=Xk(),[,ph]=X(0),gc=oe(`${Be.columns??80}x${Be.rows??24}`),ht=ee(()=>Math.max(20,(Be.columns??80)-1),[Be]),u=ee(d=>{Qt.current.push(d),console.log(Js(d,ht()))},[ht]),Pe=ee((d,l)=>{Co.current++,le(d),Ze(l??null)},[]),Ke=ee(()=>{Co.current++,le(null),Ze(null)},[]),ne=ee(d=>Pe(d,zr({kind:"cmd",cmd:d,reason:""})),[Pe]),Io=ee((d,l)=>{!l?.silent&&d.note&&u({kind:"note",tone:d.tone,text:d.note}),d.picker&&(ze(d.picker.options.map(a=>({cmd:a.cmd,desc:a.desc}))),Nn(d.picker.title)),d.lead&&Pe(d.lead.kind==="cmd"?d.lead.cmd:d.lead.text,zr(d.lead))},[u,Pe]),$e=ee((d,l,a="info")=>{d&&u({kind:"note",tone:a,text:d}),l&&Pe(l.kind==="cmd"?l.cmd:l.text,zr(l))},[u,Pe]),[Mn,ks]=X(null),[hh,yc]=X(!1),cn=ee(d=>{ks(d),yc(!1),u({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),bs=oe(!1),$s=ee(async()=>{try{if(bs.current||!Eb(Tb())||de(e)?.mode==="engineer")return;let d=await Pb({pkg:Pn,currentVersion:o,force:!0});if(!d.updateAvailable||!d.latest)return;bs.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${Pn} ${d.current} \u2192 ${d.latest}\u2026 (wait for the \u2713 before you /exit)`}),So(!0),(await Br().finally(()=>So(!1))).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${d.latest} \u2014 run /exit, then relaunch to apply.`}),ne("/exit"),ic(d.latest)):u({kind:"note",tone:"warn",text:`Update available (v${d.latest}) but auto-update failed \u2014 run: ${Wr}`})}catch{}},[e,o,u,ne]),Oo=ee(d=>{let l=Ve(e,s);return l.ok?!0:(u({kind:"note",tone:"warn",text:l.reason}),Ln.current=d,ne("/login"),!1)},[e,s,u,ne]),[Lo,vs]=X(null),Mt=ee(d=>{let l=ko(e,s,{claudeMissing:Za(t).state==="missing",allowAutoAudit:d,genreUnknown:dt.current});return l?wo(l):{kind:"idle"}},[e,s,t]),Un=oe(!0),ln=oe(!1),_o=oe(0),Fn=oe(0);Ue(()=>{let d=setInterval(()=>{if(Un.current){_o.current=0,Fn.current=0;return}if(!C)try{if(!En(qp(e)))return;if(qe(e).status==="current"){Un.current=!0,_o.current=0,Fn.current=0;let a=Mt(!1),m=a.kind==="recommend"?a.rec:null,T=ln.current?`\u2713 Your builder finished the protocol update (v${ge}) \u2014 the dev\u2194docs hand-off is current again.`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs.";u({kind:"note",tone:"ok",text:`${T}${m?.lead?` ${yo(m.lead)}`:""}`}),ks(null),m&&(m.lead||m.picker)?Io(m,{silent:!0}):ln.current||Pe("write the docs for this repo"),Y(V=>V+1);return}if(ln.current)return;_o.current+=1;let l=_o.current;if((l===4||l%15===0)&&Fn.current<3){Fn.current+=1;let a=Fn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";u({kind:"note",tone:"info",text:it(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${a}`:`\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.${a}`})}}catch{}},4e3);return()=>clearInterval(d)},[e,C,u,Mt,Io,Pe]),Ue(()=>{let d=lc??vo(e);if(!C){ns(0),Tn(`${rs} ${d}`);return}ns(3);let l=0;Tn(`${os[0]} ${d}`);let a=setInterval(()=>{l=(l+1)%os.length,Tn(`${os[l]} ${d}`)},400);return()=>clearInterval(a)},[C,e,lc]),Ue(()=>()=>ns(0),[]),Ue(()=>{let d=performance.now(),l=[],a=(w,k)=>{let y=performance.now();try{return k()}finally{let x=Math.round(performance.now()-y);x>=80&&l.push(`${w}: ${x}ms`)}};u({kind:"banner",info:a("banner",()=>Mb(e,o,t,s))});let m=Za(t).state==="missing";if(m&&u({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
401
+ ${Zk}
402
402
  Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!de(e)){u({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
403
- ${zp}`}),ne(m?"/doctor":"/init");return}m&&ne("/doctor");try{let w=_e(e,s),k=Gt(w.name);k&&St(k)&&k.refreshToken?Zk({profile:w.name,connection:w.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),Y(g=>g+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),ne("/login")}):(!k||St(k))&&(u({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 sign in with /login.`}),ne("/login"))}catch{}try{let w=de(e),k=_e(e,s),g=Gt(k.name);w&&g&&!St(g)&&ja(e,w.authoritativeSourceFiles)&&!Na(e,s)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),ne("/scope"))}catch{}try{let w=a("resolve-genre",()=>ub(e));w.persisted&&w.appType?u({kind:"note",tone:"ok",text:`\u2713 Detected a ${w.appType} app \u2014 enabled the ${w.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):w.source==="unknown"&&de(e)&&(dt.current=!0)}catch{}let j=qe(e);try{if(a("reconcile-devhints",()=>sr(e)),j.status!=="current"&&!it(e)){let w=ir(e);w.length&&(u({kind:"note",tone:"warn",text:w.join(`
404
- `)}),cn(Bt()),Un.current=!1,ln.current=!1)}}catch{}try{let w=a("reconcile-feedback",()=>Sb(e));w.archived>0&&u({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}try{let w=a("upgrade-actions",()=>Pb(e));w.applied.length>0&&u({kind:"note",tone:"warn",text:or(w.applied).join(`
405
- `)})}catch{}let V=a("ready-decision",()=>Mt(!0));V.kind==="autoAudit"?(u({kind:"note",tone:"info",text:V.note}),ro().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&ie(w.prompt,{display:w.display,quietUser:!0})})):V.kind==="recommend"&&Io(V.rec);let f=Math.round(performance.now()-d);f>=800&&Eb({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${f}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${l.length?l.join(`
403
+ ${Kp}`}),ne(m?"/doctor":"/init");return}m&&ne("/doctor");try{let w=Me(e,s),k=Gt(w.name);k&&St(k)&&k.refreshToken?ob({profile:w.name,connection:w.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),Y(y=>y+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),ne("/login")}):(!k||St(k))&&(u({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 sign in with /login.`}),ne("/login"))}catch{}try{let w=de(e),k=Me(e,s),y=Gt(k.name);w&&y&&!St(y)&&ja(e,w.authoritativeSourceFiles)&&!Na(e,s)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),ne("/scope"))}catch{}try{let w=a("resolve-genre",()=>mb(e));w.persisted&&w.appType?u({kind:"note",tone:"ok",text:`\u2713 Detected a ${w.appType} app \u2014 enabled the ${w.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):w.source==="unknown"&&de(e)&&(dt.current=!0)}catch{}let T=qe(e);try{if(a("reconcile-devhints",()=>sr(e)),T.status!=="current"&&!it(e)){let w=ir(e);w.length&&(u({kind:"note",tone:"warn",text:w.join(`
404
+ `)}),cn(Bt()),Un.current=!1,ln.current=!1)}}catch{}try{let w=a("reconcile-feedback",()=>Db(e));w.archived>0&&u({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}try{let w=a("upgrade-actions",()=>Ab(e));w.applied.length>0&&u({kind:"note",tone:"warn",text:or(w.applied).join(`
405
+ `)})}catch{}let V=a("ready-decision",()=>Mt(!0));V.kind==="autoAudit"?(u({kind:"note",tone:"info",text:V.note}),ro().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&ie(w.prompt,{display:w.display,quietUser:!0})})):V.kind==="recommend"&&Io(V.rec);let f=Math.round(performance.now()-d);f>=800&&Nb({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${f}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${l.length?l.join(`
406
406
  `):"no single phase \u226580ms"}
407
- cwd: ${e}`}),$s()},[]),Me(()=>{let d=setInterval(()=>{$s()},Hb);return()=>clearInterval(d)},[$s]),Me(()=>{if(x||pe||Yt||lt.current||Pt.current||re!==null||Ue.length>0||$!==""||Mn!==null||ge.current.length>0||Eo.current||ys)return;let d=Mt(!1);d.kind==="recommend"&&(d.rec.lead||d.rec.picker)&&Io(d.rec,{silent:!0})},[x,pe,re,Ue,$,Mn,ys,q,Mt,Yt]),Me(()=>{let d=null,l=null,a=()=>{d&&clearTimeout(d),d=setTimeout(()=>{d=null;let m=`${We.columns??80}x${We.rows??24}`;m!==fc.current&&(fc.current=m,dh(j=>j+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Pl(Qt.current,ht())+"\x1B[?2026l")},80))},400)};return We.on("resize",a),()=>{d&&clearTimeout(d),l&&clearTimeout(l),We.off("resize",a)}},[We,ht]);let Be=Math.max(20,(We.columns??80)-1),gc=qa(()=>Ob(e,s),[e,s,q]),xs=(()=>{if(ih)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(ps!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${ps?` v${ps}`:""}\u2026`,isSetup:!0};if(Lo)return{text:"\u{1F6E0} press c to copy the d360-writer feedback \u2014 then send it to the team (Teams / Slack / email)\u2026",isSetup:!0};if(Mn)return uh?{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(ge.current.length>0)return ge.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 d=de(e);if(!d)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let l=Va(e,(d.docsDir??Za).replace(/\/+$/,"")),a=(()=>{try{return En(l)&&Yk(l).length>0}catch{return!1}})();try{let m=_e(e,s),j=Gt(m.name);if(!(!!j&&!(St(j)&&!j.refreshToken)))return{text:`Sign in with /login (profile "${m.name}")\u2026`,isSetup:!0};if(!m.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!m.project.workspaceId&&!a)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return a?{text:Lb,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Xe=wl($),yc=Xe.length>0&&!x,Mo=Math.max(3,Math.min(12,(We.rows??24)-8)),Uo=Math.min(hs,Math.max(0,Xe.length-1)),Ut=Xe.length<=Mo?0:Math.min(Math.max(0,Uo-Math.floor(Mo/2)),Xe.length-Mo),Cs=Xe.slice(Ut,Ut+Mo),Rs=c!==null?Ap(c,8,Be):null,Fo=je?je.paths.filter(d=>!je.query||d.toLowerCase().includes(je.query.toLowerCase())).slice(0,8):[],Wo=Ne?Ne.sessions.filter(d=>{let l=Ne.query.toLowerCase();return!l||d.name.toLowerCase().includes(l)||d.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],Ie=ee((d,l)=>{Fe.current?.close(),Fe.current=Np({cwd:e,resume:d,profileName:l??s,allowProdWrites:Jt.current}),d||(et.current={uuid:null,firstPrompt:null,titleFired:!1},Et(null)),sn(0),an(0)},[e,s]),wc=ee((d,l,a)=>{if(_b.test(d))try{let m=_e(e,s),j=typeof l.project_id=="string"&&l.project_id||m.project.projectId,V=Zr(l,a),f=[],w=es(a);d.endsWith("publish_article")&&w&&f.push(`Live: ${w}`);let k=ts(a);k?f.push(`Preview: ${k}`):V&&j&&f.push(`Preview: ${Jr(m.connection.portalUrl,j,V,m.project.languageCode??"en")}`),f.length>0&&u({kind:"link",lines:f})}catch{}},[e,s,u]),ie=ee(async(d,l)=>{Ro(!0),lt.current=!1,Pt.current=!1,Ke(),ze([]),Nn(null),ks(null);let a=Co.current;if(l?.display?.startsWith("/"))try{let P=Gu(e,l.display);P&&(d=`${d}
408
-
409
- ${P}`)}catch{}l?.quietUser||u({kind:"user",text:l?.echoDisplay&&l.display?l.display:d});let m=et.current;m.firstPrompt||(m.firstPrompt=l?.display??d),Tt.current=Date.now(),zt(0),T(!0),To.current.clear();let j="",V=!1,f=!1,w="",k={num:0,closed:!1,cueSeen:!1},g=null,C=()=>{g||(g=setTimeout(()=>{g=null,p(w.length>0?w:null)},60))},S=()=>{g&&clearTimeout(g),g=null,p(null)},L=(P=!1)=>{let{head:H,keep:_}=Dp(w,P);H.trim()&&u({kind:"assistant",text:Ua(H.trimEnd(),k)}),w=_,S()};try{for await(let P of Fe.current.send(d))if(P.type==="session"){if(!m.uuid){m.uuid=P.sessionId;let H=new Date().toISOString(),_=ms.current,U=_??sb(m.firstPrompt??"session");ib({uuid:P.sessionId,name:U,renamed:!!_,titled:!1,cwd:e,firstPrompt:m.firstPrompt??"",createdAt:H,updatedAt:H}),Et(U),ms.current=null}}else if(P.type==="text"){w+=P.delta,j+=P.delta;let H=jp(w);if(H>0){let _=w.slice(0,H).trimEnd();_&&u({kind:"assistant",text:Ua(_,k)}),w=w.slice(H)}C(),zt(_=>_+P.delta.length)}else if(P.type==="tool"){V=!0;let _=(z=>typeof z=="string"&&z?z.replace(/\\/g,"/").toLowerCase():null)(P.input.file_path??P.input.notebook_path),U=["Edit","Write","MultiEdit","NotebookEdit"].includes(P.name),N=P.name==="Read"&&_!==null&&_===ic.current;if(ic.current=U?_:null,N)L(),u({kind:"tool",title:"Read",sep:"",arg:"(re-checking the file it just edited)"});else{let z=Xr(P.name,P.input,e);z&&(L(),u({kind:"tool",title:z.title,sep:z.sep,arg:z.arg}),To.current.set(P.id,{name:P.name,input:P.input}))}}else if(P.type==="article_diff"){let H=ct(P.oldContent,P.newContent,ht());H&&(L(),u({kind:"diff",added:H.added,removed:H.removed,lines:H.lines,hidden:H.hidden}))}else if(P.type==="tool_result"){P.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(P.output)&&(jo.current=!0);let H=To.current.get(P.id);if(H){To.current.delete(P.id),L();let _=Qr(P.output,4,P.isError?void 0:H.name,H.input);u({kind:"tool-result",lines:_.lines,hidden:_.hidden,isError:P.isError}),P.isError||wc(H.name,H.input,P.output)}}else if(P.type==="result"){L(!0),sn(_=>_+P.outputTokens),an(_=>_+P.costUsd);let H=P.inputTokens+P.cacheReadTokens+P.cacheCreationTokens;if(u({kind:"done",seconds:Math.round((Date.now()-Tt.current)/1e3),tokens:P.outputTokens,costUsd:P.costUsd,ok:P.ok,...H>0?{inTokens:H,cachedPct:Math.round(P.cacheReadTokens/H*100)}:{}}),!f&&!V&&!j.trim()&&!In.current&&u({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),P.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(j))try{let _=Bp(e);if(En(_)){let U=cs(_,"utf8").trim();U&&(vs(U),u({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(Pt.current=P.ok&&/\?[\s*_"')\]]*$/.test(j.trimEnd()),P.ok&&k.cueSeen)oc(!0),ze([]);else{let _=P.ok?yp(j,kn.map(U=>U.name)):[];if(_.length>0)ne(_[0]);else if(P.ok&&j.trim()&&!Pt.current){let U=Mt(!1);U.kind==="recommend"&&(U.rec.lead||U.rec.picker)||db(d,j,e).then(N=>{N&&Co.current===a&&Se(N)}).catch(()=>{})}}if(m.uuid&&(Ga(m.uuid),!m.titleFired)){m.titleFired=!0;let _=m.uuid,U=m.firstPrompt;U&&Ip(U,e).then(N=>{N&&(rb(_,N),Et(N))}).catch(()=>{})}}else P.type==="error"&&(L(!0),f=!0,P.kind==="auth"&&(jo.current=!0),u({kind:"note",text:`agent error: ${P.message}`,tone:"error"}))}finally{T(!1),S(),Y(P=>P+1),et.current.uuid&&fp(e,et.current.uuid,Qt.current),jo.current?(jo.current=!1,On.current=l?.display??d,Se("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):On.current=null,In.current&&(In.current=!1,Lt.current.length>0&&(u({kind:"note",tone:"info",text:`(${Lt.current.length} queued message(s) discarded)`}),Lt.current=[],gs([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,wc,ht,Se,ne,Ke,Mt]),Ft=ee(async d=>{let l=ds(e,"standard");Tt.current=Date.now(),zt(0),T(!0);let a=new AbortController;xe.current=a;let m=async(j,V)=>{let f=za(j);ce({verb:"Publishing",total:f.length,done:0,active:[],rows:$o(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:V?`Resolving cross-links in ${j.length} article${j.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${j.length} article${j.length===1?"":"s"} across ${f.length} partition${f.length===1?"":"s"} (\u2264${no} agents at once) on ${l.model}\u2026 (esc to stop)`});let w=!1;for await(let k of ls({cwd:e,partitions:f,promptFor:g=>oo(g.paths),concurrency:no,profileName:s,allowProdWrites:Jt.current,model:l.model,signal:a.signal}))if(k.type==="partition_status")k.status==="running"?ce(g=>g&&{...g,active:[...g.active,k.label],rows:Ge(g.rows,k.label,"active"),lastAt:Date.now()}):ce(g=>g&&{...g,active:g.active.filter(C=>C!==k.label),done:g.done+1,rows:Ge(g.rows,k.label,k.status==="done"?"done":"failed"),lastAt:Date.now()});else if(k.type==="partition_event")ce(g=>{if(!g)return g;let C={...g,lastAt:Date.now()};return k.event.type==="tool"?C.tools=g.tools+1:k.event.type==="text"&&(C.chars=g.chars+k.event.delta.length),C});else if(k.type==="run_done"){w=k.aborted,an(L=>L+k.totalCostUsd),sn(L=>L+k.results.reduce((P,H)=>P+H.outputTokens,0));let g=k.aborted?"Stopped. ":"",C=t.kind==="api"?"api":"subscription";u({kind:"note",tone:k.aborted?"warn":k.ok?"ok":"warn",text:g+mi(k.results,f,C).join(`
410
- `)});let S=fi(e,s);if(S&&u({kind:"note",tone:"info",text:S}),!k.aborted){try{let L=await qp({cwd:e,profileName:s}),P=Vp(L);P?u({kind:"note",tone:"info",text:P}):L.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${L.skipped}`})}catch(L){u({kind:"note",tone:"warn",text:`Order sync failed: ${L.message}`})}try{let L=Yp(await Gp({cwd:e,profileName:s}));L&&u({kind:"note",tone:"info",text:L})}catch(L){u({kind:"note",tone:"warn",text:`Related-articles sync failed: ${L.message}`})}}}return w};try{if(!await m(d,!1)){let V=await gi(e,s,d);V.length>0&&await m(V,!0)}}catch(j){u({kind:"note",tone:"error",text:`Publish run failed: ${j.message}`})}finally{xe.current=null,ce(null),T(!1),Y(j=>j+1)}},[e,s,u,t]),Ss=ee(async d=>{await ie(pi(d),{display:`/publish ${d}`,quietUser:!0});try{let l=await Ar(e,s,d.replace(/\\/g,"/"));l.length>0&&(Nn(`Related articles not yet published (${l.length}):`),ze([`/publish --related ${d}`,...l.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ie]),Bo=ee(d=>{if(d)try{for(let l of Array.isArray(d)?d:[d]){let a=Pa(e,l);if(!a)continue;Yr(e,a.title).ok&&u({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${a.title}`});return}}catch{}},[e,u]),kc=ee(async(d,l)=>{let m=kb(d,3),j=ds(e,"standard"),V=new Map;for(let k of d){let g=ti(e,k,vn(e,k));g&&V.set(k,g)}Tt.current=Date.now(),zt(0),T(!0);let f=new AbortController;xe.current=f,ce({verb:"Authoring",unit:"spec",total:m.length,done:0,active:[],rows:$o(m),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${d.length} screenshot spec${d.length===1?"":"s"} across ${m.length} partition${m.length===1?"":"s"} (\u22646 agents at once) on ${j.model}${j.forced?" (forced)":""}\u2026 (esc to stop)`});let w=!1;try{for await(let k of ls({cwd:e,partitions:m,promptFor:g=>pd(g,V),concurrency:6,profileName:s,allowProdWrites:Jt.current,model:j.model,signal:f.signal}))if(k.type==="partition_status")k.status==="running"?ce(g=>g&&{...g,active:[...g.active,k.label],rows:Ge(g.rows,k.label,"active"),lastAt:Date.now()}):ce(g=>g&&{...g,active:g.active.filter(C=>C!==k.label),done:g.done+1,rows:Ge(g.rows,k.label,k.status==="done"?"done":"failed"),lastAt:Date.now()});else if(k.type==="partition_event")ce(g=>{if(!g)return g;let C={...g,lastAt:Date.now()};return k.event.type==="tool"?C.tools=g.tools+1:k.event.type==="text"&&(C.chars=g.chars+k.event.delta.length),C});else if(k.type==="run_done"){an(L=>L+k.totalCostUsd),sn(L=>L+k.results.reduce((P,H)=>P+H.outputTokens,0));let g=k.results.filter(L=>L.ok).length,C=k.aborted?"Stopped. ":"";w=!k.aborted&&l.setup;let S=k.aborted?"":w?" Refreshing the staging checklist\u2026":" Next: /screenshot capture --all (or /screenshot checklist first for the staging checklist).";u({kind:"note",tone:k.aborted?"warn":k.ok?"ok":"warn",text:`${C}Authored specs \u2014 ${g}/${k.results.length} batches ok.${S}`}),!k.aborted&&k.ok&&Bo(l.runLine)}}catch(k){u({kind:"note",tone:"error",text:`Spec authoring failed: ${k.message}`})}finally{xe.current=null,ce(null),T(!1),Y(k=>k+1)}if(w){let k=await Sn();k.kind==="forward-to-agent"&&k.prompt&&await ie(k.prompt,{display:k.display,quietUser:!0});let g=la(e);g&&u({kind:"note",tone:"info",text:g.join(`
411
- `)})}},[e,s,u,ie,Bo]),bc=ee(async d=>{let l=ti(e,d,vn(e,d))??void 0,a=await Rr([d],void 0,{prior:l});a.kind==="forward-to-agent"&&a.prompt&&await ie(a.prompt,{display:a.display,quietUser:!0}),Zl(e,d)&&be(`Spec ready \u2014 /screenshot capture ${d} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${d}`,reason:""})},[e,ie,be]),Wn=ee(async(d,l)=>{if(!Ur(e)){await ie(aa(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!yu(e)){u({kind:"note",tone:"info",text:"No saved login for screenshot capture yet \u2014 opening a browser window. Sign in to your app (MFA included); I'll continue automatically once the session saves. (esc cancels)"}),T(!0),Do("Waiting for you to finish logging in (browser window)\u2026");let N=new AbortController;xe.current=N;let z;try{z=await wu({cwd:e,signal:N.signal})}catch(Oe){u({kind:"note",tone:"error",text:`Could not launch the login: ${Oe.message}`});return}finally{xe.current=null,Do(null),T(!1)}if(z.exitCode!==0){ia(z.exitCode,z.output)?u({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."}):/unknown option/i.test(z.output)?u({kind:"note",tone:"warn",text:"Your d360-capture is older than this writer. Update it: npm i -g document360-capture \u2014 then /screenshot capture again."}):u({kind:"note",tone:N.signal.aborted?"warn":"error",text:N.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
412
- ${ra(z.output)}`});return}u({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let a=new Map(d.map(N=>[N,od(e,N)])),m=0;if(d.length>1){let N=d.filter(z=>a.get(z).mutates);if(N.length>0&&(m=N.length,d=d.filter(z=>!a.get(z).mutates),d.length===0)){u({kind:"note",tone:"warn",text:`\u26A0 All ${N.length} spec${N.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${N[0]}`});return}}else if(d.length===1&&a.get(d[0]).mutates){let N=a.get(d[0]),z=ku(e);u({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${N.what?`: ${nd(N.what)}`:N.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. `+(z.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${z.url?` (${z.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.")})}T(!0);let j=new AbortController;xe.current=j;let V=d.map(N=>({label:N,items:1,status:"pending"}));ce({verb:"Capturing",unit:"screenshot",total:d.length,done:0,active:[],rows:V,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let f=at(e),w=Object.keys(f.shots).length>0,k=bu(l?.heldBackBlocked??[],m);u({kind:"note",tone:"info",text:`Capturing ${d.length} screenshot${d.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+(k?`
413
- ${k}`:"")});let g=Date.now(),C=[];try{for(let N of d){if(j.signal.aborted)break;ce(Q=>Q&&{...Q,active:[N],rows:Ge(Q.rows,N,"active"),lastAt:Date.now()});let{exitCode:z,output:Oe}=await sa({cwd:e,id:N,signal:j.signal,stdio:"pipe"});if(ia(z,Oe)){u({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."});return}let rt=j.signal.aborted&&z!==0?"failed":oa(e,N,z,g),pn=rt==="captured"?void 0:rt==="skipped"?mu(Oe)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":gu(Oe);C.push({id:N,outcome:rt,detail:pn}),ce(Q=>Q&&{...Q,active:[],done:Q.done+1,rows:Ge(Q.rows,N,rt==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(N){u({kind:"note",tone:"error",text:`Capture run failed: ${N.message}`})}finally{xe.current=null,ce(null),T(!1),Y(N=>N+1)}if(C.length===0)return;let S=C.filter(N=>N.outcome==="captured"),L=C.filter(N=>N.outcome==="skipped"),P=C.filter(N=>N.outcome==="failed"),H=d.length-C.length;u({kind:"note",tone:P.length?"warn":S.length?"ok":"info",text:[`\u2713 ${S.length} captured`,L.length?`\u2298 ${L.length} blocked`:"",P.length?`\u2717 ${P.length} broken`:"",H?`${H} not run (stopped)`:""].filter(Boolean).join(" ")+` ${C.length} run${m>0?` \xB7 ${m} held back`:""}`+xu($u(f,C),w).map(N=>`
414
- ${N}`).join("")});let _=vu(L);if(_.length>0&&u({kind:"note",tone:"info",text:_.join(`
415
- `)}),P.length>0){let N=Math.max(...P.map(z=>z.id.length));u({kind:"note",tone:"error",text:P.map(z=>`\u2717 ${z.id.padEnd(N)} ${Mr(z.detail)}`).join(`
416
- `)})}if(pr(e,C.map(N=>({id:N.id,outcome:N.outcome,reason:N.detail,specSource:vn(e,N.id)})),new Date().toISOString()),C.length===d.length&&P.length===0&&L.length===0&&Bo(l?.runLine),S.length>0){let N=S.map(Oe=>Oe.id);u({kind:"note",tone:"info",text:lo(N.length)}),await ie(qt(e,N),{display:"/screenshot verify",quietUser:!0});let z=uo(e,N);z.length>0&&u({kind:"note",tone:"info",text:z.join(`
417
- `)});return}let U=Cu({results:C,ids:d,articles:Ru(e,S.map(N=>N.id))});U&&be(U.note,{kind:"cmd",cmd:U.cmd,reason:""},U.tone)},[e,u,be,ie,Bo]),Ps=ee(d=>{let l=Gt(d);if(!l||St(l)&&!l.refreshToken)return null;let a={...Dn(l.idToken)??{},...Dn(l.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),Ts=ee((d,l)=>{if(l){let a=de(e);a&&(a.defaultProfile=d,Op(a,e))}i(d),Ie(void 0,d),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${d}"${l?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Ps(d)||(u({kind:"note",tone:"warn",text:`Profile "${d}" is not signed in \u2014 sign in with /login.`}),ne("/login")),Y(a=>a+1)},[e,u,Ie,Ps,ne]),Ho=ee((d,l,a)=>{zo(e,d,l,a.id,a.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),Ie(),Lp(e,d)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),u({kind:"note",tone:"info",text:yn(gn(e)).join(`
418
- `)}),cn(Bt()),Un.current=qe(e).status==="current",ln.current=it(e),u({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,u,Ie,cn]),qo=ee(async d=>{let l;try{l=await Gn(e,d)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),ne("/workspace");return}if(l.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=l.workspaces.filter(j=>(j.workspace_type??"").toLowerCase()!=="apidocumentation"),m=a.length>0?a:l.workspaces;if(m.length===1){let j=m[0],V=l.workspaces.length-m.length;u({kind:"note",tone:"ok",text:`Selected the "${j.name??j.id}" workspace${V>0?" (skipped the API-documentation workspace)":""}.`}),Ho(l.profile,l.projectId,j);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${m.length} available).`}),ne("/workspace")},[e,u,Ho,ne]),Vo=ee((d,l)=>{Ko(e,d,l.id,l.name),u({kind:"note",tone:"ok",text:`Project set to "${l.name??l.id}" (agent restarted).`}),Ie(),qo(d)},[e,u,Ie,qo]),$c=ee(async d=>{let l;try{l=_e(e,d)}catch{return}if(!l.project.workspaceId){if(l.project.projectId){if(!l.project.projectName)try{let{projects:a}=await gt(e,l.name),m=a.find(j=>j.id===l.project.projectId);m?.name&&Tb(e,l.name,{projectName:m.name})}catch{}await qo(l.name);return}try{let{projects:a}=await gt(e,l.name);if(a.length===1){let m=a[0];u({kind:"note",tone:"ok",text:`Using your Document360 project "${m.name??m.id}".`}),Vo(l.name,{id:m.id,name:m.name});return}if(a.length>1){let m=a.map(j=>({id:j.id,name:j.name??j.id,sub:j.sub_domain}));u({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),jt({cursor:0,current:-1,rows:m,profile:l.name,environment:l.connection.name});return}}catch{}u({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),ne("/project")}},[e,u,qo,Vo,ne]),dn=ee(()=>{let d=ge.current[0];if(!d)return;Ke();let{plan:l,mode:a}=d;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let j of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${j}`});l.overwritesLocalChanges&&a==="pull"&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let m=ct(l.oldContent,l.newContent,ht());u(m?{kind:"diff",added:m.added,removed:m.removed,lines:m.lines,hidden:m.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),a==="conflict"?(u({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),u({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,ht,Ke]),Es=ee(()=>{if(ge.current.length>0){dn();return}let d=Zt.current;Zt.current=[],d.length>0?(u({kind:"note",tone:"info",text:`Publishing ${d.length} kept-local article${d.length===1?"":"s"} over the portal\u2026`}),Ft(d)):ne("/pull")},[dn,u,Ft,ne]),vc=ee(d=>{if(ge.current.length===0)return!1;let l=d.trim().toLowerCase(),a=ge.current[0];if(a.mode==="conflict"){if(l==="l"||l==="local")ge.current.shift(),Zt.current.push(a.plan.path),u({kind:"note",tone:"info",text:`Keeping local ${a.plan.path} \u2014 will publish over the portal.`});else if(l==="p"||l==="portal"){ge.current.shift();try{_p({cwd:e,profileName:s},a.plan),u({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${a.plan.path} (local overwritten, sync base advanced).`})}catch(m){u({kind:"note",tone:"error",text:`Take-portal failed: ${m.message}`})}}else if(l==="s"||l==="skip"||l==="n")ge.current.shift(),u({kind:"note",tone:"info",text:`Skipped ${a.plan.path} \u2014 still a conflict.`});else{let m=ge.current.length;return ge.current=[],Zt.current=[],u({kind:"note",tone:"info",text:`Resolve cancelled (${m} conflict${m===1?"":"s"} left untouched).`}),!0}return Es(),!0}if(l==="y"||l==="yes"){let m=ge.current.shift().plan;try{_p({cwd:e,profileName:s},m),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${m.path} (sync base advanced).`})}catch(j){u({kind:"note",tone:"error",text:`Pull failed: ${j.message}`})}}else if(l==="n"||l==="no"){let m=ge.current.shift().plan;u({kind:"note",tone:"info",text:`Skipped ${m.path}.`})}else{let m=ge.current.length;return ge.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${m} article(s) left untouched).`}),!0}return Es(),!0},[e,s,Es,u]),As=ee(async d=>{u({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let l=await Ya({cwd:e,profileName:s}),a=d?.replace(/\\/g,"/"),m=l.entries.filter(V=>V.status==="conflict"&&V.path).map(V=>V.path);if(a){if(!m.includes(a)){u({kind:"note",tone:"ok",text:`${a} isn\u2019t in conflict \u2014 nothing to resolve.`});return}m=[a]}if(m.length===0){u({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let j=[];for(let V of m)try{j.push({plan:await Up({cwd:e,profileName:s,relPath:V}),mode:"conflict"})}catch(f){u({kind:"note",tone:"error",text:`Could not load ${V} from Document360: ${f.message}`})}if(j.length===0)return;u({kind:"note",tone:"info",text:`Resolving ${j.length} conflict${j.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),ge.current=j,Zt.current=[],dn()}catch(l){u({kind:"note",tone:"error",text:`Could not compute sync status: ${l.message}`})}},[e,s,u,dn]),xc=ee(d=>{let l=Eo.current;if(!l)return!1;if(Eo.current=null,Ke(),d.trim()!==l.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:m}=ba(e,l.targets);u({kind:"note",tone:m.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let j of m)u({kind:"note",tone:"error",text:` \u2717 ${j.path}: ${j.error}`});return l.hadDevhints&&(u({kind:"note",tone:"warn",text:ar().join(`
407
+ cwd: ${e}`}),$s()},[]),Ue(()=>{let d=setInterval(()=>{$s()},Gb);return()=>clearInterval(d)},[$s]),Ue(()=>{if(C||he||Yt||lt.current||Pt.current||re!==null||Fe.length>0||$!==""||Mn!==null||ye.current.length>0||Eo.current||ys)return;let d=Mt(!1);d.kind==="recommend"&&(d.rec.lead||d.rec.picker)&&Io(d.rec,{silent:!0})},[C,he,re,Fe,$,Mn,ys,q,Mt,Yt]),Ue(()=>{let d=null,l=null,a=()=>{d&&clearTimeout(d),d=setTimeout(()=>{d=null;let m=`${Be.columns??80}x${Be.rows??24}`;m!==gc.current&&(gc.current=m,ph(T=>T+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+El(Qt.current,ht())+"\x1B[?2026l")},80))},400)};return Be.on("resize",a),()=>{d&&clearTimeout(d),l&&clearTimeout(l),Be.off("resize",a)}},[Be,ht]);let Oe=Math.max(20,(Be.columns??80)-1),wc=qa(()=>Ub(e,s),[e,s,q]),xs=(()=>{if(ch)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(ps!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${ps?` v${ps}`:""}\u2026`,isSetup:!0};if(Lo)return{text:"\u{1F6E0} press c to copy the d360-writer feedback \u2014 then send it to the team (Teams / Slack / email)\u2026",isSetup:!0};if(Mn)return hh?{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(ye.current.length>0)return ye.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 d=de(e);if(!d)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let l=Va(e,(d.docsDir??tc).replace(/\/+$/,"")),a=(()=>{try{return En(l)&&Qk(l).length>0}catch{return!1}})();try{let m=Me(e,s),T=Gt(m.name);if(!(!!T&&!(St(T)&&!T.refreshToken)))return{text:`Sign in with /login (profile "${m.name}")\u2026`,isSetup:!0};if(!m.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!m.project.workspaceId&&!a)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return a?{text:Fb,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Xe=bl($),kc=Xe.length>0&&!C,Mo=Math.max(3,Math.min(12,(Be.rows??24)-8)),Uo=Math.min(hs,Math.max(0,Xe.length-1)),Ut=Xe.length<=Mo?0:Math.min(Math.max(0,Uo-Math.floor(Mo/2)),Xe.length-Mo),Cs=Xe.slice(Ut,Ut+Mo),Rs=c!==null?Np(c,8,Oe):null,Fo=Ne?Ne.paths.filter(d=>!Ne.query||d.toLowerCase().includes(Ne.query.toLowerCase())).slice(0,8):[],Wo=Ie?Ie.sessions.filter(d=>{let l=Ie.query.toLowerCase();return!l||d.name.toLowerCase().includes(l)||d.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],Le=ee((d,l)=>{We.current?.close(),We.current=Lp({cwd:e,resume:d,profileName:l??s,allowProdWrites:Jt.current}),d||(et.current={uuid:null,firstPrompt:null,titleFired:!1},Et(null)),sn(0),an(0)},[e,s]),bc=ee((d,l,a)=>{if(Qp.test(d))try{let m=Me(e,s),T=typeof l.project_id=="string"&&l.project_id||m.project.projectId,V=Zr(l,a),f=[],w=es(a);d.endsWith("publish_article")&&w&&f.push(`Live: ${w}`);let k=ts(a);k?f.push(`Preview: ${k}`):V&&T&&f.push(`Preview: ${Jr(m.connection.portalUrl,T,V,m.project.languageCode??"en")}`),f.length>0&&u({kind:"link",lines:f})}catch{}},[e,s,u]),ie=ee(async(d,l)=>{Ro(!0),lt.current=!1,Pt.current=!1,Ke(),ze([]),Nn(null),ks(null);let a=Co.current;if(l?.display?.startsWith("/"))try{let N=zu(e,l.display);N&&(d=`${d}
408
+
409
+ ${N}`)}catch{}l?.quietUser||u({kind:"user",text:l?.echoDisplay&&l.display?l.display:d});let m=et.current;m.firstPrompt||(m.firstPrompt=l?.display??d),Tt.current=Date.now(),zt(0),P(!0),To.current.clear();let T="",V=!1,f=!1,w=!1,k="",y={num:0,closed:!1,cueSeen:!1},x=null,S=()=>{x||(x=setTimeout(()=>{x=null,p(k.length>0?k:null)},60))},U=()=>{x&&clearTimeout(x),x=null,p(null)},B=(N=!1)=>{let{head:F,keep:L}=Ip(k,N);F.trim()&&u({kind:"assistant",text:Ua(F.trimEnd(),y)}),k=L,U()};try{for await(let N of We.current.send(d))if(N.type==="session"){if(!m.uuid){m.uuid=N.sessionId;let F=new Date().toISOString(),L=ms.current,j=L??lb(m.firstPrompt??"session");db({uuid:N.sessionId,name:j,renamed:!!L,titled:!1,cwd:e,firstPrompt:m.firstPrompt??"",createdAt:F,updatedAt:F}),Et(j),ms.current=null}}else if(N.type==="text"){k+=N.delta,T+=N.delta;let F=Op(k);if(F>0){let L=k.slice(0,F).trimEnd();L&&u({kind:"assistant",text:Ua(L,y)}),k=k.slice(F)}S(),zt(L=>L+N.delta.length)}else if(N.type==="tool"){V=!0,Qp.test(N.name)&&(f=!0);let L=(pe=>typeof pe=="string"&&pe?pe.replace(/\\/g,"/").toLowerCase():null)(N.input.file_path??N.input.notebook_path),j=["Edit","Write","MultiEdit","NotebookEdit"].includes(N.name),z=N.name==="Read"&&L!==null&&L===cc.current;if(cc.current=j?L:null,z)B(),u({kind:"tool",title:"Read",sep:"",arg:"(re-checking the file it just edited)"});else{let pe=Xr(N.name,N.input,e);pe&&(B(),u({kind:"tool",title:pe.title,sep:pe.sep,arg:pe.arg}),To.current.set(N.id,{name:N.name,input:N.input}))}}else if(N.type==="article_diff"){let F=ct(N.oldContent,N.newContent,ht());F&&(B(),u({kind:"diff",added:F.added,removed:F.removed,lines:F.lines,hidden:F.hidden}))}else if(N.type==="tool_result"){N.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(N.output)&&(jo.current=!0);let F=To.current.get(N.id);if(F){To.current.delete(N.id),B();let L=Qr(N.output,4,N.isError?void 0:F.name,F.input);u({kind:"tool-result",lines:L.lines,hidden:L.hidden,isError:N.isError}),N.isError||bc(F.name,F.input,N.output)}}else if(N.type==="result"){B(!0),sn(L=>L+N.outputTokens),an(L=>L+N.costUsd);let F=N.inputTokens+N.cacheReadTokens+N.cacheCreationTokens;if(u({kind:"done",seconds:Math.round((Date.now()-Tt.current)/1e3),tokens:N.outputTokens,costUsd:N.costUsd,ok:N.ok,...F>0?{inTokens:F,cachedPct:Math.round(N.cacheReadTokens/F*100)}:{}}),!w&&!V&&!T.trim()&&!In.current&&u({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),N.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(T))try{let L=Vp(e);if(En(L)){let j=cs(L,"utf8").trim();j&&(vs(j),u({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(Pt.current=N.ok&&/\?[\s*_"')\]]*$/.test(T.trimEnd()),N.ok&&y.cueSeen)sc(!0),ze([]);else{let L=N.ok?bp(T,kn.map(j=>j.name)):[];if(L.length>0)ne(L[0]);else if(N.ok&&T.trim()&&!Pt.current){let j=Mt(!1);j.kind==="recommend"&&(j.rec.lead||j.rec.picker)||fb(d,T,e).then(z=>{z&&Co.current===a&&Pe(z)}).catch(()=>{})}}if(m.uuid&&(Ga(m.uuid),!m.titleFired)){m.titleFired=!0;let L=m.uuid,j=m.firstPrompt;j&&_p(j,e).then(z=>{z&&(cb(L,z),Et(z))}).catch(()=>{})}}else N.type==="error"&&(B(!0),w=!0,N.kind==="auth"&&(jo.current=!0),u({kind:"note",text:`agent error: ${N.message}`,tone:"error"}))}finally{if(P(!1),U(),f)try{let N=Ja(await Qa({cwd:e,profileName:s}));N&&u({kind:"note",tone:N.startsWith("\u26A0")?"warn":"info",text:N})}catch{}Y(N=>N+1),et.current.uuid&&yp(e,et.current.uuid,Qt.current),jo.current?(jo.current=!1,On.current=l?.display??d,Pe("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):On.current=null,In.current&&(In.current=!1,Lt.current.length>0&&(u({kind:"note",tone:"info",text:`(${Lt.current.length} queued message(s) discarded)`}),Lt.current=[],gs([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,bc,ht,Pe,ne,Ke,Mt]),Ft=ee(async d=>{let l=ds(e,"standard");Tt.current=Date.now(),zt(0),P(!0);let a=new AbortController;Ce.current=a;let m=async(T,V)=>{let f=za(T);ce({verb:"Publishing",total:f.length,done:0,active:[],rows:$o(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:V?`Resolving cross-links in ${T.length} article${T.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${T.length} article${T.length===1?"":"s"} across ${f.length} partition${f.length===1?"":"s"} (\u2264${no} agents at once) on ${l.model}\u2026 (esc to stop)`});let w=!1;for await(let k of ls({cwd:e,partitions:f,promptFor:y=>oo(y.paths),concurrency:no,profileName:s,allowProdWrites:Jt.current,model:l.model,signal:a.signal}))if(k.type==="partition_status")k.status==="running"?ce(y=>y&&{...y,active:[...y.active,k.label],rows:Ge(y.rows,k.label,"active"),lastAt:Date.now()}):ce(y=>y&&{...y,active:y.active.filter(x=>x!==k.label),done:y.done+1,rows:Ge(y.rows,k.label,k.status==="done"?"done":"failed"),lastAt:Date.now()});else if(k.type==="partition_event")ce(y=>{if(!y)return y;let x={...y,lastAt:Date.now()};return k.event.type==="tool"?x.tools=y.tools+1:k.event.type==="text"&&(x.chars=y.chars+k.event.delta.length),x});else if(k.type==="run_done"){w=k.aborted,an(U=>U+k.totalCostUsd),sn(U=>U+k.results.reduce((B,N)=>B+N.outputTokens,0));let y=k.aborted?"Stopped. ":"",x=t.kind==="api"?"api":"subscription";u({kind:"note",tone:k.aborted?"warn":k.ok?"ok":"warn",text:y+mi(k.results,f,x).join(`
410
+ `)});let S=fi(e,s);if(S&&u({kind:"note",tone:"info",text:S}),!k.aborted){try{let U=await Qa({cwd:e,profileName:s}),B=Ja(U);B?u({kind:"note",tone:"info",text:B}):U.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${U.skipped}`})}catch(U){u({kind:"note",tone:"warn",text:`Order sync failed: ${U.message}`})}try{let U=zp(await Yp({cwd:e,profileName:s}));U&&u({kind:"note",tone:"info",text:U})}catch(U){u({kind:"note",tone:"warn",text:`Related-articles sync failed: ${U.message}`})}}}return w};try{if(!await m(d,!1)){let V=await gi(e,s,d);V.length>0&&await m(V,!0)}}catch(T){u({kind:"note",tone:"error",text:`Publish run failed: ${T.message}`})}finally{Ce.current=null,ce(null),P(!1),Y(T=>T+1)}},[e,s,u,t]),Ss=ee(async d=>{await ie(pi(d),{display:`/publish ${d}`,quietUser:!0});try{let l=await Dr(e,s,d.replace(/\\/g,"/"));l.length>0&&(Nn(`Related articles not yet published (${l.length}):`),ze([`/publish --related ${d}`,...l.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ie]),Bo=ee(d=>{if(d)try{for(let l of Array.isArray(d)?d:[d]){let a=Pa(e,l);if(!a)continue;Yr(e,a.title).ok&&u({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${a.title}`});return}}catch{}},[e,u]),$c=ee(async(d,l)=>{let m=xb(d,3),T=ds(e,"standard"),V=new Map;for(let k of d){let y=ti(e,k,vn(e,k));y&&V.set(k,y)}Tt.current=Date.now(),zt(0),P(!0);let f=new AbortController;Ce.current=f,ce({verb:"Authoring",unit:"spec",total:m.length,done:0,active:[],rows:$o(m),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${d.length} screenshot spec${d.length===1?"":"s"} across ${m.length} partition${m.length===1?"":"s"} (\u22646 agents at once) on ${T.model}${T.forced?" (forced)":""}\u2026 (esc to stop)`});let w=!1;try{for await(let k of ls({cwd:e,partitions:m,promptFor:y=>fd(y,V),concurrency:6,profileName:s,allowProdWrites:Jt.current,model:T.model,signal:f.signal}))if(k.type==="partition_status")k.status==="running"?ce(y=>y&&{...y,active:[...y.active,k.label],rows:Ge(y.rows,k.label,"active"),lastAt:Date.now()}):ce(y=>y&&{...y,active:y.active.filter(x=>x!==k.label),done:y.done+1,rows:Ge(y.rows,k.label,k.status==="done"?"done":"failed"),lastAt:Date.now()});else if(k.type==="partition_event")ce(y=>{if(!y)return y;let x={...y,lastAt:Date.now()};return k.event.type==="tool"?x.tools=y.tools+1:k.event.type==="text"&&(x.chars=y.chars+k.event.delta.length),x});else if(k.type==="run_done"){an(U=>U+k.totalCostUsd),sn(U=>U+k.results.reduce((B,N)=>B+N.outputTokens,0));let y=k.results.filter(U=>U.ok).length,x=k.aborted?"Stopped. ":"";w=!k.aborted&&l.setup;let S=k.aborted?"":w?" Refreshing the staging checklist\u2026":" Next: /screenshot capture --all (or /screenshot checklist first for the staging checklist).";u({kind:"note",tone:k.aborted?"warn":k.ok?"ok":"warn",text:`${x}Authored specs \u2014 ${y}/${k.results.length} batches ok.${S}`}),!k.aborted&&k.ok&&Bo(l.runLine)}}catch(k){u({kind:"note",tone:"error",text:`Spec authoring failed: ${k.message}`})}finally{Ce.current=null,ce(null),P(!1),Y(k=>k+1)}if(w){let k=await Sn();k.kind==="forward-to-agent"&&k.prompt&&await ie(k.prompt,{display:k.display,quietUser:!0});let y=la(e);y&&u({kind:"note",tone:"info",text:y.join(`
411
+ `)})}},[e,s,u,ie,Bo]),vc=ee(async d=>{let l=ti(e,d,vn(e,d))??void 0,a=await Rr([d],void 0,{prior:l});a.kind==="forward-to-agent"&&a.prompt&&await ie(a.prompt,{display:a.display,quietUser:!0}),td(e,d)&&$e(`Spec ready \u2014 /screenshot capture ${d} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${d}`,reason:""})},[e,ie,$e]),Wn=ee(async(d,l)=>{if(!Ur(e)){await ie(aa(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!ku(e)){u({kind:"note",tone:"info",text:"No saved login for screenshot capture yet \u2014 opening a browser window. Sign in to your app (MFA included); I'll continue automatically once the session saves. (esc cancels)"}),P(!0),Ao("Waiting for you to finish logging in (browser window)\u2026");let j=new AbortController;Ce.current=j;let z;try{z=await bu({cwd:e,signal:j.signal})}catch(pe){u({kind:"note",tone:"error",text:`Could not launch the login: ${pe.message}`});return}finally{Ce.current=null,Ao(null),P(!1)}if(z.exitCode!==0){ia(z.exitCode,z.output)?u({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."}):/unknown option/i.test(z.output)?u({kind:"note",tone:"warn",text:"Your d360-capture is older than this writer. Update it: npm i -g document360-capture \u2014 then /screenshot capture again."}):u({kind:"note",tone:j.signal.aborted?"warn":"error",text:j.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
412
+ ${ra(z.output)}`});return}u({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let a=new Map(d.map(j=>[j,sd(e,j)])),m=0;if(d.length>1){let j=d.filter(z=>a.get(z).mutates);if(j.length>0&&(m=j.length,d=d.filter(z=>!a.get(z).mutates),d.length===0)){u({kind:"note",tone:"warn",text:`\u26A0 All ${j.length} spec${j.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${j[0]}`});return}}else if(d.length===1&&a.get(d[0]).mutates){let j=a.get(d[0]),z=$u(e);u({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${j.what?`: ${rd(j.what)}`:j.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. `+(z.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${z.url?` (${z.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.")})}P(!0);let T=new AbortController;Ce.current=T;let V=d.map(j=>({label:j,items:1,status:"pending"}));ce({verb:"Capturing",unit:"screenshot",total:d.length,done:0,active:[],rows:V,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let f=at(e),w=Object.keys(f.shots).length>0,k=vu(l?.heldBackBlocked??[],m);u({kind:"note",tone:"info",text:`Capturing ${d.length} screenshot${d.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+(k?`
413
+ ${k}`:"")});let y=Date.now(),x=[];try{for(let j of d){if(T.signal.aborted)break;ce(Q=>Q&&{...Q,active:[j],rows:Ge(Q.rows,j,"active"),lastAt:Date.now()});let{exitCode:z,output:pe}=await sa({cwd:e,id:j,signal:T.signal,stdio:"pipe"});if(ia(z,pe)){u({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."});return}let rt=T.signal.aborted&&z!==0?"failed":oa(e,j,z,y),pn=rt==="captured"?void 0:rt==="skipped"?yu(pe)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":wu(pe);x.push({id:j,outcome:rt,detail:pn}),ce(Q=>Q&&{...Q,active:[],done:Q.done+1,rows:Ge(Q.rows,j,rt==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(j){u({kind:"note",tone:"error",text:`Capture run failed: ${j.message}`})}finally{Ce.current=null,ce(null),P(!1),Y(j=>j+1)}if(x.length===0)return;let S=x.filter(j=>j.outcome==="captured"),U=x.filter(j=>j.outcome==="skipped"),B=x.filter(j=>j.outcome==="failed"),N=d.length-x.length;u({kind:"note",tone:B.length?"warn":S.length?"ok":"info",text:[`\u2713 ${S.length} captured`,U.length?`\u2298 ${U.length} blocked`:"",B.length?`\u2717 ${B.length} broken`:"",N?`${N} not run (stopped)`:""].filter(Boolean).join(" ")+` ${x.length} run${m>0?` \xB7 ${m} held back`:""}`+Ru(xu(f,x),w).map(j=>`
414
+ ${j}`).join("")});let F=Cu(U);if(F.length>0&&u({kind:"note",tone:"info",text:F.join(`
415
+ `)}),B.length>0){let j=Math.max(...B.map(z=>z.id.length));u({kind:"note",tone:"error",text:B.map(z=>`\u2717 ${z.id.padEnd(j)} ${Mr(z.detail)}`).join(`
416
+ `)})}if(pr(e,x.map(j=>({id:j.id,outcome:j.outcome,reason:j.detail,specSource:vn(e,j.id)})),new Date().toISOString()),x.length===d.length&&B.length===0&&U.length===0&&Bo(l?.runLine),S.length>0){let j=S.map(pe=>pe.id);u({kind:"note",tone:"info",text:lo(j.length)}),await ie(qt(e,j),{display:"/screenshot verify",quietUser:!0});let z=uo(e,j);z.length>0&&u({kind:"note",tone:"info",text:z.join(`
417
+ `)});return}let L=Su({results:x,ids:d,articles:Pu(e,S.map(j=>j.id))});L&&$e(L.note,{kind:"cmd",cmd:L.cmd,reason:""},L.tone)},[e,u,$e,ie,Bo]),Ps=ee(d=>{let l=Gt(d);if(!l||St(l)&&!l.refreshToken)return null;let a={...An(l.idToken)??{},...An(l.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),Ts=ee((d,l)=>{if(l){let a=de(e);a&&(a.defaultProfile=d,Mp(a,e))}i(d),Le(void 0,d),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${d}"${l?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Ps(d)||(u({kind:"note",tone:"warn",text:`Profile "${d}" is not signed in \u2014 sign in with /login.`}),ne("/login")),Y(a=>a+1)},[e,u,Le,Ps,ne]),Ho=ee((d,l,a)=>{zo(e,d,l,a.id,a.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),Le(),Up(e,d)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),u({kind:"note",tone:"info",text:yn(gn(e)).join(`
418
+ `)}),cn(Bt()),Un.current=qe(e).status==="current",ln.current=it(e),u({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,u,Le,cn]),qo=ee(async d=>{let l;try{l=await Gn(e,d)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),ne("/workspace");return}if(l.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=l.workspaces.filter(T=>(T.workspace_type??"").toLowerCase()!=="apidocumentation"),m=a.length>0?a:l.workspaces;if(m.length===1){let T=m[0],V=l.workspaces.length-m.length;u({kind:"note",tone:"ok",text:`Selected the "${T.name??T.id}" workspace${V>0?" (skipped the API-documentation workspace)":""}.`}),Ho(l.profile,l.projectId,T);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${m.length} available).`}),ne("/workspace")},[e,u,Ho,ne]),Vo=ee((d,l)=>{Ko(e,d,l.id,l.name),u({kind:"note",tone:"ok",text:`Project set to "${l.name??l.id}" (agent restarted).`}),Le(),qo(d)},[e,u,Le,qo]),xc=ee(async d=>{let l;try{l=Me(e,d)}catch{return}if(!l.project.workspaceId){if(l.project.projectId){if(!l.project.projectName)try{let{projects:a}=await gt(e,l.name),m=a.find(T=>T.id===l.project.projectId);m?.name&&jb(e,l.name,{projectName:m.name})}catch{}await qo(l.name);return}try{let{projects:a}=await gt(e,l.name);if(a.length===1){let m=a[0];u({kind:"note",tone:"ok",text:`Using your Document360 project "${m.name??m.id}".`}),Vo(l.name,{id:m.id,name:m.name});return}if(a.length>1){let m=a.map(T=>({id:T.id,name:T.name??T.id,sub:T.sub_domain}));u({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),jt({cursor:0,current:-1,rows:m,profile:l.name,environment:l.connection.name});return}}catch{}u({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),ne("/project")}},[e,u,qo,Vo,ne]),dn=ee(()=>{let d=ye.current[0];if(!d)return;Ke();let{plan:l,mode:a}=d;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let T of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${T}`});l.overwritesLocalChanges&&a==="pull"&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let m=ct(l.oldContent,l.newContent,ht());u(m?{kind:"diff",added:m.added,removed:m.removed,lines:m.lines,hidden:m.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),a==="conflict"?(u({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),u({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,ht,Ke]),Es=ee(()=>{if(ye.current.length>0){dn();return}let d=Zt.current;Zt.current=[],d.length>0?(u({kind:"note",tone:"info",text:`Publishing ${d.length} kept-local article${d.length===1?"":"s"} over the portal\u2026`}),Ft(d)):ne("/pull")},[dn,u,Ft,ne]),Cc=ee(d=>{if(ye.current.length===0)return!1;let l=d.trim().toLowerCase(),a=ye.current[0];if(a.mode==="conflict"){if(l==="l"||l==="local")ye.current.shift(),Zt.current.push(a.plan.path),u({kind:"note",tone:"info",text:`Keeping local ${a.plan.path} \u2014 will publish over the portal.`});else if(l==="p"||l==="portal"){ye.current.shift();try{Fp({cwd:e,profileName:s},a.plan),u({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${a.plan.path} (local overwritten, sync base advanced).`})}catch(m){u({kind:"note",tone:"error",text:`Take-portal failed: ${m.message}`})}}else if(l==="s"||l==="skip"||l==="n")ye.current.shift(),u({kind:"note",tone:"info",text:`Skipped ${a.plan.path} \u2014 still a conflict.`});else{let m=ye.current.length;return ye.current=[],Zt.current=[],u({kind:"note",tone:"info",text:`Resolve cancelled (${m} conflict${m===1?"":"s"} left untouched).`}),!0}return Es(),!0}if(l==="y"||l==="yes"){let m=ye.current.shift().plan;try{Fp({cwd:e,profileName:s},m),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${m.path} (sync base advanced).`})}catch(T){u({kind:"note",tone:"error",text:`Pull failed: ${T.message}`})}}else if(l==="n"||l==="no"){let m=ye.current.shift().plan;u({kind:"note",tone:"info",text:`Skipped ${m.path}.`})}else{let m=ye.current.length;return ye.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${m} article(s) left untouched).`}),!0}return Es(),!0},[e,s,Es,u]),Ds=ee(async d=>{u({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let l=await Ya({cwd:e,profileName:s}),a=d?.replace(/\\/g,"/"),m=l.entries.filter(V=>V.status==="conflict"&&V.path).map(V=>V.path);if(a){if(!m.includes(a)){u({kind:"note",tone:"ok",text:`${a} isn\u2019t in conflict \u2014 nothing to resolve.`});return}m=[a]}if(m.length===0){u({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let T=[];for(let V of m)try{T.push({plan:await Bp({cwd:e,profileName:s,relPath:V}),mode:"conflict"})}catch(f){u({kind:"note",tone:"error",text:`Could not load ${V} from Document360: ${f.message}`})}if(T.length===0)return;u({kind:"note",tone:"info",text:`Resolving ${T.length} conflict${T.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),ye.current=T,Zt.current=[],dn()}catch(l){u({kind:"note",tone:"error",text:`Could not compute sync status: ${l.message}`})}},[e,s,u,dn]),Rc=ee(d=>{let l=Eo.current;if(!l)return!1;if(Eo.current=null,Ke(),d.trim()!==l.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:m}=ba(e,l.targets);u({kind:"note",tone:m.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let T of m)u({kind:"note",tone:"error",text:` \u2717 ${T.path}: ${T.error}`});return l.hadDevhints&&(u({kind:"note",tone:"warn",text:ar().join(`
419
419
  `)}),cn(Ws())),u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
420
- ${zp}`}),ne("/init"),Ro(!1),!0},[e,u,cn,Ke,ne]),Bn=ee(async d=>{let l=d.slice(1).trim().split(/\s+/),a=(l[0]??"").toLowerCase(),m=l.slice(1);if(Ro(!0),Ir(m)&&["write","check","review","reorder"].includes(a)){let f=so(e,s);if(f.length===0){u({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let w=k=>a==="write"?`/write ${Ld(m,k).join(" ")}`.trim():`/${a} ${[k,...m.filter(g=>g!=="--scope")].join(" ")}`.trim();if(f.length===1){Bn(w(f[0].token));return}It({cursor:0,rows:f,run:k=>{Bn(w(k))}});return}if(Ct(a,m)){let f=so(e,s);if(f.length>1){let w=m.filter(S=>S.startsWith("--")).join(" "),k=S=>`/${a}${S?` ${a==="write"?`--scope ${S}`:S}`:""}${w?` ${w}`:""} ${S?"":"--all"}`.replace(/\s+/g," ").trim(),g=f.reduce((S,L)=>S+L.count,0),C={token:"",label:a==="review"?`Everything \u2014 all ${g} articles + structure (IA) review`:a==="reorder"?`Everything \u2014 reorder all ${f.length} categories`:`Everything \u2014 rewrite all ${g} planned articles`,count:g};It({cursor:0,rows:[C,...f],run:S=>{Bn(k(S))}});return}}let j=async f=>{let w=ea(f);if(!Ur(e)){await ie(aa(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(w.mode==="single"){await Wn([w.id],{runLine:[`/screenshot capture ${w.id}`,`/capture ${w.id}`]});return}if(w.mode==="failed"){let g=ta(e,ho(e).rows);if(g.length===0){u({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),ne("/screenshot list");return}await Wn(g);return}if(w.mode==="blocked"){let{blocked:g,rows:C}=ho(e);if(g.length===0){u({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),ne("/screenshot list");return}let S=to(C.filter(L=>L.state==="blocked")).length;u({kind:"note",tone:"info",text:`Re-running ${g.length} shot${g.length===1?"":"s"} that skipped on missing data last run.`+(S>0?` If you haven't staged ${S===1?"it":"those "+S+" things"} yet, ${g.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await Wn(g,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if(w.mode==="all"||w.mode==="scope"){let g=w.mode==="scope"?w.scope:void 0,{ready:C,captured:S,blocked:L,rows:P}=ho(e,g),H=[...C,...S,...w.retryBlocked?L:[]];if(H.length===0&&L.length>0&&!w.retryBlocked){let U=g?`/screenshot capture ${g} --retry-blocked`:"/screenshot capture --blocked";be(`All ${L.length} shot${L.length===1?"":"s"} in scope ${L.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${U}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(H.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),ne("/screenshot");return}if(!w.retryBlocked){let U=g?`/screenshot capture ${g} --retry-blocked`:"/screenshot capture --blocked",N=na(P.filter(z=>z.state==="blocked"),U);N&&u({kind:"note",tone:"info",text:N})}let _=w.mode==="scope"?[`/screenshot capture ${w.scope}`,`/capture ${w.scope}`]:["/screenshot capture --all","/capture --all"];await Wn(H,{runLine:_,...w.retryBlocked?{}:{heldBackBlocked:P.filter(U=>U.state==="blocked")}});return}let k=fu($e(e));if(k.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),ne("/screenshot");return}Nt({cursor:0,rows:k,title:"Capture screenshots \u2014 pick what to shoot:"})},V=async()=>{let f=await Sn();f.kind==="forward-to-agent"&&f.prompt&&await ie(f.prompt,{display:f.display,quietUser:!0});let w=la(e);w&&u({kind:"note",tone:"info",text:w.join(`
421
- `)})};switch(a){case"help":_n({tab:0});return;case"exit":case"quit":Fe.current?.close(),r();return;case"clear":Ie(),Qt.current=[],Ro(!1),Ke(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let f;try{f=_e(e,s)}catch(w){u({kind:"note",tone:"error",text:w.message});return}u({kind:"note",tone:"info",text:`Profile "${f.name}" \u2192 ${f.connection.name} (${f.connection.apiUrl})${f.production?" \u26A0 PRODUCTION":""}`}),G(!0);try{let w=await Xk(f.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},g=>u({kind:"note",tone:"info",text:g})),k=Qk(f.name,w);if(Jk(k),await Is(k,f.name,g=>u({kind:"note",tone:"info",text:g})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${f.name}" as ${Jo(k)}`}),await $c(s),Ln.current){let g=Ln.current;Ln.current=null;let C=Ve(e,s);C.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${g}.`}),ne(g)):(u({kind:"note",tone:"warn",text:`${C.reason} (then ${g}.)`}),ne("/login"),Ln.current=g)}else On.current&&(Se(On.current,"\u21E5 tab to re-send your last prompt\u2026"),On.current=null)}catch(w){u({kind:"note",tone:"error",text:`Login failed: ${w.message}`})}finally{G(!1),Y(w=>w+1)}return}case"allow-prod":{let f=!1;try{f=_e(e,s).production}catch{}if(!f){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Jt.current=!0,Ie(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let f=zi(m.join(" ")),w=et.current.uuid;if(!w){if(!f){u({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}ms.current=f,Et(f),Tn(`${rs} ${f}`),u({kind:"note",tone:"ok",text:`Session will be named "${f}" once it starts.`});return}if(!f){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let k=et.current.firstPrompt??"";Ip(k,e).then(g=>{g?(Se(`/rename ${g}`),u({kind:"note",tone:"info",text:`Suggestion: "${g}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}lb(w,f),Et(f),Tn(`${rs} ${f}`),u({kind:"note",tone:"ok",text:`Session renamed to "${f}".`});return}case"profile":{let f=m[0],w=de(e);if(!f){let k=Object.entries(w?.profiles??{});if(k.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let g=k.map(([L,P])=>({name:L,env:P.connection?.environment??"custom",prod:P.production===!0,who:Ps(L)})),C=s??w?.defaultProfile,S=Math.max(0,g.findIndex(L=>L.name===C));en({cursor:S,current:S,rows:g});return}if(f==="add"){let k=Ki(e,m[1],m[2]);if(k){u({kind:"note",tone:"error",text:k});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${m[1]}" created (environment: ${m[2]??m[1]}).`}),Ts(m[1],!1);return}if(!w?.profiles?.[f]){u({kind:"note",tone:"error",text:`Unknown profile "${f}". Create it: /profile add ${f} <environment>`});return}Ts(f,!0);return}case"doctor":await ao(m,{cwd:e,version:o});return;case"genre":{await Vr(m,{cwd:e});try{dt.current=!(de(e)?.appType??pb(e))}catch{}Y(f=>f+1);return}case"roadmap":{if(m[0]?.toLowerCase()==="done"){let f=Yr(e,m.slice(1).join(" ").trim());u({kind:"note",tone:f.ok?"ok":"warn",text:f.line}),Y(w=>w+1);return}u({kind:"note",tone:"info",text:Sa(e).join(`
422
- `)});return}case"mcp":await dr(m);return;case"init":{if(de(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let f=yb().map(w=>({name:w,apiUrl:wb(w).apiUrl}));tn({cursor:0,rows:f});return}case"resume":{let f=m.join(" ").trim(),w=cb(e).filter(C=>C.uuid!==et.current.uuid);if(!f){if(!w.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}_t({query:"",cursor:0,sessions:w});return}let k=ab(e,f);if(!k){u({kind:"note",tone:"error",text:`No session matches "${f}".`});return}Ie(k.uuid),et.current={uuid:k.uuid,firstPrompt:k.firstPrompt,titleFired:!0},Et(k.name),Ga(k.uuid),Qt.current=[];let g=Fa(e,k.uuid);for(let C of g)u(C);u({kind:"note",tone:"ok",text:g.length?`Resumed "${k.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${k.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let f=m.join(" ").trim(),w;try{w=await Gn(e,s)}catch(g){u({kind:"note",tone:"error",text:`Could not list workspaces: ${g.message}`});return}if(!f){let g=w.workspaces.map(S=>({id:S.id,name:S.name??S.id,type:S.workspace_type}));if(g.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let C=Math.max(0,g.findIndex(S=>S.id===w.current));nn({cursor:C,current:C,rows:g,profile:w.profile,projectId:w.projectId,projectName:w.projectName,environment:w.environment});return}let k=js(w.workspaces,f);if(!k){u({kind:"note",tone:"error",text:`No workspace matches "${f}".`});return}Ho(w.profile,w.projectId,k);return}case"project":{let f=m.join(" ").trim(),w;try{w=await gt(e,s)}catch(g){u({kind:"note",tone:"error",text:`Could not list projects: ${g.message} (signed in? try /login)`});return}if(!f){let g=w.projects.map(S=>({id:S.id,name:S.name??S.id,sub:S.sub_domain}));if(g.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let C=g.findIndex(S=>S.id===w.current);jt({cursor:Math.max(0,C),current:C,rows:g,profile:w.profile,environment:w.environment});return}let k=Ns(w.projects,f);if(!k){u({kind:"note",tone:"error",text:`No project matches "${f}". Available: ${w.projects.map(g=>g.name??g.id).join(", ")}`});return}Vo(w.profile,k);return}case"logout":{let f;try{f=_e(e,s).name}catch(k){u({kind:"note",tone:"error",text:k.message});return}let w=nb(f);ob(e,f),Ie(),Y(k=>k+1),u({kind:"note",tone:w?"ok":"info",text:w?`\u2713 Signed out of "${f}" and cleared its project/workspace selection.`:`Profile "${f}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),ne("/login");return}case"publish":{if(!Oo(d.trim()))return;if(m.includes("--screenshots")||m.includes("--shots")){let g=$e(e),C=$r(g);if(C.length===0){u({kind:"note",tone:"info",text:"No captured screenshots yet \u2014 /screenshot capture first."});return}let S=vr(g);S&&u({kind:"note",tone:"warn",text:S}),u({kind:"note",tone:"info",text:`Re-saving ${C.length} article${C.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await Ft(C);return}if(m[0]==="--related"&&m[1]){let g=await Ar(e,s,m[1].replace(/\\/g,"/"));if(g.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Ft(g);return}let f=m.filter(g=>!g.startsWith("--"));if(f[0]){await Ss(f[0]);return}let w=m.includes("--all"),k=m.includes("--force");u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let g=await Ya({cwd:e,profileName:s}),{clean:C,conflicts:S}=Pr(g.entries),L=w&&k&&S.length>0,P=Er(g.entries);if(P>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${P} article${P===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),S.length>0&&!L&&u({kind:"note",tone:"warn",text:Tr(S.length)}),C.length===0&&!L){if(S.length>0){ne("/resolve");return}u({kind:"note",tone:"ok",text:P>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let H=g.counts["unknown-base"]??0;H>0&&u({kind:"note",tone:"info",text:`(${H} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Do("Reconciling structure on Document360 (order + related articles)\u2026");try{let _=await qp({cwd:e,profileName:s}),U=Yp(await Gp({cwd:e,profileName:s})),N=Vp(_);N?u({kind:"note",tone:"info",text:N}):_.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${_.skipped}`}),U&&u({kind:"note",tone:"info",text:U}),u({kind:"note",tone:"ok",text:N||U?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(N||U)&&ne("/structure")}catch(_){u({kind:"note",tone:"warn",text:`Structure sync failed: ${_.message}`})}finally{Do(null)}return}if(w){let H=(L?[...C,...S]:C).map(_=>_.path);await Ft(H),S.length>0&&!L&&ne("/resolve");return}on({cursor:0,rows:wd(C,S)})}catch(g){u({kind:"note",tone:"error",text:`Could not compute sync status: ${g.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!Oo(d.trim()))return;await As(m.find(f=>!f.startsWith("--")));return}case"preview":{let f=m.join(" ").trim();if(!f){let k=[];try{k=Object.keys(Lp(e,_e(e,s).name)?.articles??{})}catch{}if(k.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Ot({query:"",cursor:0,paths:k});return}let w=zk(f)?f:Va(e,f);if(En(w)){try{u({kind:"preview",name:vo(w),text:Xp(cs(w,"utf8"))})}catch(k){u({kind:"note",tone:"error",text:`Could not read ${w}: ${k.message}`})}return}if(Mb.test(f)){try{let k=_e(e,s),g={profile:k.name,connection:k.connection},C=k.project.projectId??eb(g),S=await tb(g,C,f);u({kind:"preview",name:S.title??f,text:S.content??"*(article has no content)*"})}catch(k){u({kind:"note",tone:"error",text:`Could not fetch article: ${k.message}`})}return}u({kind:"note",tone:"error",text:`"${f}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let f=m[0]?.trim();if(!f){let C=Lr(Ja(e));Dt({cursor:C,current:C});return}let{lines:w,changed:k,effective:g}=io(e,f);for(let C of w)u({kind:"note",tone:C.startsWith("\u26A0")?"warn":C.startsWith("\u2713")?"ok":"info",text:C});k&&(hc(C=>C+1),Fe.current?.setModel(g));return}case"convert":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:f,run:w}=Ri(m),k=$b(e,s);if(k.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let g=Si(k,f);if(g.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${f}". (${k.length} are tracked overall.)`});return}let C=za(g),S=3,L=`/convert${f?` --scope ${f}`:""} --run`,P=ds(e,"light");if(!w){let _=Fp({files:Pi(e,g),op:"convert",model:P.model}),U=f?`Scope: ${f} (${g.length} of ${k.length} tracked)
423
- `:"",N=`
424
- Model: ${P.model}${P.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:U+Ei(C,_,S).join(`
425
- `)+N}),ne(L);return}Tt.current=Date.now(),zt(0),T(!0);let H=new AbortController;xe.current=H,ce({verb:"Converting",total:C.length,done:0,active:[],rows:$o(C),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${g.length} articles across ${C.length} partitions (\u2264${S} agents at once) on ${P.model}\u2026 (esc to stop)`});try{for await(let _ of ls({cwd:e,partitions:C,promptFor:Ti,concurrency:S,profileName:s,allowProdWrites:Jt.current,model:P.model,signal:H.signal}))if(_.type==="partition_status")_.status==="running"?ce(U=>U&&{...U,active:[...U.active,_.label],rows:Ge(U.rows,_.label,"active"),lastAt:Date.now()}):ce(U=>U&&{...U,active:U.active.filter(N=>N!==_.label),done:U.done+1,rows:Ge(U.rows,_.label,_.status==="done"?"done":"failed"),lastAt:Date.now()});else if(_.type==="partition_event")ce(U=>{if(!U)return U;let N={...U,lastAt:Date.now()};return _.event.type==="tool"?N.tools=U.tools+1:_.event.type==="text"&&(N.chars=U.chars+_.event.delta.length),N});else if(_.type==="run_done"){an(z=>z+_.totalCostUsd),sn(z=>z+_.results.reduce((Oe,rt)=>Oe+rt.outputTokens,0));let U=_.aborted?"Stopped. ":"",N=t.kind==="api"?"api":"subscription";u({kind:"note",tone:_.aborted?"warn":_.ok?"ok":"warn",text:U+Ai(_.results,C,N).join(`
426
- `)})}}catch(_){u({kind:"note",tone:"error",text:`Convert run failed: ${_.message}`})}finally{xe.current=null,ce(null),T(!1),Y(_=>_+1)}return}case"write":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=vb(e);if(f.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:w,path:k,preview:g,concurrency:C,rewrite:S}=Ni(m),{docsDir:L,targets:P,reason:H,rewriting:_}=Fi(e,f,{scope:w,path:k,rewrite:S});if(P.length===0){u({kind:"note",tone:"warn",text:H??"Nothing to write."});return}_&&u({kind:"note",tone:"warn",text:`--rewrite: regenerating ${P.length} already-written article${P.length===1?"":"s"} (overwrites them; git has your baseline).`});let U=za(P),N=ji(C),z=ds(e,"standard"),Oe=!!k;if(g&&!Oe){let Q=Fp({files:Oi(e,f,P),op:"write",model:z.model}),he=w?`Scope: ${w} (${P.length} pending)
427
- `:"",Ce=`
428
- Model: ${z.model}${z.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:he+_i(U,Q,N).join(`
429
- `)+Ce}),ne(`/write${w?` --scope ${w}`:""}`);return}Tt.current=Date.now(),zt(0),T(!0);let rt=new AbortController;xe.current=rt,ce({verb:"Writing",total:U.length,done:0,active:[],rows:$o(U),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${P.length} article${P.length===1?"":"s"} across ${U.length} partition${U.length===1?"":"s"} (\u2264${N} agents at once) on ${z.model}${z.forced?" (forced)":""}\u2026 (esc to stop)`});let pn=new Set;try{for await(let Q of ls({cwd:e,partitions:U,promptFor:he=>Li(he,L,{rewrite:_||Oe}),concurrency:N,profileName:s,allowProdWrites:Jt.current,model:z.model,signal:rt.signal}))if(Q.type==="partition_status")Q.status==="running"?ce(he=>he&&{...he,active:[...he.active,Q.label],rows:Ge(he.rows,Q.label,"active"),lastAt:Date.now()}):ce(he=>he&&{...he,active:he.active.filter(Ce=>Ce!==Q.label),done:he.done+1,rows:Ge(he.rows,Q.label,Q.status==="done"?"done":"failed"),lastAt:Date.now()});else if(Q.type==="partition_event"){let he=null;if(Q.event.type==="tool"){let Ce=kp(Q.event.name,Q.event.input,U[Q.index]?.paths??[]);Ce&&!pn.has(Ce)&&(pn.add(Ce),he=Q.label)}ce(Ce=>{if(!Ce)return Ce;let Qe={...Ce,lastAt:Date.now()};return Q.event.type==="tool"?Qe.tools=Ce.tools+1:Q.event.type==="text"&&(Qe.chars=Ce.chars+Q.event.delta.length),he&&(Qe.rows=wp(Qe.rows,he)),Qe})}else if(Q.type==="run_done"){an(ft=>ft+Q.totalCostUsd),sn(ft=>ft+Q.results.reduce((st,fh)=>st+fh.outputTokens,0));let he=Q.aborted?"Stopped. ":"",Ce=t.kind==="api"?"api":"subscription";if(u({kind:"note",tone:Q.aborted?"warn":Q.ok?"ok":"warn",text:he+Mi(Q.results,U,Ce).join(`
430
- `)}),!Q.aborted&&Q.ok)try{let ft=(pn.size>0?[...pn]:P).map(st=>`${L}/${st}`);Ka(e,ft,{writtenCap:Xa})}catch{}let Qe=Q.aborted?null:Ui(e,L,P);if(Qe&&u({kind:"note",tone:"warn",text:Qe}),!Q.aborted&&Q.ok){let ft=w??k??"",st=ft?` ${ft}`:"";be(Qe?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${st} --fix, then /review${st} --fix for editorial quality, then /publish --all (add /screenshot author --all first if you want images).`:`Written. I\u2019d run /review${st} --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:Qe?`/check${st} --fix`:`/review${st} --fix`,reason:""})}}}catch(Q){u({kind:"note",tone:"error",text:`Write run failed: ${Q.message}`})}finally{xe.current=null,ce(null),T(!1),Y(Q=>Q+1)}return}case"draft":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:f,looseDocs:w}=Wi(e);if(f.length===0&&w===0){u({kind:"note",tone:"info",text:Hi});return}let k=m.join(" ").trim();if(!k&&f.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
420
+ ${Kp}`}),ne("/init"),Ro(!1),!0},[e,u,cn,Ke,ne]),Bn=ee(async d=>{let l=d.slice(1).trim().split(/\s+/),a=(l[0]??"").toLowerCase(),m=l.slice(1);if(Ro(!0),Ir(m)&&["write","check","review","reorder"].includes(a)){let f=so(e,s);if(f.length===0){u({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let w=k=>a==="write"?`/write ${Md(m,k).join(" ")}`.trim():`/${a} ${[k,...m.filter(y=>y!=="--scope")].join(" ")}`.trim();if(f.length===1){Bn(w(f[0].token));return}It({cursor:0,rows:f,run:k=>{Bn(w(k))}});return}if(Ct(a,m)){let f=so(e,s);if(f.length>1){let w=m.filter(S=>S.startsWith("--")).join(" "),k=S=>`/${a}${S?` ${a==="write"?`--scope ${S}`:S}`:""}${w?` ${w}`:""} ${S?"":"--all"}`.replace(/\s+/g," ").trim(),y=f.reduce((S,U)=>S+U.count,0),x={token:"",label:a==="review"?`Everything \u2014 all ${y} articles + structure (IA) review`:a==="reorder"?`Everything \u2014 reorder all ${f.length} categories`:`Everything \u2014 rewrite all ${y} planned articles`,count:y};It({cursor:0,rows:[x,...f],run:S=>{Bn(k(S))}});return}}let T=async f=>{let w=ea(f);if(!Ur(e)){await ie(aa(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(w.mode==="single"){await Wn([w.id],{runLine:[`/screenshot capture ${w.id}`,`/capture ${w.id}`]});return}if(w.mode==="failed"){let y=ta(e,ho(e).rows);if(y.length===0){u({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),ne("/screenshot list");return}await Wn(y);return}if(w.mode==="blocked"){let{blocked:y,rows:x}=ho(e);if(y.length===0){u({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),ne("/screenshot list");return}let S=to(x.filter(U=>U.state==="blocked")).length;u({kind:"note",tone:"info",text:`Re-running ${y.length} shot${y.length===1?"":"s"} that skipped on missing data last run.`+(S>0?` If you haven't staged ${S===1?"it":"those "+S+" things"} yet, ${y.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await Wn(y,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if(w.mode==="all"||w.mode==="scope"){let y=w.mode==="scope"?w.scope:void 0,{ready:x,captured:S,blocked:U,rows:B}=ho(e,y),N=[...x,...S,...w.retryBlocked?U:[]];if(N.length===0&&U.length>0&&!w.retryBlocked){let L=y?`/screenshot capture ${y} --retry-blocked`:"/screenshot capture --blocked";$e(`All ${U.length} shot${U.length===1?"":"s"} in scope ${U.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${L}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(N.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),ne("/screenshot");return}if(!w.retryBlocked){let L=y?`/screenshot capture ${y} --retry-blocked`:"/screenshot capture --blocked",j=na(B.filter(z=>z.state==="blocked"),L);j&&u({kind:"note",tone:"info",text:j})}let F=w.mode==="scope"?[`/screenshot capture ${w.scope}`,`/capture ${w.scope}`]:["/screenshot capture --all","/capture --all"];await Wn(N,{runLine:F,...w.retryBlocked?{}:{heldBackBlocked:B.filter(L=>L.state==="blocked")}});return}let k=gu(ve(e));if(k.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),ne("/screenshot");return}Nt({cursor:0,rows:k,title:"Capture screenshots \u2014 pick what to shoot:"})},V=async()=>{let f=await Sn();f.kind==="forward-to-agent"&&f.prompt&&await ie(f.prompt,{display:f.display,quietUser:!0});let w=la(e);w&&u({kind:"note",tone:"info",text:w.join(`
421
+ `)})};switch(a){case"help":_n({tab:0});return;case"exit":case"quit":We.current?.close(),r();return;case"clear":Le(),Qt.current=[],Ro(!1),Ke(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let f;try{f=Me(e,s)}catch(w){u({kind:"note",tone:"error",text:w.message});return}u({kind:"note",tone:"info",text:`Profile "${f.name}" \u2192 ${f.connection.name} (${f.connection.apiUrl})${f.production?" \u26A0 PRODUCTION":""}`}),G(!0);try{let w=await eb(f.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},y=>u({kind:"note",tone:"info",text:y})),k=tb(f.name,w);if(nb(k),await Is(k,f.name,y=>u({kind:"note",tone:"info",text:y})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${f.name}" as ${Jo(k)}`}),await xc(s),Ln.current){let y=Ln.current;Ln.current=null;let x=Ve(e,s);x.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${y}.`}),ne(y)):(u({kind:"note",tone:"warn",text:`${x.reason} (then ${y}.)`}),ne("/login"),Ln.current=y)}else On.current&&(Pe(On.current,"\u21E5 tab to re-send your last prompt\u2026"),On.current=null)}catch(w){u({kind:"note",tone:"error",text:`Login failed: ${w.message}`})}finally{G(!1),Y(w=>w+1)}return}case"allow-prod":{let f=!1;try{f=Me(e,s).production}catch{}if(!f){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Jt.current=!0,Le(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let f=zi(m.join(" ")),w=et.current.uuid;if(!w){if(!f){u({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}ms.current=f,Et(f),Tn(`${rs} ${f}`),u({kind:"note",tone:"ok",text:`Session will be named "${f}" once it starts.`});return}if(!f){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let k=et.current.firstPrompt??"";_p(k,e).then(y=>{y?(Pe(`/rename ${y}`),u({kind:"note",tone:"info",text:`Suggestion: "${y}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}hb(w,f),Et(f),Tn(`${rs} ${f}`),u({kind:"note",tone:"ok",text:`Session renamed to "${f}".`});return}case"profile":{let f=m[0],w=de(e);if(!f){let k=Object.entries(w?.profiles??{});if(k.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let y=k.map(([U,B])=>({name:U,env:B.connection?.environment??"custom",prod:B.production===!0,who:Ps(U)})),x=s??w?.defaultProfile,S=Math.max(0,y.findIndex(U=>U.name===x));en({cursor:S,current:S,rows:y});return}if(f==="add"){let k=Ki(e,m[1],m[2]);if(k){u({kind:"note",tone:"error",text:k});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${m[1]}" created (environment: ${m[2]??m[1]}).`}),Ts(m[1],!1);return}if(!w?.profiles?.[f]){u({kind:"note",tone:"error",text:`Unknown profile "${f}". Create it: /profile add ${f} <environment>`});return}Ts(f,!0);return}case"doctor":await ao(m,{cwd:e,version:o});return;case"genre":{await Vr(m,{cwd:e});try{dt.current=!(de(e)?.appType??gb(e))}catch{}Y(f=>f+1);return}case"roadmap":{if(m[0]?.toLowerCase()==="done"){let f=Yr(e,m.slice(1).join(" ").trim());u({kind:"note",tone:f.ok?"ok":"warn",text:f.line}),Y(w=>w+1);return}u({kind:"note",tone:"info",text:Sa(e).join(`
422
+ `)});return}case"mcp":await dr(m);return;case"init":{if(de(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let f=$b().map(w=>({name:w,apiUrl:vb(w).apiUrl}));tn({cursor:0,rows:f});return}case"resume":{let f=m.join(" ").trim(),w=pb(e).filter(x=>x.uuid!==et.current.uuid);if(!f){if(!w.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}_t({query:"",cursor:0,sessions:w});return}let k=ub(e,f);if(!k){u({kind:"note",tone:"error",text:`No session matches "${f}".`});return}Le(k.uuid),et.current={uuid:k.uuid,firstPrompt:k.firstPrompt,titleFired:!0},Et(k.name),Ga(k.uuid),Qt.current=[];let y=Fa(e,k.uuid);for(let x of y)u(x);u({kind:"note",tone:"ok",text:y.length?`Resumed "${k.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${k.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let f=m.join(" ").trim(),w;try{w=await Gn(e,s)}catch(y){u({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!f){let y=w.workspaces.map(S=>({id:S.id,name:S.name??S.id,type:S.workspace_type}));if(y.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let x=Math.max(0,y.findIndex(S=>S.id===w.current));nn({cursor:x,current:x,rows:y,profile:w.profile,projectId:w.projectId,projectName:w.projectName,environment:w.environment});return}let k=js(w.workspaces,f);if(!k){u({kind:"note",tone:"error",text:`No workspace matches "${f}".`});return}Ho(w.profile,w.projectId,k);return}case"project":{let f=m.join(" ").trim(),w;try{w=await gt(e,s)}catch(y){u({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!f){let y=w.projects.map(S=>({id:S.id,name:S.name??S.id,sub:S.sub_domain}));if(y.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let x=y.findIndex(S=>S.id===w.current);jt({cursor:Math.max(0,x),current:x,rows:y,profile:w.profile,environment:w.environment});return}let k=Ns(w.projects,f);if(!k){u({kind:"note",tone:"error",text:`No project matches "${f}". Available: ${w.projects.map(y=>y.name??y.id).join(", ")}`});return}Vo(w.profile,k);return}case"logout":{let f;try{f=Me(e,s).name}catch(k){u({kind:"note",tone:"error",text:k.message});return}let w=ib(f);ab(e,f),Le(),Y(k=>k+1),u({kind:"note",tone:w?"ok":"info",text:w?`\u2713 Signed out of "${f}" and cleared its project/workspace selection.`:`Profile "${f}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),ne("/login");return}case"publish":{if(!Oo(d.trim()))return;if(m.includes("--screenshots")||m.includes("--shots")){let y=ve(e),x=$r(y);if(x.length===0){u({kind:"note",tone:"info",text:"No captured screenshots yet \u2014 /screenshot capture first."});return}let S=vr(y);S&&u({kind:"note",tone:"warn",text:S}),u({kind:"note",tone:"info",text:`Re-saving ${x.length} article${x.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await Ft(x);return}if(m[0]==="--related"&&m[1]){let y=await Dr(e,s,m[1].replace(/\\/g,"/"));if(y.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Ft(y);return}let f=m.filter(y=>!y.startsWith("--"));if(f[0]){await Ss(f[0]);return}let w=m.includes("--all"),k=m.includes("--force");u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let y=await Ya({cwd:e,profileName:s}),{clean:x,conflicts:S}=Pr(y.entries),U=w&&k&&S.length>0,B=Er(y.entries);if(B>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${B} article${B===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),S.length>0&&!U&&u({kind:"note",tone:"warn",text:Tr(S.length)}),x.length===0&&!U){if(S.length>0){ne("/resolve");return}u({kind:"note",tone:"ok",text:B>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let N=y.counts["unknown-base"]??0;N>0&&u({kind:"note",tone:"info",text:`(${N} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Ao("Reconciling structure on Document360 (order + related articles)\u2026");try{let F=await Qa({cwd:e,profileName:s}),L=zp(await Yp({cwd:e,profileName:s})),j=Ja(F);j?u({kind:"note",tone:"info",text:j}):F.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${F.skipped}`}),L&&u({kind:"note",tone:"info",text:L}),u({kind:"note",tone:"ok",text:j||L?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(j||L)&&ne("/structure")}catch(F){u({kind:"note",tone:"warn",text:`Structure sync failed: ${F.message}`})}finally{Ao(null)}return}if(w){let N=(U?[...x,...S]:x).map(F=>F.path);await Ft(N),S.length>0&&!U&&ne("/resolve");return}on({cursor:0,rows:bd(x,S)})}catch(y){u({kind:"note",tone:"error",text:`Could not compute sync status: ${y.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!Oo(d.trim()))return;await Ds(m.find(f=>!f.startsWith("--")));return}case"preview":{let f=m.join(" ").trim();if(!f){let k=[];try{k=Object.keys(Up(e,Me(e,s).name)?.articles??{})}catch{}if(k.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Ot({query:"",cursor:0,paths:k});return}let w=Jk(f)?f:Va(e,f);if(En(w)){try{u({kind:"preview",name:vo(w),text:Jp(cs(w,"utf8"))})}catch(k){u({kind:"note",tone:"error",text:`Could not read ${w}: ${k.message}`})}return}if(Wb.test(f)){try{let k=Me(e,s),y={profile:k.name,connection:k.connection},x=k.project.projectId??rb(y),S=await sb(y,x,f);u({kind:"preview",name:S.title??f,text:S.content??"*(article has no content)*"})}catch(k){u({kind:"note",tone:"error",text:`Could not fetch article: ${k.message}`})}return}u({kind:"note",tone:"error",text:`"${f}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let f=m[0]?.trim();if(!f){let x=Lr(ec(e));At({cursor:x,current:x});return}let{lines:w,changed:k,effective:y}=io(e,f);for(let x of w)u({kind:"note",tone:x.startsWith("\u26A0")?"warn":x.startsWith("\u2713")?"ok":"info",text:x});k&&(mc(x=>x+1),We.current?.setModel(y));return}case"convert":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:f,run:w}=Ri(m),k=Rb(e,s);if(k.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let y=Si(k,f);if(y.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${f}". (${k.length} are tracked overall.)`});return}let x=za(y),S=3,U=`/convert${f?` --scope ${f}`:""} --run`,B=ds(e,"light");if(!w){let F=Hp({files:Pi(e,y),op:"convert",model:B.model}),L=f?`Scope: ${f} (${y.length} of ${k.length} tracked)
423
+ `:"",j=`
424
+ Model: ${B.model}${B.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:L+Ei(x,F,S).join(`
425
+ `)+j}),ne(U);return}Tt.current=Date.now(),zt(0),P(!0);let N=new AbortController;Ce.current=N,ce({verb:"Converting",total:x.length,done:0,active:[],rows:$o(x),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${y.length} articles across ${x.length} partitions (\u2264${S} agents at once) on ${B.model}\u2026 (esc to stop)`});try{for await(let F of ls({cwd:e,partitions:x,promptFor:Ti,concurrency:S,profileName:s,allowProdWrites:Jt.current,model:B.model,signal:N.signal}))if(F.type==="partition_status")F.status==="running"?ce(L=>L&&{...L,active:[...L.active,F.label],rows:Ge(L.rows,F.label,"active"),lastAt:Date.now()}):ce(L=>L&&{...L,active:L.active.filter(j=>j!==F.label),done:L.done+1,rows:Ge(L.rows,F.label,F.status==="done"?"done":"failed"),lastAt:Date.now()});else if(F.type==="partition_event")ce(L=>{if(!L)return L;let j={...L,lastAt:Date.now()};return F.event.type==="tool"?j.tools=L.tools+1:F.event.type==="text"&&(j.chars=L.chars+F.event.delta.length),j});else if(F.type==="run_done"){an(z=>z+F.totalCostUsd),sn(z=>z+F.results.reduce((pe,rt)=>pe+rt.outputTokens,0));let L=F.aborted?"Stopped. ":"",j=t.kind==="api"?"api":"subscription";u({kind:"note",tone:F.aborted?"warn":F.ok?"ok":"warn",text:L+Di(F.results,x,j).join(`
426
+ `)})}}catch(F){u({kind:"note",tone:"error",text:`Convert run failed: ${F.message}`})}finally{Ce.current=null,ce(null),P(!1),Y(F=>F+1)}return}case"write":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=Sb(e);if(f.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:w,path:k,preview:y,concurrency:x,rewrite:S}=Ni(m),{docsDir:U,targets:B,reason:N,rewriting:F}=Fi(e,f,{scope:w,path:k,rewrite:S});if(B.length===0){u({kind:"note",tone:"warn",text:N??"Nothing to write."});return}F&&u({kind:"note",tone:"warn",text:`--rewrite: regenerating ${B.length} already-written article${B.length===1?"":"s"} (overwrites them; git has your baseline).`});let L=za(B),j=ji(x),z=ds(e,"standard"),pe=!!k;if(y&&!pe){let Q=Hp({files:Oi(e,f,B),op:"write",model:z.model}),fe=w?`Scope: ${w} (${B.length} pending)
427
+ `:"",Re=`
428
+ Model: ${z.model}${z.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:fe+_i(L,Q,j).join(`
429
+ `)+Re}),ne(`/write${w?` --scope ${w}`:""}`);return}Tt.current=Date.now(),zt(0),P(!0);let rt=new AbortController;Ce.current=rt,ce({verb:"Writing",total:L.length,done:0,active:[],rows:$o(L),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${B.length} article${B.length===1?"":"s"} across ${L.length} partition${L.length===1?"":"s"} (\u2264${j} agents at once) on ${z.model}${z.forced?" (forced)":""}\u2026 (esc to stop)`});let pn=new Set;try{for await(let Q of ls({cwd:e,partitions:L,promptFor:fe=>Li(fe,U,{rewrite:F||pe}),concurrency:j,profileName:s,allowProdWrites:Jt.current,model:z.model,signal:rt.signal}))if(Q.type==="partition_status")Q.status==="running"?ce(fe=>fe&&{...fe,active:[...fe.active,Q.label],rows:Ge(fe.rows,Q.label,"active"),lastAt:Date.now()}):ce(fe=>fe&&{...fe,active:fe.active.filter(Re=>Re!==Q.label),done:fe.done+1,rows:Ge(fe.rows,Q.label,Q.status==="done"?"done":"failed"),lastAt:Date.now()});else if(Q.type==="partition_event"){let fe=null;if(Q.event.type==="tool"){let Re=vp(Q.event.name,Q.event.input,L[Q.index]?.paths??[]);Re&&!pn.has(Re)&&(pn.add(Re),fe=Q.label)}ce(Re=>{if(!Re)return Re;let Qe={...Re,lastAt:Date.now()};return Q.event.type==="tool"?Qe.tools=Re.tools+1:Q.event.type==="text"&&(Qe.chars=Re.chars+Q.event.delta.length),fe&&(Qe.rows=$p(Qe.rows,fe)),Qe})}else if(Q.type==="run_done"){an(ft=>ft+Q.totalCostUsd),sn(ft=>ft+Q.results.reduce((st,gh)=>st+gh.outputTokens,0));let fe=Q.aborted?"Stopped. ":"",Re=t.kind==="api"?"api":"subscription";if(u({kind:"note",tone:Q.aborted?"warn":Q.ok?"ok":"warn",text:fe+Mi(Q.results,L,Re).join(`
430
+ `)}),!Q.aborted&&Q.ok)try{let ft=(pn.size>0?[...pn]:B).map(st=>`${U}/${st}`);Ka(e,ft,{writtenCap:Xa})}catch{}let Qe=Q.aborted?null:Ui(e,U,B);if(Qe&&u({kind:"note",tone:"warn",text:Qe}),!Q.aborted&&Q.ok){let ft=w??k??"",st=ft?` ${ft}`:"";$e(Qe?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${st} --fix, then /review${st} --fix for editorial quality, then /publish --all (add /screenshot author --all first if you want images).`:`Written. I\u2019d run /review${st} --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:Qe?`/check${st} --fix`:`/review${st} --fix`,reason:""})}}}catch(Q){u({kind:"note",tone:"error",text:`Write run failed: ${Q.message}`})}finally{Ce.current=null,ce(null),P(!1),Y(Q=>Q+1)}return}case"draft":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:f,looseDocs:w}=Wi(e);if(f.length===0&&w===0){u({kind:"note",tone:"info",text:Hi});return}let k=m.join(" ").trim();if(!k&&f.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
431
431
  ${f.map(S=>` \u2022 ${S.name} (${S.docCount} doc${S.docCount===1?"":"s"})`).join(`
432
- `)}`}),ze(f.map(S=>`/draft ${S.name}`));return}let g="",C;if(k){let S=Bi(f,k);S?g=S:C=k}else g=f[0]?.name??"";await ie(Or(g,C),{display:k?`/draft ${k}`:"/draft",quietUser:!0});return}case"pull":{if(!Oo(d.trim()))return;let f=m.find(w=>w.startsWith("--"));try{if(f==="--status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let g=Date.now(),C=await Ya({cwd:e,profileName:s});u({kind:"note",tone:"info",text:jr(C,Date.now()-g).join(`
433
- `)});return}if(f==="--baseline"){let g=m.find(P=>!P.startsWith("--")),C=g?g.replace(/\\/g,"/"):void 0;u({kind:"note",tone:"info",text:C?`Setting the sync baseline for ${C}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let S=await fb({cwd:e,profileName:s,relPaths:C?[C]:void 0}),L=C?{rebaselined:[],skipped:[]}:await mb({cwd:e,profileName:s});if(S.baselined.length===0&&S.skipped.length===0&&L.rebaselined.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}S.baselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Baselined ${S.baselined.length} article${S.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),L.rebaselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${L.rebaselined.length} article${L.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),S.skipped.length>0&&u({kind:"note",tone:"warn",text:`${S.skipped.length} skipped:
434
- ${S.skipped.map(P=>` - ${P.path} (${P.reason})`).join(`
435
- `)}`}),Y(P=>P+1);return}if(f==="--compare"){u({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let g=await hb({cwd:e,profileName:s}),C=g.onlyInLegacy.length===0&&g.onlyInManifest.length===0&&g.mappedMissingFromManifest.length===0,S=[`Legacy listing: ${g.legacyCount} \xB7 Manifest: ${g.manifestCount} \xB7 in both: ${g.inBoth}`];C?S.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(g.mappedMissingFromManifest.length&&S.push(`\u2717 ${g.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${g.mappedMissingFromManifest.slice(0,5).join(", ")}`),g.onlyInLegacy.length&&S.push(`\u26A0 ${g.onlyInLegacy.length} only in the legacy listing: ${g.onlyInLegacy.slice(0,5).join(", ")}`),g.onlyInManifest.length&&S.push(`\u26A0 ${g.onlyInManifest.length} only in the manifest: ${g.onlyInManifest.slice(0,5).join(", ")}`),S.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),u({kind:"note",tone:C?"ok":"warn",text:S.join(`
436
- `)});return}if(f){u({kind:"note",tone:"error",text:`Unknown option: ${f} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let w=m[0];if(w){let g=await Up({cwd:e,profileName:s,relPath:w.replace(/\\/g,"/")});ge.current=[{plan:g,mode:g.overwritesLocalChanges?"conflict":"pull"}],Zt.current=[],dn();return}u({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let k=await vi({cwd:e,profileName:s});for(let g of xi(k))u({kind:"note",tone:g.tone,text:g.text});Y(g=>g+1)}catch(w){u({kind:"note",tone:"error",text:`Pull failed: ${w.message}`})}return}case"scope":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=gb(e);if(f.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}rn({cursor:0,rows:f.map(w=>({...w,checked:w.recommended}))});return}case"audit":{if(m[0]==="--auto"){let w=de(e);if(!w){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=m[1]!=="off";Op({...w,autoAudit:k},e),u({kind:"note",tone:"ok",text:k?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let f=await ro();f.kind==="forward-to-agent"&&f.prompt&&await ie(f.prompt,{display:f.display,quietUser:!0});return}case"check":{let f=m.find(g=>!g.startsWith("--")),w=f?` ${f}`:"",k=Mp({cwd:e,scope:f});if(m.includes("--fix")){if(k.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}u({kind:"note",tone:"info",text:`Fixing ${k.length} doc issue${k.length===1?"":"s"}\u2026`});let g=Hp(e,f);await ie(va(k),{display:`/check${w} --fix`,quietUser:!0});try{Ka(e,g,{reviewedCap:Xa})}catch{}let C=Mp({cwd:e,scope:f});u({kind:"note",tone:C.length===0?"ok":"warn",text:C.length===0?"\u2713 Doc-checker: all issues resolved.":qr(C).join(`
437
- `)}),be(C.length===0?`Deterministic issues fixed. Next: /review${w} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${w} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${w} --fix`,reason:""});return}u({kind:"note",tone:k.length===0?"ok":"warn",text:qr(k).join(`
438
- `)}),k.length>0&&be(`Found ${k.length} doc issue${k.length===1?"":"s"} above. /check${w} --fix has the agent fix them in place (or /review${w} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${w} --fix`,reason:""});return}case"structure":{let f=go(e,s);if(f.length===0){u({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}u({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...f].join(`
439
- `)});return}case"reorder":{let f=Ca(e,m);if(!f){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ie(f.prompt,{display:f.display,quietUser:!0}),be("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let f=xa(e,m);if(!f){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=m.includes("--fix"),k=m.find(C=>!C.startsWith("--")),g=w?Hp(e,k):[];if(await ie(f.prompt,{display:f.display,quietUser:!0}),w)try{Ka(e,g,{reviewedCap:Xa})}catch{}if(w)be("\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let C=m.filter(S=>S!=="--fix").join(" ");be(`The review listed issues above. /review${C?` ${C}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${C?` ${C}`:""} --fix`,reason:""})}return}case"capture-setup":{await V();return}case"devhints":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:yn(gn(e)).join(`
440
- `)}),cn(Bt()),Un.current=qe(e).status==="current",ln.current=it(e);return}case"discover":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ie(yi(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(da(e)===0){u({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await ie(ua(),{display:"/inbox",quietUser:!0});return}case"feedback":{let f=Bp(e),w="";try{w=En(f)?cs(f,"utf8"):""}catch{w=""}if(!/^## /m.test(w)){u({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let k=await Ma(w.trim());u({kind:"note",tone:k?"ok":"warn",text:k?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${f} and copy it manually.`}),k&&vs(null);return}case"document":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:f,what:w}=Vi(m);if(!w&&qi(e)===0){u({kind:"note",tone:"info",text:Yi});return}let k=`/document${w?` ${w}`:""}${f?" --publish":""}`;await ie(Gi(w,f),{display:k,quietUser:!0});return}case"catch-up":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Oo(d.trim()))return;let{publish:f}=ha(m);u({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let w=await ma({cwd:e,profileName:s});for(let g of ga(w))u({kind:"note",tone:g.startsWith("\u2713")?"ok":g.startsWith("\u2139")?"info":"warn",text:g});let k=mo(fo(e));u({kind:"note",tone:"info",text:k?`Catching up on ${k}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ie(fa({publish:f}),{display:`/catch-up${f?" --publish":""}`,quietUser:!0});return}case"update":{bs.current=!0,u({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),So(!0);let f=await Br().finally(()=>So(!1));f.ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated ${f.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),ne("/exit"),rc("")):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Wr}`});return}case"screenshot":{let f=Zn(m),w=eo(e);if(w&&u({kind:"note",tone:"info",text:w}),f.mode==="capture"){await j(f.rest);return}if(f.mode==="checklist"){await V();return}if(f.mode==="verify"){let C=$e(e),S=f.rest.find(H=>!H.startsWith("-")),L=S?[S]:co(C);if(S&&!C.some(H=>H.id===S)){u({kind:"note",tone:"error",text:`No screenshot placeholder called "${S}". /screenshot list shows them all.`});return}if(L.length===0){let H=C.filter(U=>U.state==="rejected").length,_=C.filter(U=>U.state==="verified").length;u({kind:"note",tone:"info",text:H>0?`Nothing left to verify. ${H} shot${H===1?"":"s"} failed verification \u2014 re-capture with /screenshot capture --failed.`:_>0?`All ${_} captured shot${_===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."});return}u({kind:"note",tone:"info",text:lo(L.length)}),await ie(qt(e,L),{display:S?`/screenshot verify ${S}`:"/screenshot verify",quietUser:!0});let P=uo(e,L);P.length>0&&u({kind:"note",tone:"info",text:P.join(`
441
- `)});return}if(f.mode==="list"){if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let C=de(e)?.docsDir??Za,S=di(e,f.scope),L=$e(e,S);if(f.picker){if(L.length===0){u({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let N=ud(L);if(N.length===0){u({kind:"note",tone:"info",text:Cr(L,{docsDir:C}).join(`
442
- `)}),be(`\u2713 All ${L.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}Nt({cursor:0,rows:N,title:"Screenshots \u2014 pick what to author or capture:"});return}u({kind:"note",tone:"info",text:Cr(L,{scope:S,detail:f.detail,docsDir:C}).join(`
443
- `)});let P=L.filter(N=>N.state==="placeholder").length,H=L.filter(N=>N.state==="spec").length,_=L.filter(N=>N.state==="captured").length,U=L.filter(N=>N.state==="rejected").length;if(P>0){let N=S?`/screenshot author ${S}`:"/screenshot author --all";be(`${P} of ${L.length} still need${P===1?"s":""} a spec \u2014 /screenshot author <id> authors one, ${N} authors them all in parallel.`,{kind:"cmd",cmd:N,reason:""})}else if(H>0){let N=S?`/screenshot capture ${S}`:"/screenshot capture";be(`${H} spec${H===1?"":"s"} ready to capture \u2014 ${N} takes ${H===1?"it":"them"} (a real browser drives your app).`,{kind:"cmd",cmd:N,reason:""})}else _>0?be(`${_} shot${_===1?"":"s"} captured but not yet verified \u2014 /screenshot verify checks each picture against what its article needs (no browser, no re-capture).`,{kind:"cmd",cmd:"/screenshot verify",reason:""}):U>0&&be(`${U} shot${U===1?"":"s"} failed verification \u2014 /screenshot capture --failed re-shoots ${U===1?"it":"them"} once the spec is fixed.`,{kind:"cmd",cmd:"/screenshot capture --failed",reason:""});return}if(f.mode==="single"){await bc(f.id);return}if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=f.mode==="scope"?f.scope:void 0,g=bb(e,{scope:k}).map(C=>C.id);if(g.length===0){u({kind:"note",tone:"info",text:k?`No screenshot placeholders under ${k}.`:"No screenshot placeholders found in the docs."});return}await kc(g,{setup:f.setup,runLine:f.mode==="scope"?[`/screenshot author ${f.scope}`,`/screenshot ${f.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await j(m);return}case"reset":{let f=ka(e);if(f.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Eo.current={repoName:vo(e),targets:f,hadDevhints:En(Wp(e))},u({kind:"note",tone:"warn",text:$a(e,f).join(`
444
- `)}),Se(vo(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,dn,As,u,Ie,ie,Ft,Ss,$c]),Go=ee(d=>{let l=(d??$).trim();if(v(""),Po(null),Kt(0),l.startsWith("/")&&(lt.current=!1,Pt.current=!1,Ke(),Nn(null),ze(m=>vp(m,l))),!l||(oc(!1),xc(l))||vc(l))return;fs.current.push(l);let a=Sp(l,sc.current);if(l.startsWith("/"))u({kind:"user",text:l}),J(!0),Bn(a).finally(()=>J(!1));else if(Ab(a)){u({kind:"user",text:l});let m=Db(a);if(!m)ie(a,{display:l,quietUser:!0});else{try{jb(e,{title:m,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ie(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${m}". 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 "${m}" and the article path(s) you wrote.`,{display:l,quietUser:!0})}}else{let m=Yu(e,a);ie(m??a,{display:l})}},[$,xc,vc,Bn,ie]),Cc=ee(d=>{if(d.length>1){if(d.includes("\x1B"))return;let l=xp(d);if(Cp(l)){let a=Rp(++ch.current,l);sc.current.set(a,l),E(a)}else E(l);return}E(d)},[E]),un=Math.max(10,Be-6),Rc=qa(()=>is(h.text,un),[h.text,un]),Ds=ee(d=>b(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+d))})),[]),Yo=ee(d=>b(l=>({...l,pos:Tp(is(l.text,un),l.pos,d)})),[un]),Hn=ee(d=>b(l=>({...l,pos:Ep(is(l.text,un),l.pos,d)})),[un]),ph=["\x1B[H","\x1B[1~","\x1BOH"],hh=["\x1B[F","\x1B[4~","\x1BOF"],Sc=ee((d,l)=>l.leftArrow?(Ds(-1),!0):l.rightArrow?(Ds(1),!0):d&&ph.includes(d)?(Hn("start"),!0):d&&hh.includes(d)?(Hn("end"),!0):l.ctrl&&d==="a"?(Hn("start"),!0):l.ctrl&&d==="e"?(Hn("end"),!0):!1,[Ds,Hn]);return Vk((d,l)=>{if(l.ctrl&&d==="c"){Fe.current?.close(),r();return}if(!F){if(x){if(l.escape){if(xe.current){if(!xe.current.signal.aborted){let a=(Ao?.verb??"work").toLowerCase(),m=Ao?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${m}s)\u2026`}),xe.current.abort()}return}In.current||(In.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Fe.current?.interrupt());return}if(l.return){let a=$.trim();if(!a)return;Lt.current.push(a),gs([...Lt.current]),v("");return}if(Sc(d,l))return;if(l.upArrow){Yo(-1);return}if(l.downArrow){Yo(1);return}if(l.backspace||l.delete){R();return}d&&!l.ctrl&&!l.meta&&Cc(d);return}if(At){if(l.upArrow){Dt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){Dt(a=>a&&{...a,cursor:Math.min(Je.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=Je.length){Dt(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=Je[At.cursor];Dt(null);let{lines:m,changed:j,effective:V}=io(e,a.value??"default");for(let f of m)u({kind:"note",tone:f.startsWith("\u26A0")?"warn":f.startsWith("\u2713")?"ok":"info",text:f});j&&(hc(f=>f+1),Fe.current?.setModel(V));return}if(d==="s"){let a=Je[At.cursor];Dt(null),Fe.current?.setModel(a.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(l.escape){Dt(null);return}return}if(tt){if(l.upArrow){en(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){en(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=tt.rows.length){en(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return||d==="s"){let a=tt.rows[tt.cursor];en(null),Ts(a.name,l.return===!0);return}if(l.escape){en(null);return}return}if(No){if(l.escape){_n(null);return}if(l.leftArrow||l.tab&&l.shift){_n(a=>a&&{tab:(a.tab-1+He.length)%He.length});return}if(l.rightArrow||l.tab){_n(a=>a&&{tab:(a.tab+1)%He.length});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=He.length){_n({tab:Number(d)-1});return}return}if(nt){if(l.upArrow){tn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){tn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=nt.rows.length){tn(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=nt.rows[nt.cursor].name;if(tn(null),!Bs(e,a).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${a}").`});let j=!1;try{let V=Gt(a);j=!!V&&!(St(V)&&!V.refreshToken)}catch{j=!1}u({kind:"note",tone:"info",text:j?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${a}) and pick your project.`}),ne("/login"),Y(V=>V+1);return}if(l.escape){tn(null);return}return}if(Re){if(l.upArrow){nn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){nn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=Re.rows.length){nn(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=Re.rows[Re.cursor],{profile:m,projectId:j}=Re;nn(null),Ho(m,j,a);return}if(l.escape){nn(null);return}return}if(De){if(l.upArrow){jt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){jt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=De.rows.length){jt(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=De.rows[De.cursor],{profile:m}=De;jt(null),Vo(m,a);return}if(l.escape){jt(null);return}return}if(Pe){if(l.upArrow){rn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){rn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d===" "){rn(a=>a&&{...a,rows:a.rows.map((m,j)=>j===a.cursor?{...m,checked:!m.checked}:m)});return}if(l.return){let a=Pe.rows.filter(m=>m.checked).map(m=>m.path);if(rn(null),a.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}wi(e,a),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let m of a)u({kind:"note",tone:"info",text:` ${m}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){rn(null);return}return}if(ot){if(l.upArrow){It(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){It(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=ot.rows.length){It(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=ot.rows[ot.cursor],m=ot.run;It(null),m(a.token);return}if(l.escape){It(null);return}return}if(ut){if(l.upArrow){on(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){on(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=ut.rows.length){on(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=ut.rows[ut.cursor];on(null),a.conflict?As(a.paths[0]):a.kind==="article"?Ss(a.paths[0]):Ft(a.paths);return}if(l.escape){on(null);return}return}if(pt){if(l.upArrow){Nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){Nt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=pt.rows.length){Nt(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=pt.rows[pt.cursor];Nt(null),a.action==="capture"?Wn(a.ids,{runLine:a.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):a.kind==="shot"?bc(a.ids[0]):kc(a.ids,{setup:!0,runLine:a.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(l.escape){Nt(null);return}return}if(je){if(l.escape){Ot(null);return}if(l.upArrow){Ot(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){Ot(a=>a&&{...a,cursor:Math.min(Math.max(0,Fo.length-1),a.cursor+1)});return}if(l.return){let a=Fo[je.cursor];if(a){Ot(null);try{u({kind:"preview",name:vo(a),text:Xp(cs(Va(e,a),"utf8"))})}catch(m){u({kind:"note",tone:"error",text:`Could not read ${a}: ${m.message}`})}}return}if(l.backspace||l.delete){Ot(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(d&&!l.ctrl&&!l.meta&&d.length===1){Ot(a=>a&&{...a,query:a.query+d,cursor:0});return}return}if(Ne){if(l.escape){_t(null);return}if(l.upArrow){_t(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){_t(a=>a&&{...a,cursor:Math.min(Math.max(0,Wo.length-1),a.cursor+1)});return}if(l.return){let a=Wo[Ne.cursor];if(a){_t(null),Ie(a.uuid),et.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Et(a.name),Ga(a.uuid),Qt.current=[];let m=Fa(e,a.uuid);for(let j of m)u(j);u({kind:"note",tone:"ok",text:m.length?`Resumed "${a.name}" \u2014 restored ${m.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(l.backspace||l.delete){_t(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(d&&!l.ctrl&&!l.meta&&d.length===1){_t(a=>a&&{...a,query:a.query+d,cursor:0});return}return}if(l.tab&&!$&&re){v(re),Ke();return}if(!$&&Ue.length>0&&!Yt&&d&&/^[1-9]$/.test(d)){let a=Ue[Number(d)-1];if(a){v(Vt(a));return}}if(!$&&(Lo||Mn)&&d==="c"&&!l.ctrl&&!l.meta&&!l.return&&!l.tab){let a=Lo!=null;Ma(Lo??Mn).then(j=>{u({kind:"note",tone:j?"ok":"warn",text:j?a?"\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.":a?"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."}),j&&a&&vs(null),j&&!a&&mc(!0)});return}if(!Sc(d,l)){if(yc){if(l.upArrow){Kt(a=>Math.max(0,a-1));return}if(l.downArrow){Kt(a=>Math.min(Xe.length-1,a+1));return}if(l.tab){v("/"+(Xe[hs]?.name??"")+" "),Kt(0);return}if(l.return){let a=Xe[hs];if(a){let m=$.trim().slice(1).split(/\s+/).slice(1).join(" ");if(kl(a.usage)&&!m){v("/"+a.name+" "),Kt(0);return}Go("/"+a.name+(m?" "+m:""));return}}}else{if(l.upArrow){if($!==""&&Xt===null){Yo(-1);return}let a=fs.current;if(!a.length)return;let m=Xt===null?a.length-1:Math.max(0,Xt-1);Po(m),v(a[m]??"");return}if(l.downArrow){if($!==""&&Xt===null){Yo(1);return}let a=fs.current;if(Xt===null)return;let m=Xt+1;m>=a.length?(Po(null),v("")):(Po(m),v(a[m]??""));return}}if(l.return){Go();return}if(l.backspace||l.delete){R();return}if(l.escape){v(""),Kt(0),Ke(),ze([]),Nn(null),lt.current=!0;return}d&&!l.ctrl&&!l.meta&&Cc(d)}}}),Me(()=>{if(x||F)return;let d=Lt.current.shift();d!==void 0&&(gs([...Lt.current]),Go(d))},[x,F,Go]),te(ue,{flexDirection:"column",width:Be,children:[Rs!==null&&te(ue,{marginTop:1,flexDirection:"column",children:[Rs.truncated&&O(I,{dimColor:!0,children:"\u2026"}),O(I,{children:Rs.text})]}),x&&(Ao?O(Bb,{p:Ao}):O(Ub,{startTime:Tt.current,chars:ah})),!x&&dc?O(Fb,{text:dc}):null,O(ue,{borderStyle:"round",borderColor:gc.prod?"yellow":Z,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:$?Rc.map((d,l)=>{let a=h.text.slice(d.start,d.end),m=l===as(Rc,h.pos),j=Math.min(h.pos,d.end)-d.start;return te(I,{children:[O(I,{color:Z,children:l===0?"> ":" "}),m?te(xo,{children:[a.slice(0,j),O(An,{ch:a[j]??" "}),a.slice(j+1)]}):a||" "]},`${l}-${d.start}`)}):te(I,{children:[O(I,{color:Z,children:"> "}),ys?O(An,{ch:" "}):re&&!x&&ae?te(xo,{children:[O(An,{ch:ae[0],dim:!0}),O(I,{color:"gray",children:ae.slice(1)})]}):re&&!x?te(xo,{children:[O(An,{ch:re[0],dim:!0}),O(I,{color:"gray",children:re.slice(1)}),O(I,{dimColor:!0,children:" (tab)"})]}):(xs.isSetup||!sh)&&!x?te(xo,{children:[O(An,{ch:xs.text[0],dim:!0}),O(I,{color:"gray",children:xs.text.slice(1)})]}):O(An,{ch:" "})]})}),lc.length>0&&O(ue,{flexDirection:"column",paddingX:1,children:lc.map((d,l)=>O(I,{color:"gray",children:`\u29D7 queued: ${d}`},`${l}-${d.slice(0,24)}`))}),No?O(gp,{tab:No.tab,width:Be,version:o,engineVersion:Qp}):At?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:"Select model"}),O(I,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Je.map((d,l)=>te(I,{color:l===At.cursor?Z:void 0,children:[l===At.cursor?"\u276F ":" ",`${l+1}. ${d.label}${l===At.current?" \u2714":""}`.padEnd(16),O(I,{color:"gray",children:d.desc})]},d.label)),O(I,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):tt?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:"Switch connection profile"}),tt.rows.map((d,l)=>te(I,{color:l===tt.cursor?Z:void 0,children:[l===tt.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===tt.current?" \u2714":""}`.padEnd(20),O(I,{color:"gray",children:`${d.env} \xB7 ${d.who??"not signed in"}`}),d.prod?O(I,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},d.name)),O(I,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):nt?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:"Pick your Document360 environment"}),nt.rows.map((d,l)=>te(I,{color:l===nt.cursor?Z:void 0,children:[l===nt.cursor?"\u276F ":" ",`${l+1}. ${d.name}`.padEnd(16),O(I,{color:"gray",children:d.apiUrl})]},d.name)),O(I,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Re?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:"Switch workspace"}),O(I,{dimColor:!0,children:`environment ${Re.environment} \xB7 project ${Re.projectName??`${Re.projectId.slice(0,8)}\u2026`}`}),Re.rows.map((d,l)=>te(I,{color:l===Re.cursor?Z:void 0,children:[l===Re.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===Re.current?" \u2714":""}`.padEnd(30),O(I,{color:"gray",children:d.type??""})]},d.id)),O(I,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):De?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:"Choose project"}),O(I,{dimColor:!0,children:`environment ${De.environment}`}),De.rows.map((d,l)=>te(I,{color:l===De.cursor?Z:void 0,children:[l===De.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===De.current?" \u2714":""}`.padEnd(30),O(I,{color:"gray",children:d.sub??""})]},d.id)),O(I,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Pe?(()=>{let l=Math.min(Math.max(0,Pe.cursor-Math.floor(7)),Math.max(0,Pe.rows.length-14)),a=Pe.rows.slice(l,l+14),m=Pe.rows.filter(j=>j.checked).length;return te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:`Which folders back the user docs? (${m} selected of ${Pe.rows.length})`}),l>0?O(I,{dimColor:!0,children:` \u2191 ${l} more`}):null,a.map((j,V)=>{let f=l+V;return te(I,{color:f===Pe.cursor?Z:void 0,children:[f===Pe.cursor?"\u276F ":" ",j.checked?"\u25C9 ":"\u25CB ",j.path.padEnd(Math.min(48,Be-34)),O(I,{color:"gray",children:Dr(j)})]},j.path)}),l+14<Pe.rows.length?O(I,{dimColor:!0,children:` \u2193 ${Pe.rows.length-l-14} more`}):null,O(I,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():ot?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:"Which category? (pick one to scope to)"}),ot.rows.map((d,l)=>{let a=l===ot.cursor,m=`${l+1}.`.padEnd(3);return te(I,{color:a?Z:void 0,children:[a?"\u276F ":" ",`${m} ${d.label} (${d.count})`.padEnd(Math.min(44,Math.max(20,Be-24))),O(I,{color:"gray",children:` ${d.token}`})]},d.token)}),O(I,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):ut?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),ut.rows.map((d,l)=>{let a=l===ut.cursor,m=d.indent?" ":" ",j=`${l+1}.`.padEnd(3);return te(I,{color:a?Z:void 0,bold:d.kind==="category"&&!a,children:[a?"\u276F ":" ",`${m}${j} ${d.label}`.padEnd(Math.min(56,Be-24)),d.note?O(I,{color:"gray",children:d.note}):null]},`${d.kind}:${d.paths.join(",")}`)}),O(I,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):pt?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:pt.title}),(()=>{let{rows:l,cursor:a}=pt,m=Math.max(0,Math.min(a-Math.floor(12/2),l.length-12)),j=l.slice(m,m+12),V=`${l.length}.`.length+1,f=dd(l,Math.max(20,Be-4-V));return te(xo,{children:[m>0?O(I,{color:"gray",children:` \u2026 ${m} more above`}):null,j.map((w,k)=>{let g=m+k,C=g===a,S=f[g];return te(I,{color:C?Z:void 0,bold:(w.kind==="all"||w.kind==="category")&&!C,children:[C?"\u276F ":" ",`${g+1}.`.padEnd(V),S.head,S.note?O(I,{color:"gray",children:S.note}):null]},`${w.action}:${w.kind}:${w.ids.join(",")}`)}),m+12<l.length?O(I,{color:"gray",children:` \u2026 ${l.length-m-12} more below`}):null]})})(),O(I,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):je?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:`Preview article${je.query?` \u2014 filter: ${je.query}`:" (type to filter)"}`}),Fo.length===0?O(I,{color:"gray",children:"no articles match"}):Fo.map((d,l)=>te(I,{color:l===je.cursor?Z:void 0,children:[l===je.cursor?"\u276F ":" ",d]},d)),O(I,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ne?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:`Resume session${Ne.query?` \u2014 filter: ${Ne.query}`:" (type to filter)"}`}),Wo.length===0?O(I,{color:"gray",children:"no sessions match"}):Wo.map((d,l)=>te(I,{color:l===Ne.cursor?Z:void 0,children:[l===Ne.cursor?"\u276F ":" ",d.name.slice(0,28).padEnd(30),O(I,{color:l===Ne.cursor?Z:"gray",children:d.firstPrompt.slice(0,Math.max(10,Be-40))})]},d.uuid)),O(I,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):yc?te(ue,{flexDirection:"column",children:[Ut>0?O(I,{dimColor:!0,children:` \u22EF ${Ut} more above`}):null,Cs.map((d,l)=>{let a=Ut+l;return te(I,{color:a===Uo?Z:void 0,children:[a===Uo?"\u276F ":" ",d.usage.padEnd(22)," ",O(I,{color:a===Uo?Z:"gray",children:d.name==="model"&&ws?`${d.desc} (currently ${ws})`:d.desc})]},d.name)}),Ut+Cs.length<Xe.length?O(I,{dimColor:!0,children:` \u22EF ${Xe.length-Ut-Cs.length} more below`}):null,O(I,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!x&&!$&&Ue.length>0?te(ue,{flexDirection:"column",paddingX:1,children:[cc?O(I,{color:Z,children:cc}):null,Ue.map((d,l)=>{let a=Vt(d),m=a.slice(0,Math.max(20,Be-5)),j=Be-m.length-7,V=j>=12?($p(d)??yl(a)).slice(0,j):"";return te(I,{children:[O(I,{color:Z,children:l+1})," ",m,V?O(I,{dimColor:!0,children:` \u2014 ${V}`}):null]},a)}),O(I,{dimColor:!0,children:`press 1-${Ue.length} to fill \xB7 esc cancel`})]}):O(ue,{paddingX:1,children:te(I,{color:"gray",children:[gc.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ws??"model n/a"}${t.kind==="api"?pc>0?` \xB7 ${Ee(pc)}`:"":uc>0?` \xB7 ${bt(uc)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}K();import{jsx as Gb}from"react/jsx-runtime";async function Zp(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Vb(t);r.kind==="none"&&(console.error(""),console.error(A("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=qb(Gb(Jp,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
445
- `),process.exit(0)}K();import{writeCrashLog as eh,isBenignTransportError as Yb}from"document360-engine";var th=!1;function ec(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function nh(e){if(th)return;th=!0;let t=(n,o)=>{if(Yb(o)){eh({kind:n,level:"transport",message:ec(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=eh({kind:n,level:"fatal",message:ec(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
446
- `+A(`\u2717 d360-writer crashed: ${ec(o)}`)+`
447
- `),r&&process.stderr.write(y(` Crash details: ${r}`)+`
448
- `+y(" Run: d360-writer logs")+`
449
- `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Qb=Kb(import.meta.url),us=Qb("../package.json");nh("d360-writer");var Ye=new zb;function tc(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Ye.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=>{tc(e),await Zo({profile:e.profile,manual:e.manual})});Ye.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{tc(e),await Mc({profile:e.profile})});Ye.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{tc(e),await _c({profile:e.profile})});var nc=Ye.command("profile").description("Manage connection profiles for the current repo");nc.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>er(process.cwd()));nc.command("use <name>").description("Set the default profile for this repo").action(e=>tr(process.cwd(),e));nc.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>nr(process.cwd(),e));var oh=Ye.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");oh.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>hn(process.cwd(),e.profile));oh.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Ac(process.cwd(),e,t.profile)});var rh=Ye.command("project").description("Choose the Document360 project for this repo (active profile's identity)");rh.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Xo(process.cwd(),e.profile));rh.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await jc(process.cwd(),e,t.profile)});Ye.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(lr(),fl));await e()});Ye.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>Bc());Ye.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(()=>(_r(),iu)),n=await t(process.cwd(),us.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Ye.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(us.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(Xb.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 Hc(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 lp(e.cwd,e.auth,e.profile,us.version):await Zp(e.cwd,e.auth,e.profile,us.version)});Ye.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
432
+ `)}`}),ze(f.map(S=>`/draft ${S.name}`));return}let y="",x;if(k){let S=Bi(f,k);S?y=S:x=k}else y=f[0]?.name??"";await ie(Or(y,x),{display:k?`/draft ${k}`:"/draft",quietUser:!0});return}case"pull":{if(!Oo(d.trim()))return;let f=m.find(w=>w.startsWith("--"));try{if(f==="--status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let y=Date.now(),x=await Ya({cwd:e,profileName:s});u({kind:"note",tone:"info",text:jr(x,Date.now()-y).join(`
433
+ `)});return}if(f==="--baseline"){let y=m.find(B=>!B.startsWith("--")),x=y?y.replace(/\\/g,"/"):void 0;u({kind:"note",tone:"info",text:x?`Setting the sync baseline for ${x}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let S=await wb({cwd:e,profileName:s,relPaths:x?[x]:void 0}),U=x?{rebaselined:[],skipped:[]}:await kb({cwd:e,profileName:s});if(S.baselined.length===0&&S.skipped.length===0&&U.rebaselined.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}S.baselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Baselined ${S.baselined.length} article${S.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),U.rebaselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${U.rebaselined.length} article${U.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),S.skipped.length>0&&u({kind:"note",tone:"warn",text:`${S.skipped.length} skipped:
434
+ ${S.skipped.map(B=>` - ${B.path} (${B.reason})`).join(`
435
+ `)}`}),Y(B=>B+1);return}if(f==="--compare"){u({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let y=await yb({cwd:e,profileName:s}),x=y.onlyInLegacy.length===0&&y.onlyInManifest.length===0&&y.mappedMissingFromManifest.length===0,S=[`Legacy listing: ${y.legacyCount} \xB7 Manifest: ${y.manifestCount} \xB7 in both: ${y.inBoth}`];x?S.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(y.mappedMissingFromManifest.length&&S.push(`\u2717 ${y.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${y.mappedMissingFromManifest.slice(0,5).join(", ")}`),y.onlyInLegacy.length&&S.push(`\u26A0 ${y.onlyInLegacy.length} only in the legacy listing: ${y.onlyInLegacy.slice(0,5).join(", ")}`),y.onlyInManifest.length&&S.push(`\u26A0 ${y.onlyInManifest.length} only in the manifest: ${y.onlyInManifest.slice(0,5).join(", ")}`),S.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),u({kind:"note",tone:x?"ok":"warn",text:S.join(`
436
+ `)});return}if(f){u({kind:"note",tone:"error",text:`Unknown option: ${f} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let w=m[0];if(w){let y=await Bp({cwd:e,profileName:s,relPath:w.replace(/\\/g,"/")});ye.current=[{plan:y,mode:y.overwritesLocalChanges?"conflict":"pull"}],Zt.current=[],dn();return}u({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let k=await vi({cwd:e,profileName:s});for(let y of xi(k))u({kind:"note",tone:y.tone,text:y.text});Y(y=>y+1)}catch(w){u({kind:"note",tone:"error",text:`Pull failed: ${w.message}`})}return}case"scope":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=bb(e);if(f.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}rn({cursor:0,rows:f.map(w=>({...w,checked:w.recommended}))});return}case"audit":{if(m[0]==="--auto"){let w=de(e);if(!w){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=m[1]!=="off";Mp({...w,autoAudit:k},e),u({kind:"note",tone:"ok",text:k?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let f=await ro();f.kind==="forward-to-agent"&&f.prompt&&await ie(f.prompt,{display:f.display,quietUser:!0});return}case"check":{let f=m.find(y=>!y.startsWith("--")),w=f?` ${f}`:"",k=Wp({cwd:e,scope:f});if(m.includes("--fix")){if(k.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}u({kind:"note",tone:"info",text:`Fixing ${k.length} doc issue${k.length===1?"":"s"}\u2026`});let y=Gp(e,f);await ie(va(k),{display:`/check${w} --fix`,quietUser:!0});try{Ka(e,y,{reviewedCap:Xa})}catch{}let x=Wp({cwd:e,scope:f});u({kind:"note",tone:x.length===0?"ok":"warn",text:x.length===0?"\u2713 Doc-checker: all issues resolved.":qr(x).join(`
437
+ `)}),$e(x.length===0?`Deterministic issues fixed. Next: /review${w} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${w} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${w} --fix`,reason:""});return}u({kind:"note",tone:k.length===0?"ok":"warn",text:qr(k).join(`
438
+ `)}),k.length>0&&$e(`Found ${k.length} doc issue${k.length===1?"":"s"} above. /check${w} --fix has the agent fix them in place (or /review${w} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${w} --fix`,reason:""});return}case"structure":{let f=go(e,s);if(f.length===0){u({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}u({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...f].join(`
439
+ `)});return}case"reorder":{let f=Ca(e,m);if(!f){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ie(f.prompt,{display:f.display,quietUser:!0}),$e("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let f=xa(e,m);if(!f){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=m.includes("--fix"),k=m.find(x=>!x.startsWith("--")),y=w?Gp(e,k):[];if(await ie(f.prompt,{display:f.display,quietUser:!0}),w)try{Ka(e,y,{reviewedCap:Xa})}catch{}if(w)$e("\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let x=m.filter(S=>S!=="--fix").join(" ");$e(`The review listed issues above. /review${x?` ${x}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${x?` ${x}`:""} --fix`,reason:""})}return}case"capture-setup":{await V();return}case"devhints":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:yn(gn(e)).join(`
440
+ `)}),cn(Bt()),Un.current=qe(e).status==="current",ln.current=it(e);return}case"discover":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ie(yi(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(da(e)===0){u({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await ie(ua(),{display:"/inbox",quietUser:!0});return}case"feedback":{let f=Vp(e),w="";try{w=En(f)?cs(f,"utf8"):""}catch{w=""}if(!/^## /m.test(w)){u({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let k=await Ma(w.trim());u({kind:"note",tone:k?"ok":"warn",text:k?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${f} and copy it manually.`}),k&&vs(null);return}case"document":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:f,what:w}=Vi(m);if(!w&&qi(e)===0){u({kind:"note",tone:"info",text:Yi});return}let k=`/document${w?` ${w}`:""}${f?" --publish":""}`;await ie(Gi(w,f),{display:k,quietUser:!0});return}case"catch-up":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Oo(d.trim()))return;let{publish:f}=ha(m);u({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let w=await ma({cwd:e,profileName:s});for(let y of ga(w))u({kind:"note",tone:y.startsWith("\u2713")?"ok":y.startsWith("\u2139")?"info":"warn",text:y});let k=mo(fo(e));u({kind:"note",tone:"info",text:k?`Catching up on ${k}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ie(fa({publish:f}),{display:`/catch-up${f?" --publish":""}`,quietUser:!0});return}case"update":{bs.current=!0,u({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),So(!0);let f=await Br().finally(()=>So(!1));f.ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated ${f.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),ne("/exit"),ic("")):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Wr}`});return}case"screenshot":{let f=Zn(m),w=eo(e);if(w&&u({kind:"note",tone:"info",text:w}),f.mode==="capture"){await T(f.rest);return}if(f.mode==="checklist"){await V();return}if(f.mode==="verify"){let x=ve(e),S=f.rest.find(N=>!N.startsWith("-")),U=S?[S]:co(x);if(S&&!x.some(N=>N.id===S)){u({kind:"note",tone:"error",text:`No screenshot placeholder called "${S}". /screenshot list shows them all.`});return}if(U.length===0){let N=x.filter(L=>L.state==="rejected").length,F=x.filter(L=>L.state==="verified").length;u({kind:"note",tone:"info",text:N>0?`Nothing left to verify. ${N} shot${N===1?"":"s"} failed verification \u2014 re-capture with /screenshot capture --failed.`:F>0?`All ${F} captured shot${F===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."});return}u({kind:"note",tone:"info",text:lo(U.length)}),await ie(qt(e,U),{display:S?`/screenshot verify ${S}`:"/screenshot verify",quietUser:!0});let B=uo(e,U);B.length>0&&u({kind:"note",tone:"info",text:B.join(`
441
+ `)});return}if(f.mode==="list"){if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let x=de(e)?.docsDir??tc,S=di(e,f.scope),U=ve(e,S);if(f.picker){if(U.length===0){u({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let j=hd(U);if(j.length===0){u({kind:"note",tone:"info",text:Cr(U,{docsDir:x}).join(`
442
+ `)}),$e(`\u2713 All ${U.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}Nt({cursor:0,rows:j,title:"Screenshots \u2014 pick what to author or capture:"});return}u({kind:"note",tone:"info",text:Cr(U,{scope:S,detail:f.detail,docsDir:x}).join(`
443
+ `)});let B=U.filter(j=>j.state==="placeholder").length,N=U.filter(j=>j.state==="spec").length,F=U.filter(j=>j.state==="captured").length,L=U.filter(j=>j.state==="rejected").length;if(B>0){let j=S?`/screenshot author ${S}`:"/screenshot author --all";$e(`${B} of ${U.length} still need${B===1?"s":""} a spec \u2014 /screenshot author <id> authors one, ${j} authors them all in parallel.`,{kind:"cmd",cmd:j,reason:""})}else if(N>0){let j=S?`/screenshot capture ${S}`:"/screenshot capture";$e(`${N} spec${N===1?"":"s"} ready to capture \u2014 ${j} takes ${N===1?"it":"them"} (a real browser drives your app).`,{kind:"cmd",cmd:j,reason:""})}else F>0?$e(`${F} shot${F===1?"":"s"} captured but not yet verified \u2014 /screenshot verify checks each picture against what its article needs (no browser, no re-capture).`,{kind:"cmd",cmd:"/screenshot verify",reason:""}):L>0&&$e(`${L} shot${L===1?"":"s"} failed verification \u2014 /screenshot capture --failed re-shoots ${L===1?"it":"them"} once the spec is fixed.`,{kind:"cmd",cmd:"/screenshot capture --failed",reason:""});return}if(f.mode==="single"){await vc(f.id);return}if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=f.mode==="scope"?f.scope:void 0,y=Cb(e,{scope:k}).map(x=>x.id);if(y.length===0){u({kind:"note",tone:"info",text:k?`No screenshot placeholders under ${k}.`:"No screenshot placeholders found in the docs."});return}await $c(y,{setup:f.setup,runLine:f.mode==="scope"?[`/screenshot author ${f.scope}`,`/screenshot ${f.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await T(m);return}case"reset":{let f=ka(e);if(f.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Eo.current={repoName:vo(e),targets:f,hadDevhints:En(qp(e))},u({kind:"note",tone:"warn",text:$a(e,f).join(`
444
+ `)}),Pe(vo(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,dn,Ds,u,Le,ie,Ft,Ss,xc]),Go=ee(d=>{let l=(d??$).trim();if(v(""),Po(null),Kt(0),l.startsWith("/")&&(lt.current=!1,Pt.current=!1,Ke(),Nn(null),ze(m=>Rp(m,l))),!l||(sc(!1),Rc(l))||Cc(l))return;fs.current.push(l);let a=Ep(l,ac.current);if(l.startsWith("/"))u({kind:"user",text:l}),J(!0),Bn(a).finally(()=>J(!1));else if(Ib(a)){u({kind:"user",text:l});let m=Ob(a);if(!m)ie(a,{display:l,quietUser:!0});else{try{Lb(e,{title:m,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ie(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${m}". 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 "${m}" and the article path(s) you wrote.`,{display:l,quietUser:!0})}}else{let m=Ku(e,a);ie(m??a,{display:l})}},[$,Rc,Cc,Bn,ie]),Sc=ee(d=>{if(d.length>1){if(d.includes("\x1B"))return;let l=Sp(d);if(Pp(l)){let a=Tp(++dh.current,l);ac.current.set(a,l),E(a)}else E(l);return}E(d)},[E]),un=Math.max(10,Oe-6),Pc=qa(()=>is(h.text,un),[h.text,un]),As=ee(d=>b(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+d))})),[]),Yo=ee(d=>b(l=>({...l,pos:Ap(is(l.text,un),l.pos,d)})),[un]),Hn=ee(d=>b(l=>({...l,pos:jp(is(l.text,un),l.pos,d)})),[un]),fh=["\x1B[H","\x1B[1~","\x1BOH"],mh=["\x1B[F","\x1B[4~","\x1BOF"],Tc=ee((d,l)=>l.leftArrow?(As(-1),!0):l.rightArrow?(As(1),!0):d&&fh.includes(d)?(Hn("start"),!0):d&&mh.includes(d)?(Hn("end"),!0):l.ctrl&&d==="a"?(Hn("start"),!0):l.ctrl&&d==="e"?(Hn("end"),!0):!1,[As,Hn]);return Kk((d,l)=>{if(l.ctrl&&d==="c"){We.current?.close(),r();return}if(!I){if(C){if(l.escape){if(Ce.current){if(!Ce.current.signal.aborted){let a=(Do?.verb??"work").toLowerCase(),m=Do?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${m}s)\u2026`}),Ce.current.abort()}return}In.current||(In.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),We.current?.interrupt());return}if(l.return){let a=$.trim();if(!a)return;Lt.current.push(a),gs([...Lt.current]),v("");return}if(Tc(d,l))return;if(l.upArrow){Yo(-1);return}if(l.downArrow){Yo(1);return}if(l.backspace||l.delete){R();return}d&&!l.ctrl&&!l.meta&&Sc(d);return}if(Dt){if(l.upArrow){At(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){At(a=>a&&{...a,cursor:Math.min(Je.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=Je.length){At(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=Je[Dt.cursor];At(null);let{lines:m,changed:T,effective:V}=io(e,a.value??"default");for(let f of m)u({kind:"note",tone:f.startsWith("\u26A0")?"warn":f.startsWith("\u2713")?"ok":"info",text:f});T&&(mc(f=>f+1),We.current?.setModel(V));return}if(d==="s"){let a=Je[Dt.cursor];At(null),We.current?.setModel(a.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(l.escape){At(null);return}return}if(tt){if(l.upArrow){en(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){en(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=tt.rows.length){en(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return||d==="s"){let a=tt.rows[tt.cursor];en(null),Ts(a.name,l.return===!0);return}if(l.escape){en(null);return}return}if(No){if(l.escape){_n(null);return}if(l.leftArrow||l.tab&&l.shift){_n(a=>a&&{tab:(a.tab-1+He.length)%He.length});return}if(l.rightArrow||l.tab){_n(a=>a&&{tab:(a.tab+1)%He.length});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=He.length){_n({tab:Number(d)-1});return}return}if(nt){if(l.upArrow){tn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){tn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=nt.rows.length){tn(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=nt.rows[nt.cursor].name;if(tn(null),!Bs(e,a).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${a}").`});let T=!1;try{let V=Gt(a);T=!!V&&!(St(V)&&!V.refreshToken)}catch{T=!1}u({kind:"note",tone:"info",text:T?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${a}) and pick your project.`}),ne("/login"),Y(V=>V+1);return}if(l.escape){tn(null);return}return}if(Se){if(l.upArrow){nn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){nn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=Se.rows.length){nn(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=Se.rows[Se.cursor],{profile:m,projectId:T}=Se;nn(null),Ho(m,T,a);return}if(l.escape){nn(null);return}return}if(je){if(l.upArrow){jt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){jt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=je.rows.length){jt(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=je.rows[je.cursor],{profile:m}=je;jt(null),Vo(m,a);return}if(l.escape){jt(null);return}return}if(Te){if(l.upArrow){rn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){rn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d===" "){rn(a=>a&&{...a,rows:a.rows.map((m,T)=>T===a.cursor?{...m,checked:!m.checked}:m)});return}if(l.return){let a=Te.rows.filter(m=>m.checked).map(m=>m.path);if(rn(null),a.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}wi(e,a),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let m of a)u({kind:"note",tone:"info",text:` ${m}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){rn(null);return}return}if(ot){if(l.upArrow){It(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){It(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=ot.rows.length){It(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=ot.rows[ot.cursor],m=ot.run;It(null),m(a.token);return}if(l.escape){It(null);return}return}if(ut){if(l.upArrow){on(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){on(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=ut.rows.length){on(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=ut.rows[ut.cursor];on(null),a.conflict?Ds(a.paths[0]):a.kind==="article"?Ss(a.paths[0]):Ft(a.paths);return}if(l.escape){on(null);return}return}if(pt){if(l.upArrow){Nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){Nt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=pt.rows.length){Nt(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=pt.rows[pt.cursor];Nt(null),a.action==="capture"?Wn(a.ids,{runLine:a.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):a.kind==="shot"?vc(a.ids[0]):$c(a.ids,{setup:!0,runLine:a.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(l.escape){Nt(null);return}return}if(Ne){if(l.escape){Ot(null);return}if(l.upArrow){Ot(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){Ot(a=>a&&{...a,cursor:Math.min(Math.max(0,Fo.length-1),a.cursor+1)});return}if(l.return){let a=Fo[Ne.cursor];if(a){Ot(null);try{u({kind:"preview",name:vo(a),text:Jp(cs(Va(e,a),"utf8"))})}catch(m){u({kind:"note",tone:"error",text:`Could not read ${a}: ${m.message}`})}}return}if(l.backspace||l.delete){Ot(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(d&&!l.ctrl&&!l.meta&&d.length===1){Ot(a=>a&&{...a,query:a.query+d,cursor:0});return}return}if(Ie){if(l.escape){_t(null);return}if(l.upArrow){_t(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){_t(a=>a&&{...a,cursor:Math.min(Math.max(0,Wo.length-1),a.cursor+1)});return}if(l.return){let a=Wo[Ie.cursor];if(a){_t(null),Le(a.uuid),et.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Et(a.name),Ga(a.uuid),Qt.current=[];let m=Fa(e,a.uuid);for(let T of m)u(T);u({kind:"note",tone:"ok",text:m.length?`Resumed "${a.name}" \u2014 restored ${m.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(l.backspace||l.delete){_t(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(d&&!l.ctrl&&!l.meta&&d.length===1){_t(a=>a&&{...a,query:a.query+d,cursor:0});return}return}if(l.tab&&!$&&re){v(re),Ke();return}if(!$&&Fe.length>0&&!Yt&&d&&/^[1-9]$/.test(d)){let a=Fe[Number(d)-1];if(a){v(Vt(a));return}}if(!$&&(Lo||Mn)&&d==="c"&&!l.ctrl&&!l.meta&&!l.return&&!l.tab){let a=Lo!=null;Ma(Lo??Mn).then(T=>{u({kind:"note",tone:T?"ok":"warn",text:T?a?"\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.":a?"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."}),T&&a&&vs(null),T&&!a&&yc(!0)});return}if(!Tc(d,l)){if(kc){if(l.upArrow){Kt(a=>Math.max(0,a-1));return}if(l.downArrow){Kt(a=>Math.min(Xe.length-1,a+1));return}if(l.tab){v("/"+(Xe[hs]?.name??"")+" "),Kt(0);return}if(l.return){let a=Xe[hs];if(a){let m=$.trim().slice(1).split(/\s+/).slice(1).join(" ");if($l(a.usage)&&!m){v("/"+a.name+" "),Kt(0);return}Go("/"+a.name+(m?" "+m:""));return}}}else{if(l.upArrow){if($!==""&&Xt===null){Yo(-1);return}let a=fs.current;if(!a.length)return;let m=Xt===null?a.length-1:Math.max(0,Xt-1);Po(m),v(a[m]??"");return}if(l.downArrow){if($!==""&&Xt===null){Yo(1);return}let a=fs.current;if(Xt===null)return;let m=Xt+1;m>=a.length?(Po(null),v("")):(Po(m),v(a[m]??""));return}}if(l.return){Go();return}if(l.backspace||l.delete){R();return}if(l.escape){v(""),Kt(0),Ke(),ze([]),Nn(null),lt.current=!0;return}d&&!l.ctrl&&!l.meta&&Sc(d)}}}),Ue(()=>{if(C||I)return;let d=Lt.current.shift();d!==void 0&&(gs([...Lt.current]),Go(d))},[C,I,Go]),te(ue,{flexDirection:"column",width:Oe,children:[Rs!==null&&te(ue,{marginTop:1,flexDirection:"column",children:[Rs.truncated&&_(O,{dimColor:!0,children:"\u2026"}),_(O,{children:Rs.text})]}),C&&(Do?_(Vb,{p:Do}):_(Bb,{startTime:Tt.current,chars:lh})),!C&&pc?_(Hb,{text:pc}):null,_(ue,{borderStyle:"round",borderColor:wc.prod?"yellow":Z,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:$?Pc.map((d,l)=>{let a=h.text.slice(d.start,d.end),m=l===as(Pc,h.pos),T=Math.min(h.pos,d.end)-d.start;return te(O,{children:[_(O,{color:Z,children:l===0?"> ":" "}),m?te(xo,{children:[a.slice(0,T),_(Dn,{ch:a[T]??" "}),a.slice(T+1)]}):a||" "]},`${l}-${d.start}`)}):te(O,{children:[_(O,{color:Z,children:"> "}),ys?_(Dn,{ch:" "}):re&&!C&&ae?te(xo,{children:[_(Dn,{ch:ae[0],dim:!0}),_(O,{color:"gray",children:ae.slice(1)})]}):re&&!C?te(xo,{children:[_(Dn,{ch:re[0],dim:!0}),_(O,{color:"gray",children:re.slice(1)}),_(O,{dimColor:!0,children:" (tab)"})]}):(xs.isSetup||!ah)&&!C?te(xo,{children:[_(Dn,{ch:xs.text[0],dim:!0}),_(O,{color:"gray",children:xs.text.slice(1)})]}):_(Dn,{ch:" "})]})}),uc.length>0&&_(ue,{flexDirection:"column",paddingX:1,children:uc.map((d,l)=>_(O,{color:"gray",children:`\u29D7 queued: ${d}`},`${l}-${d.slice(0,24)}`))}),No?_(kp,{tab:No.tab,width:Oe,version:o,engineVersion:Zp}):Dt?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:"Select model"}),_(O,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Je.map((d,l)=>te(O,{color:l===Dt.cursor?Z:void 0,children:[l===Dt.cursor?"\u276F ":" ",`${l+1}. ${d.label}${l===Dt.current?" \u2714":""}`.padEnd(16),_(O,{color:"gray",children:d.desc})]},d.label)),_(O,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):tt?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:"Switch connection profile"}),tt.rows.map((d,l)=>te(O,{color:l===tt.cursor?Z:void 0,children:[l===tt.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===tt.current?" \u2714":""}`.padEnd(20),_(O,{color:"gray",children:`${d.env} \xB7 ${d.who??"not signed in"}`}),d.prod?_(O,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},d.name)),_(O,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):nt?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:"Pick your Document360 environment"}),nt.rows.map((d,l)=>te(O,{color:l===nt.cursor?Z:void 0,children:[l===nt.cursor?"\u276F ":" ",`${l+1}. ${d.name}`.padEnd(16),_(O,{color:"gray",children:d.apiUrl})]},d.name)),_(O,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Se?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:"Switch workspace"}),_(O,{dimColor:!0,children:`environment ${Se.environment} \xB7 project ${Se.projectName??`${Se.projectId.slice(0,8)}\u2026`}`}),Se.rows.map((d,l)=>te(O,{color:l===Se.cursor?Z:void 0,children:[l===Se.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===Se.current?" \u2714":""}`.padEnd(30),_(O,{color:"gray",children:d.type??""})]},d.id)),_(O,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):je?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:"Choose project"}),_(O,{dimColor:!0,children:`environment ${je.environment}`}),je.rows.map((d,l)=>te(O,{color:l===je.cursor?Z:void 0,children:[l===je.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===je.current?" \u2714":""}`.padEnd(30),_(O,{color:"gray",children:d.sub??""})]},d.id)),_(O,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Te?(()=>{let l=Math.min(Math.max(0,Te.cursor-Math.floor(7)),Math.max(0,Te.rows.length-14)),a=Te.rows.slice(l,l+14),m=Te.rows.filter(T=>T.checked).length;return te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:`Which folders back the user docs? (${m} selected of ${Te.rows.length})`}),l>0?_(O,{dimColor:!0,children:` \u2191 ${l} more`}):null,a.map((T,V)=>{let f=l+V;return te(O,{color:f===Te.cursor?Z:void 0,children:[f===Te.cursor?"\u276F ":" ",T.checked?"\u25C9 ":"\u25CB ",T.path.padEnd(Math.min(48,Oe-34)),_(O,{color:"gray",children:Ar(T)})]},T.path)}),l+14<Te.rows.length?_(O,{dimColor:!0,children:` \u2193 ${Te.rows.length-l-14} more`}):null,_(O,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():ot?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:"Which category? (pick one to scope to)"}),ot.rows.map((d,l)=>{let a=l===ot.cursor,m=`${l+1}.`.padEnd(3);return te(O,{color:a?Z:void 0,children:[a?"\u276F ":" ",`${m} ${d.label} (${d.count})`.padEnd(Math.min(44,Math.max(20,Oe-24))),_(O,{color:"gray",children:` ${d.token}`})]},d.token)}),_(O,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):ut?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),ut.rows.map((d,l)=>{let a=l===ut.cursor,m=d.indent?" ":" ",T=`${l+1}.`.padEnd(3);return te(O,{color:a?Z:void 0,bold:d.kind==="category"&&!a,children:[a?"\u276F ":" ",`${m}${T} ${d.label}`.padEnd(Math.min(56,Oe-24)),d.note?_(O,{color:"gray",children:d.note}):null]},`${d.kind}:${d.paths.join(",")}`)}),_(O,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):pt?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:pt.title}),(()=>{let{rows:l,cursor:a}=pt,m=Math.max(0,Math.min(a-Math.floor(12/2),l.length-12)),T=l.slice(m,m+12),V=`${l.length}.`.length+1,f=pd(l,Math.max(20,Oe-4-V));return te(xo,{children:[m>0?_(O,{color:"gray",children:` \u2026 ${m} more above`}):null,T.map((w,k)=>{let y=m+k,x=y===a,S=f[y];return te(O,{color:x?Z:void 0,bold:(w.kind==="all"||w.kind==="category")&&!x,children:[x?"\u276F ":" ",`${y+1}.`.padEnd(V),S.head,S.note?_(O,{color:"gray",children:S.note}):null]},`${w.action}:${w.kind}:${w.ids.join(",")}`)}),m+12<l.length?_(O,{color:"gray",children:` \u2026 ${l.length-m-12} more below`}):null]})})(),_(O,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):Ne?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:`Preview article${Ne.query?` \u2014 filter: ${Ne.query}`:" (type to filter)"}`}),Fo.length===0?_(O,{color:"gray",children:"no articles match"}):Fo.map((d,l)=>te(O,{color:l===Ne.cursor?Z:void 0,children:[l===Ne.cursor?"\u276F ":" ",d]},d)),_(O,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ie?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:`Resume session${Ie.query?` \u2014 filter: ${Ie.query}`:" (type to filter)"}`}),Wo.length===0?_(O,{color:"gray",children:"no sessions match"}):Wo.map((d,l)=>te(O,{color:l===Ie.cursor?Z:void 0,children:[l===Ie.cursor?"\u276F ":" ",d.name.slice(0,28).padEnd(30),_(O,{color:l===Ie.cursor?Z:"gray",children:d.firstPrompt.slice(0,Math.max(10,Oe-40))})]},d.uuid)),_(O,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):kc?te(ue,{flexDirection:"column",children:[Ut>0?_(O,{dimColor:!0,children:` \u22EF ${Ut} more above`}):null,Cs.map((d,l)=>{let a=Ut+l,m=d.name==="model"&&ws?`${d.desc} (currently ${ws})`:d.desc,T=Math.max(20,Oe-4),V=d.usage.length>T?`${d.usage.slice(0,T-1)}\u2026`:d.usage,f=T-Math.max(V.length,22)-1,w=f<=1?"":m.length>f?`${m.slice(0,f-1)}\u2026`:m;return te(O,{color:a===Uo?Z:void 0,children:[a===Uo?"\u276F ":" ",V.padEnd(22)," ",_(O,{color:a===Uo?Z:"gray",children:w})]},d.name)}),Ut+Cs.length<Xe.length?_(O,{dimColor:!0,children:` \u22EF ${Xe.length-Ut-Cs.length} more below`}):null,_(O,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!C&&!$&&Fe.length>0?te(ue,{flexDirection:"column",paddingX:1,children:[dc?_(O,{color:Z,children:dc}):null,Fe.map((d,l)=>{let a=Vt(d),m=a.slice(0,Math.max(20,Oe-5)),T=Oe-m.length-7,V=T>=12?(Cp(d)??kl(a)).slice(0,T):"";return te(O,{children:[_(O,{color:Z,children:l+1})," ",m,V?_(O,{dimColor:!0,children:` \u2014 ${V}`}):null]},a)}),_(O,{dimColor:!0,children:`press 1-${Fe.length} to fill \xB7 esc cancel`})]}):_(ue,{paddingX:1,children:te(O,{color:"gray",children:[wc.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ws??"model n/a"}${t.kind==="api"?fc>0?` \xB7 ${De(fc)}`:"":hc>0?` \xB7 ${bt(hc)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}K();import{jsx as Kb}from"react/jsx-runtime";async function th(e=process.cwd(),t="auto",n,o="0.0.0"){let r=zb(t);r.kind==="none"&&(console.error(""),console.error(D("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Yb(Kb(eh,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
445
+ `),process.exit(0)}K();import{writeCrashLog as nh,isBenignTransportError as Xb}from"document360-engine";var oh=!1;function nc(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function rh(e){if(oh)return;oh=!0;let t=(n,o)=>{if(Xb(o)){nh({kind:n,level:"transport",message:nc(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=nh({kind:n,level:"fatal",message:nc(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
446
+ `+D(`\u2717 d360-writer crashed: ${nc(o)}`)+`
447
+ `),r&&process.stderr.write(g(` Crash details: ${r}`)+`
448
+ `+g(" Run: d360-writer logs")+`
449
+ `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var e$=Jb(import.meta.url),us=e$("../package.json");rh("d360-writer");var Ye=new Qb;function oc(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Ye.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=>{oc(e),await Zo({profile:e.profile,manual:e.manual})});Ye.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{oc(e),await Fc({profile:e.profile})});Ye.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{oc(e),await Uc({profile:e.profile})});var rc=Ye.command("profile").description("Manage connection profiles for the current repo");rc.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>er(process.cwd()));rc.command("use <name>").description("Set the default profile for this repo").action(e=>tr(process.cwd(),e));rc.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>nr(process.cwd(),e));var sh=Ye.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");sh.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>hn(process.cwd(),e.profile));sh.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await jc(process.cwd(),e,t.profile)});var ih=Ye.command("project").description("Choose the Document360 project for this repo (active profile's identity)");ih.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Xo(process.cwd(),e.profile));ih.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Ic(process.cwd(),e,t.profile)});Ye.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(lr(),gl));await e()});Ye.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>qc());Ye.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(()=>(_r(),cu)),n=await t(process.cwd(),us.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Ye.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(us.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(Zb.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 Vc(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 pp(e.cwd,e.auth,e.profile,us.version):await th(e.cwd,e.auth,e.profile,us.version)});Ye.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});